@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
@@ -6,14 +6,14 @@
6
6
  </non-goals>
7
7
  </MODULE_CONTRACT>
8
8
  <CHANGE_SUMMARY>
9
- <item>RFC-1461: declare rules[] severity via CommandRuleDecl workspace-wide (RFC-1461)</item>
10
- <item>RFC-1460: recurring frictions escalate to mechanical measures — FRICTION-06/07/08, registry flips, session-retro escalation</item>
11
9
  <item>RFC-1590: store append-only shared ledgers as one file per record</item>
12
10
  <item>RFC-1601: ledger writers assign + refusals teach the violated rule (RFC-1601)
13
11
 
14
12
  FRICTION-11 flags any out-of-vocabulary friction field value at validate, naming field+value+closed set — the mechanical detector for hand-edit corruption (F-0206/F-0244). queue.decision is the new decision-ledger writer: schema-gated append stamping createdAt/answeredAt, next-free Q-id default, QUEUE-05/QUEUE-DEC-01 refusals carrying the minimal shape. ecosystem.commit --rfc/--adr normalize bare digits or refuse EC-35 with the format statement — the F-0248 silent-injection-skip class is closed, and a summary-record failure now names the id + skipped injection. RFC-IMP-10 refusal leads with the rule statement; pipeline conventions and guides point at the command write path.</item>
15
13
  <item>RFC-1592: retire 3 unprobeable rules (F-0288 recurrence) unblocking this worktree's RFC-1592 ratchet</item>
16
- <history>RFC-1433</history>
14
+ <item>RFC-1639: step 3-4 — friction.migrate --from ingest, friction.add --level, CREATE-SUPERFOLDER-01 guard</item>
15
+ <item>RFC-1639: review — SYSTEM-MAP-01 rules decl, git-probe warnings, sibling kind/path discriminants, friction.add provenance, ingest hardening</item>
16
+ <history>RFC-1433, RFC-1460, RFC-1461</history>
17
17
  </CHANGE_SUMMARY>
18
18
  */
19
19
 
@@ -150,6 +150,12 @@ export async function createForgeFrictionModule(): Promise<ForgeModule> {
150
150
  description:
151
151
  "Existing record id — increments recurrences and sets lastSeen instead of writing a new record.",
152
152
  },
153
+ level: {
154
+ kind: "string",
155
+ required: false,
156
+ description:
157
+ "Record level: repo (default — omitted) or folder (RFC-1639 — the record concerns the superfolder, not this repo).",
158
+ },
153
159
  },
154
160
  execute: runFrictionAdd,
155
161
  },
@@ -160,10 +166,15 @@ export async function createForgeFrictionModule(): Promise<ForgeModule> {
160
166
  `files under ${FRICTION_DIR}/, remove the legacy file in the ` +
161
167
  "same run, and move every .agents/skills/*/qa-log.md to " +
162
168
  "qa-log/legacy.md. Idempotent — with no legacy file and no " +
163
- "qa-log.md files it reports migrated: 0.",
169
+ "qa-log.md files it reports migrated: 0. RFC-1639: --from " +
170
+ "<external frictions.yaml> ingests a registry from outside the " +
171
+ "workspace (ledger-minted ids, migratedFrom/origin/level provenance).",
164
172
  scope: "workspace",
165
173
  contract: "frictions",
166
- rules: [{ id: "FRICTION-01", severity: "error" }],
174
+ rules: [
175
+ { id: "FRICTION-01", severity: "error" },
176
+ { id: "FRICTION-03", severity: "error" },
177
+ ],
167
178
  mutatesState: true,
168
179
  idempotency: "rerun-safe",
169
180
  reads: [`${FRICTION_DIR}/**`, LEGACY_FRICTION_FILE, ".agents/skills/**"],
@@ -175,6 +186,23 @@ export async function createForgeFrictionModule(): Promise<ForgeModule> {
175
186
  required: false,
176
187
  description: "Report the split and shard moves without writing.",
177
188
  },
189
+ from: {
190
+ kind: "string",
191
+ required: false,
192
+ description:
193
+ "RFC-1639: ingest an EXTERNAL legacy frictions.yaml — records mint at the next F-ids via the shared ledger with migratedFrom+origin provenance; the source file is removed last. Must point outside the workspace.",
194
+ },
195
+ level: {
196
+ kind: "string",
197
+ required: false,
198
+ description: "Level stamped on --from-ingested records: folder (default) or repo.",
199
+ },
200
+ session: {
201
+ kind: "string",
202
+ required: false,
203
+ description:
204
+ "Session id to attribute the --from ledger allocation to — defaults to the current branch name.",
205
+ },
178
206
  },
179
207
  execute: runFrictionMigrate,
180
208
  },
@@ -22,6 +22,7 @@ and lastSeen is set — per-record files only.</purpose>
22
22
  <item>RFC-1590: friction.add — governance-reserved ids, write-time
23
23
  vocabulary gate (FRICTION-01..05 reuse), --recurrence-of counter path.</item>
24
24
  <item>RFC-1590: store append-only shared ledgers as one file per record</item>
25
+ <item>RFC-1639: step 3-4 — friction.migrate --from ingest, friction.add --level, CREATE-SUPERFOLDER-01 guard</item>
25
26
  </CHANGE_SUMMARY>
26
27
  */
27
28
 
@@ -34,9 +35,9 @@ import type {
34
35
  } from "../../../src/types.ts";
35
36
 
36
37
  import { reserveNextGovernanceId } from "../../rfc/next-id.ts";
37
- import { git } from "../../flow/git.ts";
38
38
  import {
39
39
  LegacyRecordMutationError,
40
+ defaultSession,
40
41
  frictionSourceMax,
41
42
  loadFrictionSources,
42
43
  updateFriction,
@@ -90,19 +91,6 @@ function refuse(
90
91
  };
91
92
  }
92
93
 
93
- /** Session attribution default — the current branch name; detached or
94
- * non-git invocations record "manual". */
95
- async function defaultSession(cwd: string): Promise<string> {
96
- try {
97
- const r = await git(cwd, fs, ["branch", "--show-current"]);
98
- const name = r.stdout.trim();
99
- if (r.exitCode === 0 && name.length > 0) return name;
100
- } catch {
101
- /* non-git cwd — manual attribution */
102
- }
103
- return "manual";
104
- }
105
-
106
94
  export async function runFrictionAdd(
107
95
  input: ForgeCommandInput,
108
96
  context: ForgeRuntimeContext,
@@ -161,6 +149,7 @@ export async function runFrictionAdd(
161
149
  const measure = flag(input, "measure");
162
150
  const measureKind = flag(input, "measure-kind");
163
151
  const status = flag(input, "status") ?? "open";
152
+ const level = flag(input, "level");
164
153
  const artifactsRaw = flag(input, "artifacts");
165
154
  const artifacts =
166
155
  artifactsRaw === undefined
@@ -200,12 +189,17 @@ export async function runFrictionAdd(
200
189
  `status "${status}" is outside the closed catalog (${FRICTION_STATUSES.join(", ")})`,
201
190
  );
202
191
  }
192
+ // RFC-1639: --level marks records about the superfolder (folder) vs the
193
+ // repo holding the registry (repo, the default — the field is omitted).
194
+ if (level !== undefined && level !== "repo" && level !== "folder") {
195
+ return refuse("FRICTION-03", `level "${level}" is outside the closed catalog (repo, folder)`);
196
+ }
203
197
 
204
198
  // ── reserve the id on the shared surface — allocate+append under one
205
199
  // lock so two concurrent adds can never pick the same id (AC-2).
206
200
  const sources = await loadFrictionSources(workspaceRoot, fs);
207
201
  const worktreeMax = frictionSourceMax(sources);
208
- const session = flag(input, "session") ?? (await defaultSession(workspaceRoot));
202
+ const session = flag(input, "session") ?? (await defaultSession(workspaceRoot, fs));
209
203
  const allocation = await reserveNextGovernanceId(
210
204
  fs,
211
205
  workspaceRoot,
@@ -224,6 +218,7 @@ export async function runFrictionAdd(
224
218
  signature,
225
219
  measure,
226
220
  ...(measureKind !== undefined ? { measureKind: measureKind as FrictionMeasureKind } : {}),
221
+ ...(level === "folder" ? { level: "folder" as const } : {}),
227
222
  artifacts,
228
223
  status: status as FrictionStatus,
229
224
  recurrences: 0,
@@ -23,10 +23,14 @@ Idempotent: no legacy file and no qa-log.md files reports migrated: 0.</purpose>
23
23
  <item>RFC-1590: friction.migrate — legacy split + removal, qa-log.md
24
24
  shard moves under .agents/skills/, --dry-run reporting.</item>
25
25
  <item>RFC-1590: store append-only shared ledgers as one file per record</item>
26
+ <item>RFC-1639: step 3-4 — friction.migrate --from ingest, friction.add --level, CREATE-SUPERFOLDER-01 guard</item>
27
+ <item>RFC-1639: review — SYSTEM-MAP-01 rules decl, git-probe warnings, sibling kind/path discriminants, friction.add provenance, ingest hardening</item>
26
28
  </CHANGE_SUMMARY>
27
29
  */
28
30
 
29
- import { join } from "node:path";
31
+ import path, { join } from "node:path";
32
+
33
+ import { parse as yamlParse } from "yaml";
30
34
 
31
35
  import { ambientIo as fs } from "../../../src/utils/io.ts";
32
36
  import type {
@@ -36,12 +40,16 @@ import type {
36
40
  ForgeRuntimeContext,
37
41
  } from "../../../src/types.ts";
38
42
 
43
+ import { reserveNextGovernanceId } from "../../rfc/next-id.ts";
39
44
  import {
40
45
  FRICTION_DIR,
41
46
  LEGACY_FRICTION_FILE,
47
+ defaultSession,
48
+ frictionSourceMax,
42
49
  loadFrictionSources,
43
50
  writeFriction,
44
51
  } from "../store.ts";
52
+ import { FRICTION_ID_PATTERN } from "../types.ts";
45
53
  import type { FrictionEntry } from "../types.ts";
46
54
 
47
55
  export interface FrictionMigrateResult {
@@ -82,10 +90,25 @@ async function listQaLogFiles(root: string): Promise<string[]> {
82
90
  return found;
83
91
  }
84
92
 
93
+ function flag(input: ForgeCommandInput, name: string): string | undefined {
94
+ const v = input.flags[name];
95
+ if (typeof v === "string" && v.trim().length > 0) return v.trim();
96
+ if (typeof v === "number") return String(v);
97
+ return undefined;
98
+ }
99
+
85
100
  export async function runFrictionMigrate(
86
101
  input: ForgeCommandInput,
87
102
  context: ForgeRuntimeContext,
88
103
  ): Promise<ForgeCommandResult<FrictionMigrateResult>> {
104
+ // RFC-1639: --from ingests an EXTERNAL legacy frictions.yaml into this
105
+ // workspace's registry — the superfolder-level file lands inside the
106
+ // system hub at the next F-ids with migratedFrom+origin provenance.
107
+ const from = flag(input, "from");
108
+ if (from !== undefined) {
109
+ return runIngest(input, context, from);
110
+ }
111
+
89
112
  const { workspaceRoot, logger, outputFormat } = context;
90
113
  const dryRun = input.flags["dry-run"] === true;
91
114
  const files: string[] = [];
@@ -204,3 +227,199 @@ export async function runFrictionMigrate(
204
227
  exitCode: errors.length === 0 ? 0 : 1,
205
228
  };
206
229
  }
230
+
231
+ // ── --from ingest (RFC-1639) ─────────────────────────────────────────────
232
+
233
+ /**
234
+ * Ingest an external legacy frictions.yaml into this workspace's registry.
235
+ * Records mint at the next ids via the shared git-dir ledger (never
236
+ * dir-scan), carry migratedFrom + origin + level provenance, and the source
237
+ * file is removed last so a crash-interrupted re-run re-derives the same
238
+ * mapping and skips already-ingested entries.
239
+ */
240
+ async function runIngest(
241
+ input: ForgeCommandInput,
242
+ context: ForgeRuntimeContext,
243
+ fromRaw: string,
244
+ ): Promise<ForgeCommandResult<FrictionMigrateResult>> {
245
+ const { workspaceRoot, logger, outputFormat } = context;
246
+ const dryRun = input.flags["dry-run"] === true;
247
+ const files: string[] = [];
248
+ const skipped: Array<{ id: string | null; reason: string }> = [];
249
+ const errors: Diagnostic[] = [];
250
+ let migrated = 0;
251
+ let legacyRemoved = false;
252
+
253
+ const finish = (summary: string): ForgeCommandResult<FrictionMigrateResult> => ({
254
+ data: {
255
+ command: "friction.migrate",
256
+ status: errors.length === 0 ? "pass" : "fail",
257
+ dryRun,
258
+ migrated,
259
+ files,
260
+ legacyRemoved,
261
+ qaLogMoved: [],
262
+ qaLogMerged: [],
263
+ skipped,
264
+ errors,
265
+ },
266
+ summary,
267
+ exitCode: errors.length === 0 ? 0 : 1,
268
+ });
269
+ const refuse = (message: string): ForgeCommandResult<FrictionMigrateResult> => {
270
+ errors.push({ ruleId: "FRICTION-01", severity: "error", message, file: fromRaw });
271
+ return finish(`friction.migrate --from refused: ${message}`);
272
+ };
273
+
274
+ const resolved = path.isAbsolute(fromRaw)
275
+ ? path.normalize(fromRaw)
276
+ : path.resolve(workspaceRoot, fromRaw);
277
+ const rootNorm = path.resolve(workspaceRoot);
278
+ if (resolved === rootNorm || resolved.startsWith(rootNorm + path.sep)) {
279
+ return refuse(
280
+ "--from must point outside the workspace — the no-flag path owns docs/frictions.yaml",
281
+ );
282
+ }
283
+ if (!(await fs.exists(resolved))) {
284
+ return refuse(`source file not found: ${resolved}`);
285
+ }
286
+
287
+ // origin — the source registry's dir basename, unwrapping a trailing
288
+ // docs/ so <repo>/docs/frictions.yaml records origin as <repo>.
289
+ const parent = path.dirname(resolved);
290
+ const origin =
291
+ path.basename(parent) === "docs" ? path.basename(path.dirname(parent)) : path.basename(parent);
292
+ if (origin.length === 0) {
293
+ return refuse(
294
+ `cannot derive an origin name from ${resolved} — pass a file inside a named folder`,
295
+ );
296
+ }
297
+
298
+ const levelFlag = flag(input, "level");
299
+ if (levelFlag !== undefined && levelFlag !== "repo" && levelFlag !== "folder") {
300
+ errors.push({
301
+ ruleId: "FRICTION-03",
302
+ severity: "error",
303
+ message: `level "${levelFlag}" is outside the closed catalog (repo, folder)`,
304
+ file: fromRaw,
305
+ });
306
+ return finish(`friction.migrate --from refused: invalid --level ${levelFlag}`);
307
+ }
308
+
309
+ // Parse — accept both legacy shapes ({entries: [...]} and a bare array).
310
+ let rows: Record<string, unknown>[];
311
+ try {
312
+ const parsed = yamlParse(await fs.readFile(resolved)) as unknown;
313
+ const list = Array.isArray(parsed)
314
+ ? parsed
315
+ : parsed !== null &&
316
+ typeof parsed === "object" &&
317
+ Array.isArray((parsed as Record<string, unknown>)["entries"])
318
+ ? ((parsed as Record<string, unknown>)["entries"] as unknown[])
319
+ : null;
320
+ if (list === null) {
321
+ return refuse(`${resolved} is not a legacy frictions registry (no entries array)`);
322
+ }
323
+ rows = list as Record<string, unknown>[];
324
+ } catch (e) {
325
+ return refuse(
326
+ `${resolved} is not readable YAML: ${e instanceof Error ? e.message : String(e)}`,
327
+ );
328
+ }
329
+
330
+ // Every row must name an F-NNNN id — the run refuses before writing when
331
+ // one cannot be renumbered deterministically.
332
+ for (const [i, row] of rows.entries()) {
333
+ const id = row?.["id"];
334
+ if (typeof id !== "string" || !FRICTION_ID_PATTERN.test(id)) {
335
+ return refuse(
336
+ `source entry at index ${i} carries no readable F-NNNN id — repair the source registry before ingesting`,
337
+ );
338
+ }
339
+ }
340
+
341
+ const sources = await loadFrictionSources(workspaceRoot, fs);
342
+ const ingested = new Set(
343
+ sources.dir
344
+ .map((r) => r.raw as Record<string, unknown> | undefined)
345
+ .filter(
346
+ (r): r is Record<string, unknown> =>
347
+ r !== undefined && r["origin"] === origin && typeof r["migratedFrom"] === "string",
348
+ )
349
+ .map((r) => r["migratedFrom"] as string),
350
+ );
351
+
352
+ let max = frictionSourceMax(sources);
353
+ const session = flag(input, "session") ?? (await defaultSession(workspaceRoot, fs));
354
+ const level = levelFlag === "repo" ? ("repo" as const) : ("folder" as const);
355
+
356
+ for (const row of rows) {
357
+ const oldId = row["id"] as string;
358
+ if (ingested.has(oldId)) {
359
+ skipped.push({ id: oldId, reason: `already ingested (origin: ${origin})` });
360
+ continue;
361
+ }
362
+ if (dryRun) {
363
+ files.push(join(FRICTION_DIR, `F-${String(max + 1).padStart(4, "0")}.yaml`));
364
+ max += 1;
365
+ continue;
366
+ }
367
+ const allocation = await reserveNextGovernanceId(fs, workspaceRoot, "friction", max, session);
368
+ max = Math.max(max, allocation.id);
369
+ const id = `F-${String(allocation.id).padStart(4, "0")}`;
370
+ const file = join(FRICTION_DIR, `${id}.yaml`);
371
+ files.push(file);
372
+ const record = {
373
+ ...row,
374
+ id,
375
+ migratedFrom: oldId,
376
+ origin,
377
+ level,
378
+ } as FrictionEntry;
379
+ try {
380
+ await writeFriction(workspaceRoot, record, fs);
381
+ migrated++;
382
+ ingested.add(oldId);
383
+ for (const w of allocation.warnings) {
384
+ if (outputFormat === "pretty") logger.warn(` ${w}`);
385
+ }
386
+ } catch (e) {
387
+ errors.push({
388
+ ruleId: "FRICTION-01",
389
+ severity: "error",
390
+ message: e instanceof Error ? e.message : String(e),
391
+ file,
392
+ });
393
+ break;
394
+ }
395
+ }
396
+
397
+ // Source removal is LAST — a crash before this point re-runs cleanly.
398
+ if (!dryRun && errors.length === 0) {
399
+ try {
400
+ await fs.rm(resolved);
401
+ legacyRemoved = true;
402
+ } catch (e) {
403
+ errors.push({
404
+ ruleId: "FRICTION-01",
405
+ severity: "error",
406
+ message: `records written but the source could not be removed: ${e instanceof Error ? e.message : String(e)}`,
407
+ file: resolved,
408
+ });
409
+ }
410
+ }
411
+
412
+ if (outputFormat === "pretty") {
413
+ logger.section("friction.migrate --from");
414
+ logger.info(
415
+ ` ${resolved} → ${files.length} record(s) under ${FRICTION_DIR}/ (origin: ${origin})` +
416
+ (dryRun ? " (dry-run)" : `, source ${legacyRemoved ? "removed" : "kept"}`),
417
+ );
418
+ for (const s of skipped) logger.info(` skipped ${s.id}: ${s.reason}`);
419
+ for (const e of errors) logger.error(` ${e.ruleId}: ${e.message}`);
420
+ }
421
+
422
+ return finish(
423
+ `friction.migrate --from: ${migrated} record(s) ingested from ${origin}${skipped.length > 0 ? `, ${skipped.length} skipped` : ""}${dryRun ? " (dry-run)" : ""}`,
424
+ );
425
+ }
@@ -21,6 +21,8 @@ registry goes through this module.</purpose>
21
21
  layout, legacy-fallback loader, duplicate-id error, writeFriction and
22
22
  updateFriction mutation surface.</item>
23
23
  <item>RFC-1590: store append-only shared ledgers as one file per record</item>
24
+ <item>RFC-1639: step 3-4 — friction.migrate --from ingest, friction.add --level, CREATE-SUPERFOLDER-01 guard</item>
25
+ <item>RFC-1639: review — SYSTEM-MAP-01 rules decl, git-probe warnings, sibling kind/path discriminants, friction.add provenance, ingest hardening</item>
24
26
  </CHANGE_SUMMARY>
25
27
  */
26
28
 
@@ -35,6 +37,23 @@ import type { FrictionEntry } from "./types.ts";
35
37
  export const FRICTION_DIR = "docs/frictions";
36
38
  export const LEGACY_FRICTION_FILE = "docs/frictions.yaml";
37
39
 
40
+ /** Session attribution default — the current branch name; detached or
41
+ * non-git invocations record "manual". Shared by friction.add and the
42
+ * friction.migrate --from ingest (RFC-1639). */
43
+ export async function defaultSession(cwd: string, io: WorkspaceIO): Promise<string> {
44
+ try {
45
+ // Lazy import — keeps the store leaf-shaped for consumers that never
46
+ // mint ids (friction-validate) and never needed the flow/git surface.
47
+ const { git } = await import("../flow/git.ts");
48
+ const r = await git(cwd, io, ["branch", "--show-current"]);
49
+ const name = r.stdout.trim();
50
+ if (r.exitCode === 0 && name.length > 0) return name;
51
+ } catch {
52
+ /* non-git cwd — manual attribution */
53
+ }
54
+ return "manual";
55
+ }
56
+
38
57
  /** `F-NNNN.yaml` file-name shape (prefix match — suffixes stay legal). */
39
58
  export const FRICTION_FILE_PATTERN = /^F-(\d{4})/;
40
59
 
@@ -20,6 +20,7 @@ consistent with the JSON payload. r3 review verdict: pass.</item>
20
20
  <item>RFC-1601: ledger writers assign + refusals teach the violated rule (RFC-1601)
21
21
 
22
22
  FRICTION-11 flags any out-of-vocabulary friction field value at validate, naming field+value+closed set — the mechanical detector for hand-edit corruption (F-0206/F-0244). queue.decision is the new decision-ledger writer: schema-gated append stamping createdAt/answeredAt, next-free Q-id default, QUEUE-05/QUEUE-DEC-01 refusals carrying the minimal shape. ecosystem.commit --rfc/--adr normalize bare digits or refuse EC-35 with the format statement — the F-0248 silent-injection-skip class is closed, and a summary-record failure now names the id + skipped injection. RFC-IMP-10 refusal leads with the rule statement; pipeline conventions and guides point at the command write path.</item>
23
+ <item>RFC-1639: additive record fields — level (repo|folder), origin, migratedFrom</item>
23
24
  <history>RFC-1433</history>
24
25
  </CHANGE_SUMMARY>
25
26
  */
@@ -64,6 +65,13 @@ export const frictionEntrySchema = z.object({
64
65
  measureKind: z.enum(FRICTION_MEASURE_KINDS).optional(),
65
66
  // RFC-1466: remediation-catalog ids this friction's scar was migrated into.
66
67
  catalogRefs: z.array(z.string().min(1)).optional(),
68
+ // RFC-1639: "folder" marks records about the superfolder rather than the
69
+ // repo holding the registry — metadata only, never a second namespace.
70
+ level: z.enum(["repo", "folder"]).optional(),
71
+ // RFC-1639: provenance for `friction.migrate --from` ingests — the source
72
+ // registry's dir basename and the record's old id there.
73
+ origin: z.string().min(1).optional(),
74
+ migratedFrom: z.string().regex(FRICTION_ID_PATTERN).optional(),
67
75
  artifacts: z.array(z.string().min(1)),
68
76
  status: z.enum(FRICTION_STATUSES),
69
77
  recurrences: z.number().int().min(0),
@@ -6,12 +6,12 @@
6
6
  </non-goals>
7
7
  </MODULE_CONTRACT>
8
8
  <CHANGE_SUMMARY>
9
- <item>F-0287: union the committed check-counters projection into emittedIds — journals are worktree-local, so fresh session checkouts could never reproduce primary's firing evidence and the ratchet refused on inherited develop debt</item>
10
9
  <item>RFC-1592: make probe-catalog liveness worktree-reproducible and exclude app-scope rules (F-0287)</item>
11
10
  <item>F-0287 r2: union shared flow-journal refusal ids into emittedIds — integrate refusals journal {rule} to &lt;commonGitDir&gt;/forge/journal.jsonl, the only firing evidence that outlives session worktrees for rebase-class rules (FLOW-INT-02) no file fixture can seed</item>
12
11
  <item>RFC-1592: union shared flow-journal refusal ids into probe-catalog emittedIds — FLOW-INT-02 and rebase-class rules keep firing evidence after the session worktree's counters journal dies with it (F-0287 r2)</item>
13
12
  <item>RFC-1592: use synthetic FLOW-INT-99 in the shared-journal liveness test — a real rule id literal in the diff trips FLOW-INT-19's duplicate governance scan (F-0287 r2 follow-up)</item>
14
- <history>RFC-1469, RFC-1485, RFC-1592</history>
13
+ <item>RFC-1642: make the probe ratchet reproducible — bound fixture is liveness, mutating rules exempt</item>
14
+ <history>F-0287, RFC-1469, RFC-1485, RFC-1592</history>
15
15
  </CHANGE_SUMMARY>
16
16
  */
17
17
 
@@ -237,6 +237,30 @@ async function commandScopeMap(
237
237
  return out;
238
238
  }
239
239
 
240
+ /**
241
+ * RFC-1640 follow-up: command → mutatesState from the generated command
242
+ * manifest. A mutating command's rules cannot be proven by a gate.probe
243
+ * fixture (the probe injects a violation and invokes a CHECK command), so the
244
+ * ratchet exempts them the same way it exempts app-scope rules.
245
+ */
246
+ async function commandMutatesStateMap(
247
+ root: string,
248
+ io: ReturnType<typeof resolveIo>,
249
+ ): Promise<Map<string, boolean>> {
250
+ const src = await io
251
+ .readFile(path.join(root, "docs/command-manifest.generated.yaml"))
252
+ .catch(() => null);
253
+ const out = new Map<string, boolean>();
254
+ if (src === null) return out;
255
+ const parsed = yamlParse(src) as {
256
+ commands?: { name?: unknown; mutatesState?: unknown }[];
257
+ } | null;
258
+ for (const c of parsed?.commands ?? []) {
259
+ if (typeof c.name === "string") out.set(c.name, c.mutatesState === true);
260
+ }
261
+ return out;
262
+ }
263
+
240
264
  export async function runGateProbeCatalog(
241
265
  input: ForgeCommandInput,
242
266
  context: ForgeRuntimeContext,
@@ -292,9 +316,17 @@ export async function runGateProbeCatalog(
292
316
  // F-0287/RFC-1518 D-001); commands missing from the manifest stay in-domain
293
317
  // (fail-closed).
294
318
  const commandScope = await commandScopeMap(root, io);
295
- const ratchetRules = errorRules.filter(
296
- (r) => r.command === undefined || commandScope.get(r.command) !== "app",
297
- );
319
+ const commandMutates = await commandMutatesStateMap(root, io);
320
+ // RFC-1640 follow-up: a mutating command's rule cannot be proven by a
321
+ // gate.probe fixture (the probe injects a violation and invokes a check),
322
+ // so it is exempt from the unprobed ratchet — like app-scope rules, which
323
+ // the app-side gate judges. Their coverage is the command's unit tests.
324
+ const ratchetRules = errorRules.filter((r) => {
325
+ if (r.command === undefined) return true;
326
+ if (commandScope.get(r.command) === "app") return false;
327
+ if (commandMutates.get(r.command) === true) return false;
328
+ return true;
329
+ });
298
330
  const unprobedErrorRules = errorRules.filter((r) => !bound.has(r.id)).map((r) => r.id);
299
331
  // PROBE-05: fixture bindings pointing at rules no longer declared anywhere.
300
332
  const allDeclared = new Set(allRules.map((r) => r.id));
@@ -359,7 +391,7 @@ export async function runGateProbeCatalog(
359
391
  const ratchetIds = new Set(ratchetRules.map((r) => r.id));
360
392
  const livenessById = new Map(ratchetRules.map((r) => [r.id, livenessOf(r)]));
361
393
  const noneRules = ratchetRules
362
- .filter((r) => livenessById.get(r.id) === "none")
394
+ .filter((r) => !bound.has(r.id) && livenessById.get(r.id) === "none")
363
395
  .map((r) => r.id)
364
396
  .sort();
365
397
 
@@ -370,7 +402,7 @@ export async function runGateProbeCatalog(
370
402
  // Baseline entries owned by app-scope commands are out of this surface's
371
403
  // domain — the app-side gate judges their liveness. A rule gone from the
372
404
  // inventory entirely is stale regardless of scope.
373
- ratchetIds.has(id) ? livenessById.get(id) !== "none" : !allDeclared.has(id),
405
+ ratchetIds.has(id) ? bound.has(id) || livenessById.get(id) !== "none" : !allDeclared.has(id),
374
406
  );
375
407
 
376
408
  if (writeBaseline) {
@@ -6,32 +6,11 @@
6
6
  </non-goals>
7
7
  </MODULE_CONTRACT>
8
8
  <CHANGE_SUMMARY>
9
- <item>RFC-1592: probe-or-retire ratchet for blocking check rules
10
-
11
- Every error-severity check rule now needs liveness evidence — a bound
12
- gate-probe fixture that has actually run — or an explicit entry in the
13
- shrink-only unprobed baseline, enforced by gate.probe.catalog --check
14
- (PROBE-06/07) and wired into the worktree gate as probe-ratchet.
15
-
16
- - probe-runs journal (docs/.index/gate-probes/runs.jsonl) records each
17
- gate.probe fixture execution; shared liveness.ts joins fixtures x
18
- journal for catalog + contribution report (liveness: none|fixture|fired)
19
- - gate.probe.catalog --check/--write-baseline: PROBE-06 unprobed error
20
- rule, PROBE-07 stale baseline entry, PROBE-08 baseline growth refusal
21
- (shrink-only, no file modification), PROBE-09 expired/undeclared
22
- warnOnly provisional step
23
- - checks.contribution.report adds liveness to every rule record
24
- - KernelPipelineStep/RuleDescriptor gain provisionalUntil; the two
25
- warnOnly pipeline steps carry future dates
26
- - worktree gate adds probe-ratchet step; gate-domains + forge pre-lock
27
- DELTA_STEP_SPECS mirror updated
28
- - build-verification policy states blocking rules are probed or retired;
29
- fo-session-retro preserves probe/retire evidence for escape frictions
30
- - baseline adopted at 1678 entries (forge/unprobed-baseline@1)</item>
31
9
  <item>F-0287: committed-counters union + scope:app domain exclusion tests — evidence reproducibility across worktrees</item>
32
10
  <item>RFC-1592: make probe-catalog liveness worktree-reproducible and exclude app-scope rules (F-0287)</item>
33
11
  <item>RFC-1592: union shared flow-journal refusal ids into probe-catalog emittedIds — FLOW-INT-02 and rebase-class rules keep firing evidence after the session worktree's counters journal dies with it (F-0287 r2)</item>
34
12
  <item>RFC-1592: use synthetic FLOW-INT-99 in the shared-journal liveness test — a real rule id literal in the diff trips FLOW-INT-19's duplicate governance scan (F-0287 r2 follow-up)</item>
13
+ <item>RFC-1642: make the probe ratchet reproducible — bound fixture is liveness, mutating rules exempt</item>
35
14
  <history>RFC-1592</history>
36
15
  </CHANGE_SUMMARY>
37
16
  */
@@ -125,6 +104,35 @@ async function writeBaseline(rules: string[]) {
125
104
  );
126
105
  }
127
106
 
107
+ /** Seed the inventory with a validator bound to a command (for the mutating exemption). */
108
+ async function seedInventoryForCommand(
109
+ command: string,
110
+ rules: { id: string; severity?: string }[],
111
+ ) {
112
+ await mkdir(join(root, "docs"), { recursive: true });
113
+ const body = rules
114
+ .map((r) => ` - id: ${r.id}\n severity: ${r.severity ?? "error"}`)
115
+ .join("\n");
116
+ await writeFile(
117
+ join(root, "docs", "validator-inventory.generated.yaml"),
118
+ `contracts:\n - contract: knowledge\n validators:\n - command: ${command}\n rules:\n${body}\n`,
119
+ );
120
+ }
121
+
122
+ /** Seed the generated command manifest with scope + mutatesState per command. */
123
+ async function seedCommandManifest(
124
+ commands: { name: string; mutatesState?: boolean; scope?: string }[],
125
+ ) {
126
+ await mkdir(join(root, "docs"), { recursive: true });
127
+ const body = commands
128
+ .map(
129
+ (c) =>
130
+ ` - name: ${c.name}\n scope: ${c.scope ?? "workspace"}\n mutatesState: ${c.mutatesState === true}`,
131
+ )
132
+ .join("\n");
133
+ await writeFile(join(root, "docs", "command-manifest.generated.yaml"), `commands:\n${body}\n`);
134
+ }
135
+
128
136
  beforeEach(async () => {
129
137
  root = await mkdtemp(join(tmpdir(), "probe-ratchet-"));
130
138
  });
@@ -326,4 +334,31 @@ describe("gate.probe.catalog ratchet (RFC-1592)", () => {
326
334
  expect(msg).toContain("WS-ONLY-01");
327
335
  expect(msg).not.toContain("FLOW-INT-99");
328
336
  });
337
+
338
+ test("RFC-1640 follow-up: a bound fixture counts as liveness without a recorded probe run (reproducible across checkouts)", async () => {
339
+ await seedInventory([{ id: "BOUND-NORUN-01" }]);
340
+ await seedFixture("BOUND-NORUN-01");
341
+ // No probe-run journal entry and no baseline entry — the committed fixture alone is evidence.
342
+ const res = await runGateProbeCatalog(flags({ check: true }), ctx());
343
+ expect(res.exitCode).toBe(0);
344
+ expect(res.data?.diagnostics ?? []).toHaveLength(0);
345
+ });
346
+
347
+ test("RFC-1640 follow-up: a mutating-command error rule is exempt from the unprobed ratchet", async () => {
348
+ await seedInventoryForCommand("demo.mutate", [{ id: "MUT-06" }]);
349
+ await seedCommandManifest([{ name: "demo.mutate", mutatesState: true }]);
350
+ // No fixture, no baseline — a mutating command's rule cannot be probe-fixtured → exempt.
351
+ const res = await runGateProbeCatalog(flags({ check: true }), ctx());
352
+ expect(res.exitCode).toBe(0);
353
+ expect(res.data?.diagnostics ?? []).toHaveLength(0);
354
+ });
355
+
356
+ test("RFC-1640 follow-up: a non-mutating command's unprobed error rule still flags PROBE-06", async () => {
357
+ await seedInventoryForCommand("demo.check", [{ id: "CHECK-06" }]);
358
+ await seedCommandManifest([{ name: "demo.check", mutatesState: false }]);
359
+ const res = await runGateProbeCatalog(flags({ check: true }), ctx());
360
+ expect(res.exitCode).toBe(1);
361
+ const p6 = res.data?.diagnostics?.filter((d) => d.ruleId === "PROBE-06") ?? [];
362
+ expect(p6.map((d) => d.message).join()).toContain("CHECK-06");
363
+ });
329
364
  });