rungate 0.3.0 → 0.4.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.
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Which instruction an agent worked from (#180).
3
+ *
4
+ * A ship run launched in the same turn as an unrelated user message gives
5
+ * every agent that message as its task, outranking the brief. The Workflow
6
+ * runtime prepends it — rungate does not write it and cannot remove it:
7
+ *
8
+ * > `[user request]` The harness relays, verbatim and indented below, the user
9
+ * > request that triggered this workflow run. This relayed request is the only
10
+ * > user voice in this task; …
11
+ *
12
+ * ## The run
13
+ *
14
+ * `wf_17267830-401` shipped #178. The relayed text was a status question typed
15
+ * in the parent session — *"What do we still need to do to get the pipeline to
16
+ * ship?"* — and Marcus returned:
17
+ *
18
+ * ```json
19
+ * {"success": true, "filesChanged": [], "testOutput":
20
+ * "No tests run — the relayed user request was a status/priority question, not
21
+ * an implementation task, and the harness framing states the user request
22
+ * wins over the computed task."}
23
+ * ```
24
+ *
25
+ * The agent was not confused. It followed the precedence the framing gave it,
26
+ * and the framing was wrong for this run. `marcus-brief.md` for the same run
27
+ * was correct and complete — 63 lines, five ACs, eight files, a canary. **The
28
+ * brief lost to text it never saw.**
29
+ *
30
+ * ## What changes, and what deliberately does not
31
+ *
32
+ * The relay is NOT removed (#180 AC-3). It is useful when the triggering
33
+ * message *is* about the run — "focus on the API half first" should still
34
+ * reach the agent. Two things change:
35
+ *
36
+ * - **Precedence.** Every briefed prompt now states that the brief's Task and
37
+ * Acceptance Criteria are authoritative and that a relayed request narrows
38
+ * or prioritises them but does not replace them.
39
+ * - **Reportability.** The implement reply carries `taskSource`, so a
40
+ * substitution is a value in the reply rather than a sentence in prose
41
+ * nobody parses. That is #166 applied to which instruction was obeyed:
42
+ * Marcus said what it did only because it chose to narrate it.
43
+ *
44
+ * The notice goes on every briefed role, not a list of implement roles. A
45
+ * hardcoded role name in harness code is the thing `.claude/rules` keeps
46
+ * filing issues about, and the claim is true of every computed brief anyway.
47
+ */
48
+
49
+ /** What an agent may say it worked from. */
50
+ export const TASK_SOURCES = ["brief", "relayed-request", "both"] as const;
51
+ export type TaskSource = (typeof TASK_SOURCES)[number];
52
+
53
+ /**
54
+ * The precedence paragraph appended to every briefed prompt.
55
+ *
56
+ * Written as one exported function so there is a single binding to mutate —
57
+ * a second copy of this wording somewhere else would survive the mutation and
58
+ * the test would go green for the wrong reason.
59
+ */
60
+ export function briefPrecedenceNotice(briefPath: string): string {
61
+ return (
62
+ `TASK PRECEDENCE — the brief is the task. The Task and Acceptance Criteria in ` +
63
+ `${briefPath} and in the prompt below are computed from the issue and are authoritative. ` +
64
+ `A relayed user request from the session that launched this run does NOT replace them: ` +
65
+ `it may narrow or prioritise the work, and if it is about something else entirely it is ` +
66
+ `not your task and you should say so rather than doing it. Run wf_17267830-401 did the ` +
67
+ `other thing — it answered a status question, changed no files and reported success.\n` +
68
+ `Report which you worked from in \`taskSource\`: "brief", "relayed-request", or "both".\n\n`
69
+ );
70
+ }
71
+
72
+ /** Minimal shape of an implement reply, as far as this check is concerned. */
73
+ export interface TaskSourceReading {
74
+ taskSource?: unknown;
75
+ }
76
+
77
+ /**
78
+ * Refuse a reply whose `taskSource` is missing or says the brief was replaced.
79
+ *
80
+ * **Absent is a refusal, not a pass** — the same decision `worktreeRepo` made
81
+ * in #218 and for the same reason: a field the run accepts as missing is a
82
+ * field that stops being written, and then the channel is gone without anyone
83
+ * deciding to remove it.
84
+ *
85
+ * `"both"` passes. The relay narrowing a brief is the case #180 AC-3 keeps
86
+ * working, and an agent that read both and says so is doing exactly what the
87
+ * notice asks.
88
+ */
89
+ export function taskSourceRefusal(result: TaskSourceReading | null | undefined, label: string): string | null {
90
+ const value = result?.taskSource;
91
+ if (value === undefined || value === null || value === "") {
92
+ return (
93
+ `${label} reported no taskSource, so which instruction it worked from is unknown. ` +
94
+ `The schema requires it (#180): an implement reply that cannot say whether it followed ` +
95
+ `the brief or a relayed message from the parent session is the state wf_17267830-401 ` +
96
+ `shipped in, where the substitution was visible only because the agent narrated it.`
97
+ );
98
+ }
99
+ if (typeof value !== "string" || !(TASK_SOURCES as readonly string[]).includes(value)) {
100
+ return (
101
+ `${label} reported taskSource ${JSON.stringify(value)}, which is not one of ` +
102
+ `${TASK_SOURCES.join(", ")}. An unrecognised value is not a verdict.`
103
+ );
104
+ }
105
+ if (value === "relayed-request") {
106
+ return (
107
+ `${label} worked from the relayed user request instead of its brief. The brief carries ` +
108
+ `this issue's acceptance criteria, governing spec, file list and verify commands; the ` +
109
+ `relayed text is whatever was typed in the session that launched the run and is not ` +
110
+ `guaranteed to be about this issue at all (#180).`
111
+ );
112
+ }
113
+ return null;
114
+ }
@@ -193,6 +193,21 @@ export function ciCheckoutPlan(opts: {
193
193
  source: string;
194
194
  dest: string;
195
195
  model: CheckoutModel;
196
+ /**
197
+ * The source repo's own `origin`, restored after the fetches (#183).
198
+ *
199
+ * `actions/checkout@v4` leaves `origin` pointing at the GitHub repository.
200
+ * This plan repoints it at `file://source` so the replayed fetches resolve
201
+ * offline, and before #183 it left it there — so a test asking "what
202
+ * repository is this checkout of" got a filesystem path under the model and
203
+ * `github.com/owner/name` in CI. `test/worktree-repo.test.ts`'s SC-1444
204
+ * positive control failed here for that reason and passed in CI, which is
205
+ * the inversion this whole module exists to prevent.
206
+ *
207
+ * Omit it and `origin` keeps the `file://` URL — a source with no origin
208
+ * has nothing to restore.
209
+ */
210
+ originUrl?: string | null;
196
211
  }): CheckoutCommand[] {
197
212
  const { source, dest, model } = opts;
198
213
  const cmds: CheckoutCommand[] = [];
@@ -227,6 +242,12 @@ export function ciCheckoutPlan(opts: {
227
242
  cmds.push({ kind: "exec", argv, inClone: true, tolerateFailure: true });
228
243
  }
229
244
 
245
+ // Last, and it has to be last: every fetch above needs `file://` to resolve
246
+ // without a network.
247
+ if (opts.originUrl) {
248
+ cmds.push({ kind: "exec", argv: ["git", "remote", "set-url", "origin", opts.originUrl], inClone: true });
249
+ }
250
+
230
251
  return cmds;
231
252
  }
232
253
 
@@ -363,8 +384,13 @@ export function prepareCiCheckout(opts: PrepareOptions): PrepareOutcome {
363
384
  }
364
385
 
365
386
  const dest = `${opts.tmpRoot}/repo`;
387
+ // What the runner's `origin` points at (#183). A source with no origin —
388
+ // a bare init, a consumer's unpushed scaffold — restores nothing, which is
389
+ // also what CI would have.
390
+ const srcOrigin = opts.run(["git", "remote", "get-url", "origin"], opts.source);
391
+ const originUrl = srcOrigin.status === 0 ? srcOrigin.stdout.trim() || null : null;
366
392
  const result = executeCheckoutPlan(
367
- ciCheckoutPlan({ source: opts.source, dest, model }),
393
+ ciCheckoutPlan({ source: opts.source, dest, model, originUrl }),
368
394
  dest,
369
395
  opts.tmpRoot,
370
396
  opts.run,
@@ -33,12 +33,17 @@
33
33
  import { existsSync, readFileSync, readdirSync, statSync } from "fs";
34
34
  import { basename, dirname, join, relative } from "path";
35
35
 
36
- import type { ComplianceEntry } from "./compliance-report";
36
+ import { COMPLIANCE_HISTORY_SCHEMA, type ComplianceEntry } from "./compliance-report";
37
37
 
38
38
  /** A grade file on disk, before it becomes history entries. */
39
39
  interface GradeRule {
40
40
  id?: string;
41
41
  verdict?: string;
42
+ // #116 — these three were on disk the whole time and the backfill dropped
43
+ // them, so a reconstructed entry was as unsourced as a live one.
44
+ rule?: string;
45
+ evidence?: string;
46
+ category?: string;
42
47
  }
43
48
 
44
49
  interface Grade {
@@ -182,9 +187,16 @@ export function planComplianceBackfill(root: string, existing: ComplianceEntry[]
182
187
  timestamp,
183
188
  issue,
184
189
  role: g.role,
185
- scores: Object.fromEntries(
186
- (g.rules ?? []).filter(r => r.id).map(r => [r.id as string, r.verdict || "N/A"]),
187
- ),
190
+ schema: COMPLIANCE_HISTORY_SCHEMA,
191
+ rules: (g.rules ?? [])
192
+ .filter(r => r.id)
193
+ .map(r => ({
194
+ id: r.id as string,
195
+ verdict: r.verdict || "N/A",
196
+ rule: r.rule,
197
+ evidence: r.evidence,
198
+ category: r.category,
199
+ })),
188
200
  total: g.total,
189
201
  followed: g.followed,
190
202
  pct: pct(g),
@@ -1,17 +1,111 @@
1
1
  import { appendFileSync, readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
2
2
  import { dirname, join } from "path";
3
3
 
4
+ /**
5
+ * The history's record shape (#116).
6
+ *
7
+ * **1** — `scores`, a flat `id → verdict` map, and nothing else.
8
+ * **2** — `rules`, the whole record the grader produced.
9
+ *
10
+ * A grade file carries `{ id, rule, verdict, evidence, category }` per rule.
11
+ * The history kept `id → verdict` and dropped the other three, so
12
+ *
13
+ * ```
14
+ * grade: { id: "DIR-L29", verdict: "VIOLATED",
15
+ * rule: "Run the full suite at most TWICE…",
16
+ * evidence: "5 bun test runs (expected 1-2)", category: "quality" }
17
+ * history: { "DIR-L29": "VIOLATED" }
18
+ * ```
19
+ *
20
+ * The second is an unsourced verdict. It cannot be re-checked, the rule text
21
+ * is unrecoverable once the rule is edited, and a trend built from it cannot
22
+ * explain itself — which is tier F by the standard this repo applies to ACs.
23
+ *
24
+ * The lossiness had not bitten only because the writer was never running
25
+ * (#69: the Grade-phase tail ran in a sandbox with no `require` and failed
26
+ * inside a `catch`). All four entries on disk when #116 was filed were
27
+ * synthetic fixtures, which is why the schema was changed then rather than
28
+ * migrated later.
29
+ */
30
+ export const COMPLIANCE_HISTORY_SCHEMA = 2;
31
+
32
+ /** One graded rule, as the grader produced it. */
33
+ export interface ComplianceRuleRecord {
34
+ id: string;
35
+ verdict: string;
36
+ /** The rule's text at grading time — not recoverable later if it is edited. */
37
+ rule?: string;
38
+ /** What the grader saw. Without it the verdict is unsourced. */
39
+ evidence?: string;
40
+ category?: string;
41
+ }
42
+
4
43
  export interface ComplianceEntry {
5
44
  timestamp: string;
6
45
  issue: string;
7
46
  role: string;
8
- scores: Record<string, string>;
47
+ /**
48
+ * Absent means 1. Stamped rather than inferred so a reader can tell "written
49
+ * before the change" from "written after it and carrying nothing".
50
+ */
51
+ schema?: number;
52
+ /** Schema 1 only. New entries do not write it — see `entryVerdicts`. */
53
+ scores?: Record<string, string>;
54
+ /** Schema 2. The full records. */
55
+ rules?: ComplianceRuleRecord[];
9
56
  total: number;
10
57
  followed: number;
11
58
  pct: number;
12
59
  flagged: string[];
13
60
  }
14
61
 
62
+ /** 1 for an unstamped entry, which is what every pre-#116 line is. */
63
+ export function historySchema(entry: ComplianceEntry): number {
64
+ return typeof entry.schema === "number" ? entry.schema : 1;
65
+ }
66
+
67
+ /**
68
+ * `id → verdict`, from whichever shape the entry is in.
69
+ *
70
+ * The single reader, so there is one place that knows both forms (SC-3). A
71
+ * v2 entry does NOT also carry `scores`: two copies of the same fact in one
72
+ * record can disagree, and nothing would notice which was right.
73
+ */
74
+ export function entryVerdicts(entry: ComplianceEntry): Record<string, string> {
75
+ if (Array.isArray(entry.rules)) {
76
+ const out: Record<string, string> = {};
77
+ for (const r of entry.rules) {
78
+ if (r && r.id) out[r.id] = r.verdict || "N/A";
79
+ }
80
+ return out;
81
+ }
82
+ return entry.scores ?? {};
83
+ }
84
+
85
+ /** The records, empty for a v1 entry — which is the point of the version. */
86
+ export function ruleRecords(entry: ComplianceEntry): ComplianceRuleRecord[] {
87
+ return Array.isArray(entry.rules) ? entry.rules : [];
88
+ }
89
+
90
+ /** The rule's recorded text for one id, newest entry first. Null if no entry kept it. */
91
+ export function recordedRuleText(entries: ComplianceEntry[], compId: string): string | null {
92
+ for (let i = entries.length - 1; i >= 0; i--) {
93
+ const hit = ruleRecords(entries[i]!).find(r => r.id === compId && r.rule);
94
+ if (hit?.rule) return hit.rule;
95
+ }
96
+ return null;
97
+ }
98
+
99
+ /** Everything recorded for one id, newest first, so a verdict can be re-checked. */
100
+ export function evidenceFor(entries: ComplianceEntry[], compId: string): ComplianceRuleRecord[] {
101
+ const out: ComplianceRuleRecord[] = [];
102
+ for (let i = entries.length - 1; i >= 0; i--) {
103
+ const hit = ruleRecords(entries[i]!).find(r => r.id === compId);
104
+ if (hit) out.push(hit);
105
+ }
106
+ return out;
107
+ }
108
+
15
109
  export interface TrendLine {
16
110
  compId: string;
17
111
  rule: string;
@@ -88,22 +182,29 @@ export function generateComplianceReport(
88
182
  const window = roleHistory.slice(-TREND_WINDOW);
89
183
  const allPcts = [...window.map((h) => h.pct), current.pct];
90
184
 
185
+ const considered = [...window, current];
186
+ const verdictMaps = new Map(considered.map(e => [e, entryVerdicts(e)]));
187
+
91
188
  const allCompIds = new Set<string>();
92
- for (const entry of [...window, current]) {
93
- for (const id of Object.keys(entry.scores)) allCompIds.add(id);
189
+ for (const entry of considered) {
190
+ for (const id of Object.keys(verdictMaps.get(entry)!)) allCompIds.add(id);
94
191
  }
95
192
 
193
+ // The rule text the grader recorded beats the hardcoded map (#116): the map
194
+ // goes stale the moment a rule is edited, and a v2 entry carries what the
195
+ // rule actually said when the verdict was reached.
196
+ const ruleTextFor = (compId: string) =>
197
+ recordedRuleText(considered, compId) || COMP_RULES[compId] || compId;
198
+
96
199
  const compTrends: TrendLine[] = [];
97
200
  for (const compId of [...allCompIds].sort()) {
98
- const verdicts = [...window, current].map(
99
- (e) => e.scores[compId] || "N/A"
100
- );
201
+ const verdicts = considered.map((e) => verdictMaps.get(e)![compId] || "N/A");
101
202
  const checkable = verdicts.filter((v) => v !== "N/A");
102
203
  const passed = checkable.filter((v) => v === "FOLLOWED").length;
103
204
  const passRate = checkable.length > 0 ? passed / checkable.length : 0;
104
205
 
105
206
  if (checkable.length < 2) {
106
- compTrends.push({ compId, rule: COMP_RULES[compId] || compId, lastN: verdicts, passRate, direction: "stable" });
207
+ compTrends.push({ compId, rule: ruleTextFor(compId), lastN: verdicts, passRate, direction: "stable" });
107
208
  continue;
108
209
  }
109
210
  const firstHalf = checkable.slice(0, Math.ceil(checkable.length / 2));
@@ -122,7 +223,7 @@ export function generateComplianceReport(
122
223
 
123
224
  compTrends.push({
124
225
  compId,
125
- rule: COMP_RULES[compId] || compId,
226
+ rule: ruleTextFor(compId),
126
227
  lastN: verdicts,
127
228
  passRate,
128
229
  direction,
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Thin typed accessors over the resolved config (#214, ADR-001 D1).
3
+ *
4
+ * ADR-001 decided on 2026-10-05 that `lib/config-loader.ts` is the sole config
5
+ * access point and named the enforcement: a conformity check that FAILS the
6
+ * suite. The check shipped under #309 as CONFIG-1/CONFIG-2 with a
7
+ * known-violations ratchet. This module is the other half — the migration the
8
+ * ratchet exists to let happen one commit at a time.
9
+ *
10
+ * ## Why accessors and not "just call the loader at each site"
11
+ *
12
+ * Six call sites wanted the same three values and each hand-rolled the whole
13
+ * read: `existsSync`, `JSON.parse`, pick a key, and — at four of them — a bare
14
+ * `catch` returning a default. Pointing six copies of that at the loader would
15
+ * remove the path construction and keep the six private answers to "what does
16
+ * unresolvable mean", which ADR-002 names as the defect under the defect:
17
+ *
18
+ * > Drift was not the failure. Defaulting was.
19
+ *
20
+ * Each function here answers that question once, in the open:
21
+ *
22
+ * - **absent config** — a legitimate state for every one of these callers
23
+ * (an unscaffolded directory, a consumer repo that has never run rungate),
24
+ * so the empty value is returned and that is the whole of the contract.
25
+ * - **malformed config** — THROWS, inherited from `tryLoadRungateConfig` and
26
+ * deliberately not caught here. ADR-001 D2's corollary: a malformed config
27
+ * is never a missing config. The bare `catch` at `scripts/fresh-eyes-test`
28
+ * and `scripts/grade-deterministic` converted a corrupt config into an
29
+ * unconfigured project, which is exactly how #70 stayed silent.
30
+ *
31
+ * ## What the migration actually fixes, beyond the policy
32
+ *
33
+ * Every site these replace read `.claude/rungate.json` and nothing else. A
34
+ * consumer on the directory layout — the layout
35
+ * `specs/CONFIG-DIRECTORY-STRUCTURE-SPEC.md` D-1 asks every consumer to
36
+ * migrate to — got `{}` from all of them, silently: no roles, no slug, no
37
+ * pre-flight hosts. The documented migration switched the features off.
38
+ */
39
+
40
+ import { tryLoadRungateConfig } from "./config-loader";
41
+ import type { RoleConfig } from "./rungate-schema";
42
+
43
+ /**
44
+ * Every configured role, keyed by name. `{}` when the project has no config.
45
+ *
46
+ * `roles` is `z.record(z.unknown()).default({})` in the resolved shape — the
47
+ * loader merges `roles.json` in but does not validate each entry against
48
+ * `RoleSchema`, so consumers carrying a role with a missing `brief` reach
49
+ * here. Narrowing is therefore an assertion about shape, not a guarantee of
50
+ * it; callers that index `brief` already handle it being absent.
51
+ */
52
+ export function loadRoleConfig(projectRoot: string): Record<string, RoleConfig> {
53
+ const config = tryLoadRungateConfig(projectRoot);
54
+ if (!config) return {};
55
+ return (config.roles ?? {}) as Record<string, RoleConfig>;
56
+ }
57
+
58
+ /**
59
+ * The project slug, or null when the config does not name one.
60
+ *
61
+ * Null rather than a `"project"` default: the caller that wanted that default
62
+ * uses it to name a worktree directory, and a second project falling back to
63
+ * the same literal would collide with the first. The default belongs at the
64
+ * site that can see the collision, not here.
65
+ */
66
+ export function readProjectSlug(projectRoot: string): string | null {
67
+ const config = tryLoadRungateConfig(projectRoot);
68
+ const slug = config?.project;
69
+ return typeof slug === "string" && slug.trim() ? slug : null;
70
+ }
71
+
72
+ /**
73
+ * Pre-flight SSH hosts, keyed by name. `{}` when none are configured.
74
+ *
75
+ * `remoteHosts` is not in `ProjectHarnessSchema`; it reaches the resolved
76
+ * config through `.passthrough()`, which is why the value is `unknown` and
77
+ * every field access downstream is guarded. Declaring it would be a schema
78
+ * change affecting every consumer config in the wild — out of scope here, and
79
+ * recorded rather than done.
80
+ */
81
+ export function readRemoteHosts(projectRoot: string): Record<string, unknown> {
82
+ const config = tryLoadRungateConfig(projectRoot);
83
+ const hosts = (config as Record<string, unknown> | null)?.remoteHosts;
84
+ if (!hosts || typeof hosts !== "object" || Array.isArray(hosts)) return {};
85
+ return hosts as Record<string, unknown>;
86
+ }