rungate 0.4.1 → 0.6.0

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 (87) hide show
  1. package/config/behavioral-sc-map.json +170 -0
  2. package/config/brief-policies.json +28 -0
  3. package/config/ceremony-profiles.json +207 -0
  4. package/config/check-registry.json +114 -0
  5. package/config/matcher-registry.json +142 -0
  6. package/config/prove-evidence.schema.json +65 -0
  7. package/config/spec-policies.json +36 -0
  8. package/config/universal-rules.yaml +15 -0
  9. package/config/workflow-schema.json +279 -0
  10. package/lib/agents-md-sections.ts +144 -0
  11. package/lib/branch-diff.ts +139 -0
  12. package/lib/bun-version.ts +268 -0
  13. package/lib/ci-checkout.ts +1 -1
  14. package/lib/cli-commands.ts +7 -1
  15. package/lib/compliance.ts +13 -11
  16. package/lib/config-loader.ts +12 -0
  17. package/lib/conformity.ts +1147 -116
  18. package/lib/context-docs.ts +143 -28
  19. package/lib/create-brief.ts +2 -1
  20. package/lib/create-sc.ts +90 -4
  21. package/lib/doc-scan-targets.ts +9 -0
  22. package/lib/evidence-command-transport.ts +160 -0
  23. package/lib/evidence-prevalidator.ts +22 -0
  24. package/lib/fallow-availability.ts +129 -0
  25. package/lib/gate-refusal-currency.ts +112 -0
  26. package/lib/gate-timeouts.ts +82 -0
  27. package/lib/generators/agent-briefs.ts +4 -1
  28. package/lib/generators/agents-md.ts +71 -23
  29. package/lib/generators/code-map.ts +2 -1
  30. package/lib/generators/types.ts +8 -0
  31. package/lib/git-dates.ts +55 -0
  32. package/lib/github.ts +195 -0
  33. package/lib/js-top-level-code.ts +27 -2
  34. package/lib/junit-checks.ts +484 -0
  35. package/lib/local-calendar-day.ts +78 -0
  36. package/lib/package-closure.ts +278 -2
  37. package/lib/project-state-shape.ts +59 -0
  38. package/lib/promote-outputs.ts +6 -2
  39. package/lib/release-preflight.ts +196 -0
  40. package/lib/report-provenance.ts +156 -0
  41. package/lib/sc-claim-forms.ts +75 -0
  42. package/lib/sc-id-cross-tree.ts +311 -0
  43. package/lib/scaffold/ai-review-step.ts +180 -0
  44. package/lib/scaffold/defaults.ts +40 -0
  45. package/lib/scaffold/managed-workflow.ts +125 -27
  46. package/lib/scaffold/owned-files.ts +48 -2
  47. package/lib/scaffold/profiles.ts +94 -0
  48. package/lib/scaffold/rehearsal.ts +232 -73
  49. package/lib/scaffold/steps.ts +777 -152
  50. package/lib/scaffold/write-steps.ts +56 -13
  51. package/lib/scanner.ts +38 -12
  52. package/lib/source-anchor.ts +144 -0
  53. package/lib/spec-listing.ts +148 -0
  54. package/lib/spec-requirements.ts +209 -0
  55. package/lib/success-doc.ts +779 -0
  56. package/lib/suite-run-reading.ts +364 -0
  57. package/lib/test-census.ts +199 -0
  58. package/lib/test-command.ts +133 -0
  59. package/lib/test-suite-lock.ts +166 -10
  60. package/lib/tool-probe.ts +120 -0
  61. package/lib/tracked-vs-ignored.ts +234 -0
  62. package/lib/trajectory.ts +377 -0
  63. package/lib/validators/spec-validators.ts +35 -6
  64. package/lib/workflow-security.ts +101 -0
  65. package/lib/workflow-test-harness.ts +349 -0
  66. package/package.json +6 -1
  67. package/scripts/audit-specs.ts +247 -12
  68. package/scripts/audit-transcript.ts +2 -1
  69. package/scripts/convert-spec.ts +2 -1
  70. package/scripts/create-sc.ts +17 -7
  71. package/scripts/create-spec.ts +2 -1
  72. package/scripts/create-success.ts +163 -0
  73. package/scripts/extract-constraints.ts +90 -19
  74. package/scripts/generate-code-map.ts +53 -12
  75. package/scripts/scaffold-project.ts +31 -4
  76. package/scripts/split-spec.ts +2 -1
  77. package/scripts/sync-sc-status.ts +57 -5
  78. package/scripts/sync-spec-tests.ts +2 -1
  79. package/specs/SPEC-TEMPLATE.md +200 -0
  80. package/templates/SUCCESS-TEMPLATE.md +72 -0
  81. package/templates/agent-briefs/_shared.md +9 -0
  82. package/templates/agent-briefs/aditi.md +46 -0
  83. package/templates/agent-briefs/discovery.md +37 -0
  84. package/templates/agent-briefs/marcus.md +39 -0
  85. package/templates/agent-briefs/quinn.md +67 -0
  86. package/templates/agent-briefs/rook.md +40 -0
  87. package/templates/agent-briefs/serena.md +39 -0
@@ -0,0 +1,234 @@
1
+ /**
2
+ * A file that is both tracked and ignored (#471).
3
+ *
4
+ * A `.gitignore` rule written with a trailing slash — `node_modules/` — does
5
+ * not match a **symlink** named `node_modules`. `git add .` therefore tracks
6
+ * it, and what lands in the commit is a mode `120000` blob whose entire
7
+ * content is a machine-absolute path:
8
+ *
9
+ * ```
10
+ * $ git ls-files -s node_modules
11
+ * 120000 b8d92fe8221f2696f298301e01225ec1973e5336 0 node_modules
12
+ * $ git cat-file -p b8d92fe8
13
+ * /Users/<someone>/Projects/<their-project>/node_modules
14
+ * ```
15
+ *
16
+ * Reported from a consumer repo with two such entries against a `.gitignore`
17
+ * that named both correctly. **`git status` was clean throughout**, and that
18
+ * is the whole problem: the rule is right, the mental model is right, and the
19
+ * only thing that reveals the divergence is `git ls-files`.
20
+ *
21
+ * Any worktree-isolated agent that symlinks `node_modules` instead of
22
+ * installing hits this, and the harness is what creates those worktrees.
23
+ *
24
+ * ## The obvious detector does not catch the reported case, measured
25
+ *
26
+ * The shape this was filed as is *fail when `git ls-files` returns a path
27
+ * that `git check-ignore` also matches*. That is a real contradiction and it
28
+ * is the first finding below — but run against the reported case it reports
29
+ * nothing, for the same reason the bug exists:
30
+ *
31
+ * ```
32
+ * $ git check-ignore --no-index -v node_modules
33
+ * $ echo $?
34
+ * 1
35
+ * ```
36
+ *
37
+ * `node_modules/` does not match a symlink named `node_modules`, and
38
+ * `check-ignore` says so just as faithfully as `git add` did. Asking it
39
+ * about a path below the link does not help either — `git check-ignore
40
+ * --no-index node_modules/anything` is `fatal: pathspec ... is beyond a
41
+ * symbolic link`. A detector built only on the agreement between those two
42
+ * commands is narrower than the thing it was written to detect, which is the
43
+ * second shape in `.claude/rules/checks-must-be-able-to-fail.md` arriving in
44
+ * the check rather than in the ignore rule.
45
+ *
46
+ * So there are two findings, and the second is the one that catches #471:
47
+ *
48
+ * 1. **tracked and ignored** — a statement of intent contradicting itself,
49
+ * whatever rule produced it. Catches a `git add -f` of an ignored file.
50
+ * 2. **a tracked symlink pointing at an absolute path** — which needs no
51
+ * ignore rule to be wrong. The blob's content is a path on one machine,
52
+ * so the checkout is broken for everyone else, and no `.gitignore` edit
53
+ * can make it right.
54
+ *
55
+ * ## `--no-index`, and why its absence would be a check that cannot fail
56
+ *
57
+ * `git check-ignore` SKIPS files in the index unless `--no-index` is given.
58
+ * Without it the command is asked about tracked paths and answers about
59
+ * untracked ones, so the comparison is between a list and the empty set and
60
+ * can never report anything. The one flag is the difference between this
61
+ * module and a green line in a report.
62
+ *
63
+ * ## Exit codes, and the fail-open that is one `catch` away
64
+ *
65
+ * `git check-ignore` exits 0 when something matched, **1 when nothing
66
+ * matched**, and 128 on an error. A `try { ... } catch { return [] }` around
67
+ * it reads the error case as the clean case, which is the first shape in
68
+ * `.claude/rules/checks-must-be-able-to-fail.md`. So 1 is a result and
69
+ * anything else is a `failure` the caller must surface.
70
+ *
71
+ * ## It does not read `git status`
72
+ *
73
+ * Asserted by a test, not merely intended. `git status` was clean in the
74
+ * reported case, so a detector that consults it cannot see this at all.
75
+ */
76
+ import { spawnSync } from "child_process";
77
+
78
+ /**
79
+ * Why a tracked path is a finding. A path can be both.
80
+ *
81
+ * `absolute-symlink` deliberately does not mention ignore rules: a committed
82
+ * link to `/Users/<someone>/...` is wrong in a repository that never had a
83
+ * rule about it.
84
+ */
85
+ export type FindingReason = "tracked-and-ignored" | "absolute-symlink" | "unreadable-symlink";
86
+
87
+ /** One tracked path that should not be tracked the way it is. */
88
+ export interface Finding {
89
+ path: string;
90
+ /** The index mode: `100644` a file, `100755` executable, `120000` a symlink. */
91
+ mode: string;
92
+ sha: string;
93
+ /**
94
+ * For a symlink, the blob's content — which IS the link target, and is
95
+ * usually an absolute path that means nothing on another machine. Null for
96
+ * anything else: the path and the mode are the finding there.
97
+ */
98
+ linkTarget: string | null;
99
+ reasons: FindingReason[];
100
+ }
101
+
102
+ export interface TrackedIgnoredReading {
103
+ findings: Finding[];
104
+ /**
105
+ * How many tracked paths were compared. An empty corpus and a clean one
106
+ * give the same verdict, and only this tells them apart.
107
+ */
108
+ trackedCount: number;
109
+ /**
110
+ * Non-null when the comparison could not be made. Never conflated with
111
+ * "nothing found": that conflation is the defect this module is about,
112
+ * arriving in the detector instead of in the ignore rule.
113
+ */
114
+ failure: string | null;
115
+ }
116
+
117
+ function run(root: string, args: string[], input?: string): { status: number; stdout: string; stderr: string } {
118
+ const r = spawnSync("git", args, {
119
+ cwd: root,
120
+ input,
121
+ encoding: "utf-8",
122
+ timeout: 120_000,
123
+ maxBuffer: 64 * 1024 * 1024,
124
+ });
125
+ if (r.error) return { status: -1, stdout: "", stderr: r.error.message };
126
+ return { status: r.status ?? -1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
127
+ }
128
+
129
+ /** `<mode> <sha> <stage>\t<path>` per NUL-separated record. */
130
+ function parseLsFiles(out: string): Array<{ mode: string; sha: string; path: string }> {
131
+ const entries: Array<{ mode: string; sha: string; path: string }> = [];
132
+ for (const record of out.split("\0")) {
133
+ if (record === "") continue;
134
+ const tab = record.indexOf("\t");
135
+ if (tab === -1) continue;
136
+ const [mode, sha] = record.slice(0, tab).split(/\s+/);
137
+ if (!mode || !sha) continue;
138
+ entries.push({ mode, sha, path: record.slice(tab + 1) });
139
+ }
140
+ return entries;
141
+ }
142
+
143
+ /**
144
+ * Every tracked path this repository's ignore rules also match.
145
+ *
146
+ * `root` must be inside a git repository; anything else is a `failure`
147
+ * rather than an empty result.
148
+ */
149
+ export function trackedAndIgnored(root: string): TrackedIgnoredReading {
150
+ const listed = run(root, ["ls-files", "-s", "-z"]);
151
+ if (listed.status !== 0) {
152
+ return {
153
+ findings: [],
154
+ trackedCount: 0,
155
+ failure: `git ls-files failed (${listed.status}): ${listed.stderr.trim() || "no output"}`,
156
+ };
157
+ }
158
+ const tracked = parseLsFiles(listed.stdout);
159
+ if (tracked.length === 0) {
160
+ return { findings: [], trackedCount: 0, failure: null };
161
+ }
162
+
163
+ // `--no-index` or this asks about the wrong set. `--stdin -z` because a
164
+ // path may contain anything, including a newline.
165
+ const checked = run(
166
+ root,
167
+ ["check-ignore", "--no-index", "--stdin", "-z"],
168
+ tracked.map(t => t.path).join("\0") + "\0",
169
+ );
170
+ // 0: at least one matched. 1: none did, which is the clean answer and not
171
+ // an error. Anything else is an error, and reporting it as clean is the
172
+ // fail-open this whole module exists to be the opposite of.
173
+ if (checked.status !== 0 && checked.status !== 1) {
174
+ return {
175
+ findings: [],
176
+ trackedCount: tracked.length,
177
+ failure: `git check-ignore failed (${checked.status}): ${checked.stderr.trim() || "no output"}`,
178
+ };
179
+ }
180
+
181
+ const matched = new Set(checked.stdout.split("\0").filter(p => p !== ""));
182
+ const findings: Finding[] = [];
183
+ for (const entry of tracked) {
184
+ const reasons: FindingReason[] = [];
185
+ if (matched.has(entry.path)) reasons.push("tracked-and-ignored");
186
+
187
+ let linkTarget: string | null = null;
188
+ if (entry.mode === "120000") {
189
+ // The blob of a symlink IS its target. `node_modules` tracked as a
190
+ // directory of files is wasteful; `node_modules` tracked as a link to
191
+ // an absolute path is what breaks on another machine, and the mode is
192
+ // the only thing that tells the two apart.
193
+ const blob = run(root, ["cat-file", "-p", entry.sha]);
194
+ linkTarget = blob.status === 0 ? blob.stdout.trim() : null;
195
+ if (linkTarget === null) {
196
+ // A link whose target could not be read is a finding, not a pass.
197
+ // Treating it as "no target, therefore not absolute" would make a
198
+ // broken `cat-file` the cheapest way to clear this check — the
199
+ // fail-open this module's own docstring warns about, one branch
200
+ // below where it warns about it. Found by security review.
201
+ reasons.push("unreadable-symlink");
202
+ } else if (linkTarget.startsWith("/")) {
203
+ // A relative link is a repository making a statement about itself
204
+ // and is portable. An absolute one is a statement about one
205
+ // filesystem.
206
+ reasons.push("absolute-symlink");
207
+ }
208
+ }
209
+
210
+ if (reasons.length > 0) {
211
+ findings.push({ path: entry.path, mode: entry.mode, sha: entry.sha, linkTarget, reasons });
212
+ }
213
+ }
214
+ return { findings, trackedCount: tracked.length, failure: null };
215
+ }
216
+
217
+ /** The refusal text, naming the mode and — for a link — where it points. */
218
+ export function describeFindings(reading: TrackedIgnoredReading): string[] {
219
+ if (reading.failure !== null) return [`UNMEASURED: ${reading.failure}`];
220
+ return reading.findings.map(f => {
221
+ const kind = f.mode === "120000" ? "symlink" : `mode ${f.mode}`;
222
+ const target = f.linkTarget !== null ? ` -> ${f.linkTarget}` : "";
223
+ const why = f.reasons
224
+ .map(r => {
225
+ if (r === "tracked-and-ignored") return "matched by this repository's own ignore rules";
226
+ if (r === "absolute-symlink") {
227
+ return "a link to an absolute path, which resolves to nothing on another machine";
228
+ }
229
+ return "UNMEASURED: a link whose target could not be read, so it cannot be judged";
230
+ })
231
+ .join("; ");
232
+ return `${f.path} is tracked (${kind}${target}): ${why}`;
233
+ });
234
+ }
@@ -0,0 +1,377 @@
1
+ /**
2
+ * The run's trajectory: one JSONL artifact, one short line per event, read
3
+ * back as an ordered timeline (#60).
4
+ *
5
+ * WHY THIS IS NOT A NEW ARTIFACT
6
+ *
7
+ * #60 asked for `{workDir}/trajectory.jsonl` holding agent calls, phases,
8
+ * gates and state mutations, written by wrapping `agent()` and `phase()` in
9
+ * `workflows/ship.js`. The workflow cannot do that: it runs in the Workflow
10
+ * sandbox with no filesystem, no subprocess and no `Date.now()` (#69). Every
11
+ * artifact it produces crosses that boundary through a script an agent is
12
+ * instructed to run — which is exactly what `scripts/record-agent-timings.ts`
13
+ * already is, and it already writes one short line per event to
14
+ * `${WORK_DIR}/agent-timings.jsonl` (#227, #239).
15
+ *
16
+ * So the trajectory is that file, widened. A second JSONL beside it would be a
17
+ * second source of truth for when an agent ran, and the two would disagree the
18
+ * first time one of them lost a line.
19
+ *
20
+ * WHAT A LINE LOOKS LIKE
21
+ *
22
+ * {"label":"discovery","event":"start","at":1,"phase":"Discovery"}
23
+ * {"type":"mutation","at":2,"fields":["acs","sizing"],"source":"scope-1"}
24
+ * {"type":"gate","at":3,"gate":"scope","result":"PASS","failures":[]}
25
+ *
26
+ * An agent bracket carries NO `type`, because thousands of them are already on
27
+ * disk in in-flight runs and a reader that called those malformed would be
28
+ * reporting a defect it had just introduced. `type` is absent ⇒ agent bracket;
29
+ * present ⇒ one of the kinds below.
30
+ *
31
+ * WHAT IT DOES NOT CLAIM
32
+ *
33
+ * Phase spans are DERIVED from the agent records that carry a phase, so a
34
+ * phase's measured span is "from the first agent that reported in it to the
35
+ * last". The gap between two phases — gate runs, sandbox logic, the workflow
36
+ * thinking — is visible as a gap and is not attributed to either.
37
+ *
38
+ * **A phase with no agent records is not a zero-length phase, and this module
39
+ * will not say that it is.** It is absent from `phaseSpans` entirely, and
40
+ * `scripts/view-trajectory.ts` prints a line saying the timeline reports what
41
+ * recorded rather than what ran. `0`, `{}` and silence are indistinguishable
42
+ * from success; absence that announces itself is not
43
+ * (`.claude/rules/config-access.md`, Silent Default Substitution).
44
+ */
45
+
46
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "fs";
47
+ import { dirname, join } from "path";
48
+
49
+ /** The artifact every run writes, named for what it has always been called. */
50
+ export const TRAJECTORY_FILENAME = "agent-timings.jsonl";
51
+
52
+ /** The artifact for a run whose state file is at `sf`. */
53
+ export function trajectoryFor(stateFile: string): string {
54
+ return join(dirname(stateFile), TRAJECTORY_FILENAME);
55
+ }
56
+
57
+ export interface AgentRecord {
58
+ kind: "agent";
59
+ label: string;
60
+ event: "start" | "end" | "queued";
61
+ at: number;
62
+ waitedMs?: number;
63
+ /** The ship.js phase this call site belongs to. Absent on pre-#60 lines. */
64
+ phase?: string;
65
+ }
66
+
67
+ export interface MutationRecord {
68
+ kind: "mutation";
69
+ at: number;
70
+ /** Dotted paths that changed, one level into `gates` and `environments`. */
71
+ fields: string[];
72
+ /**
73
+ * Who wrote it, when that is knowable.
74
+ *
75
+ * It usually is not: `writeWorkflowState` is called from an agent's `bun -e`
76
+ * one-liner and nothing in that process knows which call site spawned it.
77
+ * #60 asked for "by which agent" and this is the honest half of it — the
78
+ * field is omitted rather than filled with a guess, and the viewer prints
79
+ * `unattributed`, which is a different word from a name.
80
+ */
81
+ source?: string;
82
+ }
83
+
84
+ export interface GateRecord {
85
+ kind: "gate";
86
+ at: number;
87
+ gate: string;
88
+ result: string;
89
+ failures: string[];
90
+ }
91
+
92
+ export type TrajectoryRecord = AgentRecord | MutationRecord | GateRecord;
93
+
94
+ export interface TrajectoryRead {
95
+ records: TrajectoryRecord[];
96
+ /** Lines that did not parse as any known record, verbatim. Never discarded. */
97
+ malformed: string[];
98
+ /** The artifact does not exist. Distinct from "it exists and is empty". */
99
+ missing: boolean;
100
+ }
101
+
102
+ // ── writing ──────────────────────────────────────────────────
103
+
104
+ /**
105
+ * Append one record. One `JSON.stringify` and one `appendFileSync`, under the
106
+ * pipe-buffer size, which is what keeps concurrent agents from interleaving
107
+ * mid-line — the same discipline `recordEvent` has always used.
108
+ */
109
+ export function appendTrajectory(artifact: string, record: TrajectoryRecord): void {
110
+ mkdirSync(dirname(artifact), { recursive: true });
111
+ const { kind, ...rest } = record;
112
+ const line = kind === "agent" ? rest : { type: kind, ...rest };
113
+ appendFileSync(artifact, `${JSON.stringify(line)}\n`);
114
+ }
115
+
116
+ // ── reading ──────────────────────────────────────────────────
117
+
118
+ function parseAgent(v: Record<string, unknown>): AgentRecord | null {
119
+ const { label, event, at, waitedMs, phase } = v;
120
+ if (typeof label !== "string" || label.length === 0) return null;
121
+ if (event !== "start" && event !== "end" && event !== "queued") return null;
122
+ if (typeof at !== "number" || !Number.isFinite(at)) return null;
123
+ // A queued record with no readable duration is MALFORMED, never a zero wait:
124
+ // reading it as zero makes the one record whose job is to say "this call
125
+ // waited" report that it did not (#239).
126
+ if (event === "queued" && (typeof waitedMs !== "number" || !Number.isFinite(waitedMs) || waitedMs < 0)) {
127
+ return null;
128
+ }
129
+ return {
130
+ kind: "agent",
131
+ label,
132
+ event,
133
+ at,
134
+ ...(event === "queued" ? { waitedMs: waitedMs as number } : {}),
135
+ ...(typeof phase === "string" && phase.length > 0 ? { phase } : {}),
136
+ };
137
+ }
138
+
139
+ function parseMutation(v: Record<string, unknown>): MutationRecord | null {
140
+ const { at, fields, source } = v;
141
+ if (typeof at !== "number" || !Number.isFinite(at)) return null;
142
+ if (!Array.isArray(fields)) return null;
143
+ const clean = fields.filter((f): f is string => typeof f === "string" && f.length > 0);
144
+ // A mutation that changed nothing is not a mutation, and recording one would
145
+ // put a row in the timeline saying a write happened with no content — the
146
+ // shape a reader would treat as "something changed and we lost what".
147
+ if (clean.length !== fields.length || clean.length === 0) return null;
148
+ return {
149
+ kind: "mutation",
150
+ at,
151
+ fields: clean,
152
+ ...(typeof source === "string" && source.length > 0 ? { source } : {}),
153
+ };
154
+ }
155
+
156
+ function parseGate(v: Record<string, unknown>): GateRecord | null {
157
+ const { at, gate, result, failures } = v;
158
+ if (typeof at !== "number" || !Number.isFinite(at)) return null;
159
+ if (typeof gate !== "string" || gate.length === 0) return null;
160
+ if (typeof result !== "string" || result.length === 0) return null;
161
+ const lines = Array.isArray(failures) ? failures.filter((f): f is string => typeof f === "string") : [];
162
+ return { kind: "gate", at, gate, result, failures: lines };
163
+ }
164
+
165
+ export function parseTrajectoryLine(line: string): TrajectoryRecord | null {
166
+ let value: unknown;
167
+ try {
168
+ value = JSON.parse(line);
169
+ } catch {
170
+ return null;
171
+ }
172
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
173
+ const v = value as Record<string, unknown>;
174
+ if (v.type === undefined) return parseAgent(v);
175
+ if (v.type === "mutation") return parseMutation(v);
176
+ if (v.type === "gate") return parseGate(v);
177
+ // A `type` this version does not know is MALFORMED rather than skipped. A
178
+ // reader that quietly drops record kinds it has not been taught reports a
179
+ // complete timeline over a file it only partly understood.
180
+ return null;
181
+ }
182
+
183
+ export function readTrajectory(artifact: string): TrajectoryRead {
184
+ if (!existsSync(artifact)) return { records: [], malformed: [], missing: true };
185
+ const records: TrajectoryRecord[] = [];
186
+ const malformed: string[] = [];
187
+ for (const line of readFileSync(artifact, "utf-8").split("\n")) {
188
+ if (line.trim() === "") continue;
189
+ const record = parseTrajectoryLine(line);
190
+ if (record) records.push(record);
191
+ else malformed.push(line);
192
+ }
193
+ return { records, malformed, missing: false };
194
+ }
195
+
196
+ // ── phase spans ──────────────────────────────────────────────
197
+
198
+ export interface PhaseSpan {
199
+ phase: string;
200
+ /** First agent event observed in this phase. */
201
+ startedAt: number;
202
+ /** Last agent event observed in this phase. */
203
+ endedAt: number;
204
+ seconds: number;
205
+ /** How many agent brackets contributed. One is a span of one call, not a phase. */
206
+ agents: number;
207
+ }
208
+
209
+ /**
210
+ * The span of each phase that recorded anything, in first-seen order.
211
+ *
212
+ * Derived rather than written, because nothing can write it: a phase boundary
213
+ * in `workflows/ship.js` is a `phase('Goal')` call inside the sandbox, with no
214
+ * clock and no filesystem. The agents inside the phase are the only
215
+ * participants that can report, so the phase is as wide as its agents and no
216
+ * wider.
217
+ *
218
+ * Phases that recorded nothing do not appear. That is the honest answer and it
219
+ * is why `scripts/view-trajectory.ts` prints the caveat rather than listing a
220
+ * phase at zero seconds.
221
+ */
222
+ export function phaseSpans(records: TrajectoryRecord[]): PhaseSpan[] {
223
+ const order: string[] = [];
224
+ const byPhase = new Map<string, { first: number; last: number; labels: Set<string> }>();
225
+ for (const r of records) {
226
+ if (r.kind !== "agent" || !r.phase) continue;
227
+ const seen = byPhase.get(r.phase);
228
+ if (!seen) {
229
+ order.push(r.phase);
230
+ byPhase.set(r.phase, { first: r.at, last: r.at, labels: new Set([r.label]) });
231
+ continue;
232
+ }
233
+ // `min`/`max` rather than first-and-last-in-file: parallel agents append
234
+ // out of order, so the last line of a phase is not always its latest
235
+ // event.
236
+ seen.first = Math.min(seen.first, r.at);
237
+ seen.last = Math.max(seen.last, r.at);
238
+ seen.labels.add(r.label);
239
+ }
240
+ return order.map((phase) => {
241
+ const s = byPhase.get(phase)!;
242
+ return {
243
+ phase,
244
+ startedAt: s.first,
245
+ endedAt: s.last,
246
+ seconds: Math.round(((s.last - s.first) / 1000) * 1000) / 1000,
247
+ agents: s.labels.size,
248
+ };
249
+ });
250
+ }
251
+
252
+ // ── the merged timeline ──────────────────────────────────────
253
+
254
+ export interface TimelineRow {
255
+ at: number;
256
+ kind: TrajectoryRecord["kind"];
257
+ /** One line, already formatted. The viewer adds the clock column. */
258
+ text: string;
259
+ }
260
+
261
+ /**
262
+ * Every record as one ordered list of rows.
263
+ *
264
+ * Sorted by `at`, with ties keeping file order — several events inside one
265
+ * millisecond are common on a fast machine, and reordering them would make the
266
+ * timeline disagree with the artifact for no gain.
267
+ */
268
+ export function timeline(records: TrajectoryRecord[]): TimelineRow[] {
269
+ return records
270
+ .map((r, i) => ({ r, i }))
271
+ .sort((a, b) => a.r.at - b.r.at || a.i - b.i)
272
+ .map(({ r }) => {
273
+ if (r.kind === "agent") {
274
+ const where = r.phase ? ` [${r.phase}]` : "";
275
+ const waited = r.event === "queued" ? ` waited ${r.waitedMs}ms` : "";
276
+ return { at: r.at, kind: r.kind, text: `agent ${r.label} ${r.event}${waited}${where}` };
277
+ }
278
+ if (r.kind === "mutation") {
279
+ return {
280
+ at: r.at,
281
+ kind: r.kind,
282
+ text: `state ${r.source ?? "unattributed"} wrote ${r.fields.join(", ")}`,
283
+ };
284
+ }
285
+ const detail = r.failures.length > 0 ? ` — ${r.failures.join("; ")}` : "";
286
+ return { at: r.at, kind: r.kind, text: `gate ${r.gate} ${r.result}${detail}` };
287
+ });
288
+ }
289
+
290
+ // ── state mutations ──────────────────────────────────────────
291
+
292
+ /**
293
+ * Which field paths differ between two states.
294
+ *
295
+ * Top level, plus one level into the containers a run actually mutates during
296
+ * a pipeline — `gates`, `environments` and `gateContract`. Deeper than that is
297
+ * noise: every AC verdict edit would print a path per AC and the timeline
298
+ * would stop being readable, which is the one thing #60 is for.
299
+ *
300
+ * Compared by serialised value rather than by reference, because callers read
301
+ * the state, mutate it in place, and write the same object back — a reference
302
+ * comparison would report that nothing ever changed.
303
+ */
304
+ const NESTED = ["gates", "environments", "gateContract"];
305
+
306
+ export function changedFields(
307
+ before: Record<string, unknown> | null,
308
+ after: Record<string, unknown>,
309
+ ): string[] {
310
+ if (before === null) return ["<initial write>"];
311
+ const changed: string[] = [];
312
+ const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
313
+ for (const key of [...keys].sort()) {
314
+ const a = before[key];
315
+ const b = after[key];
316
+ if (stable(a) === stable(b)) continue;
317
+ if (!NESTED.includes(key) || !isRecord(a) || !isRecord(b)) {
318
+ changed.push(key);
319
+ continue;
320
+ }
321
+ const sub = new Set([...Object.keys(a), ...Object.keys(b)]);
322
+ for (const k of [...sub].sort()) {
323
+ if (stable(a[k]) !== stable(b[k])) changed.push(`${key}.${k}`);
324
+ }
325
+ }
326
+ return changed;
327
+ }
328
+
329
+ function isRecord(v: unknown): v is Record<string, unknown> {
330
+ return typeof v === "object" && v !== null && !Array.isArray(v);
331
+ }
332
+
333
+ function stable(v: unknown): string {
334
+ // `undefined` and absent are the same fact here, and JSON.stringify returns
335
+ // `undefined` (the value, not the string) for both — which would compare
336
+ // equal to itself and unequal to nothing, so it is normalised first.
337
+ if (v === undefined) return "\u0000absent";
338
+ return JSON.stringify(v, (_k, x) =>
339
+ isRecord(x)
340
+ ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, (x as Record<string, unknown>)[k]]))
341
+ : x,
342
+ );
343
+ }
344
+
345
+ /**
346
+ * Record a state write on the run's trajectory.
347
+ *
348
+ * **Never throws.** A trajectory line is a record OF a state write and must
349
+ * not be able to prevent one: losing the line costs a row in a timeline,
350
+ * losing the write costs the run. The failure goes to stderr rather than being
351
+ * swallowed — there is no channel left to record it on, since the thing that
352
+ * failed is the recorder.
353
+ *
354
+ * Returns the fields it recorded, or `null` when it recorded nothing, so a
355
+ * caller that wants to assert on the recording can.
356
+ */
357
+ export function recordStateWrite(
358
+ stateFile: string,
359
+ before: Record<string, unknown> | null,
360
+ after: Record<string, unknown>,
361
+ source?: string,
362
+ at: number = Date.now(),
363
+ ): string[] | null {
364
+ try {
365
+ const fields = changedFields(before, after);
366
+ if (fields.length === 0) return null;
367
+ appendTrajectory(trajectoryFor(stateFile), { kind: "mutation", at, fields, ...(source ? { source } : {}) });
368
+ return fields;
369
+ } catch (err) {
370
+ process.stderr.write(
371
+ `trajectory: could not record the state write to ${stateFile} — ` +
372
+ `${err instanceof Error ? err.message : String(err)}. The write itself is unaffected; ` +
373
+ `this run's timeline is missing a row (#60).\n`,
374
+ );
375
+ return null;
376
+ }
377
+ }
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import { existsSync, readFileSync, writeFileSync, readdirSync } from "fs";
8
8
  import { join } from "path";
9
+ import { localCalendarDay } from "../local-calendar-day";
9
10
 
10
11
  /**
11
12
  * SC-278: Detect specs that exceed 500 lines and suggest splitting.
@@ -54,7 +55,7 @@ export function checkGovernsAlignment(specsDir: string, actions: string[]): void
54
55
  export function addFrontmatterToSpecs(specsDir: string, actions: string[]): void {
55
56
  if (!existsSync(specsDir)) return;
56
57
 
57
- const today = new Date().toISOString().split("T")[0];
58
+ const today = localCalendarDay();
58
59
 
59
60
  for (const file of readdirSync(specsDir).filter(f => f.endsWith(".md"))) {
60
61
  const filePath = join(specsDir, file);
@@ -133,7 +134,7 @@ export function detectUnconvertedSpecs(specsDir: string, actions: string[]): voi
133
134
  export function addFrontmatterToAdrs(adrDir: string, actions: string[]): void {
134
135
  if (!existsSync(adrDir)) return;
135
136
 
136
- const today = new Date().toISOString().split("T")[0];
137
+ const today = localCalendarDay();
137
138
 
138
139
  for (const file of readdirSync(adrDir).filter(f => f.endsWith(".md"))) {
139
140
  const filePath = join(adrDir, file);
@@ -142,7 +143,7 @@ export function addFrontmatterToAdrs(adrDir: string, actions: string[]): void {
142
143
  if (!content.startsWith("---\n")) {
143
144
  const frontmatter = `---\ndoc-type: adr\nstatus: draft\nowner: TODO\ncreated: ${today}\nupdated: ${today}\n---\n\n`;
144
145
  writeFileSync(filePath, frontmatter + content);
145
- actions.push(`UPDATED: docs/adr/${file} (added frontmatter)`);
146
+ actions.push(`AUTO-FIXED: docs/adr/${file} (added frontmatter)`);
146
147
  } else {
147
148
  const fmEnd = content.indexOf("\n---", 4);
148
149
  if (fmEnd === -1) continue;
@@ -150,10 +151,38 @@ export function addFrontmatterToAdrs(adrDir: string, actions: string[]): void {
150
151
  const missing: string[] = [];
151
152
  if (!fm.includes("doc-type:")) missing.push(`doc-type: adr`);
152
153
  if (!fm.includes("created:")) missing.push(`created: ${today}`);
153
- if (missing.length > 0) {
154
- const newFm = `---\n${fm}\n${missing.join("\n")}\n---`;
154
+
155
+ // A doc-type that is present but WRONG (#42).
156
+ //
157
+ // The fixer used to key on whether the field existed while HYGIENE-10
158
+ // keys on its VALUE (`lib/conformity.ts`: `fm["doc-type"] !== "adr"`).
159
+ // So an ADR carrying `doc-type: guide` satisfied `fm.includes` and was
160
+ // never touched — re-scaffold ran, reported nothing, and the warning
161
+ // came back every single time. Two readers of one field disagreeing
162
+ // about what it means is why the auto-fix could not clear the finding
163
+ // it was written to clear.
164
+ //
165
+ // Corrected in place rather than appended: adding a second `doc-type:`
166
+ // line would leave a document with two, and a parser taking the first
167
+ // would keep the wrong one forever.
168
+ const wrongType = fm.match(/^(\s*doc-type:\s*)(.+?)\s*$/m);
169
+ let corrected = fm;
170
+ let retyped: string | null = null;
171
+ if (wrongType && wrongType[2] !== "adr") {
172
+ retyped = wrongType[2];
173
+ corrected = fm.replace(/^(\s*doc-type:\s*).+?\s*$/m, `$1adr`);
174
+ }
175
+
176
+ if (missing.length > 0 || retyped !== null) {
177
+ const newFm = missing.length > 0
178
+ ? `---\n${corrected}\n${missing.join("\n")}\n---`
179
+ : `---\n${corrected}\n---`;
155
180
  writeFileSync(filePath, newFm + content.substring(fmEnd + 4));
156
- actions.push(`UPDATED: docs/adr/${file} (added missing: ${missing.map(m => m.split(":")[0]).join(", ")})`);
181
+ const what = [
182
+ ...(missing.length > 0 ? [`added missing: ${missing.map(m => m.split(":")[0]).join(", ")}`] : []),
183
+ ...(retyped !== null ? [`doc-type was "${retyped}", set to adr`] : []),
184
+ ];
185
+ actions.push(`AUTO-FIXED: docs/adr/${file} (${what.join("; ")})`);
157
186
  }
158
187
  }
159
188
  }