@warpgogol/forge 9.7.0 → 9.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/dist/os/adr/handlers/archive.d.ts.map +1 -1
  3. package/dist/os/adr/handlers/archive.js +3 -7
  4. package/dist/os/adr/handlers/archive.js.map +1 -1
  5. package/dist/os/adr/handlers/list-create.d.ts.map +1 -1
  6. package/dist/os/adr/handlers/list-create.js +8 -6
  7. package/dist/os/adr/handlers/list-create.js.map +1 -1
  8. package/dist/os/audit/handlers/archive.d.ts.map +1 -1
  9. package/dist/os/audit/handlers/archive.js +3 -7
  10. package/dist/os/audit/handlers/archive.js.map +1 -1
  11. package/dist/os/core/archive-regen.d.ts +1 -0
  12. package/dist/os/core/archive-regen.d.ts.map +1 -1
  13. package/dist/os/core/archive-regen.js +31 -6
  14. package/dist/os/core/archive-regen.js.map +1 -1
  15. package/dist/os/core/core.module.d.ts.map +1 -1
  16. package/dist/os/core/core.module.js +5 -0
  17. package/dist/os/core/core.module.js.map +1 -1
  18. package/dist/os/core/handlers/pinned-check.d.ts +13 -0
  19. package/dist/os/core/handlers/pinned-check.d.ts.map +1 -1
  20. package/dist/os/core/handlers/pinned-check.js +25 -0
  21. package/dist/os/core/handlers/pinned-check.js.map +1 -1
  22. package/dist/os/core/handlers/pinned-types.d.ts +7 -0
  23. package/dist/os/core/handlers/pinned-types.d.ts.map +1 -1
  24. package/dist/os/core/handlers/pinned-validate.d.ts.map +1 -1
  25. package/dist/os/core/handlers/pinned-validate.js +24 -1
  26. package/dist/os/core/handlers/pinned-validate.js.map +1 -1
  27. package/dist/os/flow/digest.d.ts +73 -1
  28. package/dist/os/flow/digest.d.ts.map +1 -1
  29. package/dist/os/flow/digest.js +344 -92
  30. package/dist/os/flow/digest.js.map +1 -1
  31. package/dist/os/flow/evidence-lock.d.ts +36 -0
  32. package/dist/os/flow/evidence-lock.d.ts.map +1 -0
  33. package/dist/os/flow/evidence-lock.js +156 -0
  34. package/dist/os/flow/evidence-lock.js.map +1 -0
  35. package/dist/os/flow/flow.module.d.ts.map +1 -1
  36. package/dist/os/flow/flow.module.js +36 -14
  37. package/dist/os/flow/flow.module.js.map +1 -1
  38. package/dist/os/flow/git.d.ts +50 -3
  39. package/dist/os/flow/git.d.ts.map +1 -1
  40. package/dist/os/flow/git.js +144 -12
  41. package/dist/os/flow/git.js.map +1 -1
  42. package/dist/os/flow/handlers/flow-digest.d.ts.map +1 -1
  43. package/dist/os/flow/handlers/flow-digest.js +3 -5
  44. package/dist/os/flow/handlers/flow-digest.js.map +1 -1
  45. package/dist/os/flow/handlers/flow-push.d.ts +81 -0
  46. package/dist/os/flow/handlers/flow-push.d.ts.map +1 -1
  47. package/dist/os/flow/handlers/flow-push.js +642 -138
  48. package/dist/os/flow/handlers/flow-push.js.map +1 -1
  49. package/dist/os/flow/locks.d.ts +8 -0
  50. package/dist/os/flow/locks.d.ts.map +1 -1
  51. package/dist/os/flow/locks.js +6 -3
  52. package/dist/os/flow/locks.js.map +1 -1
  53. package/dist/os/flow/preflight.d.ts.map +1 -1
  54. package/dist/os/flow/preflight.js +4 -2
  55. package/dist/os/flow/preflight.js.map +1 -1
  56. package/dist/os/flow/registry.d.ts +9 -5
  57. package/dist/os/flow/registry.d.ts.map +1 -1
  58. package/dist/os/flow/registry.js +2 -2
  59. package/dist/os/flow/registry.js.map +1 -1
  60. package/dist/os/friction/friction.module.d.ts.map +1 -1
  61. package/dist/os/friction/friction.module.js +30 -5
  62. package/dist/os/friction/friction.module.js.map +1 -1
  63. package/dist/os/friction/handlers/friction-add.d.ts.map +1 -1
  64. package/dist/os/friction/handlers/friction-add.js +10 -17
  65. package/dist/os/friction/handlers/friction-add.js.map +1 -1
  66. package/dist/os/friction/handlers/friction-migrate.d.ts.map +1 -1
  67. package/dist/os/friction/handlers/friction-migrate.js +188 -2
  68. package/dist/os/friction/handlers/friction-migrate.js.map +1 -1
  69. package/dist/os/friction/store.d.ts +4 -0
  70. package/dist/os/friction/store.d.ts.map +1 -1
  71. package/dist/os/friction/store.js +20 -0
  72. package/dist/os/friction/store.js.map +1 -1
  73. package/dist/os/friction/types.d.ts +12 -0
  74. package/dist/os/friction/types.d.ts.map +1 -1
  75. package/dist/os/friction/types.js +8 -0
  76. package/dist/os/friction/types.js.map +1 -1
  77. package/dist/os/gate/handlers/gate-probe-catalog.d.ts.map +1 -1
  78. package/dist/os/gate/handlers/gate-probe-catalog.js +38 -5
  79. package/dist/os/gate/handlers/gate-probe-catalog.js.map +1 -1
  80. package/dist/os/mission/handlers/archive.d.ts.map +1 -1
  81. package/dist/os/mission/handlers/archive.js +3 -7
  82. package/dist/os/mission/handlers/archive.js.map +1 -1
  83. package/dist/os/plan/handlers/archive.d.ts.map +1 -1
  84. package/dist/os/plan/handlers/archive.js +3 -7
  85. package/dist/os/plan/handlers/archive.js.map +1 -1
  86. package/dist/os/rfc/handlers/archive.d.ts.map +1 -1
  87. package/dist/os/rfc/handlers/archive.js +3 -7
  88. package/dist/os/rfc/handlers/archive.js.map +1 -1
  89. package/dist/os/rfc/handlers/list-create.d.ts.map +1 -1
  90. package/dist/os/rfc/handlers/list-create.js +15 -7
  91. package/dist/os/rfc/handlers/list-create.js.map +1 -1
  92. package/dist/os/session/handlers/archive.d.ts.map +1 -1
  93. package/dist/os/session/handlers/archive.js +3 -7
  94. package/dist/os/session/handlers/archive.js.map +1 -1
  95. package/dist/os/system/handlers/system-product-register.d.ts +24 -0
  96. package/dist/os/system/handlers/system-product-register.d.ts.map +1 -0
  97. package/dist/os/system/handlers/system-product-register.js +322 -0
  98. package/dist/os/system/handlers/system-product-register.js.map +1 -0
  99. package/dist/os/system/handlers/system-products-status.d.ts +23 -0
  100. package/dist/os/system/handlers/system-products-status.d.ts.map +1 -0
  101. package/dist/os/system/handlers/system-products-status.js +235 -0
  102. package/dist/os/system/handlers/system-products-status.js.map +1 -0
  103. package/dist/os/system/schemas.d.ts +13 -0
  104. package/dist/os/system/schemas.d.ts.map +1 -1
  105. package/dist/os/system/schemas.js +15 -0
  106. package/dist/os/system/schemas.js.map +1 -1
  107. package/dist/os/system/system.module.d.ts.map +1 -1
  108. package/dist/os/system/system.module.js +113 -3
  109. package/dist/os/system/system.module.js.map +1 -1
  110. package/dist/src/config/forge-config.d.ts +2 -0
  111. package/dist/src/config/forge-config.d.ts.map +1 -1
  112. package/dist/src/config/forge-config.js +11 -10
  113. package/dist/src/config/forge-config.js.map +1 -1
  114. package/dist/src/onboarding/create.d.ts.map +1 -1
  115. package/dist/src/onboarding/create.js +27 -2
  116. package/dist/src/onboarding/create.js.map +1 -1
  117. package/dist/src/profiles/stack-profile.js +2 -2
  118. package/dist/src/types.js +2 -2
  119. package/dist/src/utils/verifier-git.d.ts +27 -1
  120. package/dist/src/utils/verifier-git.d.ts.map +1 -1
  121. package/dist/src/utils/verifier-git.js +36 -6
  122. package/dist/src/utils/verifier-git.js.map +1 -1
  123. package/docs/reference/system-hub.md +104 -0
  124. package/os/adr/handlers/archive.ts +3 -11
  125. package/os/adr/handlers/list-create.test.ts +174 -0
  126. package/os/adr/handlers/list-create.ts +16 -8
  127. package/os/audit/handlers/archive.ts +3 -11
  128. package/os/core/archive-regen.ts +33 -7
  129. package/os/core/core.module.ts +7 -0
  130. package/os/core/docs-archive.test.ts +25 -0
  131. package/os/core/handlers/pinned-check.ts +30 -0
  132. package/os/core/handlers/pinned-types.ts +7 -0
  133. package/os/core/handlers/pinned-validate.ts +28 -3
  134. package/os/flow/digest.ts +436 -95
  135. package/os/flow/evidence-lock.ts +184 -0
  136. package/os/flow/flow.module.ts +37 -14
  137. package/os/flow/git.ts +206 -11
  138. package/os/flow/handlers/flow-digest.ts +12 -8
  139. package/os/flow/handlers/flow-push.ts +725 -137
  140. package/os/flow/locks.ts +24 -7
  141. package/os/flow/preflight.ts +4 -2
  142. package/os/flow/registry.ts +7 -3
  143. package/os/flow/tests/digest-id-inputs.test.ts +106 -0
  144. package/os/flow/tests/digest-persist.test.ts +243 -0
  145. package/os/flow/tests/evidence-preflight-surface-skip.test.ts +218 -0
  146. package/os/flow/tests/flow-push-attest.test.ts +137 -0
  147. package/os/flow/tests/flow-push-review-baseline.test.ts +339 -0
  148. package/os/flow/tests/flow-push-verifier-batch.test.ts +134 -0
  149. package/os/friction/friction-add.test.ts +42 -0
  150. package/os/friction/friction-migrate.test.ts +67 -2
  151. package/os/friction/friction.module.ts +33 -5
  152. package/os/friction/handlers/friction-add.ts +10 -15
  153. package/os/friction/handlers/friction-migrate.ts +220 -1
  154. package/os/friction/store.ts +19 -0
  155. package/os/friction/types.ts +8 -0
  156. package/os/gate/handlers/gate-probe-catalog.ts +39 -7
  157. package/os/gate/handlers/gate-probe-ratchet.test.ts +57 -22
  158. package/os/mission/handlers/archive.ts +3 -11
  159. package/os/plan/handlers/archive.ts +3 -11
  160. package/os/rfc/handlers/archive.ts +3 -11
  161. package/os/rfc/handlers/list-create.ts +22 -17
  162. package/os/session/handlers/archive.ts +3 -11
  163. package/os/system/handlers/system-product-register.ts +492 -0
  164. package/os/system/handlers/system-products-status.ts +395 -0
  165. package/os/system/schemas.ts +17 -0
  166. package/os/system/system.module.ts +117 -3
  167. package/os/system/tests/system-product-register.test.ts +304 -0
  168. package/os/system/tests/system-products-status.test.ts +154 -0
  169. package/package.json +1 -1
  170. package/profiles/root-agents-system.md +82 -0
  171. package/profiles/system.yaml +1 -0
  172. package/src/config/forge-config.ts +16 -11
  173. package/src/onboarding/create-superfolder-guard.test.ts +73 -0
  174. package/src/onboarding/create.ts +28 -2
  175. package/src/profiles/stack-profile.ts +2 -2
  176. package/src/tests/evidence-consult-serialization.test.ts +202 -0
  177. package/src/tests/pinned-validate.test.ts +194 -0
  178. package/src/tests/profile-flow-hooks.test.ts +1 -0
  179. package/src/tests/profile-schema.test.ts +1 -0
  180. package/src/tests/stack-profile.test.ts +1 -0
  181. package/src/types.ts +2 -2
  182. package/src/utils/verifier-git.ts +53 -5
@@ -17,63 +17,19 @@ path.</purpose>
17
17
  <item>Publication failures are FLOW-PUSH-05 per tag; the command continues with the next tag and exits non-zero at the end.</item>
18
18
  </KEY_DECISIONS>
19
19
  <CHANGE_SUMMARY>
20
- <item>RFC-1616: close RFC-1616 r5 trust-boundary counterexamples</item>
21
- <item>RFC-1616: close RFC-1616 r7 trust-boundary counterexamples
22
-
23
- Independent clean-context verification (round 7, candidate d2f270ad6)
24
- returned REFUTED with eleven live counterexamples against the
25
- r6-hardened evidence channel — this commit closes all nine root causes.
26
-
27
- - remote.<name>.fetch is value-judged: only the clone-default
28
- +?refs/heads/*:refs/remotes/<name>/* shape stays KEEP, because git
29
- UNIONs configured refspecs with the pinned fetch argv and a session
30
- spec writes arbitrary local refs inside the trusted fetch (CX-94).
31
- remote.<name>.tagopt|promirror|followremotehead|prunetags|
32
- skipfetchall|mirror move to REFUSE for the same reason.
33
- - Alternates/shape comment lexing is col-0 `#` only — git's parser does
34
- not treat whitespace-led `#` as a comment, so ` # forged` is a real
35
- alternates path the shape check must count (CX-95).
36
- - config reads forbid the alternate-source selectors --file/-f, --blob,
37
- --worktree (reaches config.worktree even under the disabled-extension
38
- pin), --system/--global, --default and --includes, plus the
39
- write-action spellings, on both the evidence and shared read-only
40
- tables (CX-96).
41
- - verifierGit judges fabrication argv on the runner/policy channel:
42
- @{...}, -g, --reflog, --walk-reflogs and --fork-point return
43
- EVIDENCE-REFUSED before the spawn — policy.digest --base 'HEAD@{0}'
44
- can no longer verify an unattested advance (CX-97).
45
- - --use-bitmap-index/--test-bitmap are forbidden on rev-list/log in
46
- both tables — the flag opts the trusted walk into the session-
47
- writable pack bitmap cache the commitGraph/MIDX pins closed (CX-98).
48
- - for-each-ref/show-ref/ls-remote forbid --stdin and --exclude-existing
49
- on both tables — they block on input the no-stdin spawn never
50
- supplies (CX-101).
51
- - The workflow-adoption heredoc lexer is bash-faithful: openers are
52
- scanned on the raw line before the # comment strip (quoted-#
53
- delimiters, CX-99a), bare delimiters accept digits/./- (CX-99b), and
54
- the terminator match is strict — << wants the delimiter alone, <<-/
55
- <<~ skip leading tabs only (CX-100).
56
- - Trailer scans read %e beside %(trailers): a commit declaring a
57
- non-UTF-8 encoding header recodes every trusted message read, so the
58
- digest trail and the push-time scan flag it as unverifiable and the
59
- policy attestation scan skips it (CX-102).
60
-
61
- Probe premise updates for the tightened contract: CX-61's decoy
62
- remote.origin.fetch (cx4 and cx5 R5-R1) now asserts the wholesale
63
- EVIDENCE-REFUSED plus FLOW-PUSH-13 refuse — strictly stronger than the
64
- decoy-namespace guard it replaces. The independent r7 probe file and
65
- acceptance report land in the follow-up port commit.</item>
66
- <item>RFC-1616: close RFC-1616 r12 trust-boundary counterexamples</item>
67
- <item>RFC-1616: close RFC-1616 r13 trust-boundary counterexamples</item>
68
20
  <item>RFC-1616: close r21 counterexample CX-179 + push-scan refusal polarity</item>
21
+ <item>RFC-1633: serialize evidence consults + bestEffort reader mode (RFC-1633)</item>
22
+ <item>RFC-1638: persist reviewed digests + attest pushed state by input hash</item>
23
+ <item>RFC-1638: review round 1 — payload preimage binding, fail-closed coverage scan, FLOW-PUSH-15</item>
24
+ <item>RFC-1643: committed verifier-review baseline for flow.push</item>
69
25
  <history>RFC-1491, RFC-1501, RFC-1503, RFC-1616</history>
70
26
  </CHANGE_SUMMARY>
71
27
  */
72
28
  import { join } from "node:path";
73
29
  import { resolveIo } from "../../../src/utils/io.js";
74
30
  import { parse as parseYaml } from "yaml";
75
- import { collectDigest, lineForTag, versionOfTag } from "../digest.js";
76
- import { git, gitEvidence, parseGitTrailers, requireGit, verifierTopLevel } from "../git.js";
31
+ import { collectDigest, digestInputHash, lineForTag, loadPersistedDigest, observeDigestInputs, recomputePersistedDigestId, versionOfTag, } from "../digest.js";
32
+ import { assertJudgedEvidence, git, gitEvidence, parseGitTrailers, requireGit, verifierTopLevel, } from "../git.js";
77
33
  import { EVIDENCE_REFUSED_PREFIX } from "../../../src/utils/verifier-git.js";
78
34
  import { markerIsValid } from "../markers.js";
79
35
  import { publishTag, tagAnnotationLevel } from "../publish.js";
@@ -105,77 +61,438 @@ function refuse(ruleId, message, fixHint) {
105
61
  */
106
62
  /**
107
63
  * RFC-1616 (AC-6): list commits in `range` whose message carries a verifier /
108
- * audit trailer. Reads are delimiter-free: commit SHAs enumerate via
109
- * `rev-list` (hex-only output) and each commit's trailers arrive through
110
- * git's OWN `%(trailers:only)` parser — \x1e framing cannot hide a record
111
- * (CX-33), and `x-verifier-report:`/`X-Verifier-Report :` spellings count
112
- * exactly as `git interpret-trailers` counts them (CX-60). The channel is
64
+ * audit trailer. Commit SHAs enumerate via `rev-list` (hex-only output) and
65
+ * each commit's trailers arrive through git's OWN `%(trailers:only)` parser —
66
+ * `x-verifier-report:`/`X-Verifier-Report :` spellings count exactly as
67
+ * `git interpret-trailers` counts them (CX-60). The channel is
113
68
  * `gitEvidence`: session GIT_* variables and refs/replace cannot redirect
114
69
  * or substitute what the scan sees (CX-48).
70
+ *
71
+ * F-0394: the range is the whole local branch (CX-82/CX-132), and every
72
+ * judged consult re-runs the full evidence preflight (seconds each), so a
73
+ * per-commit read pair walked tens of thousands of consults — ~85 h on an
74
+ * 18k-commit repo. The scan now reads the range in TWO batched judged
75
+ * consults (`batchedCommitReads`) and falls back to the exact per-commit
76
+ * reads whenever the batch cannot be proven to frame one record per
77
+ * enumerated sha (CX-33) — the per-record judgment is byte-identical on
78
+ * both paths.
115
79
  */
116
80
  async function scanVerifierTrailers(repoRoot, io, range) {
117
81
  const list = await gitEvidence(repoRoot, ["rev-list", range]);
82
+ assertJudgedEvidence(list);
118
83
  // Any failure on an enumerable range is unverifiable — `[]` would run
119
84
  // the trailer scan over nothing (CX-174's shape inside the push gate
120
85
  // itself); null lets the caller refuse loudly.
121
86
  if (list.exitCode !== 0)
122
87
  return null;
88
+ const shas = list.stdout
89
+ .split("\n")
90
+ .map((s) => s.trim())
91
+ .filter(Boolean);
92
+ if (shas.length === 0)
93
+ return [];
94
+ const batched = await batchedCommitReads(repoRoot, range, shas);
95
+ const hits = [];
96
+ for (const sha of shas) {
97
+ const reads = batched?.get(sha) ?? (await perCommitReads(repoRoot, sha));
98
+ const found = judgeVerifierTrailers(reads);
99
+ if (found.length > 0)
100
+ hits.push({ sha, trailers: found });
101
+ }
102
+ return hits;
103
+ }
104
+ const TRAILER_READ_FORMAT = "%(trailers:only,separator=%x00)%x00%e";
105
+ /** The exact pre-F-0394 per-commit reads — two judged consults per sha. */
106
+ async function perCommitReads(repoRoot, sha) {
107
+ // `%e` rides along — a commit declaring a non-default `encoding:`
108
+ // header RECODES this very output, so %(trailers) over it is already
109
+ // garbage: the header lives in the object and no -c pin reaches it
110
+ // (CX-102). An encoded commit's trailers are unverifiable — flag it.
111
+ const parsed = await gitEvidence(repoRoot, ["log", "-1", `--format=${TRAILER_READ_FORMAT}`, sha]);
112
+ assertJudgedEvidence(parsed);
113
+ // `%s` is one line — no delimiter to smuggle.
114
+ const subj = await gitEvidence(repoRoot, ["log", "-1", "--format=%s", sha]);
115
+ assertJudgedEvidence(subj);
116
+ return {
117
+ trailers: parsed.exitCode === 0 ? parsed.stdout : null,
118
+ subject: subj.exitCode === 0 ? subj.stdout : null,
119
+ };
120
+ }
121
+ /**
122
+ * F-0394: both reads for every commit of `range` in two judged consults.
123
+ * Each record is `\x1e<sha>\x00<per-commit read output>` — the payload
124
+ * after the sha prefix is exactly what `perCommitReads` would have read.
125
+ * A \x1e or forged `<sha>\x00` inside a message can only ADD records
126
+ * (separators are never consumed), so the batch is accepted only when
127
+ * every record carries an enumerated sha, no sha repeats, and the record
128
+ * count equals the `rev-list` count (CX-33). Any mismatch, failure or
129
+ * refusal returns null and the caller reads per commit — slow but exact,
130
+ * never a narrower scan.
131
+ */
132
+ export async function batchedCommitReads(repoRoot, range, shas) {
133
+ const trailerRecords = await batchedRecords(repoRoot, range, TRAILER_READ_FORMAT, shas);
134
+ if (trailerRecords === null)
135
+ return null;
136
+ const subjectRecords = await batchedRecords(repoRoot, range, "%s", shas);
137
+ if (subjectRecords === null)
138
+ return null;
139
+ const out = new Map();
140
+ for (const sha of shas) {
141
+ out.set(sha, { trailers: trailerRecords.get(sha), subject: subjectRecords.get(sha) });
142
+ }
143
+ return out;
144
+ }
145
+ async function batchedRecords(repoRoot, range, format, shas) {
146
+ const r = await gitEvidence(repoRoot, ["log", `--format=%x1e%H%x00${format}`, range]);
147
+ assertJudgedEvidence(r);
148
+ if (r.exitCode !== 0)
149
+ return null;
150
+ const expected = new Set(shas);
151
+ const parts = r.stdout.split("\x1e");
152
+ // The output starts with the separator — anything before it is foreign.
153
+ if (parts.shift() !== "")
154
+ return null;
155
+ if (parts.length !== expected.size)
156
+ return null;
157
+ const records = new Map();
158
+ for (const part of parts) {
159
+ const nul = part.indexOf("\x00");
160
+ if (nul <= 0)
161
+ return null;
162
+ const sha = part.slice(0, nul);
163
+ if (!expected.has(sha) || records.has(sha))
164
+ return null;
165
+ records.set(sha, part.slice(nul + 1));
166
+ }
167
+ return records.size === expected.size ? records : null;
168
+ }
169
+ /** Verifier/audit trailers one commit's reads carry, sorted; [] = clean. */
170
+ function judgeVerifierTrailers(reads) {
123
171
  const wanted = new Set(VERIFIER_TRAILERS.map((t) => t.toLowerCase()));
124
172
  const canonical = new Map(VERIFIER_TRAILERS.map((t) => [t.toLowerCase(), t]));
125
- const hits = [];
126
- for (const sha of list.stdout
173
+ if (reads.trailers === null) {
174
+ // An enumerated commit whose trailer read fails is unverifiable —
175
+ // flag it like the encoding case instead of silently dropping its
176
+ // provenance under a surgical refusal.
177
+ return ["x-unverifiable-commit"];
178
+ }
179
+ const parsedParts = reads.trailers.split("\x00");
180
+ const declaredEncoding = (parsedParts.pop() ?? "").trim();
181
+ const found = new Set();
182
+ if (declaredEncoding.length > 0 && !/^utf-?8$/i.test(declaredEncoding)) {
183
+ found.add(`x-unverifiable-encoding: ${declaredEncoding}`);
184
+ }
185
+ for (const t of parseGitTrailers(parsedParts.join("\x00").replaceAll("\x00", "\n"))) {
186
+ const c = canonical.get(t.key);
187
+ if (wanted.has(t.key) && c && t.value.length > 0)
188
+ found.add(c);
189
+ }
190
+ // A trailer-shaped SUBJECT is not a git trailer on every version — but it
191
+ // looks exactly like provenance text, so flag it anyway (stricter is
192
+ // safe, CX-23).
193
+ if (reads.subject !== null) {
194
+ const m = /^([^:\s][^:]*?)\s*:\s*(.*)$/.exec(reads.subject.trim());
195
+ if (m) {
196
+ const c = canonical.get(m[1].trim().toLowerCase());
197
+ if (c && m[2].trim().length > 0)
198
+ found.add(c);
199
+ }
200
+ }
201
+ else {
202
+ // The subject-shaped-trailer check could not run — flag the sha
203
+ // rather than assume no trailer-shaped subject.
204
+ found.add("x-unverifiable-commit");
205
+ }
206
+ return [...found].sort();
207
+ }
208
+ async function readCommittedForgeDoc(repoRoot, rev) {
209
+ const show = await gitEvidence(repoRoot, ["show", `${rev}:forge.yaml`]);
210
+ assertJudgedEvidence(show);
211
+ if (show.exitCode === -1)
212
+ return { kind: "unverifiable" };
213
+ if (show.exitCode !== 0)
214
+ return { kind: "missing" };
215
+ try {
216
+ // `yaml` rejects duplicate keys by default — a shadowed `push:` block
217
+ // is a parse error, never a silently-chosen winner.
218
+ const doc = parseYaml(show.stdout);
219
+ return {
220
+ kind: "doc",
221
+ doc: typeof doc === "object" && doc !== null ? doc : null,
222
+ raw: show.stdout,
223
+ };
224
+ }
225
+ catch {
226
+ return { kind: "unparsable", raw: show.stdout };
227
+ }
228
+ }
229
+ function pushSection(doc) {
230
+ const push = doc?.["push"];
231
+ return typeof push === "object" && push !== null && !Array.isArray(push)
232
+ ? push
233
+ : undefined;
234
+ }
235
+ /** The raw declared baseline in a committed doc — `undefined` when absent. */
236
+ function declaredBaseline(doc) {
237
+ if (doc.kind !== "doc")
238
+ return undefined;
239
+ const v = pushSection(doc.doc)?.["verifierReviewedThrough"];
240
+ return v === null ? undefined : v;
241
+ }
242
+ /**
243
+ * RFC-1643: judge `push.verifierReviewedThrough` from the committed
244
+ * forge.yaml at the digest-reviewed develop tip. Every read is a judged
245
+ * consult; every failure exempts nothing (fail closed). Only a full,
246
+ * lower-case object name of the repository's format that names a commit
247
+ * reachable from `refs/heads/develop` (re-read, must equal `developTip`)
248
+ * is `applied`.
249
+ */
250
+ export async function resolveVerifierReviewBaseline(repoRoot, developTip, committed) {
251
+ if (committed.kind === "unverifiable") {
252
+ return { status: "unusable", declared: "", reason: "unverifiable" };
253
+ }
254
+ if (committed.kind === "missing")
255
+ return { status: "absent" };
256
+ if (committed.kind === "unparsable") {
257
+ return committed.raw.includes("verifierReviewedThrough")
258
+ ? { status: "unusable", declared: "", reason: "malformed" }
259
+ : { status: "absent" };
260
+ }
261
+ const raw = declaredBaseline(committed);
262
+ if (raw === undefined)
263
+ return { status: "absent" };
264
+ if (typeof raw !== "string") {
265
+ return { status: "unusable", declared: String(raw), reason: "malformed" };
266
+ }
267
+ const unusable = (reason) => ({
268
+ status: "unusable",
269
+ declared: raw,
270
+ reason,
271
+ });
272
+ const fmt = await gitEvidence(repoRoot, ["rev-parse", "--show-object-format"]);
273
+ assertJudgedEvidence(fmt);
274
+ if (fmt.exitCode !== 0)
275
+ return unusable("unverifiable");
276
+ const hexLen = fmt.stdout.trim() === "sha256" ? 64 : 40;
277
+ if (!new RegExp(`^[0-9a-f]{${hexLen}}$`).test(raw))
278
+ return unusable("malformed");
279
+ // The develop tip the baseline is judged against must still be the
280
+ // fully-qualified local branch — a persisted digest from a bare-name
281
+ // resolution, or a shadow ref, must not anchor the ancestry check.
282
+ const tip = await gitEvidence(repoRoot, [
283
+ "rev-parse",
284
+ "--verify",
285
+ "--quiet",
286
+ "refs/heads/develop",
287
+ ]);
288
+ assertJudgedEvidence(tip);
289
+ if (tip.exitCode !== 0 || tip.stdout.trim() !== developTip)
290
+ return unusable("unverifiable");
291
+ const peeled = await gitEvidence(repoRoot, [
292
+ "rev-parse",
293
+ "--verify",
294
+ "--quiet",
295
+ "--end-of-options",
296
+ `${raw}^{commit}`,
297
+ ]);
298
+ assertJudgedEvidence(peeled);
299
+ if (peeled.exitCode === -1)
300
+ return unusable("unverifiable");
301
+ if (peeled.exitCode !== 0)
302
+ return unusable("unknown");
303
+ // A tag object peels to a DIFFERENT commit — never a stand-in.
304
+ if (peeled.stdout.trim() !== raw)
305
+ return unusable("not-a-commit");
306
+ const anc = await gitEvidence(repoRoot, ["merge-base", "--is-ancestor", raw, developTip]);
307
+ assertJudgedEvidence(anc);
308
+ if (anc.exitCode === 1)
309
+ return unusable("not-ancestor");
310
+ if (anc.exitCode !== 0)
311
+ return unusable("unverifiable");
312
+ return { status: "applied", sha: raw };
313
+ }
314
+ /** `rev-list <rev>` as a set — null when the read fails (exempt nothing). */
315
+ async function ancestrySet(repoRoot, rev) {
316
+ const r = await gitEvidence(repoRoot, ["rev-list", rev]);
317
+ assertJudgedEvidence(r);
318
+ if (r.exitCode !== 0)
319
+ return null;
320
+ return new Set(r.stdout
127
321
  .split("\n")
128
322
  .map((s) => s.trim())
129
- .filter(Boolean)) {
130
- // `%e` rides along — a commit declaring a non-default `encoding:`
131
- // header RECODES this very output, so %(trailers) over it is already
132
- // garbage: the header lives in the object and no -c pin reaches it
133
- // (CX-102). An encoded commit's trailers are unverifiable — flag it.
134
- const parsed = await gitEvidence(repoRoot, [
135
- "log",
136
- "-1",
137
- "--format=%(trailers:only,separator=%x00)%x00%e",
138
- sha,
139
- ]);
140
- if (parsed.exitCode !== 0) {
141
- // An enumerated commit whose trailer read fails is unverifiable —
142
- // flag it like the encoding case instead of silently dropping its
143
- // provenance under a surgical refusal.
144
- hits.push({ sha, trailers: ["x-unverifiable-commit"] });
323
+ .filter(Boolean));
324
+ }
325
+ async function singleParent(repoRoot, sha) {
326
+ const r = await gitEvidence(repoRoot, ["rev-list", "--parents", "-n", "1", sha]);
327
+ assertJudgedEvidence(r);
328
+ if (r.exitCode !== 0)
329
+ return null;
330
+ const parts = r.stdout.trim().split(/\s+/);
331
+ return parts.length === 2 && parts[0] === sha ? parts[1] : null;
332
+ }
333
+ async function treeOf(repoRoot, sha) {
334
+ const r = await gitEvidence(repoRoot, [
335
+ "rev-parse",
336
+ "--verify",
337
+ "--quiet",
338
+ "--end-of-options",
339
+ `${sha}^{tree}`,
340
+ ]);
341
+ assertJudgedEvidence(r);
342
+ return r.exitCode === 0 ? r.stdout.trim() : null;
343
+ }
344
+ async function treeListing(repoRoot, sha) {
345
+ const r = await gitEvidence(repoRoot, ["ls-tree", "-r", "-z", sha]);
346
+ assertJudgedEvidence(r);
347
+ if (r.exitCode !== 0)
348
+ return null;
349
+ const out = new Map();
350
+ for (const rec of r.stdout.split("\0")) {
351
+ if (rec.length === 0)
145
352
  continue;
353
+ const tab = rec.indexOf("\t");
354
+ if (tab <= 0)
355
+ return null;
356
+ out.set(rec.slice(tab + 1), rec.slice(0, tab));
357
+ }
358
+ return out;
359
+ }
360
+ /** Canonical JSON for doc comparison — key order never matters. */
361
+ function canonicalDoc(v) {
362
+ if (Array.isArray(v))
363
+ return `[${v.map(canonicalDoc).join(",")}]`;
364
+ if (typeof v === "object" && v !== null) {
365
+ const rec = v;
366
+ return `{${Object.keys(rec)
367
+ .sort()
368
+ .map((k) => `${JSON.stringify(k)}:${canonicalDoc(rec[k])}`)
369
+ .join(",")}}`;
370
+ }
371
+ // NaN/±Infinity serialize as `null` and unsafe integers lose
372
+ // precision — a doc carrying one never compares equal (no exemption).
373
+ if (typeof v === "number" && (!Number.isFinite(v) || !Number.isSafeInteger(Math.trunc(v)))) {
374
+ return `\u0000unfaithful:${Math.random()}`;
375
+ }
376
+ if (typeof v === "bigint")
377
+ return `\u0000unfaithful:${Math.random()}`;
378
+ return JSON.stringify(v ?? null);
379
+ }
380
+ function withoutBaseline(doc) {
381
+ if (doc === null)
382
+ return "null";
383
+ const push = pushSection(doc);
384
+ if (push === undefined)
385
+ return canonicalDoc(doc);
386
+ const { verifierReviewedThrough: _drop, ...restPush } = push;
387
+ return canonicalDoc({ ...doc, push: restPush });
388
+ }
389
+ /**
390
+ * RFC-1643: the integrate-generated weakening record of a baseline-only
391
+ * bump. In a `policy:` repository `push` is a contour key, so
392
+ * `flow.integrate --accept-weakening` appends an EMPTY commit carrying
393
+ * `X-Correctness-Weakening` on top of the bump — always a descendant of
394
+ * the baseline it records. Exempt exactly that record: sole trailer
395
+ * X-Correctness-Weakening, empty, single parent P, P single-parent, P
396
+ * changes only forge.yaml, only `push.verifierReviewedThrough` differs,
397
+ * and P sets it to the APPLIED baseline.
398
+ */
399
+ async function isBaselineBumpRecord(repoRoot, hit, baseline) {
400
+ if (hit.trailers.length !== 1 || hit.trailers[0] !== "X-Correctness-Weakening")
401
+ return false;
402
+ const p = await singleParent(repoRoot, hit.sha);
403
+ if (p === null)
404
+ return false;
405
+ const [wTree, pTree] = await Promise.all([treeOf(repoRoot, hit.sha), treeOf(repoRoot, p)]);
406
+ if (wTree === null || wTree !== pTree)
407
+ return false;
408
+ const pp = await singleParent(repoRoot, p);
409
+ if (pp === null)
410
+ return false;
411
+ const [before, after] = await Promise.all([treeListing(repoRoot, pp), treeListing(repoRoot, p)]);
412
+ if (before === null || after === null)
413
+ return false;
414
+ const changed = new Set();
415
+ for (const [path, entry] of after)
416
+ if (before.get(path) !== entry)
417
+ changed.add(path);
418
+ for (const path of before.keys())
419
+ if (!after.has(path))
420
+ changed.add(path);
421
+ if (changed.size !== 1 || !changed.has("forge.yaml"))
422
+ return false;
423
+ const [docBefore, docAfter] = await Promise.all([
424
+ readCommittedForgeDoc(repoRoot, pp),
425
+ readCommittedForgeDoc(repoRoot, p),
426
+ ]);
427
+ if (docBefore.kind !== "doc" || docAfter.kind !== "doc")
428
+ return false;
429
+ if (declaredBaseline(docAfter) !== baseline)
430
+ return false;
431
+ if (declaredBaseline(docBefore) === baseline)
432
+ return false;
433
+ return withoutBaseline(docBefore.doc) === withoutBaseline(docAfter.doc);
434
+ }
435
+ /** RFC-1643: how far back FLOW-PUSH-17 walks forge.yaml-touching first-parent commits. */
436
+ const BASELINE_HISTORY_WINDOW = 64;
437
+ /**
438
+ * RFC-1643 (FLOW-PUSH-17 visibility): every change of the PARSED
439
+ * `push.verifierReviewedThrough` value on develop's first-parent chain,
440
+ * newest first — compared by value, never by text (a comment or a
441
+ * re-quote that `-G` would match is not a change, and a decoy commit can
442
+ * no longer pose as the bump). The walk covers the forge.yaml-touching
443
+ * first-parent commits up to BASELINE_HISTORY_WINDOW and stops where the
444
+ * key is absent (its introduction). `oldest` is the value at the window's
445
+ * far end — `undefined` when the key was introduced inside the window, so
446
+ * "newly exempted" is measured from a point a chain of session bumps
447
+ * cannot move inside the window. Advisory — a failed read yields
448
+ * `undefined`, never an exemption.
449
+ */
450
+ async function baselineHistory(repoRoot, developTip) {
451
+ const r = await gitEvidence(repoRoot, [
452
+ "log",
453
+ "--first-parent",
454
+ "--format=%H",
455
+ "-n",
456
+ String(BASELINE_HISTORY_WINDOW),
457
+ developTip,
458
+ "--",
459
+ "forge.yaml",
460
+ ]);
461
+ assertJudgedEvidence(r);
462
+ if (r.exitCode !== 0)
463
+ return undefined;
464
+ const commits = r.stdout
465
+ .split("\n")
466
+ .map((l) => l.trim())
467
+ .filter(Boolean);
468
+ if (commits.length === 0 || !commits.every((c) => /^[0-9a-f]{40,64}$/.test(c))) {
469
+ return undefined;
470
+ }
471
+ const valueAt = async (rev) => {
472
+ const doc = await readCommittedForgeDoc(repoRoot, rev);
473
+ if (doc.kind === "unverifiable" || doc.kind === "unparsable")
474
+ return null;
475
+ const v = declaredBaseline(doc);
476
+ return v === undefined ? undefined : String(v);
477
+ };
478
+ const changes = [];
479
+ let current = await valueAt(commits[0]);
480
+ if (current === null)
481
+ return undefined;
482
+ for (const c of commits) {
483
+ // History simplification: on the first-parent chain, `c^1` carries
484
+ // the same forge.yaml as the next older listed commit.
485
+ const before = await valueAt(`${c}^1`);
486
+ if (before === null)
487
+ return undefined;
488
+ if (before !== current) {
489
+ changes.push({ commit: c, from: before ?? "(absent)", to: current ?? "(absent)" });
146
490
  }
147
- const parsedParts = parsed.stdout.split("\x00");
148
- const declaredEncoding = (parsedParts.pop() ?? "").trim();
149
- const found = new Set();
150
- if (declaredEncoding.length > 0 && !/^utf-?8$/i.test(declaredEncoding)) {
151
- found.add(`x-unverifiable-encoding: ${declaredEncoding}`);
152
- }
153
- for (const t of parseGitTrailers(parsedParts.join("\x00").replaceAll("\x00", "\n"))) {
154
- const c = canonical.get(t.key);
155
- if (wanted.has(t.key) && c && t.value.length > 0)
156
- found.add(c);
157
- }
158
- // A trailer-shaped SUBJECT is not a git trailer on every version — but it
159
- // looks exactly like provenance text, so flag it anyway (stricter is
160
- // safe, CX-23). `%s` is one line — no delimiter to smuggle.
161
- const subj = await gitEvidence(repoRoot, ["log", "-1", "--format=%s", sha]);
162
- if (subj.exitCode === 0) {
163
- const m = /^([^:\s][^:]*?)\s*:\s*(.*)$/.exec(subj.stdout.trim());
164
- if (m) {
165
- const c = canonical.get(m[1].trim().toLowerCase());
166
- if (c && m[2].trim().length > 0)
167
- found.add(c);
168
- }
169
- }
170
- else {
171
- // The subject-shaped-trailer check could not run — flag the sha
172
- // rather than assume no trailer-shaped subject.
173
- found.add("x-unverifiable-commit");
174
- }
175
- if (found.size > 0)
176
- hits.push({ sha, trailers: [...found].sort() });
491
+ current = before;
492
+ if (current === undefined)
493
+ return { changes, oldest: undefined };
177
494
  }
178
- return hits;
495
+ return { changes, oldest: current };
179
496
  }
180
497
  export async function pushFlow(repoRoot, io, opts) {
181
498
  // These two reads go through gitEvidence — a refused channel (transport
@@ -200,10 +517,63 @@ export async function pushFlow(repoRoot, io, opts) {
200
517
  // RFC-1501: a dry-run never fetches — `git fetch origin --prune` rewrites
201
518
  // and prunes remote-tracking refs. It judges the digest exactly like
202
519
  // `flow.digest --no-fetch`; a real push still fetches first.
203
- const digest = await collectDigest(repoRoot, io, { fetch: !opts.dryRun });
520
+ // RFC-1638: a persisted reviewed digest attests in seconds when every
521
+ // cheap input still matches (`observeDigestInputs` re-reads through the
522
+ // judged channel — a verdict input, never bestEffort). Any drift, an
523
+ // unprovable input, or --recount falls back to the full recount — the
524
+ // FLOW-PUSH-02 contract byte-for-byte. A missing, unreadable or
525
+ // payload-forged persisted digest refuses FLOW-PUSH-15: no weaker check
526
+ // to silently downgrade to.
527
+ let digest = null;
528
+ let attestation = "recount";
529
+ let digestComputedAt;
530
+ // Attestation fields ride every refusal decided AFTER the digest loaded —
531
+ // the audit trail always records how the quoted digest was validated.
532
+ // RFC-1643: the baseline judgment rides every refusal decided after the
533
+ // verifier scan ran (FLOW-PUSH-03/06/07…), not only the stop itself.
534
+ const baselineDiags = [];
535
+ let verifierReviewBaseline;
536
+ const refuseChecked = (ruleId, message, fixHint) => {
537
+ const base = refuse(ruleId, message, fixHint);
538
+ return {
539
+ ...base,
540
+ attestation,
541
+ digestComputedAt,
542
+ ...(verifierReviewBaseline !== undefined ? { verifierReviewBaseline } : {}),
543
+ diagnostics: [...base.diagnostics, ...baselineDiags],
544
+ };
545
+ };
546
+ if (!opts.recount) {
547
+ const persisted = await loadPersistedDigest(io, common, opts.digest);
548
+ if (persisted === "missing") {
549
+ return refuse("FLOW-PUSH-15", `no persisted digest ${opts.digest} under .git/forge/digests — the quoted id predates persistence or the forge state was cleaned; re-run flow.digest to record a fresh reviewed state`, "re-run flow.digest, review the new state and re-run flow.push --digest <id>");
550
+ }
551
+ if (persisted === "unknown") {
552
+ return refuse("FLOW-PUSH-15", `the persisted digest ${opts.digest} is unreadable or carries an unknown schema — it cannot attest pushed state; re-run flow.digest to record a fresh reviewed state`, "re-run flow.digest and re-run flow.push --digest <id>");
553
+ }
554
+ // Payload binding (RFC-1638 review round 1): the file is session-writable
555
+ // like the journal, but unlike a journal `push` record it MINTS the push
556
+ // payload — so the record must preimage the quoted id. Recomputing
557
+ // digestId from the file's own fields means a forged payload needs a
558
+ // 48-bit sha256 preimage, not a plausible-looking JSON.
559
+ if (recomputePersistedDigestId(persisted) !== opts.digest ||
560
+ persisted.digest.digestId !== opts.digest) {
561
+ return refuse("FLOW-PUSH-15", `the persisted digest ${opts.digest} does not preimage the quoted id — the file is forged or corrupt; re-run flow.digest to record a fresh reviewed state`, "re-run flow.digest, review the new state and re-run flow.push --digest <id>");
562
+ }
563
+ const inputs = await observeDigestInputs(repoRoot, io);
564
+ if (inputs !== null && digestInputHash(inputs) === persisted.inputHash) {
565
+ digest = persisted.digest;
566
+ attestation = "input-hash";
567
+ digestComputedAt = persisted.computedAt;
568
+ }
569
+ }
570
+ if (digest === null) {
571
+ digest = await collectDigest(repoRoot, io, { fetch: !opts.dryRun, persist: !opts.dryRun });
572
+ digestComputedAt ??= new Date().toISOString();
573
+ }
204
574
  const noOrigin = digest.diagnostics.find((d) => d.ruleId === "FLOW-PUSH-01" && d.severity === "error");
205
575
  if (noOrigin !== undefined) {
206
- return refuse("FLOW-PUSH-01", noOrigin.message, "add an 'origin' remote first");
576
+ return refuseChecked("FLOW-PUSH-01", noOrigin.message, "add an 'origin' remote first");
207
577
  }
208
578
  // Any other error-severity digest diagnostic blocks the push too — a
209
579
  // remote identity that cannot be proven (FLOW-PUSH-09: url.insteadOf
@@ -213,7 +583,7 @@ export async function pushFlow(repoRoot, io, opts) {
213
583
  const blocking = digest.diagnostics.filter((d) => d.severity === "error");
214
584
  if (blocking.length > 0) {
215
585
  const first = blocking[0];
216
- return refuse("FLOW-PUSH-10", first.message, first.fixHint);
586
+ return refuseChecked("FLOW-PUSH-10", first.message, first.fixHint);
217
587
  }
218
588
  // No remote-verification gate exists anymore: `fetched` is
219
589
  // structurally false because the evidence channel refuses every
@@ -224,29 +594,30 @@ export async function pushFlow(repoRoot, io, opts) {
224
594
  // (`remoteVerified` is never true), so nothing narrows the check on
225
595
  // remote-derived state.
226
596
  if (digest.digestId !== opts.digest) {
227
- return refuse("FLOW-PUSH-02", `the digest is stale — the current digestId is ${digest.digestId}, not ${opts.digest}`, `run flow.digest, review the new state and re-run flow.push --digest ${digest.digestId}`);
597
+ return refuseChecked("FLOW-PUSH-02", `the digest is stale — the current digestId is ${digest.digestId}, not ${opts.digest}`, `run flow.digest, review the new state and re-run flow.push --digest ${digest.digestId}`);
228
598
  }
229
- // RFC-1616 (AC-6): verifier-trailer scan over the unpushed develop+main
230
- // range. A commit carrying a verifier/audit trailer claims provenance the
599
+ // RFC-1616 (AC-6): verifier-trailer scan over the develop+main branches.
600
+ // A commit carrying a verifier/audit trailer claims provenance the
231
601
  // session cannot self-certify — the operator must see those commits before
232
602
  // they leave the machine. `push.requireVerifierReview` defaults to true;
233
603
  // an explicit `false` opts the repository out (itself a judged key).
234
- // The declaration is read from the COMMITTED forge.yaml (HEAD) — a dirty
235
- // worktree opt-out must not take effect unjudged (CX-34); an unreadable or
604
+ // RFC-1643: both review keys are read from the COMMITTED forge.yaml at the
605
+ // digest-reviewed develop tip — never the worktree (CX-34) and never HEAD,
606
+ // which in a session worktree is an unintegrated branch. An unreadable or
236
607
  // missing committed config defaults to required (fail closed).
237
- let declared;
608
+ const developTip = digest.develop.local;
609
+ let committed;
238
610
  try {
239
- const show = await gitEvidence(repoRoot, ["show", "HEAD:forge.yaml"]);
240
- if (show.exitCode === 0) {
241
- const doc = parseYaml(show.stdout);
242
- const v = doc?.["push"]?.["requireVerifierReview"];
243
- declared = typeof v === "boolean" ? v : undefined;
244
- }
611
+ committed =
612
+ developTip === "" ? { kind: "missing" } : await readCommittedForgeDoc(repoRoot, developTip);
245
613
  }
246
614
  catch {
247
- declared = undefined;
615
+ // A throwing channel is unverifiable — review stays required and the
616
+ // baseline exempts nothing (fail closed, as a diagnostic).
617
+ committed = { kind: "unverifiable" };
248
618
  }
249
- const requireVerifierReview = declared !== false;
619
+ const declaredReview = committed.kind === "doc" ? pushSection(committed.doc)?.["requireVerifierReview"] : undefined;
620
+ const requireVerifierReview = declaredReview !== false;
250
621
  const scannedRanges = [];
251
622
  const verifierTrailerCommits = new Map();
252
623
  for (const [local, remote] of [
@@ -264,34 +635,131 @@ export async function pushFlow(repoRoot, io, opts) {
264
635
  scannedRanges.push(range);
265
636
  const scan = await scanVerifierTrailers(repoRoot, io, range);
266
637
  if (scan === null) {
267
- return refuse("FLOW-PUSH-13", `the verifier-trailer scan over '${range}' is unverifiable — the push cannot prove which commits carry verifier/audit trailers`, "remove the evidence-channel refusal and re-run flow.push");
638
+ return refuseChecked("FLOW-PUSH-13", `the verifier-trailer scan over '${range}' is unverifiable — the push cannot prove which commits carry verifier/audit trailers`, "remove the evidence-channel refusal and re-run flow.push");
268
639
  }
269
640
  for (const hit of scan) {
270
641
  verifierTrailerCommits.set(hit.sha, hit);
271
642
  }
272
643
  }
273
644
  const trailerHits = [...verifierTrailerCommits.values()].sort((a, b) => a.sha.localeCompare(b.sha));
274
- if (trailerHits.length > 0 && requireVerifierReview) {
645
+ // RFC-1643: the committed review baseline — exemption is computed AFTER
646
+ // the full scan, so the scan (batched or per-commit) never narrows and
647
+ // `verifierTrailerCommits` keeps every hit.
648
+ const exempt = new Set();
649
+ if (requireVerifierReview && trailerHits.length > 0) {
650
+ const baseline = developTip === ""
651
+ ? { status: "absent" }
652
+ : await resolveVerifierReviewBaseline(repoRoot, developTip, committed);
653
+ let reason = baseline.status === "unusable" ? baseline.reason : undefined;
654
+ const newlyExempted = [];
655
+ let bumpedBy;
656
+ let baselineChanges = [];
657
+ if (baseline.status === "applied") {
658
+ // Positive membership: an under-reporting read can only shrink the
659
+ // exemption, never widen it.
660
+ const reviewed = await ancestrySet(repoRoot, baseline.sha);
661
+ if (reviewed === null) {
662
+ reason = "unverifiable";
663
+ }
664
+ else {
665
+ for (const hit of trailerHits) {
666
+ // A pseudo-hit means the scan could not read the commit — it
667
+ // keeps blocking whatever its ancestry.
668
+ if (hit.trailers.some((t) => t.startsWith("x-unverifiable")))
669
+ continue;
670
+ if (reviewed.has(hit.sha) || (await isBaselineBumpRecord(repoRoot, hit, baseline.sha))) {
671
+ exempt.add(hit.sha);
672
+ }
673
+ }
674
+ if (exempt.size > 0) {
675
+ const history = await baselineHistory(repoRoot, developTip);
676
+ baselineChanges = history?.changes ?? [];
677
+ bumpedBy = baselineChanges[0]?.commit;
678
+ const prev = typeof history?.oldest === "string" && /^[0-9a-f]{40,64}$/.test(history.oldest)
679
+ ? await ancestrySet(repoRoot, history.oldest)
680
+ : null;
681
+ for (const sha of exempt)
682
+ if (prev === null || !prev.has(sha))
683
+ newlyExempted.push(sha);
684
+ newlyExempted.sort();
685
+ const changeLog = history === undefined
686
+ ? "baseline history unreadable"
687
+ : baselineChanges.length === 0
688
+ ? `no value change in the last ${BASELINE_HISTORY_WINDOW} forge.yaml commits`
689
+ : baselineChanges
690
+ .map((c) => `${c.commit.slice(0, 9)}: ${c.from.slice(0, 9)}→${c.to.slice(0, 9)}`)
691
+ .join("; ");
692
+ baselineDiags.push({
693
+ ruleId: "FLOW-PUSH-17",
694
+ severity: "warning",
695
+ message: `push.verifierReviewedThrough ${baseline.sha.slice(0, 9)} exempts ${exempt.size} ` +
696
+ `verifier/audit trailer commit(s) from the review stop (${newlyExempted.length} newly ` +
697
+ `exempted within the last ${BASELINE_HISTORY_WINDOW} forge.yaml commits; baseline changes: ${changeLog})`,
698
+ fixHint: "confirm the baseline was moved by the operator after reviewing the listed commits (RFC-1643)",
699
+ });
700
+ }
701
+ }
702
+ }
703
+ if (reason !== undefined) {
704
+ const declared = baseline.status === "unusable"
705
+ ? baseline.declared
706
+ : baseline.status === "applied"
707
+ ? baseline.sha
708
+ : "";
709
+ baselineDiags.push({
710
+ ruleId: "FLOW-PUSH-16",
711
+ severity: "warning",
712
+ message: `push.verifierReviewedThrough${declared ? ` '${declared}'` : ""} is unusable (${reason}) — it exempts no trailer commit`,
713
+ fixHint: "set it to a full, quoted commit sha reachable from refs/heads/develop in the committed forge.yaml (RFC-1643)",
714
+ });
715
+ }
716
+ verifierReviewBaseline = {
717
+ status: reason !== undefined ? "unusable" : baseline.status,
718
+ ...(baseline.status === "unusable" && baseline.declared
719
+ ? { declared: baseline.declared }
720
+ : {}),
721
+ ...(baseline.status === "applied" ? { declared: baseline.sha } : {}),
722
+ ...(reason !== undefined ? { reason } : {}),
723
+ exempted: [...exempt].sort(),
724
+ newlyExempted,
725
+ ...(bumpedBy !== undefined ? { bumpedBy } : {}),
726
+ changes: baselineChanges,
727
+ };
728
+ }
729
+ const blockingHits = trailerHits.filter((h) => !exempt.has(h.sha));
730
+ if (blockingHits.length > 0 && requireVerifierReview) {
275
731
  if (!opts.acceptVerifierTrailers) {
276
732
  return {
277
733
  digestId: digest.digestId,
734
+ attestation,
735
+ digestComputedAt,
278
736
  pushed: false,
279
737
  refs: [],
280
738
  publications: [],
281
739
  superseded: [],
282
740
  retired: [],
283
741
  verifierTrailerCommits: trailerHits,
742
+ ...(verifierReviewBaseline !== undefined ? { verifierReviewBaseline } : {}),
284
743
  diagnostics: [
285
744
  {
286
745
  ruleId: "FLOW-PUSH-08",
287
746
  severity: "error",
288
- message: `${trailerHits.length} unpushed commit(s) carry a verifier/audit trailer ` +
289
- `(${trailerHits.map((h) => `${h.sha.slice(0, 9)}[${h.trailers.join(",")}]`).join("; ")}) — ` +
290
- `verifier evidence must be reviewed before it leaves the machine`,
747
+ message: `${blockingHits.length} commit(s) on the scanned local branches carry a verifier/audit trailer ` +
748
+ `(the scan covers the whole branch — tracking refs cannot prove what is already pushed, CX-82) ` +
749
+ `(${blockingHits.map((h) => `${h.sha.slice(0, 9)}[${h.trailers.join(",")}]`).join("; ")})` +
750
+ (exempt.size > 0
751
+ ? ` — ${exempt.size} more exempted by push.verifierReviewedThrough`
752
+ : "") +
753
+ (verifierReviewBaseline?.status === "unusable"
754
+ ? ` — push.verifierReviewedThrough is unusable (${verifierReviewBaseline.reason ?? "unverifiable"}) and exempts nothing`
755
+ : "") +
756
+ ` — verifier evidence must be reviewed before it leaves the machine`,
291
757
  fixHint: "review the commits, then re-run with " +
292
- '--accept-verifier-trailers "<reason>" — or opt the repository out ' +
293
- "with push.requireVerifierReview: false in forge.yaml",
758
+ '--accept-verifier-trailers "<reason>" — or record the review as a committed ' +
759
+ "push.verifierReviewedThrough baseline (operator only, RFC-1643), or opt the " +
760
+ "repository out with push.requireVerifierReview: false in forge.yaml",
294
761
  },
762
+ ...baselineDiags,
295
763
  ],
296
764
  };
297
765
  }
@@ -302,9 +770,17 @@ export async function pushFlow(repoRoot, io, opts) {
302
770
  ]) {
303
771
  if (remote === null)
304
772
  continue;
305
- const ancestor = await gitEvidence(repoRoot, ["merge-base", "--is-ancestor", remote, branch]);
773
+ // RFC-1643: fully qualified — a shadow `refs/tags/<branch>` must not
774
+ // stand in for the local branch.
775
+ const ancestor = await gitEvidence(repoRoot, [
776
+ "merge-base",
777
+ "--is-ancestor",
778
+ remote,
779
+ `refs/heads/${branch}`,
780
+ ]);
781
+ assertJudgedEvidence(ancestor);
306
782
  if (ancestor.exitCode !== 0) {
307
- return refuse("FLOW-PUSH-03", `origin/${branch} is not an ancestor of ${branch} — someone pushed elsewhere`, "fetch, inspect the divergence and reconcile before pushing");
783
+ return refuseChecked("FLOW-PUSH-03", `origin/${branch} is not an ancestor of ${branch} — someone pushed elsewhere`, "fetch, inspect the divergence and reconcile before pushing");
308
784
  }
309
785
  }
310
786
  const { lines } = await discoverReleaseLines(repoRoot, io);
@@ -317,13 +793,28 @@ export async function pushFlow(repoRoot, io, opts) {
317
793
  const journalEvents = await readJournal(io, common);
318
794
  const publishedTags = new Set(journalEvents.filter((e) => e.event === "publish").map((e) => e.branch));
319
795
  const retiredTags = new Set(journalEvents.filter((e) => e.event === "publish-retired").map((e) => e.branch));
796
+ // RFC-1638: `push` records suppress tags at push-PLANNING time — the
797
+ // persisted digest's tags were suppressed at digest time, and records
798
+ // appended meanwhile must hide their tags here too. Suppression is
799
+ // monotonic (a record can only hide, R13-C), so re-filtering the digest's
800
+ // list is idempotent on the recount path.
801
+ const pushedNow = new Set();
802
+ for (const e of journalEvents) {
803
+ if (e.event !== "push")
804
+ continue;
805
+ for (const token of e.detail.split(/[^A-Za-z0-9._/@-]+/)) {
806
+ if (token.length > 0)
807
+ pushedNow.add(token);
808
+ }
809
+ }
810
+ const effectiveTags = digest.tags.filter((t) => !pushedNow.has(t));
320
811
  const publicationTags = new Map();
321
812
  const addCandidate = (tag, lineId) => {
322
813
  const line = (lineId === null ? null : lines.find((l) => l.id === lineId)) ?? lineForTag(lines, tag);
323
814
  if (line !== null && line.id !== "repo")
324
815
  publicationTags.set(tag, line);
325
816
  };
326
- for (const tag of digest.tags)
817
+ for (const tag of effectiveTags)
327
818
  addCandidate(tag, null);
328
819
  const baselineSkipped = [];
329
820
  const planCandidates = [];
@@ -352,19 +843,20 @@ export async function pushFlow(repoRoot, io, opts) {
352
843
  for (const { line } of publishable) {
353
844
  const dir = line.paths[0];
354
845
  if (!(await markerIsValid(join(primary, dir, "forge.generated.yaml"), io))) {
355
- return refuse("FLOW-PUSH-06", `package line ${line.id} has no valid forge.generated.yaml in ${dir} — it must not be published`, "re-run flow.install to restore the marker, or remove the line's tags");
846
+ return refuseChecked("FLOW-PUSH-06", `package line ${line.id} has no valid forge.generated.yaml in ${dir} — it must not be published`, "re-run flow.install to restore the marker, or remove the line's tags");
356
847
  }
357
848
  }
358
849
  const extractBin = join(primary, "node_modules", ".bin", "repo-extract");
359
850
  if (publishable.length > 0 && !(await io.exists(extractBin))) {
360
- return refuse("FLOW-PUSH-07", `${extractBin} is missing while ${publishable.length} tag(s) wait to publish`, "install the workspace dependencies so repo-extract is linked");
851
+ return refuseChecked("FLOW-PUSH-07", `${extractBin} is missing while ${publishable.length} tag(s) wait to publish`, "install the workspace dependencies so repo-extract is linked");
361
852
  }
362
853
  // Sha-pinned refspecs — the push ships exactly the reviewed tips; a local
363
854
  // branch that moved since the digest stays local instead of sneaking in.
364
- // Refspecs cover digest.tags in full (R13-C): every tag this run will
365
- // treat as publishable is pushed in the same atomic push — a fabricated
366
- // journal `push` record can never make an unpushed tag look remote.
367
- const pushedTagNames = digest.tags;
855
+ // Refspecs cover the effective tag set in full (R13-C): every tag this
856
+ // run will treat as publishable is pushed in the same atomic push — a
857
+ // fabricated journal `push` record can never make an unpushed tag look
858
+ // remote.
859
+ const pushedTagNames = effectiveTags;
368
860
  const refspecs = [
369
861
  `${digest.develop.local}:refs/heads/develop`,
370
862
  `${digest.main.local}:refs/heads/main`,
@@ -373,6 +865,8 @@ export async function pushFlow(repoRoot, io, opts) {
373
865
  if (opts.dryRun) {
374
866
  return {
375
867
  digestId: digest.digestId,
868
+ attestation,
869
+ digestComputedAt,
376
870
  fetched: digest.fetched,
377
871
  pushed: false,
378
872
  refs: refspecs,
@@ -395,7 +889,8 @@ export async function pushFlow(repoRoot, io, opts) {
395
889
  retired: [...retiredTags].sort((a, b) => a.localeCompare(b)),
396
890
  verifierTrailerCommits: trailerHits,
397
891
  verifierTrailersAccepted: opts.acceptVerifierTrailers,
398
- diagnostics: [...digest.diagnostics],
892
+ ...(verifierReviewBaseline !== undefined ? { verifierReviewBaseline } : {}),
893
+ diagnostics: [...digest.diagnostics, ...baselineDiags],
399
894
  };
400
895
  }
401
896
  // --- push ------------------------------------------------------------------
@@ -411,6 +906,8 @@ export async function pushFlow(repoRoot, io, opts) {
411
906
  if (push.exitCode !== 0) {
412
907
  return {
413
908
  digestId: digest.digestId,
909
+ attestation,
910
+ digestComputedAt,
414
911
  fetched: digest.fetched,
415
912
  pushed: false,
416
913
  refs: refspecs,
@@ -419,7 +916,9 @@ export async function pushFlow(repoRoot, io, opts) {
419
916
  retired: [...retiredTags].sort((a, b) => a.localeCompare(b)),
420
917
  verifierTrailerCommits: trailerHits,
421
918
  verifierTrailersAccepted: opts.acceptVerifierTrailers,
919
+ ...(verifierReviewBaseline !== undefined ? { verifierReviewBaseline } : {}),
422
920
  diagnostics: [
921
+ ...baselineDiags,
423
922
  {
424
923
  ruleId: "FLOW-PUSH-04",
425
924
  severity: "error",
@@ -476,6 +975,7 @@ export async function pushFlow(repoRoot, io, opts) {
476
975
  // was the invisible half of CX-63.
477
976
  const diagnostics = [
478
977
  ...digest.diagnostics,
978
+ ...baselineDiags,
479
979
  ...journalWarnings.map((message) => ({
480
980
  ruleId: "FLOW-07",
481
981
  severity: "warning",
@@ -551,6 +1051,8 @@ export async function pushFlow(repoRoot, io, opts) {
551
1051
  }
552
1052
  return {
553
1053
  digestId: digest.digestId,
1054
+ attestation,
1055
+ digestComputedAt,
554
1056
  fetched: digest.fetched,
555
1057
  pushed,
556
1058
  refs: refspecs,
@@ -559,6 +1061,7 @@ export async function pushFlow(repoRoot, io, opts) {
559
1061
  retired: [...freshRetired].sort((a, b) => a.localeCompare(b)),
560
1062
  verifierTrailerCommits: trailerHits,
561
1063
  verifierTrailersAccepted: opts.acceptVerifierTrailers,
1064
+ ...(verifierReviewBaseline !== undefined ? { verifierReviewBaseline } : {}),
562
1065
  diagnostics,
563
1066
  };
564
1067
  }
@@ -597,6 +1100,7 @@ export async function runFlowPush(input, context) {
597
1100
  digest: digestFlag,
598
1101
  dryRun: input.flags["dry-run"] === true,
599
1102
  acceptVerifierTrailers: acceptVerifierTrailers || undefined,
1103
+ recount: input.flags["recount"] === true,
600
1104
  });
601
1105
  }
602
1106
  catch (error) {