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

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: 63753136 bytes
4
+ sha256: 03c23d250dd0c873e7e5f606966860be53152ade6c2f42bd0739e979d048ddee
package/bin/job-watchdog CHANGED
@@ -55,27 +55,54 @@ if [ "$os" = Linux ] && [ -f "$systemd_dir/$pool_unit" ]; then
55
55
  fi
56
56
  fi
57
57
 
58
- # services.pool_reaper (mac): report-only check of the Hetzner dead-man switch; see docs/operations/agent-pool.md.
58
+ # services.pool_reaper (mac): re-arm the Hetzner dead-man switch when it is down or its last run failed; see docs/operations/agent-pool.md.
59
59
  reaper_label=com.adl.pool-reaper
60
- if [ "$os" = Darwin ] && [ -f "$root/Library/LaunchDaemons/$reaper_label.plist" ]; then
60
+ reaper_plist="$root/Library/LaunchDaemons/$reaper_label.plist"
61
+ reaper_failed=0
62
+ reaper_error() { log "ERROR watchdog: $*; run: sudo adl fleet setup NAME --rearm"; reaper_failed=1; }
63
+ rearm_reaper() {
64
+ log "WARN watchdog: re-arming $reaper_label: $1"
65
+ if [ "$2" = loaded ]; then
66
+ # Re-check right before bootout: a run may have started since the first look.
67
+ reaper_recheck="$(launchctl print "system/$reaper_label" 2>&1)" || reaper_recheck=""
68
+ if [ "$(printf '%s\n' "$reaper_recheck" | sed -n 's/^[[:space:]]*state = //p' | head -n 1)" = running ]; then
69
+ log "WARN watchdog: $reaper_label started running meanwhile; not booting it out"
70
+ return
71
+ fi
72
+ launchctl bootout "system/$reaper_label" || { reaper_error "launchctl bootout system/$reaper_label failed"; return; }
73
+ reaper_gone=0
74
+ for _ in 1 2 3 4 5 6 7 8 9 10; do
75
+ if ! launchctl print "system/$reaper_label" >/dev/null 2>&1; then reaper_gone=1; break; fi
76
+ sleep 0.5
77
+ done
78
+ [ "$reaper_gone" -eq 1 ] || { reaper_error "$reaper_label is still loaded after bootout (waited 5s); not bootstrapping"; return; }
79
+ fi
80
+ launchctl enable "system/$reaper_label" || { reaper_error "launchctl enable system/$reaper_label failed"; return; }
81
+ launchctl bootstrap system "$reaper_plist" || { reaper_error "launchctl bootstrap system $reaper_plist failed"; return; }
82
+ log "WARN watchdog: re-armed $reaper_label"
83
+ }
84
+ if [ "$os" = Darwin ] && [ -f "$reaper_plist" ]; then
61
85
  if reaper_printed="$(launchctl print "system/$reaper_label" 2>&1)"; then
86
+ reaper_state="$(printf '%s\n' "$reaper_printed" | sed -n 's/^[[:space:]]*state = //p' | head -n 1)"
62
87
  reaper_exit="$(printf '%s\n' "$reaper_printed" | sed -n 's/^[[:space:]]*last exit code = \([0-9][0-9]*\).*/\1/p' | head -n 1)"
63
- if [ -n "$reaper_exit" ] && [ "$reaper_exit" != 0 ]; then
64
- log "WARN watchdog: $reaper_label last run failed (exit $reaper_exit); the Hetzner dead-man switch may not be reaping: see /var/log/adl/pool-reaper.log"
88
+ if [ "$reaper_state" != running ] && [ -n "$reaper_exit" ] && [ "$reaper_exit" != 0 ]; then
89
+ rearm_reaper "its last run failed (exit $reaper_exit); see /var/log/adl/pool-reaper.log" loaded
65
90
  else
66
91
  log "INFO watchdog: $reaper_label is loaded"
67
92
  fi
68
93
  else
69
- log "WARN watchdog: $reaper_label is not loaded; the Hetzner dead-man switch is off; run: sudo adl fleet setup NAME --rearm"
94
+ rearm_reaper "it is not loaded; the Hetzner dead-man switch is off" missing
70
95
  fi
71
96
  fi
97
+ # Every exit below goes through finish, so a failed reaper re-arm still exits 1.
98
+ finish() { exit "$reaper_failed"; }
72
99
 
73
100
  case "$os" in
74
101
  Darwin)
75
102
  [ -f "$plist" ] || fail "$plist is missing; run: sudo adl fleet setup NAME --rearm"
76
103
  if printed="$(launchctl print "system/$label" 2>&1)"; then
77
104
  job_state="$(printf '%s\n' "$printed" | sed -n 's/^[[:space:]]*state = //p' | head -n 1)"
78
- [ "$job_state" = running ] && exit 0
105
+ [ "$job_state" = running ] && finish
79
106
  exit_code="$(printf '%s\n' "$printed" | sed -n 's/^[[:space:]]*last exit code = \([0-9][0-9]*\).*/\1/p' | head -n 1)"
80
107
  if [ "$exit_code" = 78 ]; then cause="launchd could not spawn the program (last exit code 78 EX_CONFIG)"; fi
81
108
  # Incident state as launchd reports it (m3, 2026-10-24): packages/fleet/README.md#self-healing-the-watchdog
@@ -87,7 +114,7 @@ case "$os" in
87
114
  Linux)
88
115
  [ -f "$systemd_dir/$service_unit" ] && [ -f "$systemd_dir/$timer_unit" ] || fail "$service_unit / $timer_unit are missing in $systemd_dir; run: sudo adl fleet setup NAME --rearm"
89
116
  service_state="$(systemctl is-active "$service_unit" 2>/dev/null)"
90
- case "$service_state" in active|activating) exit 0 ;; esac
117
+ case "$service_state" in active|activating) finish ;; esac
91
118
  timer_state="$(systemctl is-active "$timer_unit" 2>/dev/null)"
92
119
  timer_enabled="$(systemctl is-enabled "$timer_unit" 2>/dev/null)"
93
120
  if [ "$timer_state" != active ]; then cause="$timer_unit is $timer_state"
@@ -99,13 +126,13 @@ esac
99
126
 
100
127
  stale_only=0
101
128
  if [ -z "$cause" ]; then
102
- if fresh "$last_success" "$max_age_minutes"; then exit 0; fi
129
+ if fresh "$last_success" "$max_age_minutes"; then finish; fi
103
130
  cause="no successful reconcile in the last 25 hours ($last_success)"
104
131
  stale_only=1
105
132
  fi
106
133
 
107
134
  # Stale last-success alone re-arms at most once per 6 hours: packages/fleet/README.md#self-healing-the-watchdog
108
- if [ "$stale_only" -eq 1 ] && fresh "$kick_stamp" "$kick_gap_minutes"; then exit 0; fi
135
+ if [ "$stale_only" -eq 1 ] && fresh "$kick_stamp" "$kick_gap_minutes"; then finish; fi
109
136
 
110
137
  log "WARN watchdog: re-arming the scheduled job: $cause"
111
138
 
@@ -116,7 +143,7 @@ case "$os" in
116
143
  recheck_state="$(printf '%s\n' "$rechecked" | sed -n 's/^[[:space:]]*state = //p' | head -n 1)"
117
144
  if [ "$recheck_state" = running ]; then
118
145
  log "WARN watchdog: $label started running meanwhile; not booting it out"
119
- exit 0
146
+ finish
120
147
  fi
121
148
  launchctl bootout "system/$label" || fail "launchctl bootout system/$label failed"
122
149
  gone=0
@@ -144,3 +171,4 @@ case "$os" in
144
171
  Linux) systemctl start --no-block "$service_unit" || fail "systemctl start $service_unit failed" ;;
145
172
  esac
146
173
  log "WARN watchdog: re-armed and started $label"
174
+ finish
package/bin/setup CHANGED
@@ -404,6 +404,21 @@ EOF
404
404
  systemctl enable --now adl-global-tools-watchdog.timer
405
405
  systemctl restart adl-global-tools-watchdog.timer
406
406
 
407
+ # Azure Pipelines agents (svc.sh units vsts.agent.*.service) restart after any exit, an OOM kill included.
408
+ # Named zzz- so it sorts after the hand-installed zz-ci-retention.conf (Restart=on-success): the last Restart= wins.
409
+ # Takes effect at daemon-reload; a running agent is not restarted, so no job is cut short.
410
+ agent_drop_ins=0
411
+ for agent_unit in "$systemd_dir"/vsts.agent.*.service; do
412
+ [[ -f "$agent_unit" ]] || continue
413
+ mkdir -p "$agent_unit.d"
414
+ printf '%s\n' '# Written by adl fleet setup: restart the agent after any exit, an OOM kill included.' \
415
+ '[Service]' 'Restart=always' 'RestartSec=10' >"$agent_unit.d/zzz-adl-restart.conf"
416
+ chmod 0644 "$agent_unit.d/zzz-adl-restart.conf"
417
+ echo "adl fleet setup: agent restart drop-in: ${agent_unit##*/}"
418
+ agent_drop_ins=1
419
+ done
420
+ if [[ "$agent_drop_ins" -eq 1 ]]; then systemctl daemon-reload; fi
421
+
407
422
  # Long-running services the manifest declares for this host (Feature 758):
408
423
  # services.agent_pool => adl-agent-pool.service runs `adl pool run --host NAME`
409
424
  # always on. Everything the poller needs is read from the manifest by the
@@ -20,14 +20,24 @@ if ! jq -e '
20
20
  def posint: type == "number" and . >= 1 and floor == .;
21
21
  def nonneg: type == "number" and . >= 0 and floor == .;
22
22
  def nes: type == "string" and length > 0;
23
+ def guid: type == "string" and test("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
24
+ def aca_pool: type == "object" and
25
+ ((keys - ["capabilities"]) | sort) == ["cpu", "disk", "disk_image_id", "memory", "region", "resource_group", "sandbox_group", "sp_client_id", "sp_tenant_id", "subscription_id"] and
26
+ (.subscription_id | guid) and (.resource_group | nes) and (.sandbox_group | nes) and (.region | nes) and
27
+ (.disk_image_id | nes) and (.cpu | nes) and (.memory | nes) and (.disk | nes) and
28
+ (.sp_client_id | . == "UNSET" or guid) and (.sp_tenant_id | guid) and
29
+ ((has("capabilities") | not) or (.capabilities | type == "object" and all(.[]; type == "string")));
23
30
  def agent_pool: type == "object" and
24
- (keys | sort) == ["agents_per_server", "capabilities", "hour_end_window_minutes", "identity", "location", "max_lifetime_minutes", "max_servers", "org", "poll_seconds", "project", "queue_id", "queue_threshold", "register_timeout_minutes", "server_type", "snapshot_label_selector", "sp_client_id", "sp_tenant_id", "trigger_ticks"] and
31
+ ((keys - ["aca"]) | sort) == ["agents_per_server", "backend", "capabilities", "hour_end_window_minutes", "identity", "location", "max_lifetime_minutes", "max_servers", "org", "parallel_jobs", "poll_seconds", "project", "queue_id", "queue_wait_minutes", "register_timeout_minutes", "server_type", "snapshot_label_selector", "sp_client_id", "sp_tenant_id"] and
32
+ (.backend | . == "hetzner" or . == "aca-sandbox") and
33
+ ((.backend != "aca-sandbox") or (has("aca") and (.aca | has("capabilities")))) and
34
+ ((has("aca") | not) or (.aca | aca_pool)) and
25
35
  (.org | nes) and (.project | nes) and (.queue_id | posint) and
26
36
  (.identity | . == "agent-tarun" or . == "agent-vivek" or . == "agent-reviewer") and
27
37
  (.server_type | nes) and (.location | nes) and (.snapshot_label_selector | nes) and
28
38
  (.agents_per_server | posint) and (.max_servers | posint) and (.max_lifetime_minutes | posint) and
29
- (.register_timeout_minutes | posint) and (.poll_seconds | posint) and (.queue_threshold | nonneg) and
30
- (.trigger_ticks | posint) and (.hour_end_window_minutes | nonneg and . <= 59) and
39
+ (.register_timeout_minutes | posint) and (.poll_seconds | posint) and (.queue_wait_minutes | nonneg) and
40
+ (.parallel_jobs | posint) and (.hour_end_window_minutes | nonneg and . <= 59) and
31
41
  (.capabilities | type == "object" and all(.[]; type == "string")) and
32
42
  (.sp_client_id | type == "string" and (. == "UNSET" or test("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"))) and
33
43
  (.sp_tenant_id | type == "string" and test("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"));
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.70",
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
  /**
@@ -218,6 +218,7 @@
218
218
  "project": "Enact-Now-AI-AzDo",
219
219
  "queue_id": 80,
220
220
  "identity": "agent-tarun",
221
+ "backend": "hetzner",
221
222
  "server_type": "cpx52",
222
223
  "location": "fsn1",
223
224
  "snapshot_label_selector": "adl-pool-image=enact",
@@ -226,12 +227,25 @@
226
227
  "max_lifetime_minutes": 360,
227
228
  "register_timeout_minutes": 15,
228
229
  "poll_seconds": 60,
229
- "queue_threshold": 1,
230
- "trigger_ticks": 3,
230
+ "queue_wait_minutes": 5,
231
+ "parallel_jobs": 6,
231
232
  "hour_end_window_minutes": 10,
232
233
  "capabilities": {"Agent.OS": "Linux", "docker": "present"},
233
234
  "sp_client_id": "f34d1cd9-4fa1-47bb-9e82-ad9f5cb78a11",
234
- "sp_tenant_id": "49d4be4b-06f2-42b7-91bc-a17ccde6f0ce"
235
+ "sp_tenant_id": "49d4be4b-06f2-42b7-91bc-a17ccde6f0ce",
236
+ "aca": {
237
+ "subscription_id": "3ca1de39-2e87-4ba3-8a47-b3ecc4775697",
238
+ "resource_group": "enact-neu-d-rg",
239
+ "sandbox_group": "enact-neu-d-space-sandboxes",
240
+ "region": "northeurope",
241
+ "disk_image_id": "UNSET",
242
+ "cpu": "2",
243
+ "memory": "4Gi",
244
+ "disk": "40Gi",
245
+ "sp_client_id": "f34d1cd9-4fa1-47bb-9e82-ad9f5cb78a11",
246
+ "sp_tenant_id": "49d4be4b-06f2-42b7-91bc-a17ccde6f0ce",
247
+ "capabilities": {"Agent.OS": "Linux"}
248
+ }
235
249
  }
236
250
  },
237
251
  "surface_clis": [
@@ -298,14 +298,16 @@
298
298
  "properties": {
299
299
  "agent_pool": {
300
300
  "type": "object",
301
- "description": "Feature 758: `adl pool run --host NAME`, the elastic Hetzner Azure Pipelines agent poller. Maps 1:1 onto PoolConfig (packages/agent-pool/src/types.ts) in snake_case, plus `project` (the Azure DevOps project of the queue), `sp_client_id` and `sp_tenant_id` (the service principal agents register with).",
301
+ "description": "Feature 758: `adl pool run --host NAME`, the elastic Azure Pipelines agent poller (Hetzner servers or Azure Container Apps Sandboxes, per `backend`). Maps 1:1 onto PoolConfig (packages/agent-pool/src/types.ts) in snake_case, plus `backend`, `aca`, `project` (the Azure DevOps project of the queue), `sp_client_id` and `sp_tenant_id` (the service principal agents register with).",
302
302
  "additionalProperties": false,
303
- "required": ["org", "project", "queue_id", "identity", "server_type", "location", "snapshot_label_selector", "agents_per_server", "max_servers", "max_lifetime_minutes", "register_timeout_minutes", "poll_seconds", "queue_threshold", "trigger_ticks", "hour_end_window_minutes", "capabilities", "sp_client_id", "sp_tenant_id"],
303
+ "allOf": [{"if": {"properties": {"backend": {"const": "aca-sandbox"}}}, "then": {"required": ["aca"], "properties": {"aca": {"required": ["capabilities"]}}}}],
304
+ "required": ["org", "project", "queue_id", "identity", "backend", "server_type", "location", "snapshot_label_selector", "agents_per_server", "max_servers", "max_lifetime_minutes", "register_timeout_minutes", "poll_seconds", "queue_wait_minutes", "parallel_jobs", "hour_end_window_minutes", "capabilities", "sp_client_id", "sp_tenant_id"],
304
305
  "properties": {
305
306
  "org": {"type": "string", "minLength": 1},
306
307
  "project": {"type": "string", "minLength": 1},
307
308
  "queue_id": {"type": "integer", "minimum": 1},
308
309
  "identity": {"enum": ["agent-tarun", "agent-vivek", "agent-reviewer"]},
310
+ "backend": {"description": "Where pool machines run: Hetzner servers or ephemeral Azure Container Apps Sandboxes (one sandbox = one agent = one job; needs the `aca` block).", "enum": ["hetzner", "aca-sandbox"]},
309
311
  "server_type": {"type": "string", "minLength": 1},
310
312
  "location": {"type": "string", "minLength": 1},
311
313
  "snapshot_label_selector": {"type": "string", "minLength": 1},
@@ -314,12 +316,31 @@
314
316
  "max_lifetime_minutes": {"type": "integer", "minimum": 1},
315
317
  "register_timeout_minutes": {"type": "integer", "minimum": 1},
316
318
  "poll_seconds": {"type": "integer", "minimum": 1},
317
- "queue_threshold": {"type": "integer", "minimum": 0},
318
- "trigger_ticks": {"type": "integer", "minimum": 1},
319
+ "queue_wait_minutes": {"description": "A pending job counts as demand only after it has queued this many minutes.", "type": "integer", "minimum": 0},
320
+ "parallel_jobs": {"description": "Azure DevOps runs at most this many self-hosted jobs at once across all pools; the pool never creates past the free slots.", "type": "integer", "minimum": 1},
319
321
  "hour_end_window_minutes": {"type": "integer", "minimum": 0, "maximum": 59},
320
322
  "capabilities": {"type": "object", "additionalProperties": {"type": "string"}},
321
323
  "sp_client_id": {"description": "Application (client) id of the identity's Entra service principal, used by `config.sh --auth SP`; the literal UNSET until Tarun fills it (`pool run` refuses while UNSET).", "type": "string", "pattern": "^(UNSET|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$"},
322
- "sp_tenant_id": {"description": "Entra tenant id of that service principal (AGENT_TENANTS in apps/cli/src/ado-token.ts).", "type": "string", "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"}
324
+ "sp_tenant_id": {"description": "Entra tenant id of that service principal (AGENT_TENANTS in apps/cli/src/ado-token.ts).", "type": "string", "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"},
325
+ "aca": {
326
+ "type": "object",
327
+ "description": "Azure Container Apps Sandboxes backend settings; required when `backend` is `aca-sandbox` (checked by bin/validate-manifest and `adl pool`). `disk_image_id` and `sp_client_id` are the literal UNSET until Tarun fills them (`pool run` refuses while UNSET).",
328
+ "additionalProperties": false,
329
+ "required": ["subscription_id", "resource_group", "sandbox_group", "region", "disk_image_id", "cpu", "memory", "disk", "sp_client_id", "sp_tenant_id"],
330
+ "properties": {
331
+ "subscription_id": {"type": "string", "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"},
332
+ "resource_group": {"type": "string", "minLength": 1},
333
+ "sandbox_group": {"type": "string", "minLength": 1},
334
+ "region": {"type": "string", "minLength": 1},
335
+ "disk_image_id": {"type": "string", "minLength": 1},
336
+ "cpu": {"type": "string", "minLength": 1},
337
+ "memory": {"type": "string", "minLength": 1},
338
+ "disk": {"type": "string", "minLength": 1},
339
+ "sp_client_id": {"description": "Application (client) id of the Entra service principal that calls the sandbox data plane (scope https://dynamicsessions.io/.default).", "type": "string", "pattern": "^(UNSET|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$"},
340
+ "sp_tenant_id": {"type": "string", "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"},
341
+ "capabilities": {"description": "Capabilities the sandbox image really has (no docker); required when `backend` is `aca-sandbox`, where it replaces the pool `capabilities` for the servable-job filter.", "type": "object", "additionalProperties": {"type": "string"}}
342
+ }
343
+ }
323
344
  }
324
345
  },
325
346
  "pool_reaper": {