@amsterdamdatalabs/adl-agent-control-darwin-arm64 0.1.68 → 0.1.69

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.
package/bin/adl CHANGED
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/bin/adl
3
- size: 63720304 bytes
4
- sha256: 81064361d791d1f29a18197e54fa65bf96c82cbdbd56600c2501e824d9047816
3
+ size: 63736720 bytes
4
+ sha256: d5cf54c48c04b06dbd603d5bb03449bf705a65777fe5579abf138c041edbdfa1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amsterdamdatalabs/adl-agent-control-darwin-arm64",
3
- "version": "0.1.68",
3
+ "version": "0.1.69",
4
4
  "description": "adl CLI binary for darwin/arm64 (agent identity + Azure DevOps front door — see docs/architecture/cli-design.md)",
5
5
  "license": "UNLICENSED",
6
6
  "os": [
@@ -23,7 +23,11 @@ Host hook configuration points at the global binary directly, e.g.:
23
23
  adl hook <kind> [subcommand] --host=<claude|codex|cursor|kimi|opencode>
24
24
  ```
25
25
 
26
- - `kind`: `pre-tool-use`, `user-prompt-submit`, `briefing`, or `crg`
26
+ - `kind`: `pre-tool-use`, `user-prompt-submit`, `briefing`, `crg`, or `quality-gate`
27
+ - `quality-gate` (on `SessionStart` and `Stop`) runs one `adl-config.toml`-declared command chosen
28
+ from the changed file kinds and blocks the stop while it fails, at most `max_blocks` (at most 5)
29
+ times per session; see `docs/architecture/adl-config.md` ("`[hooks.quality-gate]`"). Gated
30
+ hosts: claude, codex, cursor; kimi and opencode are logged as `SKIP`
27
31
  - `crg` requires a `subcommand`: `after-file-edit`, `pre-commit`, or `session-stop`
28
32
  - `--host` accepts either `--host X` or `--host=X`; `vscode` is refused
29
33
  (a valid host id elsewhere in the fleet, but audit-only — it has no hook
@@ -43,6 +47,7 @@ to the git root, read `adl-config.toml` there), starting from
43
47
  adl hook rules list [--repo <path>] [--json]
44
48
  adl hook rules show <id> [--repo <path>] [--json]
45
49
  adl hook doctor [--repo <path>]
50
+ adl hook quality-gate override --host <claude|codex|cursor> --session <id> --reason "<text>"
46
51
  ```
47
52
 
48
53
  - `rules list` — every registered rule: id, category, severity, enabled
@@ -44,6 +44,12 @@
44
44
  "command": "adl hook briefing",
45
45
  "statusMessage": "adl-repo: session briefing",
46
46
  "timeout": 15
47
+ },
48
+ {
49
+ "type": "command",
50
+ "command": "adl hook quality-gate",
51
+ "statusMessage": "adl-repo: quality-gate baseline",
52
+ "timeout": 10
47
53
  }
48
54
  ]
49
55
  }
@@ -72,6 +78,18 @@
72
78
  }
73
79
  ]
74
80
  }
81
+ ],
82
+ "Stop": [
83
+ {
84
+ "hooks": [
85
+ {
86
+ "type": "command",
87
+ "command": "adl hook quality-gate",
88
+ "statusMessage": "adl-repo: quality gate",
89
+ "timeout": 600
90
+ }
91
+ ]
92
+ }
75
93
  ]
76
94
  }
77
95
  }
@@ -26,7 +26,8 @@
26
26
  "UserPromptSubmit": "beforeSubmitPrompt",
27
27
  "SessionStart": "sessionStart",
28
28
  "PostToolUse": "postToolUse",
29
- "SessionEnd": "sessionEnd"
29
+ "SessionEnd": "sessionEnd",
30
+ "Stop": "stop"
30
31
  },
31
32
  "matchers": {
32
33
  "Bash": "Shell",
@@ -50,7 +50,7 @@
50
50
  },
51
51
  "eventNames": {
52
52
  "$ref": "#/definitions/stringRecord",
53
- "description": "Canonical event name (PreToolUse, UserPromptSubmit, SessionStart, PostToolUse, SessionEnd) -> this surface's own event name. Omitted keys keep the canonical name unchanged."
53
+ "description": "Canonical event name (PreToolUse, UserPromptSubmit, SessionStart, PostToolUse, SessionEnd, Stop) -> this surface's own event name. Omitted keys keep the canonical name unchanged."
54
54
  },
55
55
  "matchers": {
56
56
  "$ref": "#/definitions/stringRecord",
@@ -131,7 +131,8 @@ const OPENCODE_SLOT_FOR_EVENT: Readonly<Record<string, string>> = {
131
131
  * carriers but is invisible to the opencode surface. Add a new entry here
132
132
  * only with the same justification.
133
133
  */
134
- const OPENCODE_UNSUPPORTED_CANONICAL_EVENTS: ReadonlySet<string> = new Set(['UserPromptSubmit'])
134
+ // Stop: OpenCode has no stop event that can refuse a stop (only `session.idle`), so the quality gate is not wired there.
135
+ const OPENCODE_UNSUPPORTED_CANONICAL_EVENTS: ReadonlySet<string> = new Set(['UserPromptSubmit', 'Stop'])
135
136
 
136
137
  export const OPENCODE_SLOTS: readonly string[] = [
137
138
  'HOOKS_TOOL_EXECUTE_BEFORE',
@@ -17,7 +17,7 @@ export interface ConfigTable {
17
17
  }
18
18
 
19
19
  /** The key sets of the tables a decoder checks by name (agent-hooks' own and the CLI's [assets]), named so no lookup can miss. */
20
- export const HOOKS_TABLE_KEYS: Readonly<Record<string, ConfigOwner>> = { enabled: 'agent-hooks', skills_dir: 'agent-hooks', lean_ctx_dir: 'agent-hooks' }
20
+ export const HOOKS_TABLE_KEYS: Readonly<Record<string, ConfigOwner>> = { enabled: 'agent-hooks', skills_dir: 'agent-hooks', lean_ctx_dir: 'agent-hooks', 'quality-gate': 'agent-hooks' }
21
21
  export const REPO_TABLE_KEYS: Readonly<Record<string, ConfigOwner>> = {
22
22
  protectedTrees: 'agent-hooks',
23
23
  commitProtectedTrees: 'agent-hooks',
@@ -82,6 +82,7 @@
82
82
 
83
83
  import { AGENT_TABLE_KEYS, CONFIG_TABLES, HOOKS_TABLE_KEYS, REPO_TABLE_KEYS, ROOT_KEYS, applicableMigrations } from './config-schema.ts'
84
84
  import { MARKER } from './root.ts'
85
+ import { decodeQualityGate, type QualityGateConfig } from '../hooks/quality-gate/config.ts'
85
86
  import { runningAdl } from './running-adl.ts'
86
87
 
87
88
  interface RuleSection {
@@ -111,6 +112,8 @@ export interface RulesConfig {
111
112
  interface HooksConfig {
112
113
  readonly enabled: boolean
113
114
  readonly skillsDir: string | undefined
115
+ /** `[hooks.quality-gate]`; undefined when the table is absent (the stop gate is off). */
116
+ readonly qualityGate?: QualityGateConfig | undefined
114
117
  }
115
118
 
116
119
  /**
@@ -413,11 +416,15 @@ function decodeHooks(value: unknown): { ok: true; value: HooksConfig } | { ok: f
413
416
  return { ok: false, issue: { pointer: '/hooks/skills_dir', message: 'expected a string' } }
414
417
  }
415
418
 
419
+ const qualityGate = decodeQualityGate(value['quality-gate'])
420
+ if (!qualityGate.ok) return qualityGate
421
+
416
422
  return {
417
423
  ok: true,
418
424
  value: {
419
425
  enabled: enabledRaw ?? true,
420
426
  skillsDir: skillsDirRaw,
427
+ ...(qualityGate.value === undefined ? {} : { qualityGate: qualityGate.value }),
421
428
  },
422
429
  }
423
430
  }
@@ -63,7 +63,7 @@ export interface ActivityNote {
63
63
  }
64
64
 
65
65
  export interface HookInvocation {
66
- readonly kind: 'pre-tool-use' | 'user-prompt-submit' | 'briefing' | 'crg'
66
+ readonly kind: 'pre-tool-use' | 'user-prompt-submit' | 'briefing' | 'crg' | 'quality-gate'
67
67
  readonly host: HostId
68
68
  readonly event?: string
69
69
  readonly subcommand?: string
@@ -0,0 +1,125 @@
1
+ // `[hooks.quality-gate]` in adl-config.toml: every command the stop gate runs, keyed by changed-file kind. Why: docs/architecture/adl-config.md ("[hooks.quality-gate]")
2
+
3
+ export interface QualityGateCommand {
4
+ readonly run: string;
5
+ readonly timeoutSeconds: number;
6
+ }
7
+
8
+ export interface QualityGateConfig {
9
+ readonly enabled: boolean;
10
+ /** Blocks per session before the gate lets the agent stop (Tarun: at most 5). */
11
+ readonly maxBlocks: number;
12
+ /** `operator`: `adl hook quality-gate override` may lift the gate for one session; `none`: no override. */
13
+ readonly override: "operator" | "none";
14
+ /** File kind (`.ts`, `.svelte`, …) -> the commands that check it, in declared order. */
15
+ readonly kinds: Readonly<Record<string, readonly QualityGateCommand[]>>;
16
+ }
17
+
18
+ type Issue = { readonly pointer: string; readonly message: string };
19
+
20
+ const MAX_BLOCKS_LIMIT = 5;
21
+ /** The packaged Stop carrier allows 600 s (assets/hooks.json); a command must finish well inside it. */
22
+ const MAX_TIMEOUT_SECONDS = 540;
23
+ const TABLE_KEYS = ["enabled", "max_blocks", "override", "kinds"];
24
+ const COMMAND_KEYS = ["run", "timeout_seconds"];
25
+ const KIND_RE = /^\.[A-Za-z0-9_+-]+$/;
26
+
27
+ function isTable(value: unknown): value is Record<string, unknown> {
28
+ return typeof value === "object" && value !== null && !Array.isArray(value);
29
+ }
30
+
31
+ function unknownKey(value: Record<string, unknown>, known: readonly string[], pointer: string): Issue | null {
32
+ const extra = Object.keys(value).find((key) => !known.includes(key));
33
+ return extra === undefined
34
+ ? null
35
+ : { pointer: `${pointer}/${extra}`, message: `unknown key '${extra}' (expected one of: ${known.join(", ")})` };
36
+ }
37
+
38
+ function isIntIn(value: unknown, min: number, max: number): value is number {
39
+ return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
40
+ }
41
+
42
+ function decodeCommand(
43
+ raw: unknown,
44
+ pointer: string,
45
+ ): { ok: true; value: QualityGateCommand } | { ok: false; issue: Issue } {
46
+ if (!isTable(raw)) return { ok: false, issue: { pointer, message: "expected a table { run, timeout_seconds }" } };
47
+ const extra = unknownKey(raw, COMMAND_KEYS, pointer);
48
+ if (extra !== null) return { ok: false, issue: extra };
49
+ if (typeof raw.run !== "string" || raw.run.trim() === "")
50
+ return { ok: false, issue: { pointer: `${pointer}/run`, message: "expected a non-empty command string" } };
51
+ if (!isIntIn(raw.timeout_seconds, 1, MAX_TIMEOUT_SECONDS)) {
52
+ return {
53
+ ok: false,
54
+ issue: {
55
+ pointer: `${pointer}/timeout_seconds`,
56
+ message: `expected an integer from 1 to ${MAX_TIMEOUT_SECONDS} (required: no built-in default)`,
57
+ },
58
+ };
59
+ }
60
+ return { ok: true, value: { run: raw.run, timeoutSeconds: raw.timeout_seconds } };
61
+ }
62
+
63
+ type Result<T> = { ok: true; value: T } | { ok: false; issue: Issue };
64
+
65
+ function decodeKinds(raw: unknown, base: string): Result<Record<string, readonly QualityGateCommand[]>> {
66
+ if (!isTable(raw)) {
67
+ return {
68
+ ok: false,
69
+ issue: { pointer: base, message: "expected a table of file kind -> [{ run, timeout_seconds }]" },
70
+ };
71
+ }
72
+ const kinds: Record<string, readonly QualityGateCommand[]> = {};
73
+ for (const [kind, list] of Object.entries(raw)) {
74
+ const pointer = `${base}/${kind}`;
75
+ if (!KIND_RE.test(kind))
76
+ return { ok: false, issue: { pointer, message: 'a file kind is an extension such as ".ts"' } };
77
+ if (!Array.isArray(list) || list.length === 0) {
78
+ return { ok: false, issue: { pointer, message: "expected a non-empty array of { run, timeout_seconds }" } };
79
+ }
80
+ const commands: QualityGateCommand[] = [];
81
+ for (const [index, entry] of list.entries()) {
82
+ const decoded = decodeCommand(entry, `${pointer}/${index}`);
83
+ if (!decoded.ok) return decoded;
84
+ commands.push(decoded.value);
85
+ }
86
+ kinds[kind] = commands;
87
+ }
88
+ if (Object.keys(kinds).length === 0)
89
+ return { ok: false, issue: { pointer: base, message: "declare at least one file kind" } };
90
+ return { ok: true, value: kinds };
91
+ }
92
+
93
+ /** The first scalar setting with the wrong shape, or null. */
94
+ function scalarIssue(raw: Record<string, unknown>, base: string): Issue | null {
95
+ const { enabled, max_blocks: maxBlocks, override } = raw;
96
+ if (enabled !== undefined && typeof enabled !== "boolean")
97
+ return { pointer: `${base}/enabled`, message: "expected a boolean" };
98
+ if (maxBlocks !== undefined && !isIntIn(maxBlocks, 1, MAX_BLOCKS_LIMIT)) {
99
+ return { pointer: `${base}/max_blocks`, message: `expected an integer from 1 to ${MAX_BLOCKS_LIMIT}` };
100
+ }
101
+ if (override !== undefined && override !== "operator" && override !== "none") {
102
+ return { pointer: `${base}/override`, message: 'expected "operator" or "none"' };
103
+ }
104
+ return null;
105
+ }
106
+
107
+ /** Decode `[hooks.quality-gate]`; absent means the gate is off for this repository. */
108
+ export function decodeQualityGate(raw: unknown): Result<QualityGateConfig | undefined> {
109
+ if (raw === undefined) return { ok: true, value: undefined };
110
+ const base = "/hooks/quality-gate";
111
+ if (!isTable(raw)) return { ok: false, issue: { pointer: base, message: "expected a table" } };
112
+ const issue = unknownKey(raw, TABLE_KEYS, base) ?? scalarIssue(raw, base);
113
+ if (issue !== null) return { ok: false, issue };
114
+ const kinds = decodeKinds(raw.kinds, `${base}/kinds`);
115
+ if (!kinds.ok) return kinds;
116
+ return {
117
+ ok: true,
118
+ value: {
119
+ enabled: (raw.enabled as boolean | undefined) ?? true,
120
+ maxBlocks: (raw.max_blocks as number | undefined) ?? MAX_BLOCKS_LIMIT,
121
+ override: (raw.override as "operator" | "none" | undefined) ?? "operator",
122
+ kinds: kinds.value,
123
+ },
124
+ };
125
+ }
@@ -0,0 +1,347 @@
1
+ // `adl hook quality-gate`: the stop gate; behaviour in docs/architecture/adl-config.md ("[hooks.quality-gate]").
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { extname, join } from "node:path";
4
+ import { decodeConfig } from "../../gating/config.ts";
5
+ import { MARKER } from "../../gating/root.ts";
6
+ import { spawnWithTimeout } from "../../lib/spawn-with-timeout.ts";
7
+ import type { HookHandler, HookInvocation, HookResult, HostId } from "../contract.ts";
8
+ import type { QualityGateCommand, QualityGateConfig } from "./config.ts";
9
+
10
+ export const STATE_DIR_REL = ".adl/state/quality-gate";
11
+ const GIT_TIMEOUT_MS = 10_000;
12
+ const OUTPUT_TAIL_CHARS = 3_000;
13
+ /** Hosts whose stop event can be refused (Kimi is a global carrier and OpenCode cannot block a stop). */
14
+ const GATED_HOSTS: ReadonlySet<HostId> = new Set(["claude", "codex", "cursor"]);
15
+
16
+ interface SessionState {
17
+ readonly baseHead: string;
18
+ readonly baseSource: "session-start" | "first-stop";
19
+ readonly config: QualityGateConfig;
20
+ readonly rotation: number;
21
+ readonly pending: string | null;
22
+ readonly blocks: number;
23
+ }
24
+
25
+ interface ExecResult {
26
+ readonly exitCode: number | null;
27
+ readonly output: string;
28
+ readonly timedOut: boolean;
29
+ }
30
+ export type Exec = (
31
+ cmd: string,
32
+ args: readonly string[],
33
+ opts: {
34
+ readonly cwd: string;
35
+ readonly env: Readonly<Record<string, string | undefined>>;
36
+ readonly timeoutMs: number;
37
+ },
38
+ ) => Promise<ExecResult>;
39
+
40
+ export const defaultExec: Exec = async (cmd, args, opts) => {
41
+ try {
42
+ const result = await spawnWithTimeout(cmd, args, opts);
43
+ return { exitCode: result.exitCode, output: result.stdout + result.stderr, timedOut: result.timedOut };
44
+ } catch (error) {
45
+ return { exitCode: null, output: String(error), timedOut: false };
46
+ }
47
+ };
48
+
49
+ export function sessionKey(host: HostId, session: string): string {
50
+ return `${host}-${session.replace(/[^A-Za-z0-9_.-]/g, "_")}`;
51
+ }
52
+ function statePath(root: string, key: string): string {
53
+ return join(root, STATE_DIR_REL, `${key}.json`);
54
+ }
55
+ export function overridePath(root: string, key: string): string {
56
+ return join(root, STATE_DIR_REL, "overrides", `${key}.json`);
57
+ }
58
+
59
+ /** The session state, null when none was recorded, or "corrupt" when the file is not a state record. */
60
+ function readState(root: string, key: string): SessionState | null | "corrupt" {
61
+ const path = statePath(root, key);
62
+ if (!existsSync(path)) return null;
63
+ try {
64
+ const state = JSON.parse(readFileSync(path, "utf8")) as SessionState;
65
+ const valid =
66
+ typeof state.baseHead === "string" &&
67
+ typeof state.blocks === "number" &&
68
+ typeof state.rotation === "number" &&
69
+ typeof state.config?.maxBlocks === "number" &&
70
+ typeof state.config.kinds === "object";
71
+ return valid ? state : "corrupt";
72
+ } catch {
73
+ return "corrupt";
74
+ }
75
+ }
76
+ function writeState(root: string, key: string, state: SessionState): void {
77
+ mkdirSync(join(root, STATE_DIR_REL), { recursive: true });
78
+ writeFileSync(statePath(root, key), `${JSON.stringify(state, null, 2)}\n`);
79
+ }
80
+
81
+ function currentGateConfig(root: string): QualityGateConfig | undefined {
82
+ const decoded = decodeConfig(readFileSync(join(root, MARKER), "utf8"));
83
+ return decoded.ok ? decoded.value.hooks.qualityGate : undefined;
84
+ }
85
+
86
+ async function git(exec: Exec, inv: HookInvocation, args: readonly string[]): Promise<string> {
87
+ const result = await exec("git", args, { cwd: inv.root, env: inv.env, timeoutMs: GIT_TIMEOUT_MS });
88
+ if (result.exitCode !== 0)
89
+ throw new Error(
90
+ `git ${args.join(" ")} failed: ${result.output.trim() || (result.timedOut ? "timed out" : "no output")}`,
91
+ );
92
+ return result.output;
93
+ }
94
+
95
+ /** Paths changed since `baseHead`: tracked changes (committed or not) plus untracked, non-ignored file names. */
96
+ async function changedFiles(exec: Exec, inv: HookInvocation, baseHead: string): Promise<readonly string[]> {
97
+ const tracked = await git(exec, inv, ["diff", "--name-only", "-z", baseHead, "--"]);
98
+ const untracked = await git(exec, inv, ["ls-files", "--others", "--exclude-standard", "-z"]);
99
+ return [...new Set([...tracked.split("\0"), ...untracked.split("\0")].filter((path) => path.length > 0))];
100
+ }
101
+
102
+ /** The declared commands matching the changed files' kinds, de-duplicated by command, in declared order. */
103
+ export function selectCommands(config: QualityGateConfig, files: readonly string[]): readonly QualityGateCommand[] {
104
+ const kinds = new Set(files.map((file) => extname(file)));
105
+ const out = new Map<string, QualityGateCommand>();
106
+ for (const [kind, commands] of Object.entries(config.kinds)) {
107
+ if (!kinds.has(kind)) continue;
108
+ for (const command of commands) if (!out.has(command.run)) out.set(command.run, command);
109
+ }
110
+ return [...out.values()];
111
+ }
112
+
113
+ function sessionOf(payload: Record<string, unknown>): string | null {
114
+ const raw = payload.session_id ?? payload.conversation_id;
115
+ return typeof raw === "string" && raw.trim() !== "" ? raw.trim() : null;
116
+ }
117
+
118
+ function eventOf(payload: Record<string, unknown>): string {
119
+ const raw = payload.hook_event_name;
120
+ return typeof raw === "string" ? raw.toLowerCase() : "";
121
+ }
122
+
123
+ const ALLOW: HookResult = { stdout: "", stderr: "", exitCode: 0 };
124
+
125
+ function block(host: HostId, message: string): HookResult {
126
+ if (host === "cursor") return { stdout: JSON.stringify({ followup_message: message }), stderr: "", exitCode: 0 };
127
+ return { stdout: JSON.stringify({ decision: "block", reason: message }), stderr: "", exitCode: 0 };
128
+ }
129
+
130
+ /** Allow the stop and show `message` to the human: Claude's `systemMessage`, stderr elsewhere. */
131
+ function allowWithMessage(host: HostId, message: string): HookResult {
132
+ if (host === "claude") return { stdout: JSON.stringify({ systemMessage: message }), stderr: "", exitCode: 0 };
133
+ return { stdout: host === "cursor" ? "{}" : "", stderr: `${message}\n`, exitCode: 0 };
134
+ }
135
+
136
+ function tail(text: string): string {
137
+ return text.length > OUTPUT_TAIL_CHARS ? `...${text.slice(-OUTPUT_TAIL_CHARS)}` : text;
138
+ }
139
+
140
+ async function onSessionStart(
141
+ inv: HookInvocation,
142
+ exec: Exec,
143
+ key: string,
144
+ config: QualityGateConfig,
145
+ ): Promise<HookResult> {
146
+ if (readState(inv.root, key) !== null) {
147
+ inv.record?.({ reason: "SKIP baseline already recorded for this session" });
148
+ return ALLOW;
149
+ }
150
+ try {
151
+ const baseHead = (await git(exec, inv, ["rev-parse", "HEAD"])).trim();
152
+ writeState(inv.root, key, { baseHead, baseSource: "session-start", config, rotation: 0, pending: null, blocks: 0 });
153
+ inv.record?.({ reason: "PASS", downstream: `baseline ${baseHead.slice(0, 12)}` });
154
+ return ALLOW;
155
+ } catch (error) {
156
+ // SessionStart cannot block; the stop that follows reports the missing baseline by name.
157
+ inv.record?.({ reason: "ERROR quality-gate baseline", message: String(error) });
158
+ return {
159
+ stdout: "",
160
+ stderr: `adl hook quality-gate: could not record the session baseline: ${String(error)}\n`,
161
+ exitCode: 1,
162
+ };
163
+ }
164
+ }
165
+
166
+ async function onStop(
167
+ inv: HookInvocation,
168
+ exec: Exec,
169
+ key: string,
170
+ session: string,
171
+ current: QualityGateConfig | undefined,
172
+ ): Promise<HookResult> {
173
+ const saved = readState(inv.root, key);
174
+ if (saved === "corrupt") {
175
+ // Cannot count blocks without the state, so never block on it; say so loudly instead.
176
+ const path = statePath(inv.root, key);
177
+ inv.record?.({ reason: "COULD-NOT-RUN quality-gate state unreadable", message: path });
178
+ return allowWithMessage(
179
+ inv.host,
180
+ `adl quality-gate: COULD-NOT-RUN — the session state ${path} is not a valid state record, so no check ran. Recover (operator): rm ${path}; the next stop starts from HEAD.`,
181
+ );
182
+ }
183
+ const config = saved?.config ?? current;
184
+ if (config === undefined || !config.enabled) {
185
+ inv.record?.({ reason: "SKIP quality-gate not enabled in adl-config.toml" });
186
+ return ALLOW;
187
+ }
188
+ if (config.override === "operator" && existsSync(overridePath(inv.root, key))) {
189
+ inv.record?.({ reason: "OVERRIDDEN", message: `operator override for session ${session}` });
190
+ return allowWithMessage(
191
+ inv.host,
192
+ `adl quality-gate: OVERRIDDEN by the operator for session ${session}; no check ran.`,
193
+ );
194
+ }
195
+
196
+ const blocksSoFar = saved?.blocks ?? 0;
197
+ // After `max_blocks` blocks this session the gate still runs its one command, but reports instead of blocking.
198
+ const exhausted = blocksSoFar >= config.maxBlocks;
199
+ const limit = `${config.maxBlocks} per session`;
200
+ const refuse = (state: SessionState, what: string, message: string): HookResult => {
201
+ if (exhausted) {
202
+ inv.record?.({ reason: "FAILED", message: what });
203
+ return allowWithMessage(
204
+ inv.host,
205
+ `adl quality-gate: FAILED — the block limit (${limit}) is used, so the agent may stop.\n${message}`,
206
+ );
207
+ }
208
+ const blocks = blocksSoFar + 1;
209
+ writeState(inv.root, key, { ...state, blocks });
210
+ inv.record?.({ reason: `BLOCK quality-gate ${blocks}/${config.maxBlocks}`, message: what });
211
+ return block(inv.host, `adl quality-gate: BLOCKED (block ${blocks} of ${limit}).\n${message}`);
212
+ };
213
+
214
+ let state: SessionState;
215
+ let files: readonly string[];
216
+ try {
217
+ // No baseline yet (no SessionStart, or an earlier git failure): HEAD now, keeping the block count.
218
+ state =
219
+ saved !== null && saved.baseHead !== ""
220
+ ? saved
221
+ : {
222
+ baseHead: (await git(exec, inv, ["rev-parse", "HEAD"])).trim(),
223
+ baseSource: "first-stop",
224
+ config,
225
+ rotation: 0,
226
+ pending: null,
227
+ blocks: blocksSoFar,
228
+ };
229
+ files = await changedFiles(exec, inv, state.baseHead);
230
+ } catch (error) {
231
+ // Counted even with no baseline yet, so a broken git can never loop the agent.
232
+ return refuse(
233
+ saved ?? { baseHead: "", baseSource: "first-stop", config, rotation: 0, pending: null, blocks: 0 },
234
+ `COULD-NOT-RUN ${String(error)}`,
235
+ [
236
+ `COULD-NOT-RUN: ${String(error)}`,
237
+ `Recover: make \`git -C ${inv.root} rev-parse HEAD\` and \`git -C ${inv.root} status\` succeed, then stop again.`,
238
+ ].join("\n"),
239
+ );
240
+ }
241
+
242
+ return runOneCommand(inv, exec, key, state, files, refuse);
243
+ }
244
+
245
+ function baseNoteOf(state: SessionState): string {
246
+ return state.baseSource === "session-start"
247
+ ? `since session start (${state.baseHead.slice(0, 12)})`
248
+ : `since HEAD ${state.baseHead.slice(0, 12)} at the first stop — no SessionStart baseline was recorded for this session; run \`adl hooks deploy\` so SessionStart carries \`adl hook quality-gate\``;
249
+ }
250
+
251
+ function failureCause(result: ExecResult, chosen: QualityGateCommand): string {
252
+ if (result.timedOut) return `timed out after ${chosen.timeoutSeconds}s`;
253
+ return result.exitCode === null ? "could not start" : `exit ${result.exitCode}`;
254
+ }
255
+
256
+ /** Select the matching commands, run ONE (the last failure first, else the next in rotation), allow or refuse. */
257
+ async function runOneCommand(
258
+ inv: HookInvocation,
259
+ exec: Exec,
260
+ key: string,
261
+ state: SessionState,
262
+ files: readonly string[],
263
+ refuse: (state: SessionState, what: string, message: string) => HookResult,
264
+ ): Promise<HookResult> {
265
+ const baseNote = baseNoteOf(state);
266
+ const loud = state.baseSource === "first-stop";
267
+ const commands = selectCommands(state.config, files);
268
+ if (commands.length === 0) {
269
+ writeState(inv.root, key, state);
270
+ inv.record?.({ reason: "PASS no matching change", downstream: `${files.length} changed file(s) ${baseNote}` });
271
+ return loud
272
+ ? allowWithMessage(inv.host, `adl quality-gate: no declared command matched the changes ${baseNote}.`)
273
+ : ALLOW;
274
+ }
275
+
276
+ const pendingIndex = commands.findIndex((command) => command.run === state.pending);
277
+ const index = pendingIndex >= 0 ? pendingIndex : state.rotation % commands.length;
278
+ const chosen = commands[index] as QualityGateCommand;
279
+ const result = await exec("/bin/sh", ["-c", chosen.run], {
280
+ cwd: inv.root,
281
+ env: inv.env,
282
+ timeoutMs: chosen.timeoutSeconds * 1000,
283
+ });
284
+
285
+ if (result.exitCode === 0) {
286
+ writeState(inv.root, key, { ...state, rotation: index + 1, pending: null });
287
+ inv.record?.({ reason: "PASS", downstream: chosen.run });
288
+ return loud ? allowWithMessage(inv.host, `adl quality-gate: PASS \`${chosen.run}\` (changes ${baseNote}).`) : ALLOW;
289
+ }
290
+
291
+ const why = failureCause(result, chosen);
292
+ const failed: SessionState = { ...state, pending: chosen.run };
293
+ writeState(inv.root, key, failed);
294
+ const listed = `${files.slice(0, 20).join(", ")}${files.length > 20 ? `, … (${files.length} total)` : ""}`;
295
+ return refuse(
296
+ failed,
297
+ `${chosen.run}: ${why}`,
298
+ [
299
+ `\`${chosen.run}\` failed: ${why}.`,
300
+ `It was chosen because these files changed ${baseNote}: ${listed}.`,
301
+ "Output:",
302
+ tail(result.output.trim()) || "(no output)",
303
+ `Fix it, re-run \`${chosen.run}\` to confirm, then stop again; the gate re-runs this command first.`,
304
+ ].join("\n"),
305
+ );
306
+ }
307
+
308
+ export function createQualityGateHandler(exec: Exec = defaultExec): HookHandler {
309
+ return async (inv: HookInvocation): Promise<HookResult> => {
310
+ if (!GATED_HOSTS.has(inv.host)) {
311
+ inv.record?.({ reason: `SKIP quality-gate cannot gate host ${inv.host}` });
312
+ return ALLOW;
313
+ }
314
+ const event = eventOf(inv.payload);
315
+ const session = sessionOf(inv.payload);
316
+ if (session === null) {
317
+ inv.record?.({ reason: "ERROR quality-gate no session id" });
318
+ return {
319
+ stdout: "",
320
+ stderr: `adl hook quality-gate: the ${inv.host} payload carries no session id, so blocks cannot be counted; the gate did not run\n`,
321
+ exitCode: 1,
322
+ };
323
+ }
324
+ const key = sessionKey(inv.host, session);
325
+ const current = currentGateConfig(inv.root);
326
+ if (event === "sessionstart") {
327
+ if (current?.enabled === true) return onSessionStart(inv, exec, key, current);
328
+ inv.record?.({ reason: "SKIP quality-gate not enabled in adl-config.toml" });
329
+ return ALLOW;
330
+ }
331
+ if (event === "stop") {
332
+ // Cursor reports why the agent stopped; a follow-up after the user aborted would restart it against their intent.
333
+ const status = inv.payload.status;
334
+ if (status !== "aborted" && status !== "error") return onStop(inv, exec, key, session, current);
335
+ inv.record?.({ reason: `SKIP quality-gate stop status ${status}` });
336
+ return ALLOW;
337
+ }
338
+ inv.record?.({ reason: `ERROR quality-gate unsupported event '${event}'` });
339
+ return {
340
+ stdout: "",
341
+ stderr: `adl hook quality-gate: unsupported event '${event}' (expected SessionStart or Stop)\n`,
342
+ exitCode: 1,
343
+ };
344
+ };
345
+ }
346
+
347
+ export const handleQualityGate: HookHandler = createQualityGateHandler();
@@ -0,0 +1,63 @@
1
+ // `adl hook quality-gate override`: operator lifts the stop gate for one session; see docs/architecture/adl-config.md.
2
+ import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { isMarkedHumanAzdoCaller } from "../../../../azdo/src/lib/agent-identity.ts";
5
+ import { realRootIO, resolveManagedRepo } from "../../gating/root.ts";
6
+ import { isHostId } from "../../hosts/spec.ts";
7
+ import type { HookResult } from "../contract.ts";
8
+ import { overridePath, sessionKey } from "./index.ts";
9
+
10
+ export const AUDIT_LOG_REL = ".adl/logs/agent-hooks/quality-gate-audit.log";
11
+ const USAGE = 'usage: adl hook quality-gate override --host <claude|codex|cursor> --session <id> --reason "<text>"';
12
+
13
+ function flag(argv: readonly string[], name: string): string | undefined {
14
+ const index = argv.indexOf(name);
15
+ const value = index >= 0 ? argv[index + 1] : undefined;
16
+ return value !== undefined && !value.startsWith("--") && value.trim() !== "" ? value : undefined;
17
+ }
18
+
19
+ function audit(root: string, row: Record<string, unknown>): void {
20
+ const path = join(root, AUDIT_LOG_REL);
21
+ mkdirSync(dirname(path), { recursive: true });
22
+ appendFileSync(path, `${JSON.stringify({ ts: new Date().toISOString(), ...row })}\n`);
23
+ }
24
+
25
+ export function runQualityGateOverride(
26
+ argv: readonly string[],
27
+ cwd: string,
28
+ env: NodeJS.ProcessEnv,
29
+ stdinIsTTY: boolean,
30
+ ): HookResult {
31
+ const managed = resolveManagedRepo(realRootIO, cwd);
32
+ if (managed.root === null || !managed.managed)
33
+ return {
34
+ stdout: "",
35
+ stderr: `adl hook quality-gate override: ${cwd} is not in a repository with adl-config.toml\n`,
36
+ exitCode: 1,
37
+ };
38
+ const root = managed.root;
39
+ const host = flag(argv, "--host");
40
+ const session = flag(argv, "--session");
41
+ const reason = flag(argv, "--reason");
42
+ if (host === undefined || !isHostId(host) || session === undefined || reason === undefined)
43
+ return { stdout: "", stderr: `${USAGE}\n`, exitCode: 1 };
44
+ const who = env.USER ?? "unknown";
45
+ if (!isMarkedHumanAzdoCaller(env, stdinIsTTY)) {
46
+ audit(root, { action: "refused", host, session, reason, who, cause: "no TTY or no human marker" });
47
+ return {
48
+ stdout: "",
49
+ stderr:
50
+ "adl hook quality-gate override: refused — only the operator, at a real terminal with ADL_HUMAN_AZDO=1, may override the gate. The refusal is logged.\n",
51
+ exitCode: 1,
52
+ };
53
+ }
54
+ const path = overridePath(root, sessionKey(host, session));
55
+ mkdirSync(dirname(path), { recursive: true });
56
+ writeFileSync(path, `${JSON.stringify({ host, session, reason, who, at: new Date().toISOString() }, null, 2)}\n`);
57
+ audit(root, { action: "granted", host, session, reason, who });
58
+ return {
59
+ stdout: `quality-gate override recorded for ${host} session ${session}; audit: ${AUDIT_LOG_REL}\n`,
60
+ stderr: "",
61
+ exitCode: 0,
62
+ };
63
+ }
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * adl hook <kind> [subcommand] --host=<claude|codex|cursor|kimi|opencode>
9
9
  *
10
- * kinds: pre-tool-use, user-prompt-submit, briefing, crg <subcommand>
10
+ * kinds: pre-tool-use, user-prompt-submit, briefing, crg <subcommand>, quality-gate
11
11
  * crg subcommands: after-file-edit, pre-commit, session-stop
12
12
  * payload: JSON on stdin
13
13
  * --version prints the package version and exits 0
@@ -17,6 +17,7 @@
17
17
  * adl hook rules list [--repo <path>] [--json]
18
18
  * adl hook rules show <id> [--repo <path>] [--json]
19
19
  * adl hook doctor [--repo <path>]
20
+ * adl hook quality-gate override --host <h> --session <id> --reason <text>
20
21
  *
21
22
  * Per-repo gating (HARDCUT replacement for enact-repo-controls's
22
23
  * `.agents/controls.toml` MARKER scheme — see src/gating/):
@@ -87,8 +88,10 @@ import { handleCrg } from './hooks/crg/handler.ts'
87
88
  import { runRules } from './cli/rules.ts'
88
89
  import { runDoctor } from './cli/doctor.ts'
89
90
  import { runLogged } from './hooks/log.ts'
91
+ import { handleQualityGate } from './hooks/quality-gate/index.ts'
92
+ import { runQualityGateOverride } from './hooks/quality-gate/override.ts'
90
93
 
91
- const HOOK_KINDS = ['pre-tool-use', 'user-prompt-submit', 'briefing', 'crg'] as const
94
+ const HOOK_KINDS = ['pre-tool-use', 'user-prompt-submit', 'briefing', 'crg', 'quality-gate'] as const
92
95
  type HookKind = (typeof HOOK_KINDS)[number]
93
96
 
94
97
  function isHookKind(value: string | undefined): value is HookKind {
@@ -102,6 +105,7 @@ const HANDLERS: Readonly<Record<HookKind, HookHandler>> = {
102
105
  'user-prompt-submit': handleUserPromptSubmit,
103
106
  briefing: handleBriefing,
104
107
  crg: handleCrg,
108
+ 'quality-gate': handleQualityGate,
105
109
  }
106
110
 
107
111
  /** Exit code `pre-tool-use` alone uses to fail closed on an undecidable payload — see this file's header (work item D). */
@@ -129,6 +133,16 @@ function writeResult(result: HookResult): number {
129
133
  return result.exitCode
130
134
  }
131
135
 
136
+ /** Operator commands, not hooks: no --host, no stdin payload, never a silent no-op (see src/cli/). Null: not an operator command. */
137
+ async function runOperatorCommand(argv: readonly string[]): Promise<number | null> {
138
+ if (argv[0] === 'rules') return writeResult(runRules(argv.slice(1), process.cwd()))
139
+ if (argv[0] === 'doctor') return writeResult(await runDoctor(argv.slice(1), process.cwd(), process.env))
140
+ if (argv[0] === 'quality-gate' && argv[1] === 'override') {
141
+ return writeResult(runQualityGateOverride(argv.slice(2), process.cwd(), process.env, process.stdin.isTTY === true))
142
+ }
143
+ return null
144
+ }
145
+
132
146
  /**
133
147
  * `adlVersion` is the embedding CLI's version (`adl hook` passes
134
148
  * `apps/cli/package.json`'s); the standalone entry passes none, and config
@@ -141,9 +155,8 @@ export async function run(argv: readonly string[], adlVersion?: string): Promise
141
155
  return 0
142
156
  }
143
157
 
144
- // Operator commands, not hooks: no --host, no stdin payload, never a silent no-op (see src/cli/).
145
- if (argv[0] === 'rules') return writeResult(runRules(argv.slice(1), process.cwd()))
146
- if (argv[0] === 'doctor') return writeResult(await runDoctor(argv.slice(1), process.cwd(), process.env))
158
+ const operator = await runOperatorCommand(argv)
159
+ if (operator !== null) return operator
147
160
 
148
161
  const kindArg = argv[0]
149
162
  if (!isHookKind(kindArg)) {
@@ -108,6 +108,22 @@ export function protectedCarrierMatch(path: string): string | null {
108
108
  if (candidate === target) return protectedPath
109
109
  if (candidate.endsWith(`/${target}`)) return protectedPath
110
110
  }
111
+ return protectedStateMatch(candidate)
112
+ }
113
+
114
+ /**
115
+ * Directories whose EVERY file is protected: the stop quality gate's per-session block counter
116
+ * and operator overrides (`hooks/quality-gate/`). Rewriting one resets the agent's own block
117
+ * limit or forges an operator override, which is switching the gate off.
118
+ */
119
+ const PROTECTED_STATE_DIRS: readonly string[] = ['.adl/state/quality-gate']
120
+
121
+ function protectedStateMatch(candidate: string): string | null {
122
+ for (const dir of PROTECTED_STATE_DIRS) {
123
+ // `candidate` is already case-folded on a case-insensitive host, and these literals are lowercase.
124
+ const target = dir
125
+ if (candidate === target || candidate.startsWith(`${target}/`) || candidate.endsWith(`/${target}`) || candidate.includes(`/${target}/`)) return dir
126
+ }
111
127
  return null
112
128
  }
113
129
 
@@ -136,6 +152,10 @@ const PROTECTED_CARRIER_DIRS: ReadonlySet<string> = new Set([
136
152
  '.config/opencode',
137
153
  'Library/Application Support/ClaudeCode',
138
154
  'etc/claude-code',
155
+ // The quality-gate state directory and its parents: moving or replacing them takes the state with them.
156
+ '.adl',
157
+ '.adl/state',
158
+ ...PROTECTED_STATE_DIRS,
139
159
  ])
140
160
 
141
161
  /**