import io

P = "traceable-reqs.toml"
with io.open(P, "r", encoding="utf-8", newline="") as f:
    lines = f.read().splitlines(keepends=True)

term = "\r\n" if lines[0].endswith("\r\n") else "\n"

idx = next(i for i, l in enumerate(lines) if l.startswith('id = "REQ-ECHO-DROP-DIR-RESOLVE"'))
stages_i = idx + 2
assert lines[stages_i].startswith("required_stages"), lines[stages_i][:60]

NEW_STAGES = (
    'required_stages = ["impl", "unit"]  # ACTIVATED LIFECYCLE-TRUTH W1 (todlando 2026-07-07). '
    'AMENDED releases#276 (todlando 2026-09-06): the bounded EACCES WRITE-RETRY rider is RETIRED WITH THE WRITE '
    '-- the echo no longer writes a drop file on any arm (REQ-ECHO-BRIEF-DIRECT-ROUTE), so there is no drop write '
    'to retry and its unit cell is DELETED rather than re-homed. WHAT SURVIVES, unchanged: impl = the resolver '
    'routing table on the INGEST leg and psyche_drop_file, which still resolve a relative manifest drop dir against '
    'the endpoint cwd; plus the spawn-cwd rider on fire_echo, which still reads info.cwd so the summarizer child runs '
    'where the endpoint lives. unit = the ingest leg resolver cells (relative + cwd -> resolved absolute; absolute -> '
    'as-is; relative no-cwd -> loud skip). The two lifecycle cells that pinned the ECHO arm of the resolver are '
    'removed with the arm they pinned; the ingest leg equivalents remain the evidence.'
) + term

T1 = (
    "THE ECHO-COMMUNE BRIEF ROUTES STRAIGHT FROM THE SUMMARIZER INTO THE TWO-TIER STORE AND NEVER TRANSITS THE "
    "AGENT `<id>-commune.md` DROP PATH (operator-ruled 2026-09-06, releases#276). MEASURED BEFORE THE RULING, on "
    "doyle own funnel: every `/clear` that hour was followed by an echo frame 25-45s later, landing exactly in the "
    "window where an unread Self drop sits, and 2 of 3 Self communes were lost -- the reborn session reported its own "
    "wake text as stale. WHY THIS IS A DESIGN GAP AND NOT A RACE TO PATCH: CONTEXT.md:208 names the drop as the AGENT "
    "channel and KNOWN-HAZARDS 6.4 names ONE writer on that path plus the daemon as sole deleter; echo.rs read `the "
    "mind` as the Psyche and forgot the Self, while docs/CONTEXT-MEMORY.md:25-33 states the Self DOES write that path "
    "at a boundary and that the Self signal is the STRONG live-context signal. So the echo -- weak, project-primary, "
    "live-conservative -- overwrote the strong Self capture: the exact inversion of the tiering the provenance "
    "asymmetry exists to protect. Nothing in the design ever required the brief to transit a file; the file was an "
    "implementation convenience that re-used the ingest. THE SHAPE: `run_echo_commune` loses `commune_dir` and returns "
    "the provenance-stamped body; the body-to-tiers core of `ingest_drops` is factored into ONE shared `ingest_body` so "
    "two callers cannot fork a later tiering change; `fire_echo` calls it, publishes the COMMUNE io-event carrying "
    "verbatim what ENTERED the tier (echo header first), consumes the releases#96 intent marker at THAT line rather "
    "than at the pulse file sweep, and strikes HARD on a route error through the existing EchoError classification. "
    "BEHAVIOUR CHANGE THAT MUST BE STATED IN THE PR: an adapter declaring `[session.echo_commune]` with NO "
    "`commune_dir` now echoes, where it used to no-op. Gate: doc -- the harness-contract echo-commune page rewritten "
    "to state the direct route, plus the CONTEXT.md:208 and :259 sentences; impl -- echo.rs without the write, "
    "ingest.rs `ingest_body`, and the fire_echo route-publish-consume order; unit -- the returned body carries the "
    "`Source: echo-commune` header and no drop dir survives in the signature; int -- through a real daemon the COMMUNE "
    "io-event appears with that header and NO file appears in `commune_dir`."
)

T2 = (
    "KNOWN-HAZARDS 6.12 -- THE ECHO BRIEF NEVER TRANSITS THE AGENT DROP PATH. FAILURE (field, 2026-09-06, "
    "releases#276): spt-core wrote its echo-commune brief to `<id>-commune.md`, the SAME path an agent writes its own "
    "boundary commune to, with no arbitration between the two writers -- so a Self commune authored at a `/clear` and "
    "not yet ingested was overwritten UNREAD by the boundary echo firing 25-45s later. Two of three Self communes lost "
    "inside one hour on one endpoint. INVARIANT: exactly one writer on the Self drop path -- the agent -- and the echo "
    "brief routes direct into the tiers. SPT-CORE MAPPING: `fire_echo` calls `ingest_body`; nothing writes a drop, on "
    "any arm. THE TEST IS A BYTE-IDENTITY PIN, NOT AN EXISTENCE CHECK: a pre-placed authored drop carrying Self bytes "
    "must be byte-identical after the fire, which goes RED when the write is restored -- an existence assertion would "
    "stay GREEN against an overwrite, which is the very failure this hazard names."
)

S1 = (
    'required_stages = ["doc", "impl", "unit", "int"]  # ACTIVATED releases#276 (todlando build 2026-09-06), '
    'operator-ruled the same day. doc = docs-site harness-contract/echo-commune.md rewritten to the direct route + '
    'CONTEXT.md:208 and :259. impl = spt-live echo.rs (no commune_dir, stamped body returned), spt-live ingest.rs '
    '(shared ingest_body), spt-daemon lifecycle.rs fire_echo (ingest_body -> publish_commune_io -> consume_intent). '
    'unit = the echo body cell in echo.rs. int = the daemon-level io-event cell asserting the frame appears and no '
    'file does.'
)

S2 = (
    'required_stages = ["impl", "unit"]  # ACTIVATED releases#276 (todlando build 2026-09-06). impl = the absence of '
    'any drop write on the echo path (echo.rs + fire_echo). unit = the lifecycle hazard cell: a pre-placed authored '
    '<id>-commune.md is BYTE-IDENTICAL after a fire, the live tier carries the echo brief, and the intent marker is '
    'consumed. Mutation proof recorded in the PR body: restoring the write turns the byte-identity arm RED.'
)

for t in (T1, T2):
    assert '"' not in t, "a double quote in a title breaks the TOML parse (treqs exit 2)"

block = []
for rid, title, stages in [
    ("REQ-ECHO-BRIEF-DIRECT-ROUTE", T1, S1),
    ("REQ-HAZARD-ECHO-NEVER-WRITES-AGENT-DROP", T2, S2),
]:
    block += [
        "[[requirements]]" + term,
        'id = "' + rid + '"' + term,
        'title = "' + title + '"' + term,
        stages + term,
        term,
    ]

lines[stages_i] = NEW_STAGES
lines[stages_i + 1 : stages_i + 1] = block

with io.open(P, "w", encoding="utf-8", newline="") as f:
    f.write("".join(lines))

print("terminator=%r  inserted %d lines after line %d" % (term, len(block), stages_i + 1))
