Compare commits

..
Author SHA1 Message Date
mos-dt-0andClaude Opus 5 0de8ccb52c docs(remediation): RM-62 — fleet management is a PREREQUISITE, and the rotation claim is corrected
Mos ruled (c): coder-mos1 stays idle/parked, not manually rotated. It holds no in-flight work, so
there is nothing to rotate FOR, and a manual in-pane restart would dress a missing mechanism as a
lifecycle operation — the D-41 overclaim itself. It stays AVAILABLE through RM-61's re-review in case
that review needs its context; the next NEW lane goes to a fresh seat, not to a seat at 67%.

RM-62 filed, because a dependency stated as prose with no owner becomes the permanent gap the charter
warns about. Bringing the execution fleet under roster/systemd management BLOCKS RM-50, RM-58 and
P-LIFECYCLE-001 — each is unsatisfiable against its real population until it lands. Banked explicitly
that both would FAIL against their real target today: RM-50 applied now quarantines the seat
implementing RM-50, and RM-58 has no mechanical reset path for any seat that needs one. RM-50 and
RM-58 now carry RM-62 as a hard depends_on edge, and RM-50 carries the requirement that acceptance be
proved against the unmanaged execution fleet rather than the roster-managed canaries.

RECORD CORRECTION, initiated by Mos and banked here: this session's opening rotation validated the
checkpoint+rehydration DESIGN losslessly — the residency attestation genuinely passed from the files —
but the MECHANISM was a manual pane respawn. "The handoff rehydrated losslessly" is earned; "rotation
worked" overclaims a mechanism that does not exist, and that overclaim is D-41. Same distinction as
D-23's inert guard: the step ran, one property was observed, the mechanism was not. Board header now
says so rather than implying a lifecycle rotation occurred.

D-37 and D-41 are one cluster — the execution fleet lacks both its shared-infrastructure and its
lifecycle management. Mos owns both, sequenced at a seam, never mid-lane.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 09:34:10 -05:00
mos-dt-0andClaude Opus 5 37402e9770 docs(remediation): bank D-41 — the whole execution fleet is UNMANAGED, so RM-50/RM-58 have no surface
Went to rotate coder-mos1 mechanically; `mosaic fleet restart` cannot reach it. Every seat executing
this mission is systemd inactive/disabled and flagged UNMANAGED — coder-mos1, rev-974, f10-coder,
merge-gate, the pm-scouts, rev-3107b, ultron-3107, and mos-remediation itself. The roster-managed
population is a different set of seats from the ones doing the work.

RM-50 applied today would quarantine the entire remediation fleet including the seat implementing it.
RM-58's mechanical out-of-band reset cannot be performed at all, so the only rotation available is what
D-4 says does not count: asking the agent, or killing a pane by hand. Requirement banked on both: their
acceptance must be demonstrated against the UNMANAGED execution population, because a criterion proved
only on roster-managed canaries is tested on the wrong population — D-17's coverage class one layer up.

Today's rotation is therefore labelled honestly as a manual pane restart with a hand-verified handoff,
not as a lifecycle operation. The step ran; the property was not observed (cf. D-23).

Did not run fleet restart against a disabled unit while the live pane held RM-61 and RM-03 state.
Disposition escalated to Mos.

Also records the handoff artifact as the positive control: typed state, and it surfaced D-12 recurring
live (PR #1033's draft property silently dropped by a wrapper fallback), an unrunnable check declared
rather than substituted, and suspicions labelled as suspicions.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 09:31:17 -05:00
mos-dt-0andClaude Opus 5 01831814b6 docs(remediation): board — D-40 ruled BLOCKING, RM-61 rebuilding, TS1-TS12 pre-registered
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 09:25:54 -05:00
mos-dt-0andClaude Opus 5 86cd1a0f46 docs(remediation): D-40 RULED BLOCKING; pre-register type-strict ACs before the fix is pushed
Mos ruled BLOCKING on the exit_code type confusion. Both of us had leaned non-blocking on the
unreachability argument and neither shipped it. The two decisive grounds: the direction is
wrong-ACCEPT (false and 0.0 GRANT the exemption), which is this mission's disqualifying direction and
exactly why RR12 was tolerable; and "Woodpecker is Go with an int type" is structurally the same
incidental-correlate argument RM-61 itself forbade for the signature — you cannot certify the
discriminator against infra-shift and then defend a hole in it with an infra-stability assumption.

Generalised into an RM-02 standing clause, which is the real prize: discriminator and comparison
inputs must be TYPE-STRICT. A comparison that accepts a type it should not is a wrong-ACCEPT hole by
construction; `== 0` matching False and 0.0 is one instance of a class. D-40 is the instance, the
clause is the fix. It sits alongside the D-38 clause (does this gate bind its evidence to its subject).

D-39b banks the roles-swapped half: the author does not adjudicate its own PR's blocker status and
does not move the head to enforce it. Symmetric with D-39 — a seat with a stake in the answer does not
settle the question, and a conservative motive exempts neither direction.

ACs are registered NOW, before coder-mos1 pushes and before any reviewer reads a diff; at registration
the fix exists only as an unpushed local commit I have not read, so there is no diff to retrofit to.
They also state explicitly which cases are genuine RED-FIRST (false, 0.0 — currently wrongly exempting)
and which are only regression guards ("0", null — already blocking), because demanding an impossible
red for the latter two invites weakening something real to manufacture it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 09:23:16 -05:00
mos-dt-0andClaude Opus 5 249335e515 docs(remediation): bank D-39/D-40 — gate-ready reached, then withdrawn on a finding I disclosed
D-39: I contaminated an open independent review. RR12 was an open registered check and I sent rev-974
my CONCLUSION, not just my observation. rev-974 then downgraded an automated Codex review that had
flagged RR12 as a blocker, in line with my framing. The bias sat in my instrument, not the reviewer's
diligence — a subordinate is agreeable by construction, and the divergence instruction I attached
cannot undo having named the answer first. Mos adopted the rule fleet-wide: a dispatcher may relay
observations and reproductions into an open review, never its own verdict on an open check.
Re-adjudicated by a mechanically fresh seat with no access to my framing: NON-BLOCKING, independently,
on stronger evidence than either prior pass (accept-set matrix proving the accepted set is a strict
subset of a correct case-insensitive comparison's, so it cannot false-certify; exploit path hunted and
ruled out; all 0x110000 codepoints scanned for a fold that could smuggle non-hex onto a valid SHA).
So contamination did not change the answer, and the finding stands anyway — a correct answer reached
by a contaminated process still corrupts the process.

D-40: that same fresh seat looked outside its question and found a type confusion inside the exact
conjunction the exemption rests on. `step.get("exit_code") == 0` is True for JSON false, and
coder-mos1 added the float case. Verified by me on the real #2188 record: false and 0.0 both yield
exit 0 with exempted_steps 1 — the exemption GRANTED; "0" and null correctly block. Two of four
near-miss types satisfy a conjunction whose whole justification is that it is exactly scoped.

Consequence: I reported #1033 gate-ready at 033b2ffb (RR1-RR12 pass, review 69 APPROVED, CI #2193
success 9/9) and then had to hand Mos a finding that may disqualify what I had just certified. Better
that than defending the report. Disposition is Mos's; coder-mos1 escalated it to blocker unilaterally
and moved to push — held, because the author does not adjudicate their own PR and does not void a live
APPROVED review plus terminal-green CI by pushing. Head frozen, fix prepared and unpushed, ACKed.

Board doctrine now carries both rules: never relay a conclusion into an open review, and the author
never adjudicates their own blocker status.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 09:20:15 -05:00
mos-dt-0andClaude Opus 5 d9ab6026c8 docs(remediation): RM-61 tick — twelve checks pass, blocker moved to metadata, head never moved
rev-974 review 68 @ 033b2ffb: RR1-RR12 all PASS. RR7 is the strong one — all four binding predicates
proved RED against the old e7b29219 verifier, and the original attack under the old interface returned
exit 0 with exempted_steps=1, proving the PRIOR DEFECT rather than merely unsupported syntax.

The remaining blocker was metadata, not code: the live PR body still said "DO NOT MERGE" and "the
exemption will not be implemented", describing an earlier head. Verified independently — the controls
were injected in 3931b0e2/9455cd6a/25ac5971/ef9d23ab and the final delta does not touch
.woodpecker/ci.yml at all. The body was true when written and went stale as the branch evolved. That
is D-38 one layer out: the PR that binds evidence to its subject shipped a description that was not
bound to its subject, and D-36's staleness class on provider metadata rather than a repo file.

Fixed as metadata only. Head confirmed unmoved at 033b2ffb from both provider and git, body SHA-256
b0198d98 matched the author's reported digest byte-for-byte, both stale strings absent. Because the
commit never moved, the twelve results stand and no third review round is owed — only the discharge
of the finding by the reviewer who raised it.

Exact-head CI #2193: success, 9 children, 9/9 success including clone, read from -f json (D-33).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 09:10:32 -05:00
mos-dt-0andClaude Opus 5 50c0340add docs(remediation): bank D-37/D-38, pre-register RM-61 re-review, rebuild board for a cold read
D-38 — RM-61's terminal-green verifier certified the right RECORD for the wrong COMMIT. rev-974
mutated only #2188's commit field and the gate still exited 0. Confirmed by construction: at
e7b29219 the whole verifier had exactly one "commit" line (159), no expected-head parameter, no
comparison, no failure path. D-24 at the gate layer — a true answer to a different question.
The transferable half is the AC set, not the verifier: AC1-AC8 ALL PASSED and the PR was still
NO GO, because every registered check tested whether the signature discriminates and none tested
whether the evidence was bound to its subject (coverage-failure-mode-2, D-17 class). Mos ruled a
STANDING clause into RM-02 coverage: "does this gate bind its evidence to the subject under
review?" — every gate can fail this way and pass its own ACs.

D-37 — one shared .git/config silently re-identified EVERY worktree. extensions.worktreeConfig is
unset, so a worker's repo-local identity write rebinds all linked worktrees at once; the
orchestrator checkout and rev-974's review worktree both authored as coder-mos1. Distinct from
D-34, not an instance: MOSAIC_GIT_IDENTITY was exported and correct and still resolved wrong.
Sharp edge is gate-16 defeated in the artifact — the reviewer would author its pre-registered ACs
as the author of the code under review. No contamination occurred. Containment (explicit -c, no
shared-config rewrites mid-flight) is the standing order; the real fix is authorised and owned by
Mos, sequenced at a quiet seam. #1024 is implicated: repo-local pinning is the colliding mechanism.

Also pre-registers the twelve RM-61 re-review checks at exact head 033b2ffb BEFORE the reviewer
reads the diff, and rebuilds the board for a cold read — RM-61 "building", "nothing implemented
yet", and DECISION-1/2/3 "must be ruled" were all stale, the D-36 class again at the same seam.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 08:59:40 -05:00
mos-dt-0andClaude Opus 5 345d152790 docs(remediation): RM-61 result — kill criterion NOT triggered, signature discriminates structurally
coder-mos1 ran two real ci-postgres failure controls; the orchestrator verified the JSON
records independently. #2189 (startup failure) exit 1 and #2191 (post-readiness crash,
log proves ready then postmaster killed) exit 137 both take the workflow and the test
step down — terminal red. #2188, the genuine artifact, carries exit_code 0 under a
SUCCESSFUL workflow.

So the discriminator is structural — a failed service step with exit 0 under a successful
workflow — not the message string and not an incidental correlate like node or timestamp,
which were explicitly forbidden because they pass today and mask a real failure the moment
infrastructure shifts.

Verifier: exit 0 with one named exemption on the artifact; exit 1 with exempted_steps 0 on
BOTH real controls. No fetch, trigger, retry or re-roll — the coin flip is removed, not
codified.

PR #1033 dispatched to rev-974 with eight acceptance checks pre-registered before the diff
was read; AC2 (both real failures must NOT be exempted) is the crux and a REJECT if it fails.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 08:44:46 -05:00
mos-dt-0andClaude Opus 5 f11f257368 docs(remediation): bank D-36 — rotation-seam audit found three stale restatements on the board
Preparing the checkpoint for a cold read surfaced three stale sections, each a copy of
text owned elsewhere, each of which would have misled the incoming orchestrator: a
delivery-gate list still omitting the merge-gate step (D-26's own defect, still on the
board after MISSION.md was fixed); a capability rule superseded by D-13/D-15; and
DECISION-1 still marked CONTESTED hours after it was ruled.

None were wrong when written. All three drifted because they were copies — D-14 three
times in one artifact. The failure is not that someone forgot to update three lines; it
is that three lines existed to forget.

The rotation seam is what surfaced it. A familiar section is skimmed for the line you
came for; preparing state to be read cold by a stranger is a different act from
maintaining it, and catches a class ordinary use cannot.

RM-34: a handoff must VALIDATE the checkpoint, not merely write it. RM-02 registers the
general form with a must-fail on divergence. Interim: audit the board against its
sources at every rotation seam.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 08:14:04 -05:00
mos-dt-0andClaude Opus 5 6c779595e1 docs(remediation): rotation checkpoint — board rebuilt for a cold read, three stale restatements removed
Orchestrator rotating at ~803k tokens (~4x threshold). A mission built on
rotation-not-compaction should not run its own coordinator past it.

Board rewritten as the rehydration artifact: in-flight state, a read-this-first block
for the incoming seat, and the live rulings it most needs. Under the 8KB cap.

AUDIT AT THE SEAM found THREE stale restatements on this board, each of which would have
misled the incoming orchestrator:
  1. the delivery-gate list still OMITTED the merge-gate verdict step (the D-26 defect
     itself, still sitting on the board after MISSION.md was corrected);
  2. capability described as 'token-file set = authoritative registry', superseded by
     D-13/D-15 (capability is per-path; assert permissions.push as that seat);
  3. Sequencing still said DECISION-1 was CONTESTED and 'do not treat it as settled'
     hours after it was RULED — an incoming seat would have re-litigated a closed decision.

All three were restatements of text owned elsewhere. Replaced with references, per the
mission's own render-not-restate principle: a second copy is a second thing to go stale,
and this board proved it three times in one night.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 08:13:12 -05:00
mos-dt-0andClaude Opus 5 cc097f36c5 docs(remediation): re-run failed; RM-02 blocked on RM-61, declared bound honoured
Pipeline #2188 at the same head: ci-postgres the sole failure, everything else success
including gate-verify. f10-coder independently confirmed and applied the pre-registered
rule itself.

RM-02 blocked. No ad-hoc exemption, no third roll. Recorded why: two failures against one
earlier clean run makes 'best of five' feel reasonable, and the point of declaring the
bound in advance is that it binds when the result is inconvenient. A third roll would
have been indistinguishable from diligence, including to the person doing it.

Data for RM-61: the artifact hit twice consecutively at f9746b23 while #2184 was clean at
38f1b249, so it may cluster rather than be uniformly random — which makes a one-shot
re-roll close to worthless and strengthens the ruling that it must not become policy.

And the illustration: the anti-inert-gate registry is blocked by an artifact that makes
gate evidence unreliable. The thesis demonstrating itself on its own keystone.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 01:34:20 -05:00
mos-dt-0andClaude Opus 5 56d8e8a3d5 docs(remediation): record the bounded re-trigger as a stopgap; mark the first end-to-end merge stack
The re-trigger guardrail, recorded so it cannot become practice: one bounded,
pre-declared attempt at the same head with the response to each outcome fixed before
triggering. Re-running until the desired answer appears is p-hacking the pipeline, and
silently nobody can tell it from diligence — including the person doing it. Per Mos: a
per-PR free re-roll would be D-21 normalisation wearing a new hat. RM-61 must make the
re-roll unnecessary, not codify it, and a clean re-run does not retire RM-61.

Milestone: RM-03/#1032 completed independent review -> CI terminal-green -> merge-gate GO
-> coordinator -> held for owner, the first time end-to-end. GO posted under the gate's
own minted identity by a seat that structurally cannot merge. Head verified unmoved after
the verdict, so the commit-bound GO stands.

The first delivery through the complete stack is also the last one gated by a check that
could not fail — RM-03 is that check's fix.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 01:22:32 -05:00
mos-dt-0andClaude Opus 5 4589659bc1 docs(remediation): board — RM-03 GATE-READY, merge-gate assigned, held for Jason
First genuine gate-ready of the mission. Head triple equal at 78ec47cd, latest review
APPROVED at the current head, CI 9/9 by JSON scan with two-observer agreement.

Recorded the shape worth remembering: the queue guard is still inert for this merge
because RM-03 is the fix — the last merge to pass through the broken gate is the one
that fixes it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 01:15:05 -05:00
mos-dt-0andClaude Opus 5 357a636a3a docs(remediation): promote redundant-observation to charter; bank D-35 (tool caught what attention could not)
Charter gains a fifth principle from D-33: two observers of the same evidence,
disagreeing, catch what neither catches alone — applied to evidence GATHERING, not just
judgement. A summary that resembles an enumeration is more dangerous than one that
obviously summarises; prefer the machine-readable record and state counts so divergence
is detectable.

D-35: while editing merge-gate.md to fix D-33, the coordinator recalled the mandate
string instead of reading it and the Edit tool's exact-match REJECTED it. Third instance
for that author, inside the turn fixing another instance of the same class — and the
only one that did not reach a document, because a mechanism caught it.

A rule that fails in its authors but is caught by a tool has told you where it belongs.
RM-02 should enforce verbatim citation by construction, as the Edit tool did by accident
of design.

Fix landed by annotating the source: merge-gate.md mandates 3 and 4 now require the
scan and count from the JSON record. The shared wrapper was deliberately NOT modified
mid-flight — three lanes are reading it; fix at a seam.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 00:53:27 -05:00
mos-dt-0andClaude Opus 5 9e205e8201 docs(remediation): bank D-34 — a context reset silently strips a seat's credential identity
rev-974 finished its RM-02 review and could not post it: pr-review.sh failed with
'Gitea token not found'. Verified — with MOSAIC_GIT_IDENTITY unset the token does not
resolve; with it set it resolves. The token file was correct throughout.

My own context reset wiped the seat's exported identity and my rehydration brief did not
re-establish it. git config mosaic.gitIdentity is persistent and per-worktree;
MOSAIC_GIT_IDENTITY is ephemeral and per-context. rev-974 works from ~/agent-work with no
git-config fallback, so it had no warning and the loss surfaced only when it next needed
a credential.

Intersection of two banked findings, created by acting on one: D-31 prescribes rotation,
D-11a requires identity coherence, and nothing said rotation is a credential-affecting
operation. The fix for one failure introduced another.

RM-34: rotation must re-establish AND verify seat identity before handing over work.
RM-50: prefer the durable binding (mosaic.gitIdentity in the seat's repo) so identity
survives a reset by construction. Interim: every rehydration brief re-exports identity.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 00:51:21 -05:00
mos-dt-0andClaude Opus 5 73a313301b docs(remediation): bank D-33 — the full-step-scan tool prunes a step in default output
coder-mos1 scanned pipeline #2186 with -f json and found 9/9 child steps; my scan of the
same pipeline in the wrapper's default text mode showed 8. Verified: text mode omits
clone (JSON shows the ci workflow entry, clone, and the 8 visible ones).

Every full step scan performed tonight enumerated 8 of 9 real child steps and reported
it as complete. clone succeeded throughout so no verdict changes — but the method was
incomplete and its user did not know.

The merge-gate mandate requires a FULL step scan and requires verdicts to enumerate the
step count. A verdict citing 8 where 9 exist is non-conforming evidence, and a gate using
this wrapper's default output would produce exactly that while believing it complied.

The shape is the session's thesis aimed at the detection tool: the doc says read the
artifact not the summary, and text mode IS a summary that looks like an artifact. Compare
D-24 — mergeable was a true answer to a different question; this is a true answer to a
smaller one.

Caught only because two observers' counts disagreed; neither alone would have found it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 00:49:01 -05:00
mos-dt-0andClaude Opus 5 eddf718a5c docs(remediation): board — RM-02 frozen at 38f1b249 with a fully clean 9/9 scan
First run on this branch where ci-postgres passed, so no exemption question arises.
Recorded that the artifact's intermittency is evidence FOR RM-61's negative-control
requirement: intermittent means delivery is a coin flip until the signature is proven to
discriminate from a real database failure.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 00:35:51 -05:00
mos-dt-0andClaude Opus 5 c83a3cd3e2 docs(remediation): bank D-32 — the repaired gate shipped with a documented switch to skip it
rev-974 blocked RM-03: pr-merge.sh still ships --skip-queue-guard at five sites
including a worked example. It proved this rather than reading it — stubbed the guard to
exit 99, ran a real fixture merge with the flag, and observed the guard never called,
provider payload created, 'merged successfully', exit 0.

Disqualifying because RM-03 repairs a mandatory gate that has never been able to fail;
shipping that repair with a documented bypass means the gate merely requires one flag
instead of zero, and every merge-side CANNOT_ASSERT/HOLD semantic is skipped. L0 bars
equivalent skip switches, and the merge-gate role doc names this exact hazard about
force_merge — adjacent to the field you came to edit, at the moment you are most
motivated to reach for it.

Generalizable: repairing a gate is incomplete while any supported path skips it. The
failure changes from 'cannot block' to 'can be told not to' — the same outcome one
keystroke later. Removing the bypass is part of the repair.

Everything else passed independently, including the 160 KiB stdin transport where #1023
regressed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 00:33:18 -05:00
mos-dt-0andClaude Opus 5 bf8c6f4a89 docs(remediation): bank D-31 — seat ran past 100% context with 28 uncommitted files
coder-mos1 hit 102.5%/372k on RM-03 with 28 modified files uncommitted and its branch
still at base — a full context window spent with nothing durable. Caught by polling seat
state, not by any system signal. Nothing warned anyone: no threshold alert, no
pre-compaction hook.

The founding failure mode of this mission — compaction destroying in-flight work —
nearly hit the mission's own delivery twice in one night. RM-01 survived because it had
committed work when checkpointed; this one had none. Commit-then-rotate works;
rotate-without-commit loses everything.

RM-34: a context threshold is not enough — rotation must force a durable checkpoint and
refuse to rotate a seat with uncommitted work. RM-50: seat context is observable state
and must be monitored; relying on an orchestrator to poll is instructions-not-enforcement
applied to lifecycle. Brief doctrine: commit early, commit WIP.

Adjacent: the diff spans 5 guides and 11 templates against a brief scoped to one script.
Queried, not assumed — but a 28-file diff from a one-script brief is a scope signal
regardless of the answer.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 00:07:59 -05:00
mos-dt-0andClaude Opus 5 bdf8932328 docs(remediation): RM-61 terminal-green exemption ruled B, with sequencing correction
Condition 1 tested: the signature is stable — pods "wp-svc-<ULID>-ci-postgres" not
found across all five observed failures, an orchestration-layer lookup miss structurally
unlike a service-level failure.

But discrimination is UNPROVEN: every observation co-occurs with a demonstrably working
database, and we have never seen a real ci-postgres failure on this provider. If
PostgreSQL crashes and the pod is GC'd, the status query may also return pod-not-found —
the exemption would over-match and mask a real failure.

So conditions 1 and 2 are not independent: 2 is the evidence for 1. Build the negative
control first, prove a real failure produces a different signature, then adopt the
exemption. Kill criterion stated in advance: if an injected real failure also yields
pod-not-found, B is unsafe and we do A.

Filed as RM-61, unassigned — no free write-capable seat; flagged rather than stacked
onto a busy lane.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-01 00:04:32 -05:00
mos-dt-0andClaude Opus 5 16d11cd6cd docs(remediation): bank D-29 (syntactic criterion binding) and D-30 (false comparator, mine)
D-29: rev-974 moved two criterion bindings to an unrelated case, reformatted the
manifest, and gate:verify still exited 0. The registry verifies a criterion HAS a
binding, not that the bound case can fail for that criterion's stated reason —
RM02-REQ-03 unsatisfied. The keystone reproduced the defect it exists to eliminate, in
its own coverage check. Caught only by mutating and re-running; inspection would have
passed it.

D-30: my review brief claimed the ci-postgres FAIL appeared on #2167 — it did not
(#2167 is OK). My own banked D-21 says so explicitly; I restated from memory instead of
reading my record. D-26 recurring, in a reviewer brief, hours after promoting
render-not-restate to the charter.

The harm is not the inaccuracy but that I supplied a reviewer with fabricated supporting
evidence for my own reading. It refuted me — query-for-refutation paying for itself in
the same document that introduced it.

Requirement: briefs cite evidence from the record with identifiers, never from recall.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 23:59:25 -05:00
mos-dt-0andClaude Opus 5 8ce77fcb0d docs(remediation): board — RM-02 frozen at 9b4d4beb, CI green, review in flight
Head triple verified independently twice (orchestrator + f10-coder): local = origin =
PR #1030 = pipeline #2182. Full step scan rather than a tests-complete inference.
Queue guard not offered as evidence.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 23:41:52 -05:00
mos-dt-0andClaude Opus 5 cdd5568adb docs(remediation): promote query-for-refutation to charter doctrine
Per Mos. A subordinate asked to confirm a hypothesis will agree — the bias is induced by
the query, not by the answerer's diligence. 'The DB flaked, please confirm' and 'confirm
or refute, with the log line that proves it' are different instruments returning
different answers to the same question.

This matters most with agent subordinates, which are agreeable by construction, so the
discipline cannot rest on the answerer being rigorous — it must be built into how the
question is asked.

Origin: the orchestrator's ci-postgres hypothesis was refuted by the implementing seat
with log evidence and then settled by reproduction. Phrased for confirmation, it would
have returned agreement and D-21 would have been re-classified on a false premise,
silently corrupting a banked finding.

Operational form: state the hypothesis as yours, ask for evidence that kills it, say
what would change your mind, and reproduce when the answer is consequential. Added to
KICKSTART's standing invariants so it survives compaction.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 23:21:15 -05:00
mos-dt-0andClaude Opus 5 ff4b45b025 docs(remediation): RM-03 CANNOT_ASSERT semantics ruled (option B)
Resolves an ambiguity in the orchestrator's own brief, which required CANNOT_ASSERT to
neither silently pass nor permanently block without distinguishing push from merge.
coder-mos1 stopped and asked rather than inferring authorisation; Codex security
independently flagged CWE-693.

Ruled B: merge fails CLOSED (proceeding without exact-head CI evidence is D-23's
condition in a narrower costume), push degrades AUDITED (blocking during an outage
bricks delivery — the Pi-brick class we already banked). A temporary block pending
evidence is not a permanent block, and merge is separately gated by the merge-gate and
coordinator, so nothing is stranded.

Conditions: distinct exit code or the tri-state is destroyed; the audit record asserted
by a registered case, not assumed, or 'audited' is a claim dressed as a property;
retryable and self-clearing; cases observed RED first; no silent degraded merge path —
break-glass belongs to RM-05.

Option C rejected: it bricks push during an outage and defers the degraded path, which
in this codebase means a silent bypass appears under incident pressure. Three are
already on the books.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 23:17:01 -05:00
mos-dt-0andClaude Opus 5 f47cf45b0c docs(remediation): bank D-28 — a swallowed diagnostic destroyed a fail-closed check's evidence
RM-02 CI failed on four sandbox tests. Bubblewrap is installed by the gate step but not
the test step, so spawnSync returned ENOENT; replayCommit replaced the spawn diagnostic
with an empty string, so the classifier could not prove Bubblewrap provenance and
correctly refused to treat it as expected sandbox unavailability.

The refusal was right; the information loss was the bug. For a classifier, error text is
not decoration — it is the input. Widening acceptance to make the test pass would be a
finding, not a fix.

Linkages: D-16 again (local has bwrap, CI does not — local and CI disagree a third
time), and diagnostic-preservation registered as an RM-02 gate requirement with a
must-fail control proving a swallowed message is detected.

Process note: the orchestrator's hypothesis that the coincident ci-postgres FAIL caused
this was WRONG and was refuted with log evidence. D-21 stands unchanged as a teardown
artifact and is NOT upgraded — it was about to be re-classified on a false premise.
Asking the seat to confirm or refute rather than accept is what prevented that.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 23:10:53 -05:00
mos-dt-0andClaude Opus 5 e7c9160c7b docs(remediation): board — delivery-gate doctrine change recorded with render-vs-restate root cause
Per Mos's item 4. The gate definition was incomplete from setup because the gates were
restated from memory rather than referenced, and the omission propagated into every
worker brief since — then recurred inside the correction itself (D-26).

Board now carries the referenced sources, the gate order, freeze-after-GO, the
coordinator/orchestrator split, and the queue-guard zero-information field form.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 23:01:07 -05:00
mos-dt-0andClaude Opus 5 2d58779675 docs(remediation): bank D-27 — role file certifies the inert queue guard as enforced
rev-974 found this while loading the canonical gate sources, i.e. because we switched
from restating to reading. Verified in roles.local/merge-gate.md: mandate 3 requires
verifying 'CI queue guard clear', mandate 4 requires enumerating 'the queue-guard
outcome' in every durable verdict, the merge path annotates it 'real', and the control
table at :290 certifies it ' enforced … genuinely aborts'.

The document is correct about the WIRING and wrong about the CONTROL: set -euo pipefail
with an unguarded exit does abort, but the guard cannot produce a non-zero exit for any
input (D-23). A mechanism correctly wired to a sensor that never fires, certified as
enforced.

Compounding: the verdict format REQUIRES the queue-guard outcome as evidence, so a
conforming verdict must include a meaningless field — the role file instructs the gate
to manufacture evidence, in the mandate that exists to stop bare conclusions.

Interim: record the field labelled ZERO-INFORMATION (inert, owner RM-03) rather than
omitting it — omission makes the verdict non-conforming; silent citation is worse.

Escalated: operator-owned file, coordinator's to fix. Recommend annotation not deletion
— the requirement is correct once RM-03 lands.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 22:55:28 -05:00
mos-dt-0andClaude Opus 5 cbbe3e1ce2 docs(remediation): gate definition now REFERENCES canonical roles; bank D-26
The delivery-gate definition was incomplete from setup — the merge-gate verdict step
was missing because the gates were restated from memory rather than referenced, and the
omission propagated into every worker brief since.

Then it recurred inside the correction: the correcting message was itself a restatement
and dropped five things, including a security precondition (an unminted gate seat fails
open to the owner's admin account — the #3084 breach mechanism) and a citation to a file
that does not exist.

D-26 is the definitive case because every condition favoured success: attention maximal,
actor knew the rule best, subject was the rule itself. A rule its own enforcer cannot
follow while enforcing it is not a discipline — it is a requirement for a mechanism.

MISSION.md and KICKSTART.md now reference fleet/roles.local/merge-gate.md and
fleet/roles/validator.md and state only the gate ORDER. Every reference resolves; a
dangling pointer is worse than a restatement.

Precondition independently verified: merge-gate token is least-privilege,
pull=True push=False admin=False — structurally cannot merge.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 22:53:13 -05:00
mos-dt-0andClaude Opus 5 9a7ab73952 docs(remediation): charter — Builds 1-2 justified by two independent impossibility proofs; RM-60 option analysis
Per Mos. The choke-point executor and PG spine are not a design preference — they are
forced. Twice during the mission's own first deliveries, work stopped against a security
property that cannot exist at the layer needing it: D-19 (audited party controls the
manifest certifying it — artifact integrity) and D-25 (audited party controls the code
entering the sandbox — execution integrity). Both reduce to self-verification by the
audited party is not verification, and both resolve only via an authority outside its
control.

Neither proof was sought; both arrived while shipping something else, from different
directions, at different layers. An architecture forced by two independent impossibility
proofs is stronger evidence than one argued for.

RM-60 records Mos's sharper option analysis: A (unprivileged userns) does NOT fix the
vulnerability — it grants a capability and leaves the ORDERING defect untouched, so B is
required regardless; A without B is kernel exposure bought for nothing. B is the correct
primitive, generalises to RM-59 and the choke-point executor, and may not need A at all.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 22:09:38 -05:00
mos-dt-0andClaude Opus 5 2b85afe4ea docs(remediation): bank D-25, accept RM02-REQ-10 revision, open RM-60
RM-02's per-commit replay needs isolation; the privileged CI step was correctly refused
because PR-controlled code executes before Bubblewrap establishes any boundary — the
untrusted party would obtain the capability meant to contain it. Ordering defect, not a
hardening problem.

D-25 is D-19 one layer down: audited party controls the manifest (artifact integrity)
became audited party controls the code entering the sandbox (execution integrity). Both
reduce to self-verification by the audited party is not verification, and both resolve
via an authority outside its control — twice now this mission has derived Builds 1-2
from a security impossibility rather than design preference.

Option C ruled independently by the orchestrator and rev-974 before either saw the
other. rev-974 added the condition I missed and it matters most: post-merge replay is
DETECTION, not PREVENTION, with a defined quarantine/revert response, and must never be
presented as equivalent to a pre-merge gate.

RM02-REQ-10 revision formally recorded and accepted under RM-02's own clause 4 —
original text, restatement, reason — discharging rev-974's review-readiness condition.
RM-60 opened for the external pre-execution trust boundary, cross-referenced with RM-59.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 22:05:50 -05:00
mos-dt-0andClaude Opus 5 eabe04bc5e docs(remediation): bank D-24 — mergeable:true cited as merge-readiness; D-23 corrected backward
Mos verified #1023 before relaying and corrected my framing. Verified independently:
review id-58 REQUEST_CHANGES at f6334080, the current head — the block is live, and its
findings are that #1023's own fix is defective (unknown still exits 0, payload-as-argv
hits ARG_MAX, tests do not assert exits).

mergeable:true is git-mergeability, not readiness. The charter's first principle
committed by the orchestrator inside an escalation about proxies. Fifth instance of mine.

The mechanism, named because it will recur: mergeable is not a lie, it is a true answer
to a different question. A false field would have been caught; a true-but-adjacent field
passes every sniff test — which is why the discipline must be mechanical, not attentive.

D-23 corrected backward per D-14-as-amended, original framing quoted.

RM-02: readiness cases must assert the decision-relevant property — latest review state,
CI terminal status on the exact head, required approvals — never a structural proxy.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 20:50:46 -05:00
mos-dt-0andClaude Opus 5 36018be8d1 docs(remediation): bank D-23 — the mandatory queue guard has never worked, for any input
RM-02's registered fixtures found this before the registry was built. Worse than the
banked unknown=>exit 0: ci-queue-wait.sh:266 pipes the payload into a classifier
starting 'python3 - <<PY', so python reads its PROGRAM from stdin and json.load never
sees the JSON. Proven empirically — success, failure, pending and malformed all
classify as unknown, and unknown exits 0.

The mandatory pre-push/pre-merge guard therefore returns PASS for every possible input,
including a genuinely failing CI. The six observed meaningless greens were not an edge
case; they are the only output it can produce.

PR #1023 is exactly this fix, open and parked, and its body diagnoses it precisely.
Two aggravating details from that body: pr-ci-wait.sh:38 documented the bug and remedy
and it was never backported to the mandatory sibling (D-14 propagation with a
security-adjacent blast radius); and the fix was opened without re-verification.

Escalated for Jason's #1023 disposition. RM-02 records required-vs-actual with
DEFECT (owner: RM-03); no RM-03 lane opened, guard not edited.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 20:44:34 -05:00
mos-dt-0andClaude Opus 5 8c496993e4 docs(remediation): bank D-22 — the registry would have verified the wrong artifact
The gate that actually runs is the installed copy at ~/.config/mosaic/tools/git/;
a repo-scoped registry would test packages/mosaic/framework/tools/git/. Byte-identical
today (sha256 19cda2f7009c536e both) but nothing asserts it.

A registry that verifies the wrong artifact is worse than none — it manufactures
confidence, and the divergence would be invisible from every signal we have: registry
green, CI green, deployed gate arbitrarily different.

D-1/P-ACTIVATION applied to the enforcement mechanism itself rather than to config.

RM-02 gains: for every registered gate with a deployed counterpart, assert
repo-source == deployed-copy with a must-fail control; where none exists, record that
explicitly.

Found by design review before implementation — the only finding tonight not found by
execution, which is the design-first gate on keystone tasks paying for itself.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 20:14:13 -05:00
mos-dt-0andClaude Opus 5 e85a088f85 docs(remediation): bank D-21 — a FAIL that means nothing is a green that means nothing, sign-flipped
ci-postgres reports FAIL under an overall-success pipeline on #2170 and #2175 while all
eight functional steps pass. Most likely a service-pod teardown artifact; the test
step's pg_isready fail-fast guard passed, so the database was available during the run.

Low severity, but the pattern matters: a red that is routinely present and routinely
correct to ignore trains operators and agents to discount reds, and the discounting
generalises. Six instances of a meaningless green are already banked; a meaningless
FAIL is the same erosion with the sign flipped.

Recorded rather than normalised — the first time it is waved through without a note is
when it becomes background noise.

RM-55: treat a non-terminal-success sub-step under an overall-success pipeline as a
reportable anomaly, and make the CI contract state which steps may fail without failing
the pipeline. An implicit allowance is indistinguishable from a bug.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 20:08:34 -05:00
mos-dt-0andClaude Opus 5 8a795df0ce docs(remediation): D-14 amended by D-20 — propagation is bidirectional
ci/woodpecker/pr/ci Pipeline was successful
Both the orchestrator and the coordinator read D-14 as forward propagation only: a
ruling reaches the documents stating the new rule. D-20 proved that insufficient —
when D-19 superseded part of D-18, the consequence went forward into the charter and
the delivery conditions but never backward into D-18, which kept asserting a withdrawn
claim until a reviewer disproved it by experiment.

A supersession must update BOTH the documents rendering the new rule AND the finding it
retires, with the retired wording quoted rather than deleted. Interim rule updated
accordingly.

Applying D-14's own rule to D-14, in the same commit that records the amendment.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 19:53:36 -05:00
mos-dt-0andClaude Opus 5 f5a0566198 docs(remediation): board — RM-01 MERGED (f58b3699); RM-02 keystone is next
ci/woodpecker/pr/ci Pipeline was canceled
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 19:50:36 -05:00
mos-dt-0andClaude Opus 5 1e7a0701fd docs(remediation): fix D-18 overclaim (D-20) — reviewer empirically disproved my own documentation
rev-974 blocked #1027 a second time, and the defect was in this file, not the code.

D-18's AC2 restatement omitted the accidental/independent scope D-19 made mandatory,
and D-18 asserted the tampered-manifest control turns integrity 'from a claim into a
property'. It does not and cannot — that sentence predated D-19 and was never revised
when D-19 landed. rev-974 disproved it by experiment: a same-UID consistent
manifest+marker rewrite passed preflight.

Two banked findings firing on the orchestrator at once: the integrity-claim corollary
(I wrote a claim in the voice of a property, in the document defining the rule against
it), and D-14 propagation — I carried D-19's consequence forward into the charter and
the delivery conditions but never back into the finding it superseded. Backwards
propagation is the same defect as forwards and I did not audit for it.

Corrected in place with the original wording quoted and the disproof recorded, not
silently rewritten.

RM-02 fifth clause: documentation asserting a security or integrity property is itself
a claim requiring a negative control observed red. Prose is not exempt from the
mission's evidentiary standard, and governing prose least of all.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 19:48:00 -05:00
mos-dt-0andClaude Opus 5 43f69bf167 docs(remediation): promote D-19 to charter; bind residual risk to RM-59 as a tracked edge
Per Mos, with his two additions.

Charter gains a fourth first-class principle: when a property cannot exist at the layer
that specified it, three honest moves are mandatory — implement what the layer can
guarantee; state the boundary in BOTH directions (what it does not defend AND what it
does, since either alone misleads); and record the real guarantee as a TRACKED
DEPENDENCY, not prose. A written-down gap is acceptable engineering; an implied-fixed
gap is the mission's core failure in a new costume.

The residual risk is now RM-59 (depends_on RM-12, RM-21, RM-25) — a real backlog task
owned by the choke-point executor and spine, which verify from outside the worktree's
authority. Mos's point: 'record where the guarantee comes from' only holds if the record
is a live dependency someone must close; a documented gap with no owner becomes a
permanent gap that reads as intentional.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 19:23:15 -05:00
mos-dt-0andClaude Opus 5 f9435c2a03 docs(remediation): bank D-19 — an integrity property that cannot exist at its specified layer
Implementing the D-18 manifest hit CWE-345: manifest and marker share one same-UID
writable tree, so that actor can regenerate both and pass. No local construction fixes
self-authentication without a key outside its authority. The seat escalated rather than
calling it tamper-resistant — the charter corollary working on its first real test.

Ruling: Option A, scope AC2 to accidental/independent/stale mutation, retain the design.
The undefendable boundary is not the weak link (same-UID write already owns the source,
the tests, preflight.mjs and .husky); AC2 exists for the D-5 staleness class, against
which the design works; and a real anchor arrives with the choke-point executor and PG
spine, which verify outside the worktree's authority.

Acceptable only with honest labelling: threat model verbatim in code and PR, the words
tamper-proof/tamper-evident/secure barred there, scope carried in AC2's restatement,
residual risk named as backlog, all controls kept RED-first.

Generalizable: when a property cannot exist at the layer it was specified, implement
what the layer can guarantee, state the boundary precisely, and record where the real
guarantee comes from. A known gap written down is acceptable; a gap implied fixed is not.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 19:20:05 -05:00
mos-dt-0andClaude Opus 5 3b191b6b34 docs(remediation): promote the three-mode taxonomy and the integrity-claim corollary to the charter
Per Mos. Two first-class principles alongside observe-the-property:

1. Pre-registration prevents RETROFITTING and nothing else. A pre-registered check set
   can be WRONG (D-8), INCOMPLETE (D-17), or INTERNALLY INCONSISTENT (D-18). It confers
   neither correctness nor coverage nor consistency. All three modes were found on this
   mission's own first delivery, by the machinery applied to its own work. RM-02's four
   clauses are the enforceable form.

2. Never ship an integrity claim dressed as a property. A verification artifact
   writable by the actor whose behaviour it certifies certifies the attack. It must sit
   inside its integrity envelope, publish atomically, and carry a tamper negative
   control observed red. If it cannot be made tamper-evident, say so and reconsider —
   an honest 'this cannot be verified' is always available and always preferable to
   laundering foreign content as certified.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 19:14:06 -05:00
mos-dt-0andClaude Opus 5 85bdbe3383 docs(remediation): bank D-18 — pre-registered criteria AC2 and AC4 were mutually unsatisfiable
Implementing D-17's fix surfaced a conflict between criteria, not within one. AC2
(reject symlinked generated state) cannot hold alongside AC4 (canonical build
succeeds): verified independently that apps/web sets output:'standalone' and the built
tree carries 42 legitimate pnpm symlinks under .next/standalone. Only building the
tree reveals it.

Completes the chain: a pre-registered check set can be WRONG (D-8), INCOMPLETE (D-17),
or INTERNALLY INCONSISTENT (D-18).

Ruling: build-certified symlink manifest — .next itself still rejected; descendants
rejected unless exactly certified. Stronger than blanket rejection because it catches
retargeting. AC2 restated and RECORDED with provenance rather than absorbed, since
silently resolving a conflict between pre-registered criteria destroys the point of
registering them.

Hardening: the manifest is generated state, so a manifest writable by whoever plants a
rogue symlink certifies the attack. Must be inside the integrity envelope, published
atomically, with negative controls observed red first including manifest-tampered.

RM-02 fourth clause: the registry must detect conflicts between criteria, and retain
original text plus restatement plus reason when a criterion changes meaning.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 19:11:52 -05:00
mos-dt-0andClaude Opus 5 ae4baf145d docs(remediation): bank D-17 — pre-registration confers neither correctness nor coverage
rev-974 blocked PR #1027: AC2 was pre-registered and explicitly required rejecting
symlinked generated state; the implementation accepts it (ln -s into .next, preflight
exits 0 instead of 43) while the acceptance suite ran 21/21 green throughout.

Confirmed independently: preflight.mjs:82-92 rejects symlinks on the SOURCE path,
:28 merely skips symlinked dirs, and the generated-state path :141-163 checks uid but
never isSymbolicLink(). The suite's only symlink cases cover the turbo binary and a
source file.

Sharpens D-8 rather than repeating it. D-8: pre-registration does not confer
CORRECTNESS. D-17: it does not confer COVERAGE — a suite can be green with every
criterion appearing satisfied while a criterion's actual requirement is untested.

RM-02 third clause: the registry must bind each criterion to the specific case that
exercises it and prove that case red before trusting its green. Mutation testing
pointed at the criterion-to-case mapping, not just the gate.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 19:07:58 -05:00
mos-dt-0andClaude Opus 5 4512312b9f docs(remediation): D-16 ownership — #1024 is Jason-pending; CI is the authoritative gate for #1027
Propagating Mos's ruling in the same commit that records it, per D-14's interim rule.

The hermeticity fix IS PR #1024, which sits in Jason's parked delivery stack, so its
disposition is his — marked SUPERSEDED-PENDING-JASON alongside #1023. D-16 strengthens
urgency without transferring ownership; we do not open a third lane on a parked PR.

Class sharpened: a pre-push gate an operator cannot run locally is a gate only CI
enforces, so pointing .husky/pre-push at it misrepresents where the gate lives.
Non-hermetic gates make every green host-dependent.

#1027 proceeds on CI-green; the local exit-97 is a host-specific guard abort and is
not a merge consideration.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 18:43:25 -05:00
mos-dt-0andClaude Opus 5 e233f196b5 docs(remediation): bank D-16 — local and CI test gates disagree by environment
Ran down Mos's flag. Both hypotheses were wrong: CI runs exactly 'pnpm test' (same
command, path IS exercised) and is green, while this host exits 97 on an
environment-dependent BASH_LINENO guard (#973) that aborts on bash 5.2.15 and not in
CI's container. PR #1027 touches zero files under packages/mosaic, so the guard is
genuinely pre-existing — f10-coder's report was accurate in every particular, and main
is equally affected here.

Not 'merges step around a red' but something worse in one respect: the local gate and
the CI gate disagree about what passing means. No agent on this host can get a green
pnpm test on any branch. A gate only CI can run cannot be a pre-push gate.

Second defect found while establishing this: in the main checkout the same package
fails differently (exit 1) because a test scans the working tree and picks up
apps/coordinator/venv third-party site-packages. A test whose verdict depends on
untracked files is not hermetic — same contamination source that broke format:check,
one foreign tree breaking two independent gates.

Coordinate with #1007/#1024 rather than opening a third lane.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 18:40:53 -05:00
mos-dt-0andClaude Opus 5 3477e933df docs(remediation): bank D-15 — token scope is not repository permission
f10-coder holds gitea-mosaicstack-f10-coder.token with write:repository scope and was
verified at mint by 'repo access returns 200'. It cannot push: collaborator lookup
404s and its own token reports push:false, pull:true.

Capability has three independent layers — token file (raw-API auth), tea login (tea
path), repository permission (actual write authority) — and satisfying two proves
nothing about the third. Scope bounds what a token may ATTEMPT; repository permission
decides what the user may DO.

The charter principle failing on the check meant to confirm capability: a 200 on a
READ was accepted as evidence of WRITE. written-unverified treated as verified, by
both provisioner and orchestrator, one layer above D-12.

RM-50's pre-dispatch check must assert effective permission for the intended operation
(permissions.push == true as that seat), not token existence or a read returning 200.
A capability check that cannot fail on a seat lacking write permission is itself an
inert gate.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 18:32:27 -05:00
mos-dt-0andClaude Opus 5 d0ad6e942b docs(remediation): propagate DECISION-2 to charter — second un-propagated ruling, found by applying D-14
Applied D-14's own interim rule immediately instead of waiting to be bitten again, and
it caught a second instance within minutes: MISSION.md's standing directives still
stated the DB hard-cutover with no mention of Mos's binding qualification that the
spine must not be a single-point hard-stop (degraded mode + rollback artifact
required). A seat reading the charter would have designed toward an availability
posture the coordinator had explicitly rejected, with the superseded 'no DB means the
fleet stops' recommendation nowhere contradicted.

Two un-propagated rulings out of two that touched charter text. Without a mechanism,
propagation failure is the default outcome, not an oversight — which is the argument
for D-14 being a requirement rather than a discipline.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 18:12:16 -05:00
mos-dt-0andClaude Opus 5 7f686aaf6d docs(remediation): bank D-14 decision-propagation requirement; record D-13 reconciliation
D-14: DECISION-1 was ruled and applied to TASKS.md while MISSION.md — the charter a
cold-starting seat reads first — kept the superseded wire-in target for hours, flagged
CONTESTED on the board but never corrected in the source of truth. A resuming seat
would have read the rejected target as authoritative. Caught by hand during an
unrelated edit; nothing would have caught it otherwise.

P-MISSION-001 turned on ourselves: a decision that lives in a ruling and a board note
but not in the authoritative record has been AGREED, not MADE. Requirement: rulings
must propagate mechanically — decisions as records, documents rendering rather than
restating, and a must-fail check where duplication is unavoidable. Interim rule until
the DB cutover: the same commit that records a ruling updates every document stating it.

D-13 updated with Mos's reconciliation: 5 of 6 mosaicstack-provisioned seats have no
tea login — systemic, not a one-off. Supersedes D-11(b): the token-file set is
necessary but NOT sufficient; capability is per-path.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 18:11:01 -05:00
mos-dt-0andClaude Opus 5 f13222b76b docs(remediation): charter reflects DECISION-1 corrected wire-in target and current status
The charter's build-1 cell still named mosaic_orchestrator.py::run_single_task after
DECISION-1 ruled against it. Leaving the charter contradicting the ruled decision would
mislead any future reader who starts there — corrected in place with the rationale and
provenance, rather than only in TASKS.md.

Also: status PLANNING -> EXECUTING; scout TODO discharged (file is in-tree) with a note
that its findings stand but its recommended wire-in point is superseded.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 18:07:16 -05:00
mos-dt-0andClaude Opus 5 d1e7ba19ca docs(remediation): promote observe-the-property principle to charter; bank D-13 dual credential registries
Charter gains a first-class principle per Mos: no write is done until the requested
PROPERTY is observed; a success exit code is not evidence. Success output is designed
to be believed — that is why the inert-gate class exists and why the P-WRAPPER
tri-state is not optional. Recorded with its provenance: the orchestrator committed
this exact error (D-12), and three of the session's twelve instances were its own.

D-13: diagnosing D-12 found two parallel credential registries that can disagree.
gitea-mosaicstack-mos-dt-0.token EXISTS, but tea has no mosaicstack login for that
identity — so raw-API paths work while tea-dependent wrapper paths silently degrade.
tea is not stale; the login does not exist. Capability declared authoritative by the
token-file set does not govern the tea path.

RM-04 must reconcile the registries (or assert agreement at startup, with a must-fail
control). RM-50's pre-dispatch check must verify capability for the path actually used.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 18:06:18 -05:00
mos-dt-0andClaude Opus 5 0ffdcf14bd docs(remediation): bank D-12 — pr-create silently dropped --draft; I trusted exit 0 over observed state
PR #1027 was created with -d because it carries partial unproven work. tea auth was
stale, the wrapper fell back to the raw API which cannot set draft, warned on stderr,
and exited 0. The PR sat open and mergeable for ~25 minutes, protected only by the
word DRAFT in its title and body. I had reported it to the coordinator as a draft.

Three failures: a fallback silently degrading a SAFETY flag (nuisance for --labels,
dangerous for --draft); a correct warning nobody consumed; and my own failure to
verify the flag took effect — I checked the PR existed, not that it had the property
I required. That is written-unverified treated as verified, by me, on exactly the
class of tool this mission exists to distrust.

Fixed via the WIP: title prefix; draft:True verified after.

RM-02 gains a must-fail control: a wrapper that cannot honour a safety-relevant
argument must exit non-zero. RM-24 gains this as its canonical tri-state example.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 18:03:29 -05:00
mos-dt-0andClaude Opus 5 be10bdc828 docs(remediation): board tick — 2 PRs merged, RM-01 on rotated seat, dispatch doctrine
Board now carries the pre-dispatch capability check (token-file existence), the
token/authorship coherence rule, and the accreted worker-brief doctrine, so a
compacted or fresh seat inherits them mechanically rather than by recall.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 18:01:55 -05:00
mos-dt-0andClaude Opus 5 2201c30284 docs(remediation): correct D-11(a) mechanism — token identity and commit authorship are separate
Per Mos. MOSAIC_GIT_IDENTITY resolves the TOKEN; commit author comes from git config
user.name/user.email, a separate setting that fell back to the generic value. The
export could never have fixed authorship — my worker brief instructed only the export,
so the seat did what it was told and the commits were still mis-attributed. The error
was in the brief before it was in the finding.

Requirement is COHERENCE: token and authorship must agree; either half alone is drift.
Belongs in seat setup, verified by an exit-asserting test that commits and asserts the
author — not in prose a seat can follow correctly and still end up wrong.

Capability check mechanized: capability IS token-file existence. Before dispatching
seat X to provider Y, test gitea-<Y>-<X>.token exists. The token-file set is the
authoritative capability registry.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 17:59:06 -05:00
mos-dt-0andClaude Opus 5 75dfe2fa75 docs(remediation): bank D-11 — identity drift + seat capability opacity at dispatch
RM-01's seat was briefed to export MOSAIC_GIT_IDENTITY; its commits are authored as
the generic mosaic-coder fallback, so git history cannot say which seat did the work.
P-WRAPPER-001 reproduced on our own delivery.

Separately, nothing at dispatch time revealed the seat lacked a credential for the
target provider — discovered only when it failed mid-task after ~$9 and 69% context.
get_gitea_token behaved correctly by refusing to borrow another slot's token; the
dispatch-time information simply did not exist.

RM-50 gains per-seat capability declaration + pre-dispatch check; RM-04 gains
identity-binding verified by an exit-asserting test rather than assumed from an
export in a brief.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 17:56:34 -05:00
mos-dt-0andClaude Opus 5 409bf23e6a docs(remediation): bank D-10 — the queue guard's failure modes are inverted
Same required gate, both directions wrong: fails OPEN on state=unknown (5 meaningless
greens this session, wrong branch too), and fails CLOSED on credential resolution,
hard-blocking a worker's completed work. The identical command succeeded from that
worker's own worktree in another shell, so the checkout was fine.

A gate that waves through unchecked work and blocks ready work has its failure modes
backwards. Availability failures must degrade to a loud, audited CANNOT_ASSERT;
correctness failures must block. Also the Pi-brick shape: a gate whose unavailability
prevents recovery from it.

RM-03 extended to a third requirement: distinguish CANNOT_ASSERT from
ASSERTED_NOT_READY, both registered with must-fail controls, neither exiting 0 silently.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 17:52:42 -05:00
mos-dt-0andClaude Opus 5 31c3191305 docs(remediation): rolling-branch resume pointer + D-9 interim comms rule
KICKSTART resume now points at origin/remediation/state for the live board, per Mos's
cadence ruling: every tick is pushed to the rolling branch immediately (durable
per-tick, no per-tick main PR); main carries periodic snapshots only. Reading the
board from main would silently yield a stale tick, so the step warns explicitly.

D-9 hardened: comms/v1 must use file/stdin transport, never argv interpolation.
Standing interim rule until then — agent-send -f for any body with special
characters, never -m. Mandatory in every worker brief alongside the D-8 clause.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 17:50:26 -05:00
mos-dt-0andClaude Opus 5 6a067174ed docs(remediation): bank D-9 — comms path shell-interprets message bodies
agent-send.sh -m with backticks executes them as command substitution: the recipient
got a mangled body plus a shell error, and the send still reported success. Same class
as the known pr-create.sh backtick bug — two tools in the comms path treating a
message body as shell input.

The failure mode is the mission's own pattern: silent corruption with a success
receipt.

Requirement on RM-40/RM-42: comms/v1 must carry payloads verbatim with no shell
interpretation at any hop, with a byte-identical round-trip test (backticks, command
substitution, quotes, newlines) registered under RM-02 including a must-fail control.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-31 17:48:17 -05:00
28 changed files with 1360 additions and 1886 deletions
-1
View File
@@ -8,7 +8,6 @@ coverage
.env.local
*.tsbuildinfo
.pnpm-store
__pycache__/
docs/reports/
# Step-CA dev password — real file is gitignored; commit only the .example
+1 -1
View File
@@ -1 +1 @@
pnpm preflight && pnpm typecheck && pnpm lint && pnpm format:check
pnpm typecheck && pnpm lint && pnpm format:check
+4 -4
View File
@@ -1,5 +1,5 @@
@mosaicstack:registry=https://git.mosaicstack.dev/api/packages/mosaicstack/npm/
# HOME resolves to /root in the ci-base image, preserving its warmed-store path.
# Non-root checkouts use their own HOME. Override without editing this file via
# NPM_CONFIG_STORE_DIR (pnpm's environment form of the store-dir setting).
store-dir=${HOME}/.local/share/pnpm/store
# Pin the pnpm store to the same path the ci-base image warms (Dockerfile.ci),
# so the pipeline `pnpm install --prefer-offline` consumes the baked store
# instead of repopulating a fresh one.
store-dir=/root/.local/share/pnpm/store
-14
View File
@@ -201,21 +201,8 @@ git clone [email protected]:mosaicstack/stack.git
cd stack
# Install dependencies. The local tier uses in-process PGlite; leave DATABASE_URL unset.
# The pnpm store defaults to $HOME/.local/share/pnpm/store. Override it without
# editing the checkout with NPM_CONFIG_STORE_DIR=$HOME/another-store if needed.
pnpm install
# Verify dependencies and generated state before running source-quality gates.
# Missing dependencies exit 42; stale/foreign apps/web/.next state exits 43.
# The web build certifies its exact standalone symlink manifest; added, removed,
# retargeted, or manifest-only-tampered generated links also exit 43. This detects
# accidental, independent, stale, and foreign-residue mutation—the class exposed by
# a five-month-stale .next that produced 19 phantom TS2307 errors.
# It does NOT defend against a same-UID actor that can rewrite both manifest and
# marker consistently (CWE-345). RM-59 tracks the required executor/spine-side
# trust anchor outside worktree authority.
pnpm preflight
# Optional local queue service only. This does not start PostgreSQL.
docker compose up -d valkey
@@ -243,7 +230,6 @@ Gateway start command until KBN-101-02 makes that state fail closed.
### Quality Gates
```bash
pnpm preflight # Checkout/dependency/generated-state validation
pnpm typecheck # TypeScript type checking (all packages)
pnpm lint # ESLint (all packages)
pnpm test # Vitest (all packages)
+1 -1
View File
@@ -3,7 +3,7 @@
"version": "0.0.2",
"private": true,
"scripts": {
"build": "node ../../scripts/build-web.mjs",
"build": "next build",
"dev": "next dev",
"lint": "eslint src",
"typecheck": "tsc --noEmit",
@@ -0,0 +1,40 @@
# RM-61 / PR #1033 — PRE-REGISTERED RE-REVIEW ACCEPTANCE CHECKS
**Subject head (exact):** `033b2ffb46674b2c0bcc5197273c109b461f62d9`
**Supersedes:** review 67 / comment 20403 @ `e7b29219` (NO GO). That verdict is VOID — the head moved.
**Registered by:** `mos-remediation` (orchestrator). **Reviewer:** `rev-974` (author ≠ reviewer).
**Registered BEFORE the reviewer read the diff.** Any head move after this file is committed voids the
re-review and requires re-registration.
## Scope discipline
The prior review passed AC1AC8 and still found a blocker, because the registered set tested whether the
signature DISCRIMINATES and never tested whether the evidence was BOUND TO ITS SUBJECT (Finding 3 /
coverage-failure-mode-2, D-17 class). This set therefore carries the binding property as a first-class
check, and **RR7 explicitly invites the reviewer to attack outside the set** — a registered set is
protection against retrofitting only, never a ceiling on scrutiny.
## Checks
| id | check | verdict form |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------- |
| **RR1** | The full 12-case contract harness passes at the exact head: `bash test-terminal-green-contract.sh` | ⇒0, and states 12 cases |
| **RR2** | ★CRUX — the ORIGINAL ATTACK IS DEAD. Take the real `#2188` record, mutate ONLY `commit` to an unrelated 40-hex value, verify against the true expected head | ⇒1, `exempted_steps == 0`, anomaly naming expected vs actual |
| **RR3** | Missing `--expect-commit` cannot be defaulted, inferred, or skipped | ⇒2 (not 0, not 1) |
| **RR4** | Malformed expected commit (short SHA, non-hex, empty) is rejected — no silent normalisation into a pass | ⇒2 |
| **RR5** | A record with the `commit` key ABSENT (not merely different) is rejected — fail-closed on missing, not just on mismatch | ⇒1, `exempted_steps == 0` |
| **RR6** | The genuine artifact still passes when correctly bound: real `#2188` + its true head | ⇒0, `exempted_steps == 1`, exactly one `WP-K8S-1000-CI-POSTGRES-TEARDOWN` |
| **RR7** | ★RED-FIRST, PROVED RETROACTIVELY. The four new cases must FAIL against the OLD verifier at `e7b29219` — otherwise they do not test what they claim (D-8 class). Run the new cases against the previous implementation | new cases ⇒≠0 under `e7b29219` |
| **RR8** | AC2 OF THE PRIOR SET DID NOT REGRESS: both REAL controls stay terminal red — `#2189` (`ci-postgres` exit 1) and `#2191` (exit 137, `test` exit 61) | both ⇒1, `exempted_steps == 0` |
| **RR9** | Still NO fetch / trigger / retry / re-roll / sleep / network of any kind in the verifier or harness. The coin flip must remain removed, not codified (D-21) | grep ⇒ no such call sites |
| **RR10** | The doc/baseline changes REQUIRE the current provider PR head to be passed — they must not merely mention it. Check `merge-gate.md`, `CI-CD-PIPELINES.md`, `woodpecker/README.md` state it as a requirement a gate operator cannot satisfy by omission | reviewer judgement, quote the lines |
| **RR11** | Exemption remains bound to #1000 and retires with it; signature conjunction unchanged and not widened by this fix | diff-scoped, ⇒ no widening |
| **RR12** | Case-sensitivity: an uppercase-hex record commit against a lowercase expected head must NOT silently pass by accident of comparison. State which way it resolves and whether it fails closed | state the observed behaviour |
## Reviewer instruction
Report the verdict **bound to `033b2ffb46674b2c0bcc5197273c109b461f62d9`** and state each check's
observed result, including counts read from `pipeline-status.sh -f json` (never default text — it omits
`clone`, D-33). If any check is unrunnable, **say so** — never substitute a passing variant. Attack
outside this set and report anything it finds; RR7 and RR12 exist because the last blocker was found
exactly that way.
+60
View File
@@ -0,0 +1,60 @@
# RM-61 / PR #1033 — PRE-REGISTERED ACCEPTANCE CHECKS: `exit_code` TYPE-STRICTNESS (D-40)
**Registered by:** `mos-remediation` (orchestrator) — **BEFORE the fix was pushed and before any
reviewer read a diff.** At registration time the fix existed only as an unpushed local commit
(`6e7a336d`) on coder-mos1's machine which **I have not read**. There is therefore no diff for these
checks to have been retrofitted to.
**Subject head:** TBD — binds to the NEW head once coder-mos1 pushes. The prior head
`033b2ffb46674b2c0bcc5197273c109b461f62d9` and its review 69 / pipeline #2193 go VOID on that push;
that cost was accepted deliberately by Mos's BLOCKING ruling on D-40.
**Ruling being enforced (Mos, 2026-08-01):** `exit_code` must be accepted ONLY as a real integer.
`false`, `0.0`, `"0"`, and `null` must all fail to satisfy the exemption. Wrong-ACCEPT is the
disqualifying direction; this hole sits inside the load-bearing discriminator.
## ⚠ Read this before writing the tests — RED-FIRST HERE IS NOT UNIFORM
Two of the four near-miss values **already block** at `033b2ffb`. Demanding "all four observed RED
first" would be demanding an impossible red for two of them, and the predictable response to an
impossible demand is a fudge — weakening something real to manufacture the red. So state it precisely:
| value | behaviour at `033b2ffb` (pre-fix) | what the new case is |
| ------- | --------------------------------- | ------------------------- |
| `false` | **WRONGLY EXEMPTS** (exit 0) | **genuine RED-FIRST** |
| `0.0` | **WRONGLY EXEMPTS** (exit 0) | **genuine RED-FIRST** |
| `"0"` | correctly blocks (exit 1) | **regression guard** only |
| `null` | correctly blocks (exit 1) | **regression guard** only |
Claiming red-first for `"0"` or `null` would be a false claim about your own evidence. Say which is
which. **Do not weaken anything to make a green case go red** (D-8).
## Checks
| id | check | verdict form |
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| **TS1** | ★RED-FIRST. `exit_code: false` on the real #2188 record is **observed wrongly exempting at `033b2ffb`** (exit 0, `exempted_steps 1`), then blocks after the fix | pre-fix ⇒0/exempt 1 · post-fix ⇒1/exempt 0 |
| **TS2** | ★RED-FIRST. Same for `exit_code: 0.0` | pre-fix ⇒0/exempt 1 · post-fix ⇒1/exempt 0 |
| **TS3** | REGRESSION GUARD. `exit_code: "0"` blocked before AND after — state honestly that it was already green | both ⇒1, `exempted_steps 0` |
| **TS4** | REGRESSION GUARD. `exit_code: null` blocked before AND after | both ⇒1, `exempted_steps 0` |
| **TS5** | ★NOT OVER-TIGHTENED. The genuine artifact — real #2188, real integer `exit_code: 0`, correctly bound head — still passes | ⇒0, `exempted_steps 1`, exactly one `WP-K8S-1000-CI-POSTGRES-TEARDOWN` |
| **TS6** | The strictness sits on the value the EXEMPTION rests on, not on a cosmetic sibling. Show the guarded comparison is the one feeding `exemption_applies` | reviewer quotes the line |
| **TS7** | `bool` is excluded EXPLICITLY, not incidentally. A bare `isinstance(x, int)` still admits `True`/`False` — verify the `not isinstance(x, bool)` clause exists | ⇒ clause present; `true` also blocks |
| **TS8** | Negative control unaffected: a genuine failed step with a real integer non-zero exit still blocks | ⇒1, `exempted_steps 0` |
| **TS9** | NO REGRESSION ON THE PRIOR ROUND'S BINDING WORK: mutated record commit ⇒1; `--expect-commit` omitted ⇒2; record `commit` absent ⇒1 | ⇒1 / ⇒2 / ⇒1 |
| **TS10** | Signature conjunction NOT widened elsewhere by this fix — `POD_NOT_FOUND` / name / type / state untouched | diff-scoped ⇒ no widening |
| **TS11** | Still no fetch / trigger / retry / re-roll / sleep / network | grep ⇒ no call sites |
| **TS12** | Full harness passes at the new head; **state the case count** (12 previously, expected 16 — confirm the actual number rather than the expected one) | ⇒0, count stated |
## Reviewer instruction
Verdict bound to the NEW head, evidence enumerated per check, CI counts from `pipeline-status.sh -f json`
(never default text — it omits `clone`, D-33). If a check is unrunnable, **say so**; never substitute a
passing variant.
**Attack outside this set and report what you find.** Both blockers on this PR so far — the missing
commit binding, and this type confusion — were found outside the registered set, by mutating a field
nobody had registered a check for. That is now the expectation, not a bonus.
**Nobody dispatching this review may state a conclusion on an open check here (D-39).** If you are sent
an observation, it is an observation; the ruling is yours.
+16
View File
@@ -23,3 +23,19 @@ Merged PR #868 (`b79336a8`) shipped a file that FAILS `pnpm format:check` ⇒ th
### **D-4 / P-LIFECYCLE + hygiene — a dispatched agent silently IGNORED an in-message context reset.**
planner-sol was at 64.3%/372k; the brief asked it to reset first; it began work on dirty context anyway. Only an out-of-band `/new` driven by the orchestrator guaranteed clean state. Confirms the postmortem thesis: **instructions are not enforcement.** Reset must be a mechanical pre-dispatch step, not a request.
<!-- board-roll: 2 entries rolled from BOARD.md -->
### **D-7 / P-FLEET-001 — stale-GC-on-disk: shared 30G /tmp hit 100% ENOSPC, degrading two seats.**
~5.2G was session scratch dead 8-9 days (this session's own footprint: 88K). Same missing capability as orphaned-tmux-session GC, applied to disk — not a quota or discipline problem. Resolved manually by Mos (lead coordinator) after independent verification; `/tmp` now 79%. **The gap IS the finding:** the authority to reap exists, the deterministic reaper does not. Folded into RM-50 with explicit requirements (mechanical liveness, age threshold, dry-run, audit event per reap — never a heuristic sweep). Refusing to unilaterally delete another session's scratch was correct doctrine; the fix is a reaper, not braver agents.
### **D-6 / P-QUEUE-001 — the mandated queue guard returned PASS on an UNKNOWN state, live, today.**
Running the required `ci-queue-wait.sh --purpose push` before pushing produced `state=unknown ... exit 0` — the exact defect at `ci-queue-wait.sh:282-288` that PR #1023 is parked on. It also evaluated `branch=main` rather than the branch being pushed. The mission's own required pre-push gate passed me on an indeterminate result. Third independent live instance of the class.
<!-- board-roll: 1 entry rolled from BOARD.md -->
### **D-8 / P-CONFORMANCE-001 — a PRE-REGISTERED acceptance check that was not runnable as written.**
PR #1025 AC2's fixture `mkdir -p apps/*/venv/lib` creates a literal `apps/*/venv/lib` dir when the glob is unmatched — it did not test what it claimed. rev-974 ran it exactly as written, caught it, re-ran the intended assertion at an explicit path, and **disclosed** rather than silently substituting a working fixture and reporting PASS. **Pre-registration protects a check from being retrofitted to the implementation; it does not make the check correct.** An unverified gate appeared inside the mechanism built to catch unverified gates. Hard requirement on RM-02: the registry must self-verify that every registered case runs AND can fail — presence is not evidence.
+70 -64
View File
@@ -1,28 +1,55 @@
# mos-remediation — LIVE BOARD (keep < 8 KB)
**Phase:** EXECUTING — P0 open. RM-01 MERGED; RM-02 (keystone gate registry) is next.
**Updated:** 2026-07-31 (mos-remediation orchestrator; seat active on `mosaic-fleet`).
**Phase:** EXECUTING — RM-03 at owner-merge; RM-02 blocked on RM-61; RM-61 **rebuilding on D-40 BLOCKING**.
**Updated:** 2026-08-01 — seam crossed; successor seat resumed, attested from the files, and is driving.
⚠ That was a **MANUAL pane respawn** (prior seat ~803k tokens): it validates the checkpoint+rehydration
**design**, NOT a lifecycle **mechanism** — P-LIFECYCLE rotation does not exist yet (**D-41 / RM-62**).
## Head
- Mission charter + 15 decisions + 4-build plan: PERSISTED (`docs/remediation/MISSION.md`).
- HOLD lifted for this workstream (Jason 2026-07-31). Nothing implemented yet — planning first.
- Orchestrator seat `mos-remediation` is LIVE and owns the mission. Residency attestation: PASS.
- **TASK-0 DONE** — checkout repaired, all three gates green HONESTLY (no `--no-verify`), branch pushed.
- **TASK-1 DONE** — both planners delivered independently on clean context; reconciled into `TASKS.md`
(58 tasks across P0P5, 7 convergences, 7 adjudicated disagreements, 3 escalated decisions).
- **NEXT ACTION IS NOT MINE:** DECISION-1/2/3 (`TASKS.md` §5) must be ruled before P0 dispatch.
RM-01 is dispatchable immediately regardless — it depends on nothing and blocks everything.
- Charter + 15 decisions + 4-build plan: `MISSION.md`. Backlog + all findings: `TASKS.md`.
- Planning DONE (58 tasks, P0P5). **DECISION-1/2/3 all RULED by Mos 2026-07-31** (`TASKS.md` §5) —
nothing is waiting on a decision. D-2's availability _target_ is Jason-pending and non-blocking.
- **Executing, not planning.** RM-01 is MERGED; three lanes are live (see In-flight).
- Orchestrator seat `mos-remediation` LIVE, owns the mission, resumed across the rotation seam
2026-08-01 and re-attested to Mos from the files. Residency attestation: PASS.
## In-flight
| Task | Owner | State |
| ----------------------------------- | --------------- | ------------------------------------------------------------------------- |
| RM-01 reproducible checkout | — | **MERGED** `f58b3699` (PR #1027) — rev-974 APPROVE + CI #2172 8/8 green |
| RM-02 gate registry ★keystone | unassigned | **READY** — depends only on RM-01; not held by RM-03 |
| RM-03 queue guard (3 defects) | — | HOLD — #1023 SUPERSEDED-PENDING-JASON |
| RM-59 close D-19 residual risk | — | BLOCKED by RM-12/RM-21/RM-25 (spine + executor) — tracked edge, not prose |
| `remediation/state` snapshot → main | mos-remediation | opening at this mission seam |
| Task | Owner | State |
| ------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| RM-01 checkout | — | **MERGED** `f58b3699` (#1027) |
| RM-03 queue guard | **Jason** | **GO** @ `78ec47cd` (cmt 20392) — HELD FOR OWNER MERGE. Head unmoved; GO commit-bound, VOID if it moves — **do not push #1032** |
| RM-02 registry ★key | — | **BLOCKED on RM-61.** Complete @ `f9746b23`, head FROZEN, 2 live REQUEST_CHANGES. `ci-postgres` FAIL on #2187 **and** #2188 |
| RM-61 CI exemption | coder-mos1 | **D-40 RULED BLOCKING.** `033b2ffb`/review 69/CI #2193 VOID on push. TS1TS12 pre-registered @ `86cd1a0f`. Awaiting new head |
| RM-59 / RM-60 | Jason (infra) | tracked deps; RM-60 option **B** |
| #1023 queue attempt | Jason | SUPERSEDED-PENDING-JASON — live REQUEST_CHANGES, do **not** merge |
### For the incoming orchestrator — read this before acting
1. **Nothing is waiting on you that is urgent.** RM-03 waits on Jason; RM-02 waits on RM-61; RM-61 is
rebuilding on the D-40 ruling. Read the record before touching any lane.
2. **`docs/remediation/TASKS.md` is authoritative**, not the newest voice in a chat. It holds 41 findings
(D-1…D-6 in `BOARD-LEDGER.md`, D-7…D-41 in TASKS.md), every ruling with its rationale, and the
requirements each finding placed on RM-02/RM-34/RM-50/RM-55.
3. **`MISSION.md` carries five first-class principles**, all earned by live failures — observe the
property not the proxy · pre-registration prevents retrofitting and nothing else · never ship an
integrity claim dressed as a property · when a property cannot exist at its layer, bound it and track
the real guarantee · query for refutation, never for confirmation · redundant observation on
evidence-bearing steps.
4. **Seat identity:** `export MOSAIC_GIT_IDENTITY=<seat>` is stripped by a context reset (**D-34**) —
every dispatch/rehydration brief must re-export it, or the seat cannot use its credentials.
5. **Scan CI from `-f json`, never default text** — text mode omits `clone` (**D-33**). State counts.
6. **The queue guard is zero-information until RM-03 merges** (**D-23**) — never cite its green.
7. **The bounded CI re-roll used on RM-02 was a one-time stopgap, NOT policy.** A per-PR free re-roll is
D-21 normalisation. Do not repeat it; RM-61 is the fix.
## Delivery gates — REFERENCE, do not restate
Canonical: `~/.config/mosaic/fleet/roles.local/merge-gate.md` (verdict authority) +
`~/.config/mosaic/fleet/roles/validator.md`. Order and the freeze/zero-information rules: `MISSION.md`
and `KICKSTART.md`. **Read them there** — restating the gate from memory is how the merge-gate step
went missing from mission setup twice, once inside the correction for it (**D-26**).
## Fleet seats
@@ -34,60 +61,39 @@
## Gate status
- Delivery gates active: author≠reviewer, diff-blind pre-registered checks, CI-green, merged-PR completion.
- Freeze: LIFTED for this workstream only.
- Git identity: `MOSAIC_GIT_IDENTITY=mos-dt-0` INTERIM. Mos ruled gate-16 HOLDS (author≠reviewer is what
- Git identity: orchestrator runs `MOSAIC_GIT_IDENTITY=mos-dt-0` INTERIM. Mos ruled gate-16 HOLDS (author≠reviewer is what
gate-16 protects; rev-974 reviews, mos-dt-0 never self-reviews). Dedicated identity TRACKED, Mos provisions.
- Capability check (D-11b): before dispatching seat X to provider Y, verify
`~/.config/mosaic/secrets/gitea-tokens/gitea-<Y>-<X>.token` exists. Token-file set = authoritative
capability registry. Mos owns provisioning; escalate missing pairs to him.
- Capability is **per-path** (D-11b → **superseded in part by D-13/D-15**): a token file is **necessary,
not sufficient**. Three layers — token file (raw-API), `tea` login (tea paths), **repository permission**
(writes). Before dispatch, assert `permissions.push == true` **as that seat**, not token existence and
not a 200 on a read. Mos owns provisioning; escalate missing pairs.
- Seat identity (D-11a): token identity AND `git config user.name`/`user.email` must BOTH be set and
agree. Exporting `MOSAIC_GIT_IDENTITY` alone does NOT fix commit authorship.
- Standing worker-brief doctrine (accreted, mandatory in every brief): don't weaken a RED test to make
it pass; if a check is unrunnable as written SAY SO, never silently substitute; `agent-send -f` never
`-m`; heavy artifacts off shared `/tmp`.
- **LIVE HAZARD (D-37) — one shared `.git/config` re-identifies EVERY worktree at once.** Every seat,
including `rev-974`'s review worktree, currently authors as **`coder-mos1`**; `MOSAIC_GIT_IDENTITY`
does **not** override it. **STANDING ORDER: commit with explicit
`git -c user.name=<seat> -c user.email=<seat>@…`, and NOBODY rewrites the shared config mid-flight.**
Real fix authorised, Mos owns it, sequenced at a quiet seam. **#1024 implicated.** Detail: D-37.
- Standing worker-brief doctrine (mandatory in EVERY brief): re-export `MOSAIC_GIT_IDENTITY` (**D-34**);
commit early/WIP (**D-31**); don't weaken a RED test to pass; if a check is unrunnable SAY SO, never
substitute; `agent-send -f` never `-m`; artifacts off shared `/tmp`; scan CI from `-f json` (**D-33**);
**relay observations into an open review, NEVER your own conclusion on an open check (D-39)**; the
**author never adjudicates their own PR's blocker status** — surface evidence, prepare the fix, hold.
- Remote control: native `/remote-control` NOT wired in this runtime. Path is **Mos-relay**
(Jason ↔ mos-claude via Discord ↔ mos-remediation via agent-send). Not a blocker.
## Sequencing (from MISSION.md)
## Sequencing — see [`MISSION.md`](./MISSION.md)
1. Spine + choke-point service (MACP wiring @ mosaic_orchestrator.py::run_single_task) + PG/Redis
**CONTESTED — see DECISION-1.** Both planners independently reject this wire-in point: that
controller is `"enabled": false` and references a dispatcher that does not exist here. Charter text
left UNCHANGED pending Mos/Jason ruling; do not treat it as settled.
2. Rotation daemon (finish Mission Control Plane, reuse packages/coord)
3. Comms service (envelope→service→PG/Redis→adapters)
4. Hygiene + conformance harness
Cross-cutting retirements: flat-file tracking, 3 MACP islands, silent MOSAIC BYPASS.
Builds 1-5, the cross-cutting retirements, and DECISION-1's corrected wire-in target are stated once in
the charter and `TASKS.md` §5. **Not repeated here** the previous copy of DECISION-1's status on this
board is one of the six stale restatements below.
## Dogfood evidence — live failure classes, not hypotheticals
## Decisions log — full record in [`TASKS.md`](./TASKS.md)
> Newest first. Oldest entries roll to `BOARD-LEDGER.md` via `board-roll.sh` when this file
> exceeds its 8 KB cap. Keystone detail is duplicated in `TASKS.md` §1a, so rolling loses nothing.
<!-- BOARD-ROLL:START -->
### **D-8 / P-CONFORMANCE-001 — a PRE-REGISTERED acceptance check that was not runnable as written.**
PR #1025 AC2's fixture `mkdir -p apps/*/venv/lib` creates a literal `apps/*/venv/lib` dir when the glob is unmatched — it did not test what it claimed. rev-974 ran it exactly as written, caught it, re-ran the intended assertion at an explicit path, and **disclosed** rather than silently substituting a working fixture and reporting PASS. **Pre-registration protects a check from being retrofitted to the implementation; it does not make the check correct.** An unverified gate appeared inside the mechanism built to catch unverified gates. Hard requirement on RM-02: the registry must self-verify that every registered case runs AND can fail — presence is not evidence.
### **D-7 / P-FLEET-001 — stale-GC-on-disk: shared 30G /tmp hit 100% ENOSPC, degrading two seats.**
~5.2G was session scratch dead 8-9 days (this session's own footprint: 88K). Same missing capability as orphaned-tmux-session GC, applied to disk — not a quota or discipline problem. Resolved manually by Mos (lead coordinator) after independent verification; `/tmp` now 79%. **The gap IS the finding:** the authority to reap exists, the deterministic reaper does not. Folded into RM-50 with explicit requirements (mechanical liveness, age threshold, dry-run, audit event per reap — never a heuristic sweep). Refusing to unilaterally delete another session's scratch was correct doctrine; the fix is a reaper, not braver agents.
### **D-6 / P-QUEUE-001 — the mandated queue guard returned PASS on an UNKNOWN state, live, today.**
Running the required `ci-queue-wait.sh --purpose push` before pushing produced `state=unknown ... exit 0` — the exact defect at `ci-queue-wait.sh:282-288` that PR #1023 is parked on. It also evaluated `branch=main` rather than the branch being pushed. The mission's own required pre-push gate passed me on an indeterminate result. Third independent live instance of the class.
<!-- BOARD-ROLL:END -->
## Decisions log
- 2026-07-31 — Mission set up by Mos post-postmortem (15/15 decided). Dogfood posture active.
- 2026-07-31 — Mos: stale `.mosaic/orchestrator/mission.json` is RESIDUE of the disabled Python
orchestrator rail that this plan RETIRES. Do NOT invest in it; do NOT build on that rail. The 0/0
milestone banner is cosmetic. (Supersedes any plan to repair it.)
- 2026-07-31 — Mos: planners must be dispatched with GUARANTEED clean context, not requested-clean.
Prior default-socket planner sessions predate this mission; dirty context is the indicted hygiene.
- 2026-07-31 — mos-remediation: worker briefs forbid all git ops and restrict each worker to a single
named output file, so two planners can share one checkout without a branch race (M2-era incident doctrine).
All 41 findings (D-1…D-6 in `BOARD-LEDGER.md`, D-7…D-41 in `TASKS.md`) and every ruling with its
rationale live there. **Not duplicated here** — a second copy is a second thing to go stale, which this
board had done three times in one night (gate list, capability registry, DECISION-1 status), and three
more times by the next rotation seam (RM-61 "building", "nothing implemented yet", DECISION-1/2/3
"must be ruled"). The rulings a fresh seat needs are items 47 above; they are **not** repeated here,
because that repetition is what went stale.
+12 -2
View File
@@ -25,8 +25,18 @@ mechanically until Build 3 (rotation) makes it automatic.
## Standing invariants (never violate)
- **North star:** deterministic-right-answer → code/gate; LLM only for judgment.
- **Delivery gates:** author≠reviewer; PRE-REGISTERED diff-blind checks committed before reading the diff;
CI terminal-green; completion = merged PR + closed issue. rev-974 = the mosaicstack reviewer identity.
- **Delivery gates — REFERENCE the canonical files, never restate them:**
`~/.config/mosaic/fleet/roles.local/merge-gate.md` (verdict authority) and
`~/.config/mosaic/fleet/roles/validator.md` (validator role). Order:
independent review (author ≠ reviewer, `rev-974`; pre-registered diff-blind checks committed before the
diff is read) → remediation → **CI terminal-green at the exact head by full step scan**
**merge-gate verdict `GO`/`NO-GO`/`HOLD`**, commit-bound and **void the instant the head moves**, posted
durably with enumerated evidence under its own minted identity → **coordinator head-pinned merge**.
The queue guard runs but is **zero-information until RM-03 lands** (D-23) and must not be cited as evidence.
**After a `GO`, freeze pushes** — even a doc tweak voids the verdict. The coordinator assigns the gate seat.
- **Query for refutation, never for confirmation.** A subordinate asked to confirm a hypothesis will
agree — the bias is in the question, not the answerer, and agent seats are agreeable by construction.
State the hypothesis as yours, ask for the evidence that KILLS it, and reproduce when it matters.
- **Dogfooding:** every fix validated against its live seed case (MISSION.md lists them).
- **Tracking → DB** (hard cutover); do NOT re-invest in flat-file tracking. jarvis-brain PDA is off-limits.
- **Git identity:** export `MOSAIC_GIT_IDENTITY=<your-seat>` so wrappers author correctly and survive respawn.
+98 -2
View File
@@ -91,6 +91,54 @@ gate/program; the LLM handles only genuine judgment.
> seat in the loop. Residual risk bound to **RM-59** (`depends_on: RM-12, RM-21, RM-25`), where the
> choke-point executor and spine verify from _outside_ the worktree's authority.
### First-class principle — query for refutation, never for confirmation
> **A subordinate asked to confirm a hypothesis will agree. Ask it to refute, with evidence.**
>
> The bias is induced by the **query**, not by the answerer's diligence. _"The DB flaked — please
> confirm"_ and _"confirm or refute this, with the log line that proves it"_ are different instruments,
> and they return different answers to the same question. The first harvests agreement; only the second
> can return **"you are wrong, and here is why."**
>
> This matters most with agent subordinates, which are **agreeable by construction**: fluent, eager to
> be useful, and structurally disinclined to tell the dispatcher their premise is false. A confirmation
> query aimed at one is close to a guaranteed yes — so the discipline cannot rest on the answerer being
> rigorous. **It has to be built into how the question is asked.**
>
> Promoted to the charter by Mos (2026-08-01). Origin: the orchestrator hypothesised that a coincident
> `ci-postgres` failure caused a CI test failure and asked the implementing seat to **confirm or refute**
> it. The seat **refuted it** with the log (`ci-postgres:5432 - accepting connections`, migrations
> completed) and identified the real cause. Reproduction on an identical head then settled it. Had the
> query been phrased for confirmation, the agreement would have been returned, **D-21 would have been
> re-classified on a false premise**, and a banked finding would have been silently corrupted.
>
> **Operationally:** state your hypothesis explicitly, mark it as yours, ask for _evidence that kills
> it_, and say what evidence would change your mind. A hypothesis you cannot describe how to falsify is
> not yet a hypothesis. Where the answer is consequential, **reproduce** rather than accept — two
> independent runs beat one confident report.
### First-class principle — redundant observation on evidence-bearing steps
> **Two observers of the same evidence, disagreeing, catch what neither catches alone.** Apply redundancy
> not only to judgement calls but to **evidence gathering itself** — the step everyone assumes is
> mechanical and therefore skips.
>
> Promoted by Mos (2026-08-01) from **D-33**. A seat scanned a pipeline with `-f json` and reported 9
> steps; the orchestrator scanned the same pipeline in the wrapper's default text mode and reported 8.
> **The default output omits `clone`.** Every "full step scan" that night had been 8-of-9 and was stated
> as complete in good faith. No verdict changed — but the _method_ was wrong, invisibly, and **only the
> disagreement between two counts surfaced it.**
>
> The reason it survived: **a summary that resembles an enumeration is more dangerous than one that
> obviously summarises.** A labelled list of named steps with states _looks_ like the artifact, so nobody
> checks it against the record. Compare D-24 — `mergeable` was a _true answer to a different question_;
> this was a _true answer to a smaller one_. Neither is a lie; both pass every sniff test.
>
> **Operationally:** where a step _produces evidence a decision rests on_, have it produced twice by
> different means, and treat **any divergence as a finding rather than as noise to reconcile**. Prefer the
> machine-readable record over the human-readable rendering — _read the artifact, not the summary_ — and
> state the counts observed so a divergence is detectable at all.
## Decision record (authoritative, immutable)
- **15/15 proposals decided: 13 accept, 2 modify (P-AUTHORITY-001, P-INBOX-001), 0 reject.**
@@ -109,6 +157,31 @@ gate/program; the LLM handles only genuine judgment.
| **4. Comms service** | AUTHORITY, INBOX (+ versioning roadmap) | Envelope (comms/v1) → sole-path service → PG/Redis → pluggable adapters (tmux→Matrix/Discord/Slack/Telegram). Version the protocol, not participants. |
| **+ Hygiene & proof** | FLEET, WORKFLOW, CONFORMANCE | One roster-owned socket/host + stale GC; allowlist auto-sync; the conformance harness that fault-injects the failure classes and proves builds 14 hold. |
## Why Builds 12 are necessary — two independent impossibility proofs
**The choke-point executor and PG spine are not a design preference. They are forced.** Twice during
the mission's own first deliveries, work stopped against a security property that **cannot exist** at
the layer that needed it — and both times the only resolution was an authority _outside_ the audited
party's control, which is precisely what Builds 12 provide.
| | the audited party controls… | so what fails | found as |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------- | --------------- | -------- |
| **Artifact integrity** | the manifest that certifies its own generated tree (same-UID write ⇒ regenerate manifest _and_ marker consistently, CWE-345) | tamper-evidence | **D-19** |
| **Execution integrity** | the code that enters the sandbox (PR-controlled config executes _before_ the boundary exists) | isolation | **D-25** |
Both reduce to one sentence:
> **Self-verification by the audited party is not verification.**
And to one consequence: **the anchor must live outside the audited party's authority.** A local check
cannot defend against an actor who can rewrite the check; a repo cannot grant a capability to
PR-controlled config and simultaneously prevent that config from using it.
**An architecture forced by two independent impossibility proofs is stronger evidence than one argued
for.** Neither proof was sought — both arrived while trying to ship something else, from different
directions (a symlink manifest; a CI sandbox), at different layers. RM-59 and RM-60 are the two tracked
dependencies this creates, and they are the same dependency in different clothes.
## The finding that sets the cost
**Built-but-unwired disease.** `@mosaicstack/macp` is stranded (nothing calls it); `packages/coord` primitives
@@ -161,6 +234,29 @@ orphaned context loader, a fail-open bypass. **Work = wire + consolidate + retir
- **Project orchestrator** `mos-remediation` (this seat) owns the mission; coordinates under Mos (lead).
- **Adversarial task decomposition:** `planner-opus` (robustness) + `planner-sol` (pragmatic) each decompose
the plan independently; orchestrator reconciles into `TASKS.md`/DB tasks. Oppositional by design.
- **Delivery gates (non-negotiable):** author≠reviewer, PRE-REGISTERED diff-blind acceptance checks committed
before reading the diff, CI terminal-green, completion = merged PR + closed issue. rev-974 = mosaicstack reviewer.
- **Delivery gates — REFERENCE, do not restate.** The authoritative definitions live at
[`~/.config/mosaic/fleet/roles.local/merge-gate.md`](file:///home/hermes/.config/mosaic/fleet/roles.local/merge-gate.md)
(verdict authority) and
[`~/.config/mosaic/fleet/roles/validator.md`](file:///home/hermes/.config/mosaic/fleet/roles/validator.md)
(validator/certificate role). **Read them; do not paraphrase them.** Restating an authoritative source
is lossy every time — see D-26, where a subset restated from memory dropped a security precondition.
**Gate order** (the sequence only; the definitions are in the files above):
1. Independent review, **author ≠ reviewer** (`rev-974` on mosaicstack), with PRE-REGISTERED diff-blind
acceptance checks committed before the diff is read
2. Remediation of findings
3. **CI terminal-green** at the exact full-40 head, by **full step scan**
4. **Merge-gate verdict — `GO` / `NO-GO` / `HOLD`** (class `merge-gate`; "Ultron" is an _instance name_,
display data, never an authority source). **Bound to a commit and VOID the instant the head moves.**
`HOLD` persists until replaced; a `NO-GO` answered by an empty commit must be re-issued as `NO-GO`.
Posted durably on the PR under the gate's own minted identity, **enumerating** its evidence — a bare
"GO — gates verified" is non-conforming.
5. **Coordinator merge**, head-pinned. The gate never merges; it holds `push=False` by design.
**The CI queue guard runs but is ZERO-INFORMATION until RM-03 lands** (D-23: it returns pass for every
possible input). It must not be cited as evidence by any gate, including the coordinator's own merge path.
**Assignment:** the coordinator assigns the merge-gate seat; the orchestrator does not. The orchestrator
owns getting a PR _gate-ready_.
- **Compaction survival:** see `KICKSTART.md` in this dir — the resume procedure. Persist typed state, not transcript.
+1047 -12
View File
File diff suppressed because it is too large Load Diff
@@ -1,118 +0,0 @@
# RM-61 — CI contract exemption for #1000 teardown artifact
**Tracking:** RM-61 / issue #1000
**Branch:** `fix/rm-61-ci-contract-exemption`
**Owner:** `coder-mos1`
## Objective
Determine, by red-first provider controls, whether the `ci-postgres` pod-not-found teardown signature discriminates from a real PostgreSQL failure. Only if it discriminates may a named, bounded CI-contract exemption be implemented. The exemption must retire when #1000 is fixed; fixing #1000 is the closure path.
## Pre-registered kill criterion
If an injected real `ci-postgres` failure also yields `pods "wp-svc-<ULID>-ci-postgres" not found` as the service's provider-visible failure, the signature does not discriminate. Option B is unsafe; stop exemption implementation and fall to Option A (#1000).
## Plan
1. Capture full `-f json` records for the 11 supplied observations and state counts.
2. Run one startup-failure control using the real pgvector/PostgreSQL image with an invalid `initdb` argument.
3. Run one post-readiness crash control using real PostgreSQL, `pg_isready`, and a deliberate postmaster kill while a DB-dependent probe is active.
4. Compare the raw `ci-postgres` service record independently of failures in dependent steps.
5. Investigate runner/time/head clustering only as a hypothesis; never encode incidental correlates or retries into policy.
6. If and only if the controls discriminate, implement and test the exact exemption, document its two-way boundary, and track retirement at #1000.
## Budget
No explicit token cap supplied. Working estimate: 20K30K tokens. Limit provider controls to the two pre-registered runs; no retries or re-roll policy.
## Initial evidence
Historical JSON saved locally under `.evidence/rm-61/` (not for commit). Supplied pipelines: 11 total. Child-step counts: five pipelines with 9 children and six with 10 children. Seven contain the `ci-postgres` pod-not-found failure (#2170, #2175, #2180, #2181, #2182, #2187, #2188); four do not (#2158, #2167, #2184, #2186). Every observed workflow reports `agent_id=44`, so the available JSON does not separate clean and artifact runs by runner. This refutes runner identity as a discriminator in the sampled record.
## Progress
- [x] Requirements and kill criterion recorded before control implementation.
- [x] Historical full-JSON records captured.
- [x] Startup-failure control observed terminal.
- [x] Post-readiness crash control observed terminal.
- [x] Discrimination verdict recorded: Option B may proceed.
- [x] Conditional exemption implementation.
## Tests / evidence
### Control 1 — real startup failure
- Commit: `3931b0e29eb834914f7b17e4db7e221481d436fa`
- Pipeline: #2189, exact commit match.
- Full JSON child scan: 9 total — 7 success, 2 failure, 0 skipped/pending/running.
- `ci-postgres`: `state=failure`, `exit_code=1`, `error=null`, with a five-second execution window.
- `test`: `state=failure`, `exit_code=1` after the readiness budget expired.
- Pipeline/workflow: terminal `failure`.
This control is red and its service record differs from #1000 (`exit_code=0` plus pod-not-found). It proves the startup-failure direction only. It does not settle the dangerous post-readiness crash/garbage-collection path.
### Control 2 — real post-readiness crash
- Commit: `25ac59715a94dd1b52ef42577472eb44ecc4b446`
- Pipeline: #2191, exact commit match.
- Full JSON child scan: 9 total — 7 success, 2 failure, 0 skipped/pending/running.
- Service log proves PostgreSQL reached `database system is ready to accept connections`, the test created the arm table, and the service then killed postmaster PID 7.
- Test log proves a successful `SELECT 1` followed by `Connection refused`; it exited the pre-registered control code 61.
- `ci-postgres`: `state=failure`, `exit_code=137`, `error=null`, with a 203-second execution window.
- `test`: `state=failure`, `exit_code=61`.
- Pipeline/workflow: terminal `failure`.
This is the dangerous post-readiness crash path. Its service record is not pod-not-found and therefore differs from #1000 independently of the dependent test failure.
### Discrimination verdict
Both real failures are provider-visible as process exits (`exit_code=1` startup; `exit_code=137` crash) with no pod-not-found error. The seven observed #1000 artifacts are provider reconciliation misses (`exit_code=0` plus the exact pod-not-found error). The declared kill criterion did not fire, so Option B may proceed with a matcher requiring the full conjunction. This evidence does **not** prove every future Kubernetes failure is distinguishable; it proves these two concrete real-failure classes remain blocking and bounds the exemption to the observed reconciliation shape.
### Unit red-first checkpoint
The nine-case contract harness was written before the verifier. First execution exited 1 because `verify-terminal-green.py` did not exist; no exemption implementation was live. Cases pre-register ordinary green, the exact artifact, both provider controls, near-miss signatures, an independent failure, and a skipped step.
### Control 2 setup attempt — invalid, excluded from evidence
- Commit: `9455cd6a2650b2b7e70f746c07933d96e5cb3d20`
- Pipeline: #2190, exact commit match.
- Full JSON child scan: 9 total — 7 success, 2 failure, 0 skipped/pending/running.
- Service log: `/bin/sh: 0: -c requires an argument`.
- Root cause: Woodpecker service `commands` did not become the third `sh -c` argument. PostgreSQL never started, so this run is **not** the post-readiness crash control and provides no discrimination evidence.
- Focused remediation: place the script directly in the third `entrypoint` element and supply `PGPASSWORD` for the marker query. This is a control-fixture correction, not a retry of #1000 and not evidence for either verdict.
## Implementation evidence
- `verify-terminal-green.py` consumes only the full JSON/API record; it performs no fetch, retry, or trigger.
- Exact #2188 record: exit 0, 10 children, 9 success + 1 named exemption.
- Historical set: #2158/#2167/#2184/#2186 pass with no exemption; #2170/#2175/#2182/#2187/#2188 pass with one named exemption; #2180/#2181 remain red because independent failures exist.
- Provider controls: #2189 and #2191 both exit 1 under the verifier; neither is exempted.
- Unit harness: initial 9/9 cases passed after the red-first checkpoint; review remediation expands this to 12 cases with expected-head match/missing/mismatch coverage.
- Test-membership guard: PASS, population 45; 26 enumerated, 19 signed exclusions; all 39 surface paths present.
- Python compile: PASS.
- `pnpm typecheck`: PASS, 45/45 tasks.
- `pnpm lint`: PASS, 25/25 tasks.
- `pnpm format:check`: PASS after moving local evidence outside the repository tree.
- `test:framework-shell`: RM-61 and all preceding suites passed, then the pre-existing wake assertion aborted with exit 97 because this host's Bash 5.2.15 reports `BASH_LINENO [3 5]` where that suite requires `[3 4]`. RM-61 does not modify the wake suite; the command is not fully runnable on this host as written and no substitute result is claimed.
## Independent review
- Review 67 / comment 20403 at exact head `e7b29219e11efd0a19395156ac0b154bec0c3a73`: **REQUEST CHANGES**.
- Blocker: the verifier echoed the pipeline commit but did not bind it to the current PR head; mutating only #2188's commit still returned terminal-green.
- Remediation: require `--expect-commit <full-40>`, add a pipeline anomaly on missing/mismatched record commits, emit expected and observed values, wire both CI documentation and the merge-gate baseline to pass provider PR head, and add match/missing/mismatch tests.
- This binding is not prohibited head-based clustering policy: it proves the evidence belongs to the commit under verdict. Runner/node/time/head correlation remains excluded from the teardown signature itself.
- Review 69 later approved the commit-binding remediation at exact head `033b2ffb46674b2c0bcc5197273c109b461f62d9`; pipeline #2193 was 9/9 success. Before merge-gate, an independent adjudicator found that Python treats JSON `false == 0`, allowing a non-integer exit value to match. The prior gate-ready state was withdrawn. The type-strict set distinguishes genuine red-first controls (`false`, `0.0`, which wrongly exempted) from regression guards (`true`, `"0"`, `null`, which already blocked). Remediation requires the decoded type to be exactly `int` and excludes `bool` explicitly.
## Documentation checklist
- [x] CI contract documented in the canonical framework CI/CD guide.
- [x] Operator command documented in the Woodpecker tool README.
- [x] Merge-gate baseline points to the deterministic verifier and named retirement.
- [x] Tracking and retirement cite issue #1000.
- [x] Both positive and negative guarantee boundaries are stated.
- [x] No API/auth/schema/user-facing navigation change; OpenAPI, user guide, and sitemap are not applicable.
## Risks
The controls establish discrimination for deterministic startup failure and an armed post-readiness postmaster crash on the current Woodpecker Kubernetes provider. They cannot prove that every future Kubernetes failure mode will preserve a non-zero exit before reconciliation. The exact matcher minimizes that residual risk, and issue #1000 remains the mandatory provider-seam closure and retirement trigger.
@@ -1,58 +0,0 @@
# RM-01 — Reproducible checkout
- Task/ref: RM-01 (`docs/remediation/TASKS.md`, internal mission tracking)
- Objective: make checkout/install/typecheck hooks fail on code rather than environmental residue, for root CI and non-root seats.
- Scope: pnpm store configuration, transactional Husky installation, dependency/generated-state preflight, checkout regression tests, developer documentation.
- Constraints: isolated worktree; no skip-switch fixes; no writes under `/root` or `/tmp`; workers do not edit `docs/remediation/TASKS.md`; author does not review or merge.
- Acceptance: AC1AC8 from the orchestrator dispatch/addendum.
- Plan:
1. Add RED-first tests for missing dependencies, stale/foreign `.next`, and interrupted hook installation.
2. Implement environment-overridable HOME-based pnpm store defaults, deterministic preflight, and transactional hook installation.
3. Run focused tests, install/build/baseline gates, and explicit AC negative controls.
4. Obtain independent review, push after queue guard, open PR, and send evidence to `mos-remediation`.
- Budget: orchestrator estimate 6K/60K; no explicit hard token cap. Keep scope to RM-01 and avoid unrelated cleanup.
- Risks: 97%-full shared `/tmp`; native dependency install size; root-owned fixtures may require Docker for realistic verification.
## Progress / evidence
- Worktree created at `/home/hermes/agent-work/rm-01` from `origin/main` `06e0d403`.
- `/tmp` baseline: 28G used, 889M available (97%); worktree and planned store are on `/home`.
- Root causes confirmed from source: committed `.npmrc` pins `/root`; `prepare` invokes Husky directly; web typecheck includes generated `.next` types without validating ownership/freshness.
## Checkpoint evidence (c45e5e19)
- AC1 IN PROGRESS: non-root `pnpm install --frozen-lockfile --store-dir "$HOME/.local/share/pnpm/store"` exited 0; `pnpm exec turbo run typecheck --force` exited 0 (45/45 uncached). Clean CI-container run not performed.
- AC2 DONE: with `node_modules` absent, `pnpm preflight` exited 42 with `MOSAIC_PREFLIGHT_MISSING_DEPS` and `run pnpm install`; after install it exited 0.
- AC3 DONE: appending `export const x: number = "s"` to `packages/types/src/index.ts` made `pnpm -w typecheck` exit 2 with TS2322; reverting made it exit 0.
- AC4 IN PROGRESS: local `pnpm -w build` exited 0 and `git status --porcelain` showed no generated residue beyond the intended RM-01 source changes. Fresh-clone proof not performed.
- AC5 DONE: non-root install exited 0; `pnpm store path` resolved `/home/hermes/.local/share/pnpm/store/v10`; no `/root` write was attempted.
- AC6 IN PROGRESS: focused failure/rollback tests passed, but final review found a concurrent-install race. Two installers can both observe `.husky/_` absent; after one installs successfully, the losing install's catch path can quarantine the winner's active hooks and restore stale Git config (`scripts/install-hooks.mjs`, activation/catch transaction). A RED regression is committed after the checkpoint.
- AC7 DONE: install/store/worktree were on `/home`; full `pnpm -w build` exited 0; `/tmp` usage changed by 4096 bytes during the build (23,805,173,760 → 23,805,177,856 bytes), not materially.
- AC8 DONE for the implemented path: store resolves under `$HOME`; test/quarantine/build state resolves under the worktree; no implemented component requires a writable path outside `$HOME` or the worktree.
## Continuation evidence
- AC6 DONE: the committed race reproducer was observed RED (`node --test --test-name-pattern='a competing successful installer is not removed by the losing process' scripts/install-hooks.test.mjs`, exit 1/ENOENT), then passed after cleanup became ownership-safe. The losing installer never removes an active hook set or restores Git configuration it did not activate. `pnpm test:checkout` passes 21/21, exit 0, including the original race and a post-rename peer-replacement regression.
- Generated-state remediation: replaced mtime inference with a source/build-input fingerprint, written only after a serialized successful Next build with unchanged inputs. Failed/interrupted/overlapping builds leave no trusted marker. The fingerprint uses Next's own environment loader, covers resolved `NEXT_PUBLIC_*` values, inherited TypeScript configuration, lock/workspace inputs, and rejects symlink inputs.
- Baseline: `pnpm typecheck`, `pnpm lint`, and `pnpm format:check` each exit 0. Local `pnpm test` still exits 97 only at the pre-existing Bash `BASH_LINENO` convention guard (#973/#1003), after checkout tests and package tests pass; this is not reported as a green full-suite result.
- Automated review remediation: resolved findings for peer-hook ownership, stale/failed build markers, build-input changes, expanded environment inputs, inherited TypeScript config, symlink inputs, and overlapping build serialization. Independent PR review remains assigned to rev-974.
- AC1 DONE at `0f706119`: a clean clone created inside `git.mosaicstack.dev/mosaicstack/stack/ci-base:latest` ran the exact acceptance sequence `pnpm install --frozen-lockfile && pnpm -w typecheck`; exit 0 with 45/45 uncached typecheck tasks successful. An earlier bind-mounted clone attempt exited 1 because root in the container rejected the host-owned Git directory; that failed attempt is not counted as evidence.
- AC4 DONE at `0f706119`: in that same fresh clone and CI image, `pnpm -w build` completed 25/25 tasks and the immediately following `git status --porcelain` was empty; combined assertion exit 0.
- Push BLOCKED after the required queue guard: `git push origin fix/rm-01-reproducible-checkout` was rejected by Gitea with `User permission denied for writing` / `pre-receive hook declined`, despite `MOSAIC_GIT_IDENTITY=f10-coder` resolving username `f10-coder` from the provisioned `gitea-mosaicstack-f10-coder.token`.
## Review remediation — restated AC2
- Independent review correctly found that an added symlink under a successfully built `.next` tree passed preflight. The exact reviewer control, `ln -s /etc/hosts apps/web/.next/reviewer-symlink && pnpm preflight`, was observed passing before remediation.
- The original blanket symlink wording conflicts with AC4 because canonical Next `output: 'standalone'` emits legitimate pnpm dependency symlinks. The coordinator independently verified 42 such links and approved the operative restatement: `.next` itself must not be a symlink; descendant symlinks must exactly match the successful build's certified manifest.
- RED-first controls were observed failing together against the prior implementation (exit 1): `.next` root, added, removed, retargeted, tampered-manifest, and canonical-style certified-link cases. The build now publishes the manifest atomically before the existing source certification commit marker; that marker binds the manifest SHA-256. Missing/partial/modified manifests remain untrusted.
- GREEN evidence: the six-case symlink control passes; the exact reviewer-added link exits 43; removing it restores preflight exit 0. The added RED-first build-publication control also proves a symlinked `.next` cannot redirect certification writes outside the checkout. `pnpm test:checkout` passes 23 top-level tests / 29 including subtests. Canonical `pnpm --filter @mosaicstack/web build` and the following `pnpm preflight` both exit 0.
- Threat-model ruling: the manifest detects accidental, independent, stale, and foreign-residue mutation—the class exposed by the five-month-stale `.next` that produced 19 phantom TS2307 errors. It does not defend against a same-UID actor able to rewrite both manifest and marker consistently (CWE-345); no local worktree construction can without an external trust anchor. RM-59 tracks the residual: executor/spine-side attestation outside worktree authority, dependent on RM-12, RM-21, and RM-25.
- AC8 concrete proof at `df7530ae`: a clean clone ran in `ci-base:latest` with Docker `--read-only`; its only writable mounts were `/workspace` (the worktree) and `/home/ci` (`HOME`, with `NPM_CONFIG_STORE_DIR=/home/ci/store`). `pnpm install --frozen-lockfile && pnpm -w typecheck` exited 0 with 45/45 uncached tasks. This proves the implemented checkout path requires no writable location outside `$HOME` and the worktree. An initial fixture attempt failed only because Git required `/workspace` safe-directory setup; it is not counted as evidence.
## Handoff
1. Keep the newly committed RED tests red until implementing: (a) source-fingerprint marker support for valid incremental `.next` output, and (b) ownership-safe concurrent hook activation.
2. The latest automated review rejected oldest-generated-file mtime as a false positive for valid incremental Next output. Use a source-content fingerprint marker written only after successful `next build`; do not continue tuning mtimes.
3. For Husky, generation in an isolated temporary Git repo avoids mutating real `core.hooksPath` during staging. Preserve that design. Fix the losing concurrent process so it never removes a peer's completed hook set or restores stale config.
4. Codex review runs in a read-only sandbox, so its attempts to run the fixture-writing Node tests report opaque test-file failures. The same tests run normally in the worktree.
5. Full `pnpm test` is not green on this host: it exits 97 at the pre-existing Bash `BASH_LINENO` convention guard (#1003), after the changed checkout tests and package tests pass. Do not weaken that gate.
+3 -6
View File
@@ -6,14 +6,11 @@
"build": "turbo run build",
"dev": "turbo run dev",
"lint": "turbo run lint",
"preflight": "node scripts/preflight.mjs",
"clean:generated": "node scripts/clean-generated.mjs",
"typecheck": "pnpm preflight && turbo run typecheck",
"test:checkout": "node --test scripts/*.test.mjs",
"test": "pnpm test:checkout && turbo run test",
"typecheck": "turbo run typecheck",
"test": "turbo run test",
"format": "prettier --write \"**/*.{ts,tsx,js,jsx,json,md}\"",
"format:check": "prettier --check \"**/*.{ts,tsx,js,jsx,json,md}\"",
"prepare": "node scripts/install-hooks.mjs"
"prepare": "husky"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^8.0.0",
@@ -13,14 +13,7 @@ It is a **gate** role: the one and only merge path.
2. **Use the wrapped scripts as the ONLY merge path** — the merge-gate merges
**exclusively** by calling **`pr-merge.sh`** (the merge action, which carries the
authoritative forbidden-path guard) and **`pr-ci-wait.sh`** (to wait for green
CI before merging). Before issuing a verdict, scan the full JSON/API child-step
record (including `clone`) with **`verify-terminal-green.py --expect-commit
<current-provider-PR-head>`** and record the equal expected/observed full-40
commits, exact step count, anomalies, and named exemptions. Missing or mismatched
commit binding is a hard refusal. The verifier's sole interim
exemption is `WP-K8S-1000-CI-POSTGRES-TEARDOWN`; it is signature-scoped, tracked
by #1000, and retires when #1000 is fixed. These scripts are the _only_
sanctioned merge path.
CI before merging). These two scripts are the _only_ sanctioned merge path.
3. **Never call the raw API** — the merge-gate **does NOT** call `tea`, the raw
Gitea/forge HTTP API, or any other merge mechanism directly. Only `pr-merge.sh`
and `pr-ci-wait.sh`.
@@ -868,38 +868,6 @@ steps:
7. **Test on a short-lived non-main branch first** — open a PR and verify quality gates before merging to `main`
8. **Verify images appear** in Gitea Packages tab after successful pipeline
## Terminal-Green Full-Step Contract
A successful pipeline summary is not sufficient: verification MUST consume the full JSON/API child-step record, including `clone`.
```bash
PR_HEAD=<full-40-hex-provider-head>
~/.config/mosaic/tools/woodpecker/pipeline-status.sh \
-r mosaicstack/stack -n <pipeline-number> -f json \
| ~/.config/mosaic/tools/woodpecker/verify-terminal-green.py \
--expect-commit "$PR_HEAD" -
```
`PR_HEAD` MUST come from the current provider PR metadata and MUST be the full 40-hex head, not a local branch guess. The verifier fails if the argument is missing, malformed, absent from the pipeline record, or differs from that record.
The verifier reports the expected and observed commits, total step count, state counts, anomalies, and any applied exemption. Exit `0` means the record satisfies the contract; exit `1` means the commit binding or at least one pipeline, workflow, or child-step state blocks terminal-green; exit `2` means the invocation or JSON input could not be verified.
### Named interim exemption: `WP-K8S-1000-CI-POSTGRES-TEARDOWN`
Only this exact conjunction is exempted:
- pipeline and workflow state are `success`;
- exactly one non-success child exists;
- its name is `ci-postgres` and type is `service`;
- its state is `failure`, exit code is the JSON integer `0` (not boolean, float, string, or null); and
- its error exactly matches `pods "wp-svc-<ULID>-ci-postgres" not found`.
Every near miss remains blocking, including non-zero service exits, startup failures, post-readiness crashes, connection errors, image-pull errors, skipped steps, another failed child, malformed pod names, duplicate matches, or a non-success pipeline/workflow.
**Boundary in both directions:** this exemption recognizes the observed Woodpecker Kubernetes reconciliation miss after an otherwise-successful run. It does not prove that every future PostgreSQL or Kubernetes failure is distinguishable. It does prove, through provider controls, that a deterministic startup failure (`exit_code=1`) and an armed post-readiness postmaster crash (`exit_code=137`, dependent probe `Connection refused`) do not match and remain red.
**Tracking and retirement:** [mosaicstack/stack#1000](https://git.mosaicstack.dev/mosaicstack/stack/issues/1000) owns the provider-seam fix. This exemption MUST be removed when #1000 is fixed. It is not authority to retry or re-trigger a pipeline, and no per-PR re-roll is part of the contract.
## Post-Merge CI Monitoring (Hard Rule)
For source-code delivery, completion is not allowed at "PR opened" stage.
@@ -26,13 +26,12 @@ A Woodpecker API token is required. To configure:
## Scripts
| Script | Purpose |
| -------------------------- | -------------------------------------------------------------- |
| `pipeline-list.sh` | List recent pipelines for a repo |
| `pipeline-status.sh` | Get status of a specific or latest pipeline |
| `pipeline-trigger.sh` | Trigger a new pipeline build |
| `ci-wait.sh` | Block until pipeline(s) reach terminal state |
| `verify-terminal-green.py` | Verify every JSON/API child step under the bounded CI contract |
| Script | Purpose |
| --------------------- | -------------------------------------------- |
| `pipeline-list.sh` | List recent pipelines for a repo |
| `pipeline-status.sh` | Get status of a specific or latest pipeline |
| `pipeline-trigger.sh` | Trigger a new pipeline build |
| `ci-wait.sh` | Block until pipeline(s) reach terminal state |
## Common Options
@@ -60,9 +59,4 @@ A Woodpecker API token is required. To configure:
# Block until one or more pipelines finish (event-driven CI wait)
~/.config/mosaic/tools/woodpecker/ci-wait.sh -r usc/uconnect -n 3917 -n 3918
# Verify the full JSON child-step record; do not use the text summary for this gate
PR_HEAD=<full-40-hex-provider-head>
~/.config/mosaic/tools/woodpecker/pipeline-status.sh -r mosaicstack/stack -n 2188 -f json \
| ~/.config/mosaic/tools/woodpecker/verify-terminal-green.py --expect-commit "$PR_HEAD" -
```
@@ -1,109 +0,0 @@
#!/usr/bin/env bash
# Red-first contract harness for RM-61 / #1000.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VERIFIER="$SCRIPT_DIR/verify-terminal-green.py"
EXPECTED_COMMIT=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
write_fixture() {
local file="$1" pipeline_status="$2" postgres_state="$3" postgres_exit="$4" postgres_error="$5" test_state="$6"
python3 - "$file" "$pipeline_status" "$postgres_state" "$postgres_exit" "$postgres_error" "$test_state" <<'PY'
import json, sys
path, pipeline_status, pg_state, pg_exit, pg_error, test_state = sys.argv[1:]
steps = [
{"name": "clone", "type": "clone", "state": "success", "exit_code": 0, "error": None},
{"name": "ci-postgres", "type": "service", "state": pg_state, "exit_code": int(pg_exit), "error": pg_error or None},
{"name": "test", "type": "commands", "state": test_state, "exit_code": 0 if test_state == "success" else 1, "error": None},
]
json.dump({
"number": 9999,
"status": pipeline_status,
"commit": "a" * 40,
"workflows": [{"name": "ci", "state": pipeline_status, "children": steps}],
}, open(path, "w"))
PY
}
expect_exit() {
local expected_exit="$1" label="$2" file="$3" expected_commit="${4:-$EXPECTED_COMMIT}"
set +e
output=$(python3 "$VERIFIER" --expect-commit "$expected_commit" "$file" 2>&1)
actual=$?
set -e
if [[ "$actual" -ne "$expected_exit" ]]; then
printf 'FAIL %s: expected exit %s, got %s\n%s\n' "$label" "$expected_exit" "$actual" "$output" >&2
exit 1
fi
printf 'PASS %s\n' "$label"
printf '%s' "$output"
}
# Ordinary terminal green.
write_fixture "$TMP/green.json" success success 0 '' success
out=$(expect_exit 0 green "$TMP/green.json")
grep -q '"total_steps": 3' <<<"$out"
grep -q '"exempted_steps": 0' <<<"$out"
# Exact, named #1000 teardown artifact: the only permitted non-success child.
artifact='pods "wp-svc-01kyxzjhdf6w81swsnbfzh85z9-ci-postgres" not found'
write_fixture "$TMP/artifact.json" success failure 0 "$artifact" success
out=$(expect_exit 0 exact-artifact "$TMP/artifact.json")
grep -q '"exemption_id": "WP-K8S-1000-CI-POSTGRES-TEARDOWN"' <<<"$out"
grep -q '"exempted_steps": 1' <<<"$out"
# Negative controls: both real PostgreSQL failures must remain red.
write_fixture "$TMP/startup.json" failure failure 1 '' failure
expect_exit 1 startup-failure "$TMP/startup.json" >/dev/null
write_fixture "$TMP/crash.json" failure failure 137 '' failure
expect_exit 1 post-readiness-crash "$TMP/crash.json" >/dev/null
# The exemption is signature-scoped, not step-scoped.
write_fixture "$TMP/wrong-error.json" success failure 0 'connection refused' success
expect_exit 1 other-postgres-error "$TMP/wrong-error.json" >/dev/null
write_fixture "$TMP/wrong-pod.json" success failure 0 'pods "other-ci-postgres" not found' success
expect_exit 1 wrong-pod-signature "$TMP/wrong-pod.json" >/dev/null
write_fixture "$TMP/nonzero-artifact.json" success failure 137 "$artifact" success
expect_exit 1 nonzero-with-artifact-text "$TMP/nonzero-artifact.json" >/dev/null
# JSON booleans and non-integer zero look equal to 0 in Python but are not exit codes.
python3 - "$TMP/artifact.json" "$TMP" <<'PY'
import json, os, sys
record = json.load(open(sys.argv[1]))
for label, value in (("false", False), ("true", True), ("float", 0.0), ("string", "0"), ("null", None)):
changed = json.loads(json.dumps(record))
changed["workflows"][0]["children"][1]["exit_code"] = value
json.dump(changed, open(os.path.join(sys.argv[2], f"exit-{label}.json"), "w"))
PY
for label in false true float string null; do
expect_exit 1 "non-integer-exit-$label" "$TMP/exit-$label.json" >/dev/null
done
# Exact artifact cannot mask any independent failure or non-success pipeline.
write_fixture "$TMP/artifact-plus-failure.json" failure failure 0 "$artifact" failure
expect_exit 1 artifact-plus-real-failure "$TMP/artifact-plus-failure.json" >/dev/null
write_fixture "$TMP/skipped.json" success success 0 '' skipped
expect_exit 1 skipped-step "$TMP/skipped.json" >/dev/null
# The scanned pipeline must be bound to an explicit, full PR-head commit.
set +e
missing_output=$(python3 "$VERIFIER" "$TMP/artifact.json" 2>&1)
missing_rc=$?
set -e
if [[ "$missing_rc" -ne 2 ]] || ! grep -q -- '--expect-commit' <<<"$missing_output"; then
printf 'FAIL missing-expected-commit: expected usage exit 2\n%s\n' "$missing_output" >&2
exit 1
fi
expect_exit 1 mismatched-expected-commit "$TMP/artifact.json" bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb >/dev/null
python3 - "$TMP/artifact.json" "$TMP/missing-record-commit.json" <<'PY'
import json, sys
record = json.load(open(sys.argv[1]))
record.pop("commit")
json.dump(record, open(sys.argv[2], "w"))
PY
expect_exit 1 missing-record-commit "$TMP/missing-record-commit.json" >/dev/null
printf 'terminal-green contract harness: PASS (17 cases)\n'
@@ -1,230 +0,0 @@
#!/usr/bin/env python3
"""Verify Mosaic's full-step Woodpecker terminal-green contract.
RM-61 permits one named, signature-scoped exception for issue #1000. The
exception retires when #1000 is fixed; all other non-success states block.
This program consumes the JSON/API record emitted by pipeline-status.sh -f json.
It does not fetch, retry, or re-trigger pipelines.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from collections import Counter
from pathlib import Path
from typing import Any
EXEMPTION_ID = "WP-K8S-1000-CI-POSTGRES-TEARDOWN"
EXEMPTION_ISSUE = "https://git.mosaicstack.dev/mosaicstack/stack/issues/1000"
POD_NOT_FOUND = re.compile(
r'^pods "wp-svc-[0-9a-hjkmnp-tv-z]{26}-ci-postgres" not found$'
)
def fail_usage(message: str) -> int:
print(f"terminal-green contract input error: {message}", file=sys.stderr)
return 2
def load_record(argument: str | None) -> dict[str, Any]:
if argument in (None, "-"):
value = json.load(sys.stdin)
else:
with Path(argument).open(encoding="utf-8") as handle:
value = json.load(handle)
if not isinstance(value, dict):
raise ValueError("pipeline record must be a JSON object")
return value
def is_issue_1000_artifact(step: dict[str, Any]) -> bool:
error = step.get("error")
exit_code = step.get("exit_code")
return (
step.get("name") == "ci-postgres"
and step.get("type") == "service"
and step.get("state") == "failure"
and type(exit_code) is int
and not isinstance(exit_code, bool)
and exit_code == 0
and isinstance(error, str)
and POD_NOT_FOUND.fullmatch(error) is not None
)
def verify(record: dict[str, Any], expected_commit: str) -> tuple[int, dict[str, Any]]:
anomalies: list[dict[str, Any]] = []
candidates: list[dict[str, Any]] = []
steps: list[dict[str, Any]] = []
pipeline_status = record.get("status")
actual_commit = record.get("commit")
if actual_commit != expected_commit:
anomalies.append(
{
"scope": "pipeline",
"name": str(record.get("number", "unknown")),
"state": pipeline_status,
"reason": "pipeline commit does not equal the expected PR head",
"expected_commit": expected_commit,
"actual_commit": actual_commit,
}
)
if pipeline_status != "success":
anomalies.append(
{
"scope": "pipeline",
"name": str(record.get("number", "unknown")),
"state": pipeline_status,
"reason": "pipeline status is not success",
}
)
workflows = record.get("workflows")
if not isinstance(workflows, list) or not workflows:
anomalies.append(
{
"scope": "pipeline",
"name": str(record.get("number", "unknown")),
"state": pipeline_status,
"reason": "workflows are missing or empty",
}
)
workflows = []
for workflow_index, workflow in enumerate(workflows):
if not isinstance(workflow, dict):
anomalies.append(
{
"scope": "workflow",
"name": str(workflow_index),
"state": None,
"reason": "workflow is not an object",
}
)
continue
workflow_name = str(workflow.get("name", workflow_index))
if workflow.get("state") != "success":
anomalies.append(
{
"scope": "workflow",
"name": workflow_name,
"state": workflow.get("state"),
"reason": "workflow state is not success",
}
)
children = workflow.get("children")
if not isinstance(children, list) or not children:
anomalies.append(
{
"scope": "workflow",
"name": workflow_name,
"state": workflow.get("state"),
"reason": "child-step list is missing or empty",
}
)
continue
for child_index, child in enumerate(children):
if not isinstance(child, dict):
anomalies.append(
{
"scope": "step",
"name": f"{workflow_name}[{child_index}]",
"state": None,
"reason": "step is not an object",
}
)
continue
steps.append(child)
if child.get("state") == "success":
continue
if is_issue_1000_artifact(child):
candidates.append(child)
continue
anomalies.append(
{
"scope": "step",
"name": child.get("name"),
"type": child.get("type"),
"state": child.get("state"),
"exit_code": child.get("exit_code"),
"error": child.get("error"),
"reason": "non-success step does not match the #1000 teardown signature",
}
)
if len(candidates) > 1:
anomalies.append(
{
"scope": "exemption",
"name": EXEMPTION_ID,
"state": "invalid",
"reason": "the #1000 exemption may apply to exactly one step",
}
)
exemption_applies = len(candidates) == 1 and not anomalies
state_counts = Counter(str(step.get("state", "missing")) for step in steps)
result: dict[str, Any] = {
"schema_version": "mosaic-terminal-green/v1",
"verdict": "terminal-green" if not anomalies else "not-terminal-green",
"pipeline_number": record.get("number"),
"commit": actual_commit,
"expected_commit": expected_commit,
"pipeline_status": pipeline_status,
"total_steps": len(steps),
"state_counts": dict(sorted(state_counts.items())),
"exempted_steps": 1 if exemption_applies else 0,
"anomalies": anomalies,
}
if exemption_applies:
candidate = candidates[0]
result["exemptions"] = [
{
"exemption_id": EXEMPTION_ID,
"step": candidate.get("name"),
"signature": candidate.get("error"),
"tracking_issue": EXEMPTION_ISSUE,
"retires_when": "issue #1000 is fixed",
}
]
else:
result["exemptions"] = []
return (0 if not anomalies else 1), result
def parse_arguments() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="verify the full Woodpecker terminal-green child-step contract"
)
parser.add_argument(
"--expect-commit",
required=True,
metavar="FULL_SHA",
help="full 40-hex PR-head commit that the pipeline record must match",
)
parser.add_argument("record", nargs="?", default="-", help="pipeline JSON file or -")
arguments = parser.parse_args()
if re.fullmatch(r"[0-9a-fA-F]{40}", arguments.expect_commit) is None:
parser.error("--expect-commit must be a full 40-hex commit")
arguments.expect_commit = arguments.expect_commit.lower()
return arguments
def main() -> int:
arguments = parse_arguments()
try:
record = load_record(arguments.record)
except (OSError, ValueError, json.JSONDecodeError) as error:
return fail_usage(str(error))
code, result = verify(record, arguments.expect_commit)
print(json.dumps(result, indent=2, sort_keys=True))
return code
if __name__ == "__main__":
raise SystemExit(main())
+1 -1
View File
@@ -25,7 +25,7 @@
"lint": "eslint src",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests && pnpm run test:framework-shell",
"test:framework-shell": "bash framework/tools/quality/scripts/check-test-enumeration.sh && bash framework/tools/quality/scripts/test-check-test-enumeration.sh && python3 src/lease-broker/daemon_deadline_unittest.py && python3 src/lease-broker/normative_fragments_unittest.py && python3 src/lease-broker/receipt_challenge_unittest.py && python3 src/lease-broker/context_recovery_unittest.py && python3 src/lease-broker/recovery_runtime_unittest.py && python3 src/lease-broker/recovery_b1_adversarial_unittest.py && python3 src/lease-broker/framework_skill_portability_unittest.py && python3 src/mutator-gate/runtime_tools_unittest.py && python3 src/mutator-gate/runtime_launch_guard_unittest.py && python3 src/mutator-gate/version_coupling_unittest.py && python3 framework/tools/lease-broker/check-runtime-launches.py --root ../.. && bash framework/tools/codex/test-pr-diff-context.sh && bash framework/tools/qa/test-deps-preflight.sh && bash framework/tools/git/test-pr-review-gitea-comment.sh && bash framework/tools/git/test-pr-review-repo-host-override.sh && bash framework/tools/git/test-ci-queue-wait-branch-absent.sh && bash framework/tools/git/test-git-credential-mosaic.sh && bash framework/tools/git/test-gitea-token-identity.sh && bash framework/tools/woodpecker/test-terminal-green-contract.sh && bash framework/tools/_scripts/test-install-ordering-guard.sh && bash framework/tools/tmux/agent-send.test.sh && bash framework/tools/wake/test-wake-store-ack.sh && bash framework/tools/wake/test-wake-store-enqueue-race.sh && bash framework/tools/wake/test-wake-digest-hmac.sh && bash framework/tools/wake/test-wake-digest-quarantine.sh && bash framework/tools/wake/test-wake-detector.sh && bash framework/tools/wake/test-wake-fn-oracle.sh && bash framework/tools/wake/test-wake-reconcile.sh && bash framework/tools/wake/test-wake-beacon.sh && bash framework/tools/wake/test-wake-preimage.sh && bash framework/tools/wake/test-wake-install.sh"
"test:framework-shell": "bash framework/tools/quality/scripts/check-test-enumeration.sh && bash framework/tools/quality/scripts/test-check-test-enumeration.sh && python3 src/lease-broker/daemon_deadline_unittest.py && python3 src/lease-broker/normative_fragments_unittest.py && python3 src/lease-broker/receipt_challenge_unittest.py && python3 src/lease-broker/context_recovery_unittest.py && python3 src/lease-broker/recovery_runtime_unittest.py && python3 src/lease-broker/recovery_b1_adversarial_unittest.py && python3 src/lease-broker/framework_skill_portability_unittest.py && python3 src/mutator-gate/runtime_tools_unittest.py && python3 src/mutator-gate/runtime_launch_guard_unittest.py && python3 src/mutator-gate/version_coupling_unittest.py && python3 framework/tools/lease-broker/check-runtime-launches.py --root ../.. && bash framework/tools/codex/test-pr-diff-context.sh && bash framework/tools/qa/test-deps-preflight.sh && bash framework/tools/git/test-pr-review-gitea-comment.sh && bash framework/tools/git/test-pr-review-repo-host-override.sh && bash framework/tools/git/test-ci-queue-wait-branch-absent.sh && bash framework/tools/git/test-git-credential-mosaic.sh && bash framework/tools/git/test-gitea-token-identity.sh && bash framework/tools/_scripts/test-install-ordering-guard.sh && bash framework/tools/tmux/agent-send.test.sh && bash framework/tools/wake/test-wake-store-ack.sh && bash framework/tools/wake/test-wake-store-enqueue-race.sh && bash framework/tools/wake/test-wake-digest-hmac.sh && bash framework/tools/wake/test-wake-digest-quarantine.sh && bash framework/tools/wake/test-wake-detector.sh && bash framework/tools/wake/test-wake-fn-oracle.sh && bash framework/tools/wake/test-wake-reconcile.sh && bash framework/tools/wake/test-wake-beacon.sh && bash framework/tools/wake/test-wake-preimage.sh && bash framework/tools/wake/test-wake-install.sh"
},
"dependencies": {
"@mosaicstack/brain": "workspace:*",
-146
View File
@@ -1,146 +0,0 @@
#!/usr/bin/env node
import { spawn } from 'node:child_process';
import { createHash, randomUUID } from 'node:crypto';
import { lstat, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import { generatedSymlinkManifest, sourceFingerprint } from './preflight.mjs';
const scriptRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
function run(command, args, options) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, options);
child.once('error', reject);
child.once('exit', (code, signal) => {
if (code === 0) resolve();
else
reject(
new Error(signal ? `next build terminated by ${signal}` : `next build exited ${code}`),
);
});
});
}
const delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
async function requireRealDirectory(target, { allowMissing = false } = {}) {
try {
const stats = await lstat(target);
if (!stats.isDirectory() || stats.isSymbolicLink()) {
throw new Error(`${target} must be a real directory, not a symbolic link.`);
}
} catch (error) {
if (allowMissing && error.code === 'ENOENT') return;
throw error;
}
}
async function acquireBuildLock(root) {
const workRoot = path.join(root, '.mosaic-test-work');
const lock = path.join(workRoot, 'web-build.lock');
const nonce = randomUUID();
const owner = JSON.stringify({ pid: process.pid, nonce });
const deadline = Date.now() + 120_000;
await mkdir(workRoot, { recursive: true });
while (Date.now() < deadline) {
try {
await mkdir(lock);
await writeFile(path.join(lock, 'owner.json'), owner, { mode: 0o600 });
return async () => {
const current = await readFile(path.join(lock, 'owner.json'), 'utf8');
if (current !== owner) throw new Error('Web build lock ownership changed before release.');
const released = `${lock}.released-${nonce}`;
await rename(lock, released);
await rm(released, { recursive: true, force: true });
};
} catch (error) {
if (error.code !== 'EEXIST') throw error;
let lockOwner;
try {
lockOwner = JSON.parse(await readFile(path.join(lock, 'owner.json'), 'utf8'));
} catch (ownerError) {
if (ownerError.code === 'ENOENT') {
await delay(25);
continue;
}
throw new Error(`Web build lock is unreadable at ${lock}.`, { cause: ownerError });
}
try {
process.kill(lockOwner.pid, 0);
} catch (processError) {
if (processError.code !== 'ESRCH') throw processError;
const stale = `${lock}.stale-${nonce}`;
try {
await rename(lock, stale);
await rm(stale, { recursive: true, force: true });
} catch (renameError) {
if (renameError.code !== 'ENOENT') throw renameError;
}
continue;
}
await delay(25);
}
}
throw new Error(`Timed out waiting for the web build lock at ${lock}.`);
}
export async function buildWeb({
root = scriptRoot,
fingerprint = sourceFingerprint,
runBuild = async (webDir) =>
run(path.join(webDir, 'node_modules', '.bin', 'next'), ['build'], {
cwd: webDir,
stdio: 'inherit',
}),
} = {}) {
const releaseLock = await acquireBuildLock(root);
try {
const webDir = path.join(root, 'apps', 'web');
const nextDir = path.join(webDir, '.next');
const certificationMarker = path.join(nextDir, '.mosaic-source-hash');
const symlinkManifest = path.join(nextDir, '.mosaic-symlink-manifest');
const certificationTemporary = `${certificationMarker}.${randomUUID()}.tmp`;
const manifestTemporary = `${symlinkManifest}.${randomUUID()}.tmp`;
const before = await fingerprint(root);
await requireRealDirectory(nextDir, { allowMissing: true });
await Promise.all([
rm(certificationMarker, { force: true }),
rm(symlinkManifest, { force: true }),
]);
await runBuild(webDir);
await requireRealDirectory(nextDir);
const after = await fingerprint(root);
if (after !== before) {
throw new Error(
'Web build inputs changed during next build; generated output was not certified.',
);
}
const manifestContents = await generatedSymlinkManifest(nextDir);
const certificationContents = `${JSON.stringify({
version: 1,
sourceFingerprint: before,
symlinkManifestHash: createHash('sha256').update(manifestContents).digest('hex'),
})}\n`;
await Promise.all([
writeFile(certificationTemporary, certificationContents, { mode: 0o600 }),
writeFile(manifestTemporary, manifestContents, { mode: 0o600 }),
]);
// The certification marker is the commit point. Publishing the manifest first
// leaves interrupted builds untrusted because the marker remains absent.
await rename(manifestTemporary, symlinkManifest);
await rename(certificationTemporary, certificationMarker);
} finally {
await releaseLock();
}
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
await buildWeb();
}
-149
View File
@@ -1,149 +0,0 @@
import assert from 'node:assert/strict';
import { access, mkdir, readFile, rm, symlink, writeFile } from 'node:fs/promises';
import path from 'node:path';
import test from 'node:test';
import { buildWeb } from './build-web.mjs';
const fixtureRoot = path.join(process.cwd(), '.mosaic-test-work', `build-web-${process.pid}`);
async function fixture(name) {
const root = path.join(fixtureRoot, name);
await mkdir(path.join(root, 'apps', 'web', '.next'), { recursive: true });
return root;
}
async function exists(target) {
try {
await access(target);
return true;
} catch {
return false;
}
}
test.after(async () => {
await rm(fixtureRoot, { recursive: true, force: true });
});
test('a successful web build atomically publishes its source and symlink certification', async () => {
const root = await fixture('success');
const marker = path.join(root, 'apps', 'web', '.next', '.mosaic-source-hash');
const manifest = path.join(root, 'apps', 'web', '.next', '.mosaic-symlink-manifest');
await buildWeb({ root, fingerprint: async () => 'certified', runBuild: async () => {} });
assert.deepEqual(JSON.parse(await readFile(marker, 'utf8')), {
version: 1,
sourceFingerprint: 'certified',
symlinkManifestHash: '8a5a375cea6a55d24bd5f875856da63feba33adbefb15a92a0007719b84bcf11',
});
assert.equal(await readFile(manifest, 'utf8'), '{"version":1,"links":[]}\n');
});
test('a failed web build leaves no certification marker', async () => {
const root = await fixture('failure');
const marker = path.join(root, 'apps', 'web', '.next', '.mosaic-source-hash');
const manifest = path.join(root, 'apps', 'web', '.next', '.mosaic-symlink-manifest');
await writeFile(marker, 'stale\n');
await writeFile(manifest, 'stale\n');
await assert.rejects(
buildWeb({
root,
fingerprint: async () => 'before',
runBuild: async () => {
throw new Error('build failed');
},
}),
/build failed/,
);
assert.equal(await exists(marker), false);
assert.equal(await exists(manifest), false);
});
test('overlapping web builds are serialized while the marker remains absent', async () => {
const root = await fixture('overlap');
const marker = path.join(root, 'apps', 'web', '.next', '.mosaic-source-hash');
const manifest = path.join(root, 'apps', 'web', '.next', '.mosaic-symlink-manifest');
await writeFile(marker, 'stale\n');
await writeFile(manifest, 'stale\n');
let releaseFirst;
let secondEntered = false;
const firstEntered = new Promise((resolve) => {
releaseFirst = resolve;
});
let markFirstEntered;
const firstStarted = new Promise((resolve) => {
markFirstEntered = resolve;
});
const first = buildWeb({
root,
fingerprint: async () => 'certified',
runBuild: async () => {
markFirstEntered();
await firstEntered;
},
});
await firstStarted;
const second = buildWeb({
root,
fingerprint: async () => 'certified',
runBuild: async () => {
secondEntered = true;
},
});
await new Promise((resolve) => setTimeout(resolve, 75));
assert.equal(secondEntered, false);
assert.equal(await exists(marker), false);
assert.equal(await exists(manifest), false);
releaseFirst();
await Promise.all([first, second]);
assert.equal(secondEntered, true);
assert.equal(JSON.parse(await readFile(marker, 'utf8')).sourceFingerprint, 'certified');
assert.equal(await readFile(manifest, 'utf8'), '{"version":1,"links":[]}\n');
});
test('a build that replaces .next with a symbolic link cannot publish outside the checkout', async () => {
const root = await fixture('symbolic-next');
const nextDir = path.join(root, 'apps', 'web', '.next');
const outside = path.join(root, 'outside-generated');
await mkdir(outside);
await assert.rejects(
buildWeb({
root,
fingerprint: async () => 'certified',
runBuild: async () => {
await rm(nextDir, { recursive: true });
await symlink(outside, nextDir);
},
}),
/must be a real directory/,
);
assert.equal(await exists(path.join(outside, '.mosaic-source-hash')), false);
assert.equal(await exists(path.join(outside, '.mosaic-symlink-manifest')), false);
});
test('inputs changed during a web build are not certified', async () => {
const root = await fixture('changed-inputs');
const marker = path.join(root, 'apps', 'web', '.next', '.mosaic-source-hash');
const manifest = path.join(root, 'apps', 'web', '.next', '.mosaic-symlink-manifest');
const fingerprints = ['before', 'after'];
await assert.rejects(
buildWeb({
root,
fingerprint: async () => fingerprints.shift(),
runBuild: async () => {},
}),
/inputs changed during next build/,
);
assert.equal(await exists(marker), false);
assert.equal(await exists(manifest), false);
});
-34
View File
@@ -1,34 +0,0 @@
#!/usr/bin/env node
import { access, mkdir, rename, rm } from 'node:fs/promises';
import path from 'node:path';
const root = process.cwd();
const generated = path.join(root, 'apps', 'web', '.next');
const quarantineRoot = path.join(root, '.mosaic-test-work', 'generated-quarantine');
try {
await access(generated);
} catch (error) {
if (error.code === 'ENOENT') process.exit(0);
throw error;
}
await mkdir(quarantineRoot, { recursive: true });
const quarantine = path.join(quarantineRoot, `web-next-${Date.now()}-${process.pid}`);
try {
await rename(generated, quarantine);
} catch (error) {
console.error(
`MOSAIC_GENERATED_CLEAN_FAILED: could not quarantine apps/web/.next. Fix: sudo rm -rf '${generated}', then rerun pnpm preflight`,
);
throw error;
}
try {
await rm(quarantine, { recursive: true, force: true });
} catch {
console.warn(
`Generated state was deactivated but could not be deleted; quarantined at ${quarantine}`,
);
}
-146
View File
@@ -1,146 +0,0 @@
#!/usr/bin/env node
import { access, lstat, mkdir, readFile, readdir, rename, rm } from 'node:fs/promises';
import { execFile, spawn } from 'node:child_process';
import { promisify } from 'node:util';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const execFileAsync = promisify(execFile);
function run(command, args, options) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, options);
child.once('error', reject);
child.once('exit', (code, signal) => {
if (code === 0) resolve();
else reject(new Error(signal ? `husky terminated by ${signal}` : `husky exited ${code}`));
});
});
}
async function pathExists(target) {
try {
await access(target);
return true;
} catch (error) {
if (error.code === 'ENOENT') return false;
throw error;
}
}
async function directorySnapshot(root) {
const snapshot = [];
async function walk(current) {
const children = await readdir(current, { withFileTypes: true });
for (const child of children.sort((left, right) => left.name.localeCompare(right.name))) {
const target = path.join(current, child.name);
const relative = path.relative(root, target);
const stats = await lstat(target);
if (child.isDirectory()) {
snapshot.push([relative, 'directory', stats.mode & 0o777]);
await walk(target);
} else {
snapshot.push([
relative,
'file',
stats.mode & 0o777,
(await readFile(target)).toString('base64'),
]);
}
}
}
await walk(root);
return JSON.stringify(snapshot);
}
async function directoriesMatch(left, right) {
return (await directorySnapshot(left)) === (await directorySnapshot(right));
}
export async function installHooks({
root = process.cwd(),
disabled = process.env.HUSKY === '0',
quarantineRoot = path.join(root, '.mosaic-test-work', 'husky-quarantine'),
runHusky = async (_stagingHooks, stagingRepo) => {
await execFileAsync('git', ['init', '--quiet', stagingRepo]);
await run(path.join(root, 'node_modules', '.bin', 'husky'), ['.husky'], {
cwd: stagingRepo,
stdio: 'inherit',
});
},
activateHooks = async () => {
await run('git', ['config', 'core.hooksPath', '.husky/_'], { cwd: root, stdio: 'inherit' });
},
} = {}) {
if (disabled) return;
const huskyDir = path.join(root, '.husky');
const active = path.join(huskyDir, '_');
const nonce = `${Date.now()}-${process.pid}`;
const stagingRepo = path.join(root, '.mosaic-test-work', `husky-stage-${nonce}`);
const stagingHooks = path.join(stagingRepo, '.husky');
const quarantined = path.join(quarantineRoot, `${path.basename(root)}-${nonce}`);
await mkdir(huskyDir, { recursive: true });
await mkdir(quarantineRoot, { recursive: true });
const previousComplete = (await pathExists(active)) && (await pathExists(path.join(active, 'h')));
let previousQuarantined = false;
try {
if ((await pathExists(active)) && !previousComplete) {
await rename(active, quarantined);
previousQuarantined = true;
}
await mkdir(stagingRepo, { recursive: true });
await runHusky(stagingHooks, stagingRepo);
const staged = path.join(stagingHooks, '_');
if (!(await pathExists(path.join(staged, 'h')))) {
throw new Error('husky did not produce its required h shim');
}
if (previousComplete) {
if (!(await directoriesMatch(active, staged))) {
throw new Error('existing complete hook set differs from the installed Husky version');
}
await rm(stagingRepo, { recursive: true, force: true });
} else {
await rename(staged, active);
await rm(stagingRepo, { recursive: true, force: true });
}
await activateHooks();
if (previousQuarantined) {
try {
await rm(quarantined, { recursive: true, force: true });
} catch {
console.warn(
`Previous hook state was deactivated but remains quarantined at ${quarantined}`,
);
}
}
} catch (error) {
const cleanupFailures = [];
try {
if (await pathExists(stagingRepo)) {
await rename(stagingRepo, `${quarantined}-staging`);
}
} catch (cleanupError) {
cleanupFailures.push(`staging hooks: ${cleanupError.message}`);
}
const cleanup =
cleanupFailures.length === 0
? 'No partial hook set was activated.'
: `Automatic cleanup was incomplete (${cleanupFailures.join('; ')}).`;
throw new Error(
`Hook installation failed: ${error.message}. ${cleanup} Fix: rm -rf .husky/_ && git config core.hooksPath .husky/_ && pnpm install --frozen-lockfile`,
{ cause: error },
);
}
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
try {
await installHooks();
} catch (error) {
console.error(error.message);
process.exitCode = 1;
}
}
-208
View File
@@ -1,208 +0,0 @@
import assert from 'node:assert/strict';
import { access, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
import test from 'node:test';
import { installHooks } from './install-hooks.mjs';
const fixtureRoot = path.join(process.cwd(), '.mosaic-test-work', `hooks-${process.pid}`);
const quarantineRoot = path.join(fixtureRoot, 'quarantine');
async function fixture(name) {
const root = path.join(fixtureRoot, name);
await mkdir(path.join(root, '.husky'), { recursive: true });
return root;
}
async function exists(target) {
try {
await access(target);
return true;
} catch {
return false;
}
}
test.after(async () => {
await rm(fixtureRoot, { recursive: true, force: true });
});
test('an interrupted install quarantines the partial active hook set and fails loudly', async () => {
const root = await fixture('interrupted');
let restoredHooksPath = 'not-called';
await assert.rejects(
installHooks({
root,
quarantineRoot,
runHusky: async (stagingHooks) => {
await mkdir(path.join(stagingHooks, '_'), { recursive: true });
await writeFile(path.join(stagingHooks, '_', 'h'), 'partial');
throw new Error('simulated interruption');
},
activateHooks: async () => {},
readHooksPath: async () => null,
restoreHooksPath: async (value) => {
restoredHooksPath = value;
},
}),
(error) => {
assert.match(error.message, /Hook installation failed/);
assert.match(error.message, /pnpm install --frozen-lockfile/);
return true;
},
);
assert.equal(await exists(path.join(root, '.husky', '_')), false);
assert.equal(restoredHooksPath, 'not-called');
const quarantined = await readdir(quarantineRoot);
assert.equal(quarantined.length, 1);
});
test('a failed replacement restores a previously complete active hook set', async () => {
const root = await fixture('rollback');
const activeShim = path.join(root, '.husky', '_', 'h');
await mkdir(path.dirname(activeShim), { recursive: true });
await writeFile(activeShim, 'previous-complete');
let previousRemainedActiveDuringStaging = false;
await assert.rejects(
installHooks({
root,
quarantineRoot: path.join(fixtureRoot, 'rollback-quarantine'),
runHusky: async () => {
previousRemainedActiveDuringStaging =
(await readFile(activeShim, 'utf8')) === 'previous-complete';
throw new Error('simulated replacement failure');
},
activateHooks: async () => {},
readHooksPath: async () => '.husky/_',
restoreHooksPath: async () => {},
}),
/Hook installation failed/,
);
assert.equal(previousRemainedActiveDuringStaging, true);
assert.equal(await readFile(activeShim, 'utf8'), 'previous-complete');
});
test('a mismatched complete hook set fails loudly instead of reporting a stale install as current', async () => {
const root = await fixture('mismatch');
const activeShim = path.join(root, '.husky', '_', 'h');
await mkdir(path.dirname(activeShim), { recursive: true });
await writeFile(activeShim, 'old-complete');
await assert.rejects(
installHooks({
root,
quarantineRoot: path.join(fixtureRoot, 'mismatch-quarantine'),
runHusky: async (stagingHooks) => {
await mkdir(path.join(stagingHooks, '_'), { recursive: true });
await writeFile(path.join(stagingHooks, '_', 'h'), 'new-complete');
},
activateHooks: async () => {},
readHooksPath: async () => '.husky/_',
restoreHooksPath: async () => {},
}),
/Hook installation failed.*pnpm install --frozen-lockfile/,
);
assert.equal(await readFile(activeShim, 'utf8'), 'old-complete');
});
test('a competing successful installer is not removed by the losing process', async () => {
const root = await fixture('concurrent');
const activeShim = path.join(root, '.husky', '_', 'h');
let restored = false;
await assert.rejects(
installHooks({
root,
quarantineRoot: path.join(fixtureRoot, 'concurrent-quarantine'),
runHusky: async (stagingHooks) => {
await mkdir(path.join(stagingHooks, '_'), { recursive: true });
await writeFile(path.join(stagingHooks, '_', 'h'), 'ours');
await mkdir(path.dirname(activeShim), { recursive: true });
await writeFile(activeShim, 'peer');
},
activateHooks: async () => {},
readHooksPath: async () => null,
restoreHooksPath: async () => {
restored = true;
},
}),
/Hook installation failed/,
);
assert.equal(await readFile(activeShim, 'utf8'), 'peer');
assert.equal(restored, false);
});
test("a competing installer that replaces this installer's active set is preserved", async () => {
const root = await fixture('concurrent-after-rename');
const active = path.join(root, '.husky', '_');
const activeShim = path.join(active, 'h');
let restored = false;
await assert.rejects(
installHooks({
root,
quarantineRoot: path.join(fixtureRoot, 'concurrent-after-rename-quarantine'),
runHusky: async (stagingHooks) => {
await mkdir(path.join(stagingHooks, '_'), { recursive: true });
await writeFile(path.join(stagingHooks, '_', 'h'), 'ours');
},
activateHooks: async () => {
await rm(active, { recursive: true, force: true });
await mkdir(active, { recursive: true });
await writeFile(activeShim, 'peer');
throw new Error('our activation lost to peer');
},
readHooksPath: async () => null,
restoreHooksPath: async () => {
restored = true;
},
}),
/Hook installation failed/,
);
assert.equal(await readFile(activeShim, 'utf8'), 'peer');
assert.equal(restored, false);
});
test('an explicit interactive HUSKY=0 opt-out preserves existing hooks without running installer', async () => {
const root = await fixture('disabled');
const activeShim = path.join(root, '.husky', '_', 'h');
await mkdir(path.dirname(activeShim), { recursive: true });
await writeFile(activeShim, 'preserved');
let ran = false;
await installHooks({
root,
disabled: true,
runHusky: async () => {
ran = true;
},
});
assert.equal(ran, false);
assert.equal(await readFile(activeShim, 'utf8'), 'preserved');
});
test('a successful install leaves a complete active hook set', async () => {
const root = await fixture('success');
await installHooks({
root,
quarantineRoot,
runHusky: async (stagingHooks) => {
await mkdir(path.join(stagingHooks, '_'), { recursive: true });
await writeFile(path.join(stagingHooks, '_', 'h'), 'complete');
},
activateHooks: async () => {},
readHooksPath: async () => null,
restoreHooksPath: async () => {},
});
assert.equal(await exists(path.join(root, '.husky', '_', 'h')), true);
});
-254
View File
@@ -1,254 +0,0 @@
#!/usr/bin/env node
import { constants } from 'node:fs';
import { access, lstat, readFile, readdir, readlink } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
export const MISSING_DEPS_EXIT = 42;
export const GENERATED_STATE_EXIT = 43;
const scriptRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
async function entries(root) {
const result = [];
async function walk(current) {
let children;
try {
children = await readdir(current, { withFileTypes: true });
} catch (error) {
if (error.code === 'ENOENT') return;
throw error;
}
for (const child of children) {
const target = path.join(current, child.name);
result.push(target);
if (child.isDirectory() && !child.isSymbolicLink()) await walk(target);
}
}
await walk(root);
return result;
}
export async function generatedSymlinkManifest(nextDir) {
const links = [];
for (const target of (await entries(nextDir)).sort()) {
const stats = await lstat(target);
if (!stats.isSymbolicLink()) continue;
links.push({
path: path.relative(nextDir, target).split(path.sep).join('/'),
target: await readlink(target),
});
}
return `${JSON.stringify({ version: 1, links })}\n`;
}
const webSourceRoots = (root) => [
path.join(root, 'apps', 'web', 'src'),
path.join(root, 'apps', 'web', 'public'),
path.join(root, 'apps', 'web', 'next-env.d.ts'),
path.join(root, 'apps', 'web', 'next.config.ts'),
path.join(root, 'apps', 'web', 'postcss.config.mjs'),
path.join(root, 'apps', 'web', 'package.json'),
path.join(root, 'apps', 'web', 'tsconfig.json'),
path.join(root, 'packages', 'design-tokens', 'src'),
path.join(root, 'packages', 'design-tokens', 'package.json'),
path.join(root, 'packages', 'design-tokens', 'tsconfig.json'),
path.join(root, 'package.json'),
path.join(root, 'tsconfig.base.json'),
path.join(root, 'pnpm-lock.yaml'),
path.join(root, 'pnpm-workspace.yaml'),
path.join(root, 'turbo.json'),
];
// next.config.ts currently reads no server-only environment. Add any future
// server-side build inputs here; all resolved NEXT_PUBLIC_* inputs are automatic.
const serverBuildEnvironmentKeys = [];
function publicBuildEnvironment(root) {
const webDir = path.join(root, 'apps', 'web');
const requireFromWeb = createRequire(path.join(scriptRoot, 'apps', 'web', 'package.json'));
const requireFromNext = createRequire(requireFromWeb.resolve('next/package.json'));
const { loadEnvConfig, resetEnv, updateInitialEnv } = requireFromNext('@next/env');
const originalEnvironment = { ...process.env };
updateInitialEnv(originalEnvironment);
try {
const { combinedEnv } = loadEnvConfig(webDir, false, { info() {}, error() {} }, true);
return Object.fromEntries(
Object.entries(combinedEnv).filter(
([key, value]) =>
value !== undefined &&
(key.startsWith('NEXT_PUBLIC_') || serverBuildEnvironmentKeys.includes(key)),
),
);
} finally {
resetEnv();
}
}
export async function sourceFingerprint(root = process.cwd()) {
const files = [];
for (const sourceRoot of webSourceRoots(root)) {
try {
const stats = await lstat(sourceRoot);
if (stats.isSymbolicLink()) {
throw new Error(
`Web build input must not be a symbolic link: ${path.relative(root, sourceRoot)}`,
);
}
if (stats.isFile()) files.push(sourceRoot);
if (stats.isDirectory()) {
for (const target of await entries(sourceRoot)) {
const targetStats = await lstat(target);
if (targetStats.isSymbolicLink()) {
throw new Error(
`Web build input must not be a symbolic link: ${path.relative(root, target)}`,
);
}
if (targetStats.isFile()) files.push(target);
}
}
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
}
const digest = createHash('sha256');
for (const [key, value] of Object.entries(publicBuildEnvironment(root)).sort()) {
digest.update(`env:${key}\0${value.length}\0${value}\0`);
}
for (const target of files.sort()) {
const contents = await readFile(target);
digest.update(path.relative(root, target).split(path.sep).join('/'));
digest.update('\0');
digest.update(String(contents.length));
digest.update('\0');
digest.update(contents);
digest.update('\0');
}
return digest.digest('hex');
}
export async function runPreflight({ root = process.cwd(), uid = process.getuid?.() } = {}) {
const binDir = path.join(root, 'node_modules', '.bin');
const requiredBinaries = ['eslint', 'husky', 'prettier', 'tsc', 'turbo', 'vitest'];
const missingBinaries = [];
for (const binary of requiredBinaries) {
try {
await access(path.join(binDir, binary), constants.X_OK);
} catch {
missingBinaries.push(binary);
}
}
if (missingBinaries.length > 0) {
return {
code: MISSING_DEPS_EXIT,
message: `MOSAIC_PREFLIGHT_MISSING_DEPS: dependency installation is missing ${missingBinaries.join(', ')}; run pnpm install --frozen-lockfile`,
};
}
const buildLock = path.join(root, '.mosaic-test-work', 'web-build.lock');
try {
await lstat(buildLock);
return {
code: GENERATED_STATE_EXIT,
message: `MOSAIC_PREFLIGHT_GENERATED_STATE: web build is in progress or interrupted at ${buildLock}; wait for it to finish or rerun pnpm build to recover the stale lock`,
};
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
const nextDir = path.join(root, 'apps', 'web', '.next');
let generated = [];
try {
const nextStats = await lstat(nextDir);
if (!nextStats.isDirectory() || nextStats.isSymbolicLink()) {
return {
code: GENERATED_STATE_EXIT,
message:
'MOSAIC_PREFLIGHT_GENERATED_STATE: apps/web/.next must be a real directory, not a symbolic link, and is not trustworthy; run pnpm clean:generated, then rerun the gate',
};
}
generated = [nextDir, ...(await entries(nextDir))];
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
if (generated.length > 0) {
const foreign = [];
for (const target of generated) {
const stats = await lstat(target);
if (uid !== undefined && stats.uid !== uid) foreign.push(path.relative(root, target));
}
// Detects accidental, independent, stale, and foreign-residue mutation of
// generated state: the class this check was born from was a five-month-stale
// .next whose validator referenced deleted pages and produced 19 phantom TS2307
// errors indistinguishable from real type errors.
//
// Does NOT defend against an actor with same-UID write access to the generated
// tree, which can regenerate both the manifest and marker consistently
// (CWE-345). No local construction can, absent a trust anchor outside that
// actor's authority. RM-59 tracks executor/spine-side attestation.
let certification = null;
let certifiedManifest = null;
try {
const [certificationContents, manifestContents] = await Promise.all([
readFile(path.join(nextDir, '.mosaic-source-hash'), 'utf8'),
readFile(path.join(nextDir, '.mosaic-symlink-manifest'), 'utf8'),
]);
try {
const parsed = JSON.parse(certificationContents);
if (
parsed.version === 1 &&
typeof parsed.sourceFingerprint === 'string' &&
typeof parsed.symlinkManifestHash === 'string'
) {
certification = parsed;
certifiedManifest = manifestContents;
}
} catch {
// Invalid certification is handled as untrusted generated state below.
}
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
const stale = certification?.sourceFingerprint !== (await sourceFingerprint(root));
const actualManifest = await generatedSymlinkManifest(nextDir);
const certifiedManifestHash =
certifiedManifest === null
? null
: createHash('sha256').update(certifiedManifest).digest('hex');
const changedSymlinks =
certification?.symlinkManifestHash !== certifiedManifestHash ||
certifiedManifest !== actualManifest;
if (foreign.length > 0 || stale || changedSymlinks) {
const reasons = [
foreign.length > 0 ? `foreign-owned paths: ${foreign.slice(0, 3).join(', ')}` : '',
stale ? 'generated source fingerprint does not match web source/configuration' : '',
changedSymlinks
? 'generated symbolic-link manifest does not match the certified build'
: '',
].filter(Boolean);
return {
code: GENERATED_STATE_EXIT,
message: `MOSAIC_PREFLIGHT_GENERATED_STATE: apps/web/.next is not trustworthy (${reasons.join('; ')}); run pnpm clean:generated, then rerun the gate`,
};
}
}
return { code: 0, message: 'checkout preflight passed' };
}
async function main() {
const result = await runPreflight();
const stream = result.code === 0 ? process.stdout : process.stderr;
stream.write(`${result.message}\n`);
process.exitCode = result.code;
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
await main();
}
-274
View File
@@ -1,274 +0,0 @@
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { chmod, mkdir, rm, symlink, utimes, writeFile } from 'node:fs/promises';
import path from 'node:path';
import test from 'node:test';
import { runPreflight, sourceFingerprint } from './preflight.mjs';
const fixtureRoot = path.join(process.cwd(), '.mosaic-test-work', `preflight-${process.pid}`);
const requiredBins = ['eslint', 'husky', 'prettier', 'tsc', 'turbo', 'vitest'];
async function fixture(name) {
const root = path.join(fixtureRoot, name);
await mkdir(path.join(root, 'apps', 'web', 'src', 'app'), { recursive: true });
await writeFile(path.join(root, 'apps', 'web', 'src', 'app', 'page.tsx'), 'export default 1;\n');
return root;
}
async function installRequiredBins(root) {
const binDir = path.join(root, 'node_modules', '.bin');
await mkdir(binDir, { recursive: true });
await Promise.all(
requiredBins.map(async (name) => {
const target = path.join(binDir, name);
await writeFile(target, '');
await chmod(target, 0o755);
}),
);
}
async function certifyGeneratedState(root, links = []) {
const nextDir = path.join(root, 'apps', 'web', '.next');
await mkdir(nextDir, { recursive: true });
const manifest = `${JSON.stringify({ version: 1, links })}\n`;
const manifestHash = createHash('sha256').update(manifest).digest('hex');
await writeFile(path.join(nextDir, '.mosaic-symlink-manifest'), manifest);
await writeFile(
path.join(nextDir, '.mosaic-source-hash'),
`${JSON.stringify({
version: 1,
sourceFingerprint: await sourceFingerprint(root),
symlinkManifestHash: manifestHash,
})}\n`,
);
}
test.after(async () => {
await rm(fixtureRoot, { recursive: true, force: true });
});
test('missing dependencies have a dedicated exit code and install remediation', async () => {
const root = await fixture('missing-deps');
const result = await runPreflight({ root });
assert.equal(result.code, 42);
assert.match(result.message, /MOSAIC_PREFLIGHT_MISSING_DEPS/);
assert.match(result.message, /run pnpm install/i);
});
test('a partial dependency install keeps the dedicated missing-deps result', async () => {
const root = await fixture('partial-deps');
await mkdir(path.join(root, 'node_modules', '.bin'), { recursive: true });
await writeFile(path.join(root, 'node_modules', '.bin', 'tsc'), '', { mode: 0o755 });
const result = await runPreflight({ root });
assert.equal(result.code, 42);
assert.match(result.message, /turbo/);
});
test('a dangling required dependency shim keeps the dedicated missing-deps result', async () => {
const root = await fixture('dangling-deps');
await installRequiredBins(root);
const turbo = path.join(root, 'node_modules', '.bin', 'turbo');
await rm(turbo);
await symlink(path.join(root, 'node_modules', 'missing-turbo'), turbo);
const result = await runPreflight({ root });
assert.equal(result.code, 42);
assert.match(result.message, /turbo/);
});
test('installed dependencies pass when generated state is absent', async () => {
const root = await fixture('clean');
await installRequiredBins(root);
assert.deepEqual(await runPreflight({ root }), { code: 0, message: 'checkout preflight passed' });
});
test('foreign-owned generated Next state is identified separately from source errors', async () => {
const root = await fixture('foreign-next');
await installRequiredBins(root);
const generated = path.join(root, 'apps', 'web', '.next', 'types', 'validator.ts');
await mkdir(path.dirname(generated), { recursive: true });
await writeFile(generated, 'generated output');
const result = await runPreflight({ root, uid: (process.getuid?.() ?? 0) + 1 });
assert.equal(result.code, 43);
assert.match(result.message, /MOSAIC_PREFLIGHT_GENERATED_STATE/);
assert.match(result.message, /foreign-owned/);
});
test('a generated marker mismatch is identified separately from source errors', async () => {
const root = await fixture('stale-next');
await installRequiredBins(root);
const generated = path.join(root, 'apps', 'web', '.next', 'types', 'validator.ts');
await mkdir(path.dirname(generated), { recursive: true });
await writeFile(generated, 'stale generated output');
await writeFile(path.join(root, 'apps', 'web', '.next', '.mosaic-source-hash'), 'old-source');
const result = await runPreflight({ root });
assert.equal(result.code, 43);
assert.match(result.message, /MOSAIC_PREFLIGHT_GENERATED_STATE/);
assert.match(result.message, /apps\/web\/\.next/);
assert.match(result.message, /pnpm clean:generated/);
});
test('generated-state symbolic links are accepted only when exactly build-certified', async (t) => {
await t.test('apps/web/.next itself is rejected when it is a symbolic link', async () => {
const root = await fixture('symbolic-next-root');
await installRequiredBins(root);
await writeFile(path.join(root, 'outside-generated'), 'not a Next build\n');
await symlink(path.join(root, 'outside-generated'), path.join(root, 'apps', 'web', '.next'));
const result = await runPreflight({ root });
assert.equal(result.code, 43);
assert.match(result.message, /MOSAIC_PREFLIGHT_GENERATED_STATE/);
assert.match(result.message, /symbolic link/);
});
await t.test('apps/web/.next is rejected when it is not a directory', async () => {
const root = await fixture('non-directory-next-root');
await installRequiredBins(root);
await writeFile(path.join(root, 'apps', 'web', '.next'), 'not a Next build\n');
const result = await runPreflight({ root });
assert.equal(result.code, 43);
assert.match(result.message, /MOSAIC_PREFLIGHT_GENERATED_STATE/);
assert.match(result.message, /real directory/);
});
await t.test('an added descendant symlink is rejected', async () => {
const root = await fixture('symbolic-next-added');
await installRequiredBins(root);
await certifyGeneratedState(root);
await symlink('/etc/hosts', path.join(root, 'apps', 'web', '.next', 'reviewer-symlink'));
const result = await runPreflight({ root });
assert.equal(result.code, 43);
assert.match(result.message, /symbolic-link manifest/);
});
await t.test('a removed certified descendant symlink is rejected', async () => {
const root = await fixture('symbolic-next-removed');
await installRequiredBins(root);
const link = path.join(root, 'apps', 'web', '.next', 'dependency-link');
await mkdir(path.dirname(link), { recursive: true });
await symlink('../dependency-one', link);
await certifyGeneratedState(root, [{ path: 'dependency-link', target: '../dependency-one' }]);
await rm(link);
const result = await runPreflight({ root });
assert.equal(result.code, 43);
assert.match(result.message, /symbolic-link manifest/);
});
await t.test('a retargeted certified descendant symlink is rejected', async () => {
const root = await fixture('symbolic-next-retargeted');
await installRequiredBins(root);
const link = path.join(root, 'apps', 'web', '.next', 'dependency-link');
await mkdir(path.dirname(link), { recursive: true });
await symlink('../dependency-one', link);
await certifyGeneratedState(root, [{ path: 'dependency-link', target: '../dependency-one' }]);
await rm(link);
await symlink('../dependency-two', link);
const result = await runPreflight({ root });
assert.equal(result.code, 43);
assert.match(result.message, /symbolic-link manifest/);
});
await t.test('a manifest edited to whitelist a rogue symlink is rejected', async () => {
const root = await fixture('symbolic-next-tampered-manifest');
await installRequiredBins(root);
await certifyGeneratedState(root);
const nextDir = path.join(root, 'apps', 'web', '.next');
await symlink('/etc/hosts', path.join(nextDir, 'reviewer-symlink'));
await writeFile(
path.join(nextDir, '.mosaic-symlink-manifest'),
`${JSON.stringify({
version: 1,
links: [{ path: 'reviewer-symlink', target: '/etc/hosts' }],
})}\n`,
);
const result = await runPreflight({ root });
assert.equal(result.code, 43);
assert.match(result.message, /symbolic-link manifest/);
});
await t.test('unchanged canonical-style descendant symlinks are accepted', async () => {
const root = await fixture('symbolic-next-certified');
await installRequiredBins(root);
const link = path.join(
root,
'apps',
'web',
'.next',
'standalone',
'node_modules',
'dependency',
);
await mkdir(path.dirname(link), { recursive: true });
await symlink('../.pnpm/dependency', link);
await certifyGeneratedState(root, [
{ path: 'standalone/node_modules/dependency', target: '../.pnpm/dependency' },
]);
assert.deepEqual(await runPreflight({ root }), {
code: 0,
message: 'checkout preflight passed',
});
});
});
test('the source fingerprint includes inherited TypeScript configuration', async () => {
const root = await fixture('inherited-typescript-config');
const config = path.join(root, 'tsconfig.base.json');
await writeFile(config, '{"compilerOptions":{"strict":true}}\n');
const first = await sourceFingerprint(root);
await writeFile(config, '{"compilerOptions":{"strict":false}}\n');
const second = await sourceFingerprint(root);
assert.notEqual(first, second);
});
test('the source fingerprint rejects symbolic-link build inputs', async () => {
const root = await fixture('symbolic-source');
await writeFile(path.join(root, 'outside.ts'), 'export default 1;\n');
await symlink(path.join(root, 'outside.ts'), path.join(root, 'apps', 'web', 'src', 'linked.ts'));
await assert.rejects(sourceFingerprint(root), /must not be a symbolic link/);
});
test('the source fingerprint includes expanded public web build environment', async () => {
const root = await fixture('public-build-environment');
const envFile = path.join(root, 'apps', 'web', '.env.production');
await writeFile(
envFile,
'RM01_GATEWAY_URL=https://one.example\nNEXT_PUBLIC_RM01_URL=$RM01_GATEWAY_URL\n',
);
const first = await sourceFingerprint(root);
await writeFile(
envFile,
'RM01_GATEWAY_URL=https://two.example\nNEXT_PUBLIC_RM01_URL=$RM01_GATEWAY_URL\n',
);
const second = await sourceFingerprint(root);
assert.notEqual(first, second);
});
test('a matching generation marker accepts incremental output with mixed mtimes', async () => {
const root = await fixture('incremental-next');
await installRequiredBins(root);
const generated = path.join(root, 'apps', 'web', '.next', 'types', 'validator.ts');
await mkdir(path.dirname(generated), { recursive: true });
await writeFile(generated, 'unchanged generated output');
await utimes(generated, new Date('2020-01-01T00:00:00Z'), new Date('2020-01-01T00:00:00Z'));
const fresh = path.join(root, 'apps', 'web', '.next', 'types', 'routes.ts');
await writeFile(fresh, 'fresh generated output');
await certifyGeneratedState(root);
assert.deepEqual(await runPreflight({ root }), { code: 0, message: 'checkout preflight passed' });
});