@event4u/agent-config 9.34.0 → 9.35.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 (69) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +91 -0
  3. package/CONTRIBUTING.md +23 -14
  4. package/dist/agent-src/commands/roadmap/next.md +37 -5
  5. package/dist/agent-src/scripts/roadmap_gates.ts +119 -4
  6. package/dist/agent-src/skills/testing-anti-patterns/SKILL.md +25 -0
  7. package/dist/agent-src/templates/agents/agent-project-settings.example.yml +1 -1
  8. package/dist/agent-src/templates/scripts/memory_lookup.ts +1 -2
  9. package/dist/agent-src/templates/scripts/memory_signal.ts +2 -4
  10. package/dist/agent-src/templates/scripts/work_engine/hooks/builtin/decision_gate.ts +35 -5
  11. package/dist/agent-src/templates/scripts/work_engine/hooks/builtin/staged_confirmation.ts +252 -0
  12. package/dist/agent-src/templates/scripts/work_engine/hooks/builtin/staged_confirmation_store.ts +307 -0
  13. package/dist/cli/registry.js +2 -2
  14. package/dist/cli/registry.js.map +1 -1
  15. package/dist/cli-delegate/{chunk-REMEZSVP.js → chunk-2TGMGLBL.js} +2 -2
  16. package/dist/cli-delegate/{chunk-YPAWXXXR.js → chunk-55RI5UXK.js} +17 -0
  17. package/dist/cli-delegate/{chunk-MA4GFWDY.js → chunk-H6F2CQFI.js} +1 -1
  18. package/dist/cli-delegate/{chunk-UVKNIJH2.js → chunk-ZAXH3ZWU.js} +3 -0
  19. package/dist/cli-delegate/cmd_conformance.js +2 -2
  20. package/dist/cli-delegate/cmd_doctor.js +2 -2
  21. package/dist/cli-delegate/cmd_export.js +2 -2
  22. package/dist/cli-delegate/cmd_handoff.js +1 -1
  23. package/dist/cli-delegate/cmd_prune.js +2 -2
  24. package/dist/cli-delegate/cmd_settings_migrate.js +2 -2
  25. package/dist/cli-delegate/cmd_settings_set.js +1 -1
  26. package/dist/cli-delegate/cmd_sync.js +2 -2
  27. package/dist/cli-delegate/cmd_uninstall.js +2 -2
  28. package/dist/cli-delegate/cmd_validate.js +2 -2
  29. package/dist/discovery/deprecation-report.md +1 -1
  30. package/dist/discovery/discovery-manifest.json +4 -4
  31. package/dist/discovery/discovery-manifest.json.sha256 +1 -1
  32. package/dist/discovery/discovery-manifest.summary.md +1 -1
  33. package/dist/discovery/dormancy-report.md +1 -1
  34. package/dist/discovery/orphan-report.md +1 -1
  35. package/dist/discovery/packs.json +2 -2
  36. package/dist/discovery/trust-report.md +1 -1
  37. package/dist/discovery/workspaces.json +2 -2
  38. package/dist/hooks/dispatch.js +259 -78
  39. package/dist/install/install.mjs +3 -0
  40. package/dist/mcp/registry-manifest.json +2 -2
  41. package/dist/mcp/server.json +2 -2
  42. package/dist/mcp/server.mjs +74 -2
  43. package/dist/server/schemas/settings.js +1 -0
  44. package/dist/server/schemas/settings.js.map +1 -1
  45. package/docs/contracts/settings-classes.md +3 -2
  46. package/package.json +1 -1
  47. package/src/agent-src/scripts/roadmap_gates.ts +119 -4
  48. package/src/agent-src/templates/scripts/memory_lookup.ts +1 -2
  49. package/src/agent-src/templates/scripts/memory_signal.ts +2 -4
  50. package/src/agent-src/templates/scripts/work_engine/hooks/builtin/decision_gate.ts +35 -5
  51. package/src/agent-src/templates/scripts/work_engine/hooks/builtin/staged_confirmation.ts +252 -0
  52. package/src/agent-src/templates/scripts/work_engine/hooks/builtin/staged_confirmation_store.ts +307 -0
  53. package/src/config/agent-settings.template.yml +11 -2
  54. package/src/config/quorum-attendance-budget.json +10 -2
  55. package/src/scripts/_dispatch.bash +6 -2
  56. package/src/scripts/_lib/session_register.ts +67 -1
  57. package/src/scripts/ai_council/config.ts +60 -0
  58. package/src/scripts/ai_council/events_log.ts +103 -4
  59. package/src/scripts/ai_council/quorum.ts +83 -6
  60. package/src/scripts/council_cli.ts +36 -1
  61. package/src/scripts/hooks/turn_end_gate_hook.ts +172 -11
  62. package/src/scripts/lint_framework_leakage.ts +195 -28
  63. package/src/scripts/lint_framework_leakage_allowlist.json +94 -86
  64. package/src/scripts/memory_lookup.ts +1 -2
  65. package/src/scripts/schemas/command.schema.json +4 -0
  66. package/src/scripts/schemas/skill.schema.json +4 -0
  67. package/src/scripts/session_register_hook.ts +238 -18
  68. package/src/scripts/sessions_cli.ts +377 -12
  69. package/src/server/schemas/settings.ts +3 -0
@@ -0,0 +1,252 @@
1
+ /**
2
+ * Staged confirmation — the pure half of exactly-once confirmed execution.
3
+ *
4
+ * `src/rules/non-destructive-by-default.md` already carries the whole policy:
5
+ * an irreversible action is confirmed on THIS turn, ask and action are strictly
6
+ * sequential ("Never act while asking"), and the approval names the exact
7
+ * object. What the tree had no mechanism for is the *sequencing itself* — a
8
+ * staged action, a confirmation that matches it, and the guarantee that a
9
+ * second approval of the same stage does not fire the action twice.
10
+ *
11
+ * Two properties carry that guarantee, and they are split across two files on
12
+ * purpose:
13
+ *
14
+ * - **Identity is derived, not invented.** {@link stageAction} hashes the
15
+ * action, the exact object, and a caller-supplied nonce into a token, so a
16
+ * confirmation can only match the stage it was issued for. Restaging the
17
+ * same object under a fresh nonce yields a different token — an approval
18
+ * never carries over to "the next one like it".
19
+ * - **The claim is atomic, and it lives in the store.** Nothing here can be
20
+ * exactly-once by itself: two processes reading the same `pending` record
21
+ * and both deciding "execute" is a check-then-act race no pure function can
22
+ * close. This module decides WHAT the outcome should be;
23
+ * `staged_confirmation_store.ts` makes the transition atomic with a
24
+ * directory rename, which either succeeds once or fails.
25
+ *
26
+ * Nothing binds on this yet, deliberately. `pre_tool_use` exists on 3 of 8
27
+ * platform rows (`hook_manifest.yaml`), so a guard that claimed to enforce
28
+ * confirmation would be prose on the other five while reading like a control —
29
+ * the failure `src/rules/ui-audit-gate.md` names about its own scope. The
30
+ * decision is deferred behind blocker `confirmation-degraded-host-semantics`;
31
+ * until it lands, callers opt in explicitly.
32
+ *
33
+ * Pure: no filesystem, no clock, no randomness. `now` and `nonce` are
34
+ * parameters so a test pins a whole lifecycle without faking globals.
35
+ */
36
+
37
+ import { createHash } from 'node:crypto';
38
+
39
+ /**
40
+ * Lifecycle of one staged action. `expired` is not a stored state — it is
41
+ * derived from the clock by {@link stageStatus}, so a stale pending record
42
+ * cannot read as awaiting-approval merely because nobody swept it.
43
+ */
44
+ export type StageState = 'pending' | 'confirmed' | 'declined';
45
+
46
+ /** What {@link confirmOnce} concluded. Only `execute` authorizes the action. */
47
+ export type ConfirmOutcome =
48
+ | 'execute'
49
+ | 'already-confirmed'
50
+ | 'expired'
51
+ | 'declined'
52
+ | 'token-mismatch';
53
+
54
+ /**
55
+ * The `on_block_fallback` vocabulary from
56
+ * `work_engine/scoring/decision_engine.ts` (`stop` / `warn`, default `stop`),
57
+ * reused rather than re-invented: this module extends that gate's ask path, so
58
+ * a second fallback vocabulary would be a second contract to keep in sync.
59
+ */
60
+ export type NonInteractiveFallback = 'stop' | 'warn';
61
+
62
+ /**
63
+ * Default staging window. A confirmation the user never gives must not sit in
64
+ * the store as an approval waiting to be collected: an abandoned stage that
65
+ * stays valid indefinitely is a pre-approved irreversible action, which is the
66
+ * opposite of what the policy asks for. Fifteen minutes is long enough for a
67
+ * human to read the surface and answer, short enough that a turn which ended
68
+ * hours ago cannot authorize anything.
69
+ */
70
+ export const STAGE_TTL_MS = 15 * 60 * 1000;
71
+
72
+ export interface StagedAction {
73
+ /** Confirmation token — derived, never guessable from the object alone. */
74
+ readonly token: string;
75
+ /** What would fire: a command name, a skill slug, a concern id. */
76
+ readonly action: string;
77
+ /**
78
+ * The exact object the approval names — a path, a URL, a recipient, an
79
+ * amount. The policy's "names the exact object" clause lives here, which is
80
+ * why it is required rather than optional: a stage with no object is a
81
+ * category confirmation, and the rule forbids exactly that.
82
+ */
83
+ readonly object: string;
84
+ /** Who staged it — the surface a `gates --pending` reader needs. */
85
+ readonly source: string;
86
+ readonly staged_at: string;
87
+ readonly expires_at: string;
88
+ readonly state: StageState;
89
+ /** Set on the transition out of `pending`, never rewritten afterwards. */
90
+ readonly resolved_at?: string;
91
+ }
92
+
93
+ /** ISO-8601 seconds, matching the runtime records already in the tree. */
94
+ function iso(ms: number): string {
95
+ return new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z');
96
+ }
97
+
98
+ /**
99
+ * Derive the confirmation token.
100
+ *
101
+ * The nonce is a parameter and not read from a clock or an RNG here, so the
102
+ * derivation is reproducible in a test. It is also what makes two stages of the
103
+ * same object distinct: without it, approving a delete of `x` once would
104
+ * produce a token that matches every future delete of `x`.
105
+ *
106
+ * The separator is NUL, written as an escape sequence and never as a raw byte.
107
+ * NUL is the right separator — it cannot occur in an action, a path or a nonce,
108
+ * so no two different triples concatenate to the same string. A RAW NUL in a
109
+ * text source would make git, grep and file(1) treat the whole file as binary
110
+ * and skip it silently, which `lint_hidden_unicode` blocks on; the escape keeps
111
+ * the domain separation and leaves the file readable by every tool.
112
+ */
113
+ export function deriveToken(action: string, object: string, nonce: string): string {
114
+ return createHash('sha256')
115
+ .update(`${action}\u0000${object}\u0000${nonce}`)
116
+ .digest('hex')
117
+ .slice(0, 16);
118
+ }
119
+
120
+ /** Stage an action. Returns the record; it is the caller's job to persist it. */
121
+ export function stageAction(args: {
122
+ action: string;
123
+ object: string;
124
+ source: string;
125
+ nonce: string;
126
+ now: number;
127
+ ttlMs?: number;
128
+ }): StagedAction {
129
+ const ttl = args.ttlMs ?? STAGE_TTL_MS;
130
+ return {
131
+ token: deriveToken(args.action, args.object, args.nonce),
132
+ action: args.action,
133
+ object: args.object,
134
+ source: args.source,
135
+ staged_at: iso(args.now),
136
+ expires_at: iso(args.now + ttl),
137
+ state: 'pending',
138
+ };
139
+ }
140
+
141
+ /**
142
+ * Effective status at `now` — `expired` is derived, not stored.
143
+ *
144
+ * A pending record past its `expires_at` reads as `expired` even though no
145
+ * sweep has run, so the guarantee does not depend on a pruner having been
146
+ * called. Prune is housekeeping; this is the decision.
147
+ */
148
+ export function stageStatus(stage: StagedAction, now: number): StageState | 'expired' {
149
+ if (stage.state === 'pending' && Date.parse(stage.expires_at) <= now) {
150
+ return 'expired';
151
+ }
152
+ return stage.state;
153
+ }
154
+
155
+ export function isExpired(stage: StagedAction, now: number): boolean {
156
+ return stageStatus(stage, now) === 'expired';
157
+ }
158
+
159
+ /**
160
+ * Decide what a confirmation attempt means. `execute` — and only `execute` —
161
+ * authorizes the action, and it is returned at most once per stage because the
162
+ * caller writes the returned record back before acting.
163
+ *
164
+ * The token is compared in full: a confirmation for a different stage is
165
+ * `token-mismatch` rather than a silent no-op, because a mismatch is a real
166
+ * signal (a stale surface, a copied token) and swallowing it would hide it.
167
+ */
168
+ export function confirmOnce(
169
+ stage: StagedAction,
170
+ token: string,
171
+ now: number,
172
+ ): { outcome: ConfirmOutcome; stage: StagedAction } {
173
+ if (token !== stage.token) {
174
+ return { outcome: 'token-mismatch', stage };
175
+ }
176
+ const status = stageStatus(stage, now);
177
+ if (status === 'confirmed') {
178
+ return { outcome: 'already-confirmed', stage };
179
+ }
180
+ if (status === 'declined') {
181
+ return { outcome: 'declined', stage };
182
+ }
183
+ if (status === 'expired') {
184
+ return { outcome: 'expired', stage };
185
+ }
186
+ return {
187
+ outcome: 'execute',
188
+ stage: { ...stage, state: 'confirmed', resolved_at: iso(now) },
189
+ };
190
+ }
191
+
192
+ /** Decline a stage. Idempotent for the same reason `confirmOnce` is. */
193
+ export function declineStage(
194
+ stage: StagedAction,
195
+ token: string,
196
+ now: number,
197
+ ): { declined: boolean; stage: StagedAction } {
198
+ if (token !== stage.token || stageStatus(stage, now) !== 'pending') {
199
+ return { declined: false, stage };
200
+ }
201
+ return { declined: true, stage: { ...stage, state: 'declined', resolved_at: iso(now) } };
202
+ }
203
+
204
+ /**
205
+ * What a non-interactive context does with a stage.
206
+ *
207
+ * Both fallbacks REFUSE — `decision_engine`'s `stop` and `warn` differ in how
208
+ * loudly they surface, never in whether the gated thing proceeds, and a staged
209
+ * irreversible action is the last place to invent an auto-approve. Naming the
210
+ * `warn` case explicitly is the point: a reader looking for the permissive
211
+ * branch finds it absent on purpose.
212
+ */
213
+ export function nonInteractiveDecision(fallback: NonInteractiveFallback): {
214
+ execute: false;
215
+ surface: 'halt' | 'warn';
216
+ } {
217
+ return { execute: false, surface: fallback === 'warn' ? 'warn' : 'halt' };
218
+ }
219
+
220
+ /**
221
+ * The confirmation surface, in the numbered-options shape
222
+ * `src/rules/user-interaction.md` requires. Returned as lines rather than
223
+ * written, so the same text serves a hook halt, a CLI pane, and a chat reply.
224
+ *
225
+ * `confirmWith` / `declineWith` are the caller's channel and are NOT defaulted
226
+ * to a command name. Which channel confirms a staged action is precisely what
227
+ * blocker `confirmation-degraded-host-semantics` has not decided — a
228
+ * `pre_tool_use` reply on three hosts, prose on the other five — and printing
229
+ * an invocation that does not exist yet would put a false instruction into a
230
+ * shipped surface. Until a binding caller supplies one, the surface names the
231
+ * token and says plainly that no channel is wired.
232
+ */
233
+ export function confirmationSurface(
234
+ stage: StagedAction,
235
+ channel?: { confirmWith?: string; declineWith?: string },
236
+ ): string[] {
237
+ const confirm = channel?.confirmWith;
238
+ const decline = channel?.declineWith;
239
+ return [
240
+ `Confirmation required: ${stage.action}`,
241
+ `Object: ${stage.object}`,
242
+ `Staged by: ${stage.source} · token ${stage.token} · expires ${stage.expires_at}`,
243
+ confirm === undefined
244
+ ? `1) Confirm — quote token ${stage.token} back to the caller that staged it.`
245
+ : `1) Confirm — ${confirm}`,
246
+ decline === undefined
247
+ ? '2) Decline — say so; the stage is resolved without firing.'
248
+ : `2) Decline — ${decline}`,
249
+ '3) Do nothing — the stage expires and the action never fires.',
250
+ 'Pending stages: `agent-config gates --pending`.',
251
+ ];
252
+ }
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Staged-confirmation store — the I/O half, and the half that makes
3
+ * exactly-once real.
4
+ *
5
+ * `staged_confirmation.ts` decides what a confirmation attempt MEANS. It cannot
6
+ * make the transition happen only once: two processes that both read a
7
+ * `pending` record and both conclude `execute` is a check-then-act race, and no
8
+ * pure function closes it. So the claim is a **directory rename**, which the
9
+ * filesystem performs atomically — the first caller moves
10
+ * `pending/<token>.json` to `resolved/`, every later caller gets `ENOENT` and
11
+ * learns the stage is already taken.
12
+ *
13
+ * That is also why the state lives in the path and not only in a field: a
14
+ * read-modify-write of a `state:` key would reopen exactly the window the
15
+ * rename closes.
16
+ *
17
+ * Records live under `agents/runtime/staged-confirmations/`, which the repo
18
+ * `.gitignore` already covers via the `/agents/runtime/` catch-all — a staged
19
+ * action is machine-generated local state, never a tracked artefact. The store
20
+ * mirrors `_lib/self_repair_store.ts`: one file per identity, every read
21
+ * tolerant of a malformed file, and no throw on a missing directory.
22
+ */
23
+ import * as fs from 'node:fs';
24
+ import * as path from 'node:path';
25
+
26
+ import {
27
+ confirmOnce,
28
+ declineStage,
29
+ type ConfirmOutcome,
30
+ type StageState,
31
+ type StagedAction,
32
+ stageStatus,
33
+ } from './staged_confirmation.js';
34
+
35
+ export const STORE_REL = path.join('agents', 'runtime', 'staged-confirmations');
36
+
37
+ export function storeDir(root: string): string {
38
+ return path.join(root, STORE_REL);
39
+ }
40
+
41
+ function pendingDir(root: string): string {
42
+ return path.join(storeDir(root), 'pending');
43
+ }
44
+
45
+ function resolvedDir(root: string): string {
46
+ return path.join(storeDir(root), 'resolved');
47
+ }
48
+
49
+ /**
50
+ * A token is a filename before it is an identifier, so every site that turns
51
+ * one into a path checks it first — the read verbs, the write verb, and the
52
+ * record guard itself.
53
+ *
54
+ * `deriveToken` returns a 16-char sha256 prefix, so a token this module mints
55
+ * is always safe. Everything else is a way in: `readPending`,
56
+ * `claimConfirmation` and `declineConfirmation` take a caller-supplied token;
57
+ * `putPending` joins `stage.token` from a caller-built record (verified: it
58
+ * wrote outside the store root); and `isStage` accepted any string, so a record
59
+ * written by something else carried its token into the prune path. All four are
60
+ * guarded, and `path.join(pendingDir(root), '../x.json')` resolving outside
61
+ * `pending/` is what makes that necessary.
62
+ */
63
+ const _TOKEN_RE = /^[0-9a-f]{8,64}$/;
64
+
65
+ export function isSafeToken(token: string): boolean {
66
+ return _TOKEN_RE.test(token);
67
+ }
68
+
69
+ /**
70
+ * Every field the module later reads, `staged_at` included.
71
+ *
72
+ * It checked four of five while still asserting `v is StagedAction`, so a
73
+ * record that was valid JSON but carried no `staged_at` passed the guard and
74
+ * reached `listPending`'s `staged_at.localeCompare(...)`: a TypeError thrown
75
+ * through `roadmap_gates.renderPending`, i.e. one malformed file on disk taking
76
+ * out a shipped gate. An unsound guard is worse than no guard — it makes the
77
+ * caller's `!== null` check read as a proof that it is not.
78
+ */
79
+ function isStage(v: unknown): v is StagedAction {
80
+ if (typeof v !== 'object' || v === null) {
81
+ return false;
82
+ }
83
+ const s = v as Partial<StagedAction>;
84
+ return (
85
+ typeof s.token === 'string' &&
86
+ isSafeToken(s.token) &&
87
+ typeof s.action === 'string' &&
88
+ typeof s.object === 'string' &&
89
+ typeof s.staged_at === 'string' &&
90
+ typeof s.expires_at === 'string'
91
+ );
92
+ }
93
+
94
+ function readStageFile(file: string): StagedAction | null {
95
+ try {
96
+ const parsed: unknown = JSON.parse(fs.readFileSync(file, 'utf-8'));
97
+ return isStage(parsed) ? parsed : null;
98
+ } catch {
99
+ return null;
100
+ }
101
+ }
102
+
103
+ function writeStageFile(file: string, stage: StagedAction): void {
104
+ fs.mkdirSync(path.dirname(file), { recursive: true });
105
+ fs.writeFileSync(file, `${JSON.stringify(stage, null, 2)}\n`, 'utf-8');
106
+ }
107
+
108
+ /**
109
+ * Persist a freshly staged action. Returns the path written.
110
+ *
111
+ * Throws on an unsafe token rather than returning: a caller reaching here with
112
+ * one built the record itself and has a bug, and `writeStageFile` creates
113
+ * directories, so a silent refusal would look like a successful stage nothing
114
+ * can ever confirm.
115
+ */
116
+ export function putPending(root: string, stage: StagedAction): string {
117
+ if (!isSafeToken(stage.token)) {
118
+ throw new Error(
119
+ `staged-confirmation: refusing to write under an unsafe token '${stage.token}' — ` +
120
+ 'a token is a filename and must match the deriveToken shape',
121
+ );
122
+ }
123
+ const file = path.join(pendingDir(root), `${stage.token}.json`);
124
+ writeStageFile(file, stage);
125
+ return file;
126
+ }
127
+
128
+ export function readPending(root: string, token: string): StagedAction | null {
129
+ if (!isSafeToken(token)) {
130
+ return null;
131
+ }
132
+ return readStageFile(path.join(pendingDir(root), `${token}.json`));
133
+ }
134
+
135
+ export function readResolved(root: string, token: string): StagedAction | null {
136
+ if (!isSafeToken(token)) {
137
+ return null;
138
+ }
139
+ return readStageFile(path.join(resolvedDir(root), `${token}.json`));
140
+ }
141
+
142
+ /**
143
+ * Every stage still in `pending/`, with its effective status at `now` so an
144
+ * expired one is never rendered as awaiting approval. Sorted by `staged_at`
145
+ * (oldest first, ties by token) so two runs on an unchanged store print
146
+ * byte-identical output.
147
+ */
148
+ export function listPending(
149
+ root: string,
150
+ now: number,
151
+ ): { stage: StagedAction; status: StageState | 'expired' }[] {
152
+ let names: string[];
153
+ try {
154
+ names = fs.readdirSync(pendingDir(root));
155
+ } catch {
156
+ return [];
157
+ }
158
+ const out: { stage: StagedAction; status: StageState | 'expired' }[] = [];
159
+ for (const n of names.sort()) {
160
+ if (!n.endsWith('.json')) {
161
+ continue;
162
+ }
163
+ const stage = readStageFile(path.join(pendingDir(root), n));
164
+ if (stage !== null) {
165
+ out.push({ stage, status: stageStatus(stage, now) });
166
+ }
167
+ }
168
+ out.sort(
169
+ (a, b) =>
170
+ a.stage.staged_at.localeCompare(b.stage.staged_at) ||
171
+ a.stage.token.localeCompare(b.stage.token),
172
+ );
173
+ return out;
174
+ }
175
+
176
+ /**
177
+ * Atomically claim a pending stage and decide the outcome.
178
+ *
179
+ * Order matters and is the whole mechanism:
180
+ *
181
+ * 1. Read the record. An absent one is `token-mismatch` — from the caller's
182
+ * side an unknown token and a wrong token are the same fact, and inventing
183
+ * a third outcome for "was never staged" would only be actionable if the
184
+ * store were a public index, which it is not.
185
+ * 2. Ask `confirmOnce` what the outcome WOULD be. A mismatch, a decline, or
186
+ * an expiry never claims anything — a stale surface must not consume a
187
+ * stage a human might still legitimately confirm.
188
+ * 3. Only for `execute`: rename `pending/` → `resolved/`. That is the claim.
189
+ * `ENOENT` means a concurrent caller won the race, so this caller reports
190
+ * `already-confirmed` and does NOT act — the exactly-once guarantee.
191
+ * 4. Write the confirmed record into `resolved/`, overwriting the moved file
192
+ * with the same content plus `state`/`resolved_at`.
193
+ */
194
+ export function claimConfirmation(
195
+ root: string,
196
+ token: string,
197
+ now: number,
198
+ ): { outcome: ConfirmOutcome; stage: StagedAction | null } {
199
+ if (!isSafeToken(token)) {
200
+ // Nothing this module staged can have that shape, so the honest answer
201
+ // is the same one an unknown token gets — and refusing here is what
202
+ // keeps the rename below off an arbitrary path.
203
+ return { outcome: 'token-mismatch', stage: null };
204
+ }
205
+ const pendingFile = path.join(pendingDir(root), `${token}.json`);
206
+ const stage = readStageFile(pendingFile);
207
+ if (stage === null) {
208
+ const already = readResolved(root, token);
209
+ if (already !== null) {
210
+ // `pruneExpired` moves a stage here WITHOUT rewriting `state`, so the
211
+ // status is derived rather than read off the field — otherwise an
212
+ // expired stage swept out of `pending/` would report as confirmed,
213
+ // which is the one wrong answer available here.
214
+ const status = stageStatus(already, now);
215
+ const outcome: ConfirmOutcome =
216
+ status === 'expired' ? 'expired' : status === 'declined' ? 'declined' : 'already-confirmed';
217
+ return { outcome, stage: already };
218
+ }
219
+ return { outcome: 'token-mismatch', stage: null };
220
+ }
221
+
222
+ const decided = confirmOnce(stage, token, now);
223
+ if (decided.outcome !== 'execute') {
224
+ return decided;
225
+ }
226
+
227
+ const resolvedFile = path.join(resolvedDir(root), `${token}.json`);
228
+ fs.mkdirSync(resolvedDir(root), { recursive: true });
229
+ try {
230
+ fs.renameSync(pendingFile, resolvedFile);
231
+ } catch {
232
+ // Lost the race, or the pending file vanished between the read and the
233
+ // rename. Either way this caller has NOT claimed the stage and must not
234
+ // act on it.
235
+ return { outcome: 'already-confirmed', stage: readResolved(root, token) ?? stage };
236
+ }
237
+ writeStageFile(resolvedFile, decided.stage);
238
+ return decided;
239
+ }
240
+
241
+ /** Decline a pending stage. Same claim discipline as `claimConfirmation`. */
242
+ export function declineConfirmation(
243
+ root: string,
244
+ token: string,
245
+ now: number,
246
+ ): { declined: boolean; stage: StagedAction | null } {
247
+ if (!isSafeToken(token)) {
248
+ return { declined: false, stage: null };
249
+ }
250
+ const pendingFile = path.join(pendingDir(root), `${token}.json`);
251
+ const stage = readStageFile(pendingFile);
252
+ if (stage === null) {
253
+ return { declined: false, stage: readResolved(root, token) };
254
+ }
255
+ const decided = declineStage(stage, token, now);
256
+ if (!decided.declined) {
257
+ return { declined: false, stage };
258
+ }
259
+ const resolvedFile = path.join(resolvedDir(root), `${token}.json`);
260
+ fs.mkdirSync(resolvedDir(root), { recursive: true });
261
+ try {
262
+ fs.renameSync(pendingFile, resolvedFile);
263
+ } catch {
264
+ return { declined: false, stage: readResolved(root, token) ?? stage };
265
+ }
266
+ writeStageFile(resolvedFile, decided.stage);
267
+ return { declined: true, stage: decided.stage };
268
+ }
269
+
270
+ /**
271
+ * Move expired stages out of `pending/` so the enumeration stays a list of
272
+ * live decisions. Housekeeping only — `stageStatus` already derives expiry, so
273
+ * skipping the sweep changes what is *listed*, never what may execute.
274
+ */
275
+ export function pruneExpired(root: string, now: number): number {
276
+ let names: string[];
277
+ try {
278
+ names = fs.readdirSync(pendingDir(root));
279
+ } catch {
280
+ return 0;
281
+ }
282
+ let moved = 0;
283
+ for (const name of names.sort()) {
284
+ if (!name.endsWith('.json')) {
285
+ continue;
286
+ }
287
+ // Move the file that was ENUMERATED, never a path rebuilt from the
288
+ // record's `token` field. The two disagree whenever a filename and its
289
+ // token do — a record written by anything but `putPending` — and the
290
+ // rebuilt path then hits ENOENT, gets swallowed by the catch below, and
291
+ // the stage sits in `pending/` forever while `moved` under-reports it.
292
+ const from = path.join(pendingDir(root), name);
293
+ const stage = readStageFile(from);
294
+ if (stage === null || stageStatus(stage, now) !== 'expired') {
295
+ continue;
296
+ }
297
+ const to = path.join(resolvedDir(root), name);
298
+ fs.mkdirSync(resolvedDir(root), { recursive: true });
299
+ try {
300
+ fs.renameSync(from, to);
301
+ } catch {
302
+ continue;
303
+ }
304
+ moved += 1;
305
+ }
306
+ return moved;
307
+ }
@@ -1207,9 +1207,17 @@ hooks:
1207
1207
  # language — detector B: the user-visible prose is not in the pinned
1208
1208
  # language, with code, quotes, paths and identifiers already
1209
1209
  # excluded (19 measured).
1210
+ # verification — detector C: the turn changed a file and then ran nothing that
1211
+ # could have checked it — no test, type-check, lint or build call
1212
+ # follows the LAST edit. Ordering is the point: a run before the
1213
+ # final edit did not exercise it, which is the freshness clause
1214
+ # verify-before-complete states. Reads the turn's tool calls, not
1215
+ # the prose. Deliberately narrow on what counts as verification —
1216
+ # a missed detection costs one unguarded turn, a false refusal
1217
+ # teaches you to switch the gate off.
1210
1218
  #
1211
- # Both detectors default ON *within* the master switch, so opting in needs
1212
- # one line, and either can be silenced without editing the hook manifest.
1219
+ # All three detectors default ON *within* the master switch, so opting in needs
1220
+ # one line, and any one can be silenced without editing the hook manifest.
1213
1221
  # A refused turn continues in the same turn and is never refused twice —
1214
1222
  # re-entrancy is `stop_hook_active` plus a marker keyed on the last user
1215
1223
  # message, never on the reply.
@@ -1217,6 +1225,7 @@ hooks:
1217
1225
  enabled: false
1218
1226
  promissory: true
1219
1227
  language: true
1228
+ verification: true
1220
1229
 
1221
1230
  # PreToolUse RTK-wrap nudge (token-saving Phase 3). Default-OFF. When enabled
1222
1231
  # AND `rtk` is on PATH (a live probe — not a self-reported flag), warns (exit
@@ -1,11 +1,11 @@
1
1
  {
2
- "_comment": "Pre-registered council ATTENDANCE metrics (road-to-inbox-harvest-2026-08-b Phase 1.4). Registered here rather than in roadmap prose because a roadmap is archived when it closes and a metric outlives it — the sibling budget files (hook-token-budget.json, recycle-threshold-budget.json) already carry the owner / review_by / honest-gap discipline this reuses. The instrument is the quorum_result line appendQuorumEvent writes to agents/runtime/council/events.log (schema v2); nothing here is measured yet, and no threshold is committed before data exists.",
2
+ "_comment": "Pre-registered council ATTENDANCE metrics (road-to-inbox-harvest-2026-08-b Phase 1.4). Registered here rather than in roadmap prose because a roadmap is archived when it closes and a metric outlives it — the sibling budget files (hook-token-budget.json, recycle-threshold-budget.json) already carry the owner / review_by / honest-gap discipline this reuses. The instrument is the quorum_result line appendQuorumEvent writes to agents/runtime/council/events.log (schema v4 since the ADR-224 shadow floor added gate_class + floor_would_hold at v3 and min_present at v4; v2 lines carry none of the three and v3 lines carry no min_present, so a rate over them must exclude rather than assume them); nothing here is measured yet, and no threshold is committed before data exists.",
3
3
  "schema_version": 1,
4
4
  "registered_at": "2026-08-10",
5
5
  "owner": "maintainer",
6
6
  "review_by": "2026-11-10",
7
7
  "unit": "quorum_result event lines in agents/runtime/council/events.log",
8
- "privacy": "a quorum_result line carries {phase, command, dispatch, verdict, threshold, configured_total, total, present, solo, absent[{member, reason}]} — counts, closed vocabularies, and member ids only. The type has no field able to hold free-form content, so the CLI's own `detail` string (provider error text, which can embed paths and prompt fragments) is dropped at the boundary rather than scrubbed.",
8
+ "privacy": "a quorum_result line carries {phase, command, dispatch, verdict, threshold, configured_total, total, present, solo, gate_class, min_present, floor_would_hold, absent[{member, reason}]} — counts, closed vocabularies, booleans, and member ids only. The type has no field able to hold free-form content, so the CLI's own `detail` string (provider error text, which can embed paths and prompt fragments) is dropped at the boundary rather than scrubbed. The two v3 additions are booleans and the v4 addition is a small integer read from config, none of which can widen that surface.",
9
9
  "phase_split": "A pass emits `pre_run` (build_members — who could be constructed) and, on the `run` path, `post_run` (_postRunQuorum — who actually returned a usable response). They disagree whenever a member constructs and then fails mid-flight, so a rate computed over both double-counts. A `pre_run` line is NOT evidence a pass ran: `command: estimate` is a spend-free preview, and a `run` / `debate` line is written before the `--confirm` gate (which defaults to false and returns before any provider call) and before the necessity and size-fit gates. A `post_run` line is the only line that proves providers were called — which is why every rate below is post_run-scoped, and why `command` exists at all.",
10
10
  "attendance_rate": {
11
11
  "definition": "of the members that entered the pass, how many answered: present / total per post_run pass. Bounded by 1 by construction (evaluateQuorum clamps present into [0, total]).",
@@ -23,6 +23,13 @@
23
23
  "instrument": "quorum_result lines, phase=post_run, command=run, field solo, split by dispatch + configured_total",
24
24
  "threshold": "DECIDED 2026-08-11 against real data — see ADR-224 (docs/decisions/ADR-224-gate-scoped-solo-attendance-floor.md). The quorum-solo-floor blocker pre-registered three outcomes — a third CLI member, a gate-scoped min_present: 2, or a published null under 5 %. Read at 2026-08-11T09:30Z with the definition above: 1 of 8 post_run/command=run passes carried a degraded solo conclusion = 12.5 %, so the under-5 % null did not fire and the gate-scoped floor was chosen (council 2/2). It was decided on the degraded case only; a --single pass is the operator asking for one voice, not the council failing to assemble. Still no numeric threshold is committed here, deliberately: at n=8 the 95 % interval around 1/8 spans roughly 0.3 %-53 %, so the rate established urgency and not certainty, and ADR-224's review trigger reopens the null at n=40. What this metric measures does NOT change; once the floor lands, how often it FIRES is a second and different question needing its own instrument."
25
25
  },
26
+ "shadow_floor_fire_rate": {
27
+ "definition": "share of post_run passes where a min_present floor WOULD have held the pass, had one been enforced: `floor_would_hold: true` over post_run/command=run lines. Written by the wouldSoloFloorHold predicate in quorum.ts, never re-derived from present/threshold here, for the same reason solo_conclusion_rate defers to isSoloConcluded — one definition, so a change to the rule cannot leave this file stale. This is the instrument solo_conclusion_rate's threshold note said the FIRING question would need; it answers 'how often would the floor hold a gate', which is NOT the question solo_conclusion_rate answers ('how often did a pass conclude on one voice'). The two are NOT the same rate and diverge in both directions. solo: true / floor_would_hold: false — a council configured with one member (the ceiling clamps to 1, deliberately). solo: false / floor_would_hold: true — any pass concluding on 2+ voices under a configured quorum_min_present above 2. They also AGREE on the case that matters most: a construction-degraded roster (2 configured, 1 constructed, 1 answered) is solo: true and floor_would_hold: true, because the floor is judged against max(total, configured_total) — judging it against total alone made this pass, the very one ADR-224 was decided on, structurally unable to fire.",
28
+ "instrument": "quorum_result lines, phase=post_run, command=run, field floor_would_hold, split by dispatch + configured_total AND BY min_present (schema v4+)",
29
+ "threshold": "none committed before data — and deliberately none at the review date either unless a gate-class caller exists by then. A fire-rate over passes that gate nothing measures a counterfactual, not a risk; it is registered now so ADR-224's review trigger (b) has an accumulating series rather than a series that starts on the day someone remembers to add one.",
30
+ "split_by_min_present_or_the_rate_is_uninterpretable": "The floor this rate counts against is `quorum_min_present`, which lives in the USER-GLOBAL .ai-council.yml (ADR-104) — per developer machine, gitignored, invisible in this repository. Schema v3 consumed that value and did not record it, so two operators produced byte-identical lines while measuring different counterfactuals, and a pooled rate over them was a mean of incomparable things. Schema v4 records it as `min_present`; group on it before reading, and treat v3 lines as a separate stratum whose floor is UNKNOWN rather than assuming the default. The sharpest case: `quorum_min_present: 1` is valid config and, per the predicate's own test, can never hold anything — so it drives this rate to a permanent zero. Without min_present on the line that zero is indistinguishable from 'the floor genuinely never would have fired', which is precisely the reading ADR-224's review trigger (b) would act on. No threshold was loosened by adding this field; nothing was gated on it before.",
31
+ "nothing_is_enforced": "No value of this metric holds, delays or fails a council pass. wouldSoloFloorHold is a counterfactual with no caller branching on it, and quorum_min_present configures only what the counterfactual is computed against. A reader must not cite this rate as evidence that the floor protected anything — it has never protected anything."
32
+ },
26
33
  "absent_reason_distribution": {
27
34
  "definition": "count per reason over absent[] entries — no_binary / no_auth / timeout / quota (AbsentReason) plus the two runtime fallbacks the CLI writes directly, `unavailable` (transport resolved to nothing) and `binary_missing` (a CLI client refused to construct). Distinguishes a council degraded by configuration from one degraded by provider behaviour, which have opposite fixes.",
28
35
  "instrument": "quorum_result lines, absent[].reason, split by phase (a pre_run absence is configuration; a post_run absence is mid-flight). Excluding `command: estimate` is NOT sufficient: `run` and `debate` also reach construction and return at the `--confirm` gate, which defaults to false. The reliable filter is a pre_run line whose pass produced a matching post_run line; a pre_run line with no post_run partner reached construction and stopped there, whatever its command says.",
@@ -34,6 +41,7 @@
34
41
  "`lens` and `invocation` are empty on every pre_run line — neither is known at member-construction time — so any per-lens breakdown is post_run-only.",
35
42
  "`command: debate` carries the pre_run half ONLY. There is no _postRunQuorum on the debate path, and defining `usable response` for a multi-round debate is a separate question this registration does not answer. So debate contributes to absent_reason_distribution and to nothing else: attendance_rate and solo_conclusion_rate cover the `run` path, and a reader must not read them as covering every metered pass.",
36
43
  "A pre_run line proves construction happened, never that a pass followed — the `--confirm` gate (default false), the necessity gate and the size-fit gate all abort afterwards and nothing on the line records it. Any count over pre_run lines is an upper bound; pair it with a post_run line before treating it as a pass.",
44
+ "`gate_class` is `false` on EVERY line written so far and will stay false until a caller declares otherwise — nothing in the tree branches on QuorumStatus to hold a gate, so there is no gate-class caller to mark. shadow_floor_fire_rate is therefore a rate over ALL post_run passes, not over gate-class ones, and the gate-class-scoped rate ADR-224 actually cares about is UNMEASURED, not zero. Do not read a `false` majority as evidence that gate-class passes are rare; it is evidence that the concept has no consumer yet.",
37
45
  "The CLI emit wiring itself has no test. The two modules are covered directly, but nothing exercises build_members / cmd_run / cmd_debate end-to-end against a captured log — and `_emitQuorumEvent` forwards no AppendEventOptions, so there is no target to capture into. Two defects in this file's first version (a `dispatch` written from the flag rather than the outcome, and a rate mixing config entries with clients) were found by review rather than by a test, which is what that gap costs."
38
46
  ]
39
47
  }
@@ -194,7 +194,10 @@ Tier 2 — maintenance / internal (hooks, MCP, memory, telemetry):
194
194
  code-graph Deterministic code-graph engine (ADR-124, Class A).
195
195
  Usage: code-graph build|validate|detect|query|explain|affected|path [options]
196
196
  sessions:list List live agent sessions on this repository (shared
197
- session register). Flags: --json
197
+ session register) PLUS the unmerged branches checked
198
+ out in other worktrees — the axis that needs no
199
+ claim. Flags: --json, --branches (adds the branch
200
+ axis to the JSON; the human form always shows it)
198
201
  sessions:claim Claim a roadmap for this session so other sessions skip
199
202
  it; --release clears the claim
200
203
  session:recycle Validate + write the main-session recycle envelope (--verify validates only)
@@ -209,7 +212,8 @@ Tier 2 — maintenance / internal (hooks, MCP, memory, telemetry):
209
212
  first. Flags: --all (include maintainer/external),
210
213
  --json, --reply (reply-close form: the one blocking
211
214
  decision in full, the rest as a count; prints
212
- nothing when none are yours)
215
+ nothing when none are yours), --pending (staged
216
+ requires_confirmation actions awaiting you)
213
217
  capabilities:index Regenerate CAPABILITIES.yaml — the package coverage index
214
218
  (capability area → coverage → backing skills/commands → gaps).
215
219
  Pass --check to fail if stale (for CI). Reads src/ (package repo).