@amsterdamdatalabs/adl-agent-control-darwin-arm64 0.1.54 → 0.1.59

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 (66) hide show
  1. package/bin/adl +2 -2
  2. package/bin/git-defaults +4 -1
  3. package/bin/job-watchdog +119 -0
  4. package/bin/reconcile +91 -24
  5. package/bin/reconcile-host +10 -1
  6. package/bin/repo-search-mcp +2 -2
  7. package/bin/setup +161 -26
  8. package/bin/validate-manifest +3 -1
  9. package/package.json +1 -1
  10. package/packages/agent-hooks/src/deploy/deploy.ts +39 -4
  11. package/packages/agent-hooks/src/deploy/doctor.ts +6 -1
  12. package/packages/agent-hooks/src/deploy/index.ts +1 -1
  13. package/packages/agent-hooks/src/deploy/json-merge.ts +2 -2
  14. package/packages/agent-hooks/src/deploy/list.ts +13 -0
  15. package/packages/agent-hooks/src/deploy/lock.ts +2 -0
  16. package/packages/agent-hooks/src/gating/config-schema.ts +83 -0
  17. package/packages/agent-hooks/src/gating/config.ts +56 -6
  18. package/packages/agent-hooks/src/main.ts +11 -4
  19. package/packages/agent-hooks/src/pre-tool-use/handler.ts +37 -12
  20. package/packages/agent-settings/src/deploy/agents-deploy.ts +48 -5
  21. package/packages/agent-settings/src/deploy/deployed-names.ts +22 -0
  22. package/packages/agent-settings/src/deploy/index.ts +1 -0
  23. package/packages/agent-settings/src/deploy/lock.ts +9 -2
  24. package/packages/agent-settings/src/deploy/mcp-deploy.ts +39 -4
  25. package/packages/agent-settings/src/deploy/mcp-inspect.ts +3 -11
  26. package/packages/agent-settings/src/deploy/mcp-merge.ts +14 -1
  27. package/packages/agent-settings/src/deploy/retire-lean-ctx.ts +1 -1
  28. package/packages/agent-settings/src/deploy/safe-path.ts +42 -0
  29. package/packages/agent-settings/src/deploy/settings.ts +10 -2
  30. package/packages/agent-skills/dist/deploy.d.ts +25 -0
  31. package/packages/agent-skills/dist/deploy.d.ts.map +1 -1
  32. package/packages/agent-skills/dist/deploy.js +97 -11
  33. package/packages/agent-skills/dist/deploy.js.map +1 -1
  34. package/packages/agent-skills/dist/doctor.d.ts +2 -0
  35. package/packages/agent-skills/dist/doctor.d.ts.map +1 -1
  36. package/packages/agent-skills/dist/doctor.js +1 -1
  37. package/packages/agent-skills/dist/doctor.js.map +1 -1
  38. package/packages/agent-skills/dist/index.d.ts +3 -2
  39. package/packages/agent-skills/dist/index.d.ts.map +1 -1
  40. package/packages/agent-skills/dist/index.js +3 -2
  41. package/packages/agent-skills/dist/index.js.map +1 -1
  42. package/packages/agent-skills/dist/manifest.d.ts +5 -1
  43. package/packages/agent-skills/dist/manifest.d.ts.map +1 -1
  44. package/packages/agent-skills/dist/manifest.js +29 -4
  45. package/packages/agent-skills/dist/manifest.js.map +1 -1
  46. package/packages/agent-skills/dist/safe-path.d.ts +4 -0
  47. package/packages/agent-skills/dist/safe-path.d.ts.map +1 -0
  48. package/packages/agent-skills/dist/safe-path.js +45 -0
  49. package/packages/agent-skills/dist/safe-path.js.map +1 -0
  50. package/packages/agent-skills/dist/skill-config.d.ts.map +1 -1
  51. package/packages/agent-skills/dist/skill-config.js +5 -3
  52. package/packages/agent-skills/dist/skill-config.js.map +1 -1
  53. package/packages/agent-skills/src/deploy.ts +111 -11
  54. package/packages/agent-skills/src/doctor.ts +3 -1
  55. package/packages/agent-skills/src/index.ts +5 -1
  56. package/packages/agent-skills/src/manifest.ts +29 -4
  57. package/packages/agent-skills/src/safe-path.ts +42 -0
  58. package/packages/agent-skills/src/skill-config.ts +5 -3
  59. package/packages/fleet/manifest.json +2 -0
  60. package/packages/fleet/manifest.schema.json +6 -0
  61. package/packages/fleet/src/repo-maintain.ts +16 -16
  62. package/packages/repo-controls/AGENTS.md +6 -2
  63. package/packages/repo-controls/README.md +9 -6
  64. package/packages/repo-controls/src/doctor.ts +9 -4
  65. package/packages/repo-controls/src/hook.ts +10 -3
  66. package/packages/repo-controls/src/runtime.ts +137 -8
@@ -12,7 +12,7 @@
12
12
  * malformed target JSON file, or a missing template all throw. There is no
13
13
  * partial-success return value.
14
14
  */
15
- import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
15
+ import { existsSync, mkdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
16
16
  import { dirname, join } from 'node:path'
17
17
  import { renderOpencodePlugin } from './opencode-template.ts'
18
18
  import { type AmbiguousPairConflict, mergeCursorHooksFile, mergeJsonHooksFile, type RestoredHook } from './json-merge.ts'
@@ -76,6 +76,10 @@ export interface DeployHooksResult {
76
76
  readonly written: readonly string[]
77
77
  readonly unchanged: readonly string[]
78
78
  readonly conflicts: readonly HookConflict[]
79
+ /** `<file>` (a wholly adl-owned file) or `<file>: <event>/<command>` for each hook a previous deploy wrote (per the lock) that is no longer desired and was removed this run. */
80
+ readonly removed: readonly string[]
81
+ /** Wholly adl-owned files left in place because their bytes no longer match what deploy wrote, or no hash exists to prove they do (az000 review): the user's file now, reported, never deleted. */
82
+ readonly kept: readonly string[]
79
83
  readonly lockPath: string
80
84
  /** Hooks healed via the pair fallback this run, named explicitly (round 5, finding 2) so deploy's own output, doctor's preview, and `adl install` can all say "restored adl hook <event>/<matcher>/<command> — local changes to it were replaced". */
81
85
  readonly restored: readonly RestoredHookReport[]
@@ -123,10 +127,12 @@ export function deployHooks(options: DeployHooksOptions): DeployHooksResult {
123
127
  const unchanged: string[] = []
124
128
  const conflicts: HookConflict[] = []
125
129
  const restored: RestoredHookReport[] = []
130
+ const removed: string[] = []
131
+ const kept: string[] = []
126
132
  const takeover = { any: false }
127
133
 
128
134
  for (const surface of profile.surfaces) {
129
- deploySurface(surface, { assetsDir, targetRepo, hooksDoc, lock, legacyDoc, takeover, newEntries, written, unchanged, conflicts, restored, dryRun })
135
+ deploySurface(surface, { assetsDir, targetRepo, hooksDoc, lock, legacyDoc, takeover, newEntries, written, unchanged, conflicts, restored, removed, kept, dryRun })
130
136
  }
131
137
 
132
138
  if (!dryRun) writeLock(targetRepo, { version: 1, entries: newEntries })
@@ -144,6 +150,8 @@ export function deployHooks(options: DeployHooksOptions): DeployHooksResult {
144
150
  written: written.sort(),
145
151
  unchanged: unchanged.sort(),
146
152
  conflicts: conflicts.sort((a, b) => a.file.localeCompare(b.file)),
153
+ removed: removed.sort(),
154
+ kept: kept.sort(),
147
155
  lockPath: lockPathFor(targetRepo),
148
156
  restored,
149
157
  }
@@ -163,9 +171,19 @@ interface DeploySurfaceContext {
163
171
  readonly unchanged: string[]
164
172
  readonly conflicts: HookConflict[]
165
173
  readonly restored: RestoredHookReport[]
174
+ readonly removed: string[]
175
+ readonly kept: string[]
166
176
  readonly dryRun: boolean
167
177
  }
168
178
 
179
+ /** Records every hook the lock says a previous deploy wrote into `file` whose hash is no longer owned after this run's merge. */
180
+ function recordRemovedHooks(ctx: DeploySurfaceContext, file: string, recorded: Readonly<Record<string, readonly { readonly hash: string; readonly command: string }[]>>, now: Readonly<Record<string, readonly { readonly hash: string }[]>>): void {
181
+ for (const [event, entries] of Object.entries(recorded)) {
182
+ const kept = new Set((now[event] ?? []).map((entry) => entry.hash))
183
+ for (const entry of entries) if (!kept.has(entry.hash)) ctx.removed.push(`${file}: ${event}/${entry.command}`)
184
+ }
185
+ }
186
+
169
187
  function deploySurface(surface: HookSurface, ctx: DeploySurfaceContext): void {
170
188
  const targetAbs = join(ctx.targetRepo, surface.file)
171
189
  const prevEntry = ctx.lock.entries[surface.file]
@@ -176,7 +194,22 @@ function deploySurface(surface: HookSurface, ctx: DeploySurfaceContext): void {
176
194
  if (legacyTakeover) ctx.takeover.any = true
177
195
  const wasOwned = (prevEntry?.format === 'opencode-plugin' && prevEntry.owned === true) || legacyTakeover
178
196
  if (exists && !wasOwned) {
179
- ctx.conflicts.push({ file: surface.file, reason: 'a non-adl file already exists at this path; deploy left it untouched' })
197
+ // With nothing to deploy there is nothing to collide with: the user's file is simply not ours.
198
+ if (ctx.hooksDoc.size > 0) ctx.conflicts.push({ file: surface.file, reason: 'a non-adl file already exists at this path; deploy left it untouched' })
199
+ return
200
+ }
201
+ if (ctx.hooksDoc.size === 0) {
202
+ // No hook is allowed: the adl-owned plugin file goes, but only when its bytes still match what deploy wrote (or a legacy hash proved it ours);
203
+ // an edited file, or one with no recorded hash, is the user's now: kept and reported (a non-adl file at the path was refused above).
204
+ if (exists) {
205
+ const recordedHash = prevEntry?.format === 'opencode-plugin' ? prevEntry.hash : undefined
206
+ if (!legacyTakeover && (recordedHash === undefined || sha256Hex(readFileSync(targetAbs)) !== recordedHash)) {
207
+ ctx.kept.push(surface.file)
208
+ return
209
+ }
210
+ if (!ctx.dryRun) unlinkSync(targetAbs)
211
+ ctx.removed.push(surface.file)
212
+ }
180
213
  return
181
214
  }
182
215
  const rendered = renderOpencodePlugin({ assetsDir: ctx.assetsDir, surface, hooksDoc: ctx.hooksDoc })
@@ -190,7 +223,7 @@ function deploySurface(surface: HookSurface, ctx: DeploySurfaceContext): void {
190
223
  } else {
191
224
  ctx.unchanged.push(surface.file)
192
225
  }
193
- ctx.newEntries[surface.file] = { format: 'opencode-plugin', owned: true }
226
+ ctx.newEntries[surface.file] = { format: 'opencode-plugin', owned: true, hash: sha256Hex(rendered) }
194
227
  return
195
228
  }
196
229
 
@@ -216,6 +249,7 @@ function deploySurface(surface: HookSurface, ctx: DeploySurfaceContext): void {
216
249
  writeJsonIfChanged(targetAbs, fileContent, changed, ctx.dryRun)
217
250
  ;(changed ? ctx.written : ctx.unchanged).push(surface.file)
218
251
  ctx.newEntries[surface.file] = { format: 'cursor-hooks-v1', ownedCommands, ownedEntries }
252
+ recordRemovedHooks(ctx, surface.file, recordedEntries, ownedEntries)
219
253
  for (const hook of restored) ctx.restored.push(makeRestoredReport(surface.file, hook))
220
254
  for (const conflict of ambiguousConflicts) ctx.conflicts.push({ file: surface.file, reason: ambiguousConflictReason(conflict) })
221
255
  return
@@ -227,6 +261,7 @@ function deploySurface(surface: HookSurface, ctx: DeploySurfaceContext): void {
227
261
  writeJsonIfChanged(targetAbs, fileContent, changed, ctx.dryRun)
228
262
  ;(changed ? ctx.written : ctx.unchanged).push(surface.file)
229
263
  ctx.newEntries[surface.file] = { format: surface.format, ownedCommands, ownedEntries }
264
+ recordRemovedHooks(ctx, surface.file, recordedEntries, ownedEntries)
230
265
  for (const hook of restored) ctx.restored.push(makeRestoredReport(surface.file, hook))
231
266
  for (const conflict of ambiguousConflicts) ctx.conflicts.push({ file: surface.file, reason: ambiguousConflictReason(conflict) })
232
267
  }
@@ -51,6 +51,8 @@ export interface DoctorDeploymentOptions {
51
51
  readonly targetRepo: string
52
52
  readonly profilePath?: string
53
53
  readonly profileSchemaPath?: string
54
+ /** The hooks the repo declares (`[assets] hooks`); defaults to every hook in assets/hooks.json. A declared hook that is missing, or a deployed one no longer declared, is drift. */
55
+ readonly hooksDoc?: CanonicalHooksDoc
54
56
  }
55
57
 
56
58
  /**
@@ -93,6 +95,8 @@ function doctorJsonSurface(surface: HookSurface, targetRepo: string, hooksDoc: C
93
95
  : mergeJsonHooksFile(existingRaw, renderJsonHooksGroups(hooksDoc, surface), recordedEntries)
94
96
 
95
97
  if (!exists) {
98
+ // Nothing declared: a missing file is what was asked for.
99
+ if (hooksDoc.size === 0) return []
96
100
  return [{ severity: 'error', path: surface.file, reason: 'expected hook wiring has not been deployed' }]
97
101
  }
98
102
  // Independent review, 2026-09-30, round 5 (finding 1, pair-scoped —
@@ -156,6 +160,7 @@ function doctorOpencodeSurface(surface: HookSurface, ctx: { assetsDir: string; t
156
160
  const wasOwned = lockEntry?.format === 'opencode-plugin' && lockEntry.owned === true
157
161
 
158
162
  if (!exists) {
163
+ if (ctx.hooksDoc.size === 0) return []
159
164
  return [{ severity: 'error', path: surface.file, reason: 'expected hook wiring has not been deployed' }]
160
165
  }
161
166
  if (!wasOwned) {
@@ -187,7 +192,7 @@ export function doctorDeployment(options: DoctorDeploymentOptions): DoctorResult
187
192
 
188
193
  let hooksDoc: CanonicalHooksDoc
189
194
  try {
190
- hooksDoc = loadHooksSource(join(dirname(options.assetsDir), profile.source))
195
+ hooksDoc = options.hooksDoc ?? loadHooksSource(join(dirname(options.assetsDir), profile.source))
191
196
  } catch (cause) {
192
197
  return toResult([{ severity: 'error', path: profile.source, reason: (cause as Error).message }])
193
198
  }
@@ -1,6 +1,6 @@
1
1
  export { deployHooks, type DeployHooksResult, } from './deploy.ts'
2
2
  export { doctorDeployment, type DoctorResult } from './doctor.ts'
3
- export { formatHookLine, listHooks, } from './list.ts'
3
+ export { deployedHookLabels, formatHookLine, listHooks, } from './list.ts'
4
4
 
5
5
  export {
6
6
 
@@ -336,7 +336,7 @@ export function mergeJsonHooksFile(
336
336
  const duplicateCommands: Record<string, readonly string[]> = {}
337
337
  const restored: (RestoredHook & { readonly event: string })[] = []
338
338
  const ambiguousConflicts: AmbiguousPairConflict[] = []
339
- let changed = existing === undefined
339
+ let changed = existing === undefined && desired.size > 0
340
340
 
341
341
  for (const event of orderedEvents) {
342
342
  const existingGroups = Array.isArray(existingHooks[event]) ? (existingHooks[event] as unknown[]) : []
@@ -457,7 +457,7 @@ export function mergeCursorHooksFile(
457
457
  const duplicateCommands: Record<string, readonly string[]> = {}
458
458
  const restored: (RestoredHook & { readonly event: string })[] = []
459
459
  const ambiguousConflicts: AmbiguousPairConflict[] = []
460
- let changed = existing === undefined
460
+ let changed = existing === undefined && desired.size > 0
461
461
 
462
462
  for (const event of orderedEvents) {
463
463
  const existingEntries = Array.isArray(existingHooks[event]) ? (existingHooks[event] as unknown[]) : []
@@ -73,6 +73,19 @@ function ownedLabelsForSurface(entry: HookLockEntry | undefined, surface: HookSu
73
73
  return out
74
74
  }
75
75
 
76
+ /** Every hook label a previous deploy wrote, from the lock's owned entries on the JSON surfaces (the opencode plugin is rendered whole from the same document and records no per-hook breakdown), sorted: a named, additive deploy keeps these. */
77
+ export function deployedHookLabels(targetRepo: string, profile: HookDeployProfile): readonly string[] {
78
+ const lock = readLock(targetRepo)
79
+ const labels = new Set<string>()
80
+ for (const surface of profile.surfaces) {
81
+ if (surface.format === 'opencode-plugin') continue
82
+ const targetAbs = join(targetRepo, surface.file)
83
+ const present = extractCommandLabels(existsSync(targetAbs) ? readFileSync(targetAbs, 'utf8') : '', surface.hostSuffix)
84
+ for (const label of ownedLabelsForSurface(lock.entries[surface.file], surface, present)) labels.add(label)
85
+ }
86
+ return [...labels].sort()
87
+ }
88
+
76
89
  export function listHooks(options: ListHooksOptions): HookListing {
77
90
  const profile = options.profile ?? loadProfile()
78
91
  const hooksDoc = options.hooksDoc ?? loadHooksSource(join(dirname(options.assetsDir), profile.source))
@@ -59,6 +59,8 @@ export interface JsonHooksLockEntry {
59
59
  interface OpencodePluginLockEntry {
60
60
  readonly format: 'opencode-plugin'
61
61
  readonly owned: true
62
+ /** sha256 of the plugin file deploy wrote. Absent in locks written before az000's review; removal then cannot prove the file unedited and keeps it. */
63
+ readonly hash?: string
62
64
  }
63
65
 
64
66
  export type HookLockEntry = JsonHooksLockEntry | OpencodePluginLockEntry
@@ -0,0 +1,83 @@
1
+ // The ONE schema of adl-config.toml key names, imported by both validators. Why: docs/architecture/adl-config.md (rule 6)
2
+
3
+ export type ConfigOwner =
4
+ | 'shared'
5
+ | 'agent-hooks'
6
+ | 'cli'
7
+ | 'repo-controls'
8
+ | 'agent-extensions'
9
+ | 'azdo'
10
+ | 'dispatcher'
11
+ | 'fleet'
12
+
13
+ export interface ConfigTable {
14
+ readonly owner: ConfigOwner
15
+ /** Allowed sub-keys and who validates each. Absent: the table's contents are not key-checked by the shared schema. */
16
+ readonly keys?: Readonly<Record<string, ConfigOwner>>
17
+ }
18
+
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' }
21
+ export const REPO_TABLE_KEYS: Readonly<Record<string, ConfigOwner>> = {
22
+ protectedTrees: 'agent-hooks',
23
+ commitProtectedTrees: 'agent-hooks',
24
+ trustedScriptPrefixes: 'agent-hooks',
25
+ azdo: 'cli',
26
+ }
27
+ export const AGENT_TABLE_KEYS: Readonly<Record<string, ConfigOwner>> = { user: 'agent-hooks', protected_branches: 'agent-hooks' }
28
+ export const ASSETS_TABLE_KEYS: Readonly<Record<string, ConfigOwner>> = { skills: 'cli', agents: 'cli', hooks: 'cli', mcp_servers: 'cli' }
29
+
30
+ export const CONFIG_TABLES: Readonly<Record<string, ConfigTable>> = {
31
+ version: { owner: 'shared' },
32
+ hooks: { owner: 'agent-hooks', keys: HOOKS_TABLE_KEYS },
33
+ rules: { owner: 'agent-hooks' },
34
+ repo: { owner: 'agent-hooks', keys: REPO_TABLE_KEYS },
35
+ agent: { owner: 'agent-hooks', keys: AGENT_TABLE_KEYS },
36
+ assets: { owner: 'cli', keys: ASSETS_TABLE_KEYS },
37
+ controls: { owner: 'repo-controls' },
38
+ // Legacy: superseded by [extensions]; still accepted so an untouched repo does not fail (see MIGRATIONS).
39
+ skills: { owner: 'agent-extensions' },
40
+ extensions: { owner: 'agent-extensions' },
41
+ azdo: { owner: 'azdo' },
42
+ dispatch: { owner: 'dispatcher' },
43
+ fleet: { owner: 'fleet' },
44
+ }
45
+
46
+ export const ROOT_KEYS: ReadonlySet<string> = new Set(Object.keys(CONFIG_TABLES))
47
+
48
+ /** Keys of `table` that `owner` validates. */
49
+ export function keysOwnedBy(table: string, owner: ConfigOwner): readonly string[] {
50
+ const keys = CONFIG_TABLES[table]?.keys ?? {}
51
+ return Object.keys(keys).filter((key) => keys[key] === owner)
52
+ }
53
+
54
+ // One declared change `adl config migrate` applies; every migration says why. Why: docs/architecture/adl-config.md ("Backup and schema migration")
55
+ export interface ConfigMigration {
56
+ readonly from: readonly string[]
57
+ readonly to?: readonly string[]
58
+ readonly reason: string
59
+ }
60
+
61
+ export const CONFIG_MIGRATIONS: readonly ConfigMigration[] = [
62
+ {
63
+ from: ['skills'],
64
+ reason: '[skills] was superseded by [extensions] (adl-extensions HARDCUT); nothing reads it any more',
65
+ },
66
+ ]
67
+
68
+ /** Whether `doc` (a parsed adl-config.toml) contains the path a migration moves or drops. */
69
+ export function migrationApplies(doc: Readonly<Record<string, unknown>>, migration: ConfigMigration): boolean {
70
+ const [first, second] = migration.from
71
+ if (first === undefined || !(first in doc)) return false
72
+ if (second === undefined) return true
73
+ const table = doc[first]
74
+ return typeof table === 'object' && table !== null && !Array.isArray(table) && second in table
75
+ }
76
+
77
+ /** The declared migrations that would change `doc`. */
78
+ export function applicableMigrations(
79
+ doc: Readonly<Record<string, unknown>>,
80
+ migrations: readonly ConfigMigration[] = CONFIG_MIGRATIONS,
81
+ ): readonly ConfigMigration[] {
82
+ return migrations.filter((migration) => migrationApplies(doc, migration))
83
+ }
@@ -61,6 +61,7 @@
61
61
  * cannot resolve to disabled unless `unsafeAllowUncertain` is set.
62
62
  */
63
63
 
64
+ import { AGENT_TABLE_KEYS, CONFIG_TABLES, HOOKS_TABLE_KEYS, REPO_TABLE_KEYS, ROOT_KEYS, applicableMigrations } from './config-schema.ts'
64
65
  import { MARKER } from './root.ts'
65
66
  import { runningAdl } from './running-adl.ts'
66
67
 
@@ -157,6 +158,45 @@ export function describeConfigIssue(configPath: string, issue: ConfigDecodeIssue
157
158
  return `invalid ${configPath} at ${issue.pointer}: ${issue.message}${runningAdl()}`
158
159
  }
159
160
 
161
+ /**
162
+ * The PreToolUse line printed on EVERY call while `adl-config.toml` is invalid
163
+ * (Tarun, 2026-10-25: a bad config must never block the tool call that would
164
+ * fix it). The hook keeps enforcing the default rules, so this is a loud
165
+ * warning, not a switch-off. The fix names `adl config migrate` only when a
166
+ * declared migration applies to the file (`migratable`); otherwise migrate
167
+ * cannot help, so it names the pointer to edit and the backup to take first.
168
+ */
169
+ function describeConfigWarning(repo: string, issue: ConfigDecodeIssue, migratable: boolean): string {
170
+ const fix = migratable
171
+ ? `fix with: adl config migrate --repo ${repo}`
172
+ : `fix ${issue.pointer} in ${MARKER} (back it up first: adl config backup --repo ${repo})`
173
+ return `adl hook: WARN invalid ${MARKER} at ${issue.pointer}: ${issue.message}; hook rules running on defaults — ${fix}`
174
+ }
175
+
176
+ /** Whether a declared migration applies to this text; invalid TOML has no document, so none. */
177
+ function hasApplicableMigration(text: string): boolean {
178
+ try {
179
+ return applicableMigrations(Bun.TOML.parse(text) as Record<string, unknown>).length > 0
180
+ } catch {
181
+ return false
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Decode for the PreToolUse path: an invalid file yields the schema defaults
187
+ * plus the warning line to print; a valid file yields its own config, no warning.
188
+ */
189
+ export function decodeConfigOrDefaults(
190
+ text: string,
191
+ repo: string,
192
+ ): { readonly config: AdlRepoConfig; readonly warning: string | null } {
193
+ const decoded = decodeConfig(text)
194
+ if (decoded.ok) return { config: decoded.value, warning: null }
195
+ const defaults = decodeConfig('')
196
+ if (!defaults.ok) throw new Error(`the empty config must decode to defaults: ${defaults.issue.message}`)
197
+ return { config: defaults.value, warning: describeConfigWarning(repo, decoded.issue, hasApplicableMigration(text)) }
198
+ }
199
+
160
200
  export type ConfigDecodeResult =
161
201
  | { readonly ok: true; readonly value: AdlRepoConfig }
162
202
  | { readonly ok: false; readonly issue: ConfigDecodeIssue }
@@ -244,9 +284,8 @@ function rejectUnknownKeys(
244
284
  * before that change still carries one until it is reinstalled. Dropping it
245
285
  * here would fail exactly those repos, the ones nobody has touched yet.
246
286
  */
247
- const KNOWN_ROOT_KEYS: ReadonlySet<string> = new Set([
248
- 'version', 'hooks', 'rules', 'repo', 'agent', 'controls', 'skills', 'extensions', 'azdo', 'dispatch', 'fleet',
249
- ])
287
+ const KNOWN_ROOT_KEYS: ReadonlySet<string> = ROOT_KEYS
288
+
250
289
 
251
290
  /**
252
291
  * Parse `adl-config.toml`'s already-read text into an
@@ -270,6 +309,16 @@ export function decodeConfig(text: string): ConfigDecodeResult {
270
309
  const unknownRoot = rejectUnknownKeys(raw, KNOWN_ROOT_KEYS, '')
271
310
  if (unknownRoot !== null) return { ok: false, issue: unknownRoot }
272
311
 
312
+ // Tables another tool owns are still key-checked against the shared schema
313
+ // (never value-checked): a misspelt key in `[assets]` fails here exactly as
314
+ // it fails `adl config check`, so the two validators cannot disagree.
315
+ for (const [table, schema] of Object.entries(CONFIG_TABLES)) {
316
+ const value = raw[table]
317
+ if (schema.owner === 'agent-hooks' || schema.keys === undefined || !isPlainObject(value)) continue
318
+ const unknownKey = rejectUnknownKeys(value, new Set(Object.keys(schema.keys)), `/${table}`)
319
+ if (unknownKey !== null) return { ok: false, issue: unknownKey }
320
+ }
321
+
273
322
  if (raw.version !== undefined && typeof raw.version !== 'number') {
274
323
  return { ok: false, issue: { pointer: '/version', message: 'expected a number' } }
275
324
  }
@@ -301,7 +350,7 @@ export function decodeConfig(text: string): ConfigDecodeResult {
301
350
  }
302
351
  }
303
352
 
304
- const KNOWN_HOOKS_KEYS: ReadonlySet<string> = new Set(['enabled', 'skills_dir', 'lean_ctx_dir'])
353
+ const KNOWN_HOOKS_KEYS = new Set(Object.keys(HOOKS_TABLE_KEYS))
305
354
 
306
355
  function decodeHooks(value: unknown): { ok: true; value: HooksConfig } | { ok: false; issue: ConfigDecodeIssue } {
307
356
  if (value === undefined) return { ok: true, value: DEFAULT_CONFIG.hooks }
@@ -380,7 +429,8 @@ function decodeStringArray(
380
429
  return { ok: true, value: value as readonly string[] }
381
430
  }
382
431
 
383
- const KNOWN_REPO_KEYS: ReadonlySet<string> = new Set(['protectedTrees', 'commitProtectedTrees', 'trustedScriptPrefixes'])
432
+ // `azdo` is accepted (the CLI owns and validates `[repo.azdo]`); this decoder never reads it.
433
+ const KNOWN_REPO_KEYS = new Set(Object.keys(REPO_TABLE_KEYS))
384
434
 
385
435
  function decodeRepo(value: unknown): { ok: true; value: RepoSection } | { ok: false; issue: ConfigDecodeIssue } {
386
436
  if (value === undefined) return { ok: true, value: DEFAULT_REPO }
@@ -458,7 +508,7 @@ export function isRuleEnabled(
458
508
  return { ok: true, enabled: resolved }
459
509
  }
460
510
 
461
- const KNOWN_AGENT_KEYS: ReadonlySet<string> = new Set(['user', 'protected_branches'])
511
+ const KNOWN_AGENT_KEYS = new Set(Object.keys(AGENT_TABLE_KEYS))
462
512
 
463
513
  function decodeAgent(value: unknown): { ok: true; value: AgentSection } | { ok: false; issue: ConfigDecodeIssue } {
464
514
  if (value === undefined) return { ok: true, value: DEFAULT_AGENT }
@@ -78,7 +78,7 @@ import { payloadCwd } from './hooks/contract.ts'
78
78
  import { resolveHost, readHostFlag, type HostId } from './hosts/spec.ts'
79
79
  import { resolveManagedRepo, realRootIO } from './gating/root.ts'
80
80
  import { setRunningAdlVersion } from './gating/running-adl.ts'
81
- import { decodeConfig, describeConfigIssue, type AdlRepoConfig } from './gating/config.ts'
81
+ import { decodeConfig, decodeConfigOrDefaults, describeConfigIssue, type AdlRepoConfig } from './gating/config.ts'
82
82
  import { FAIL_CLOSED_EXIT_CODE } from './rules/engine.ts'
83
83
  import { handlePreToolUse } from './pre-tool-use/handler.ts'
84
84
  import { handleUserPromptSubmit } from './hooks/user-prompt-submit/handler.ts'
@@ -225,13 +225,20 @@ export async function run(argv: readonly string[], adlVersion?: string): Promise
225
225
  return kind === 'pre-tool-use' ? FAIL_CLOSED_EXIT_CODE : NON_BLOCKING_FAIL_EXIT_CODE
226
226
  }
227
227
  const decoded = decodeConfig(text)
228
- if (!decoded.ok) {
228
+ if (!decoded.ok && kind === 'pre-tool-use') {
229
+ // Never block pre-tool-use on a bad config (Tarun, 2026-10-25): it would
230
+ // block the edit that repairs the file. `handlePreToolUse` prints the
231
+ // one WARN line per call and runs the default rules; here the defaults
232
+ // only decide `[hooks] enabled` (true).
233
+ config = decodeConfigOrDefaults('', managed.root).config
234
+ } else if (!decoded.ok) {
229
235
  process.stderr.write(
230
236
  `adl hook: ${describeConfigIssue(managed.configPath, decoded.issue)}\n`,
231
237
  )
232
- return kind === 'pre-tool-use' ? FAIL_CLOSED_EXIT_CODE : NON_BLOCKING_FAIL_EXIT_CODE
238
+ return NON_BLOCKING_FAIL_EXIT_CODE
239
+ } else {
240
+ config = decoded.value
233
241
  }
234
- config = decoded.value
235
242
  }
236
243
 
237
244
  if (!config.hooks.enabled) {
@@ -9,17 +9,16 @@
9
9
  * having `main.ts` thread the already-decoded `AdlRepoConfig` through
10
10
  * `HookInvocation` (whose shape is fixed by `../hooks/contract.ts` and is
11
11
  * deliberately the same for every hook kind, none of which need a config
12
- * object in their invocation). A decode failure here, on a file `main.ts`
13
- * just decoded successfully, would mean the file changed on disk between the
14
- * two reads or `decodeConfig` is non-deterministic — either way a real bug,
15
- * not a condition to fail closed over quietly, so it is thrown rather than
16
- * swallowed into a `HookResult`.
12
+ * object in their invocation). A file that fails to decode does NOT block
13
+ * (Tarun, 2026-10-25): the handler runs the default rules and prefixes every
14
+ * result's stderr with one WARN line naming `adl config migrate`; `main.ts`
15
+ * stays silent for pre-tool-use so the line is printed once per call.
17
16
  */
18
17
 
19
18
  import { readFileSync } from 'node:fs'
20
19
  import { join } from 'node:path'
21
20
  import type { ActivityNote, HookInvocation, HookResult } from '../hooks/contract.ts'
22
- import { decodeConfig, describeConfigIssue } from '../gating/config.ts'
21
+ import { decodeConfigOrDefaults, type AdlRepoConfig } from '../gating/config.ts'
23
22
  import { runningAdl } from '../gating/running-adl.ts'
24
23
  import { MARKER } from '../gating/root.ts'
25
24
  import {
@@ -219,13 +218,39 @@ export function denyHostCannotRewrite(spec: HostSpec, host: string, message: Rul
219
218
 
220
219
  export async function handlePreToolUse(inv: HookInvocation): Promise<HookResult> {
221
220
  const configPath = join(inv.root, MARKER)
222
- const text = readFileSync(configPath, 'utf8')
223
- const decoded = decodeConfig(text)
224
- if (!decoded.ok) {
225
- throw new Error(`adl hook: ${describeConfigIssue(configPath, decoded.issue)}`)
226
- }
227
- const config = decoded.value
221
+ // An invalid adl-config.toml never blocks the tool call (Tarun, 2026-10-25):
222
+ // it would block the very edit that repairs the file. The default rules
223
+ // still run, and one loud WARN line goes to stderr on every call.
224
+ const loaded = decodeConfigOrDefaults(readFileSync(configPath, 'utf8'), inv.root)
225
+ const result = await decideWithConfig(inv, configPath, loaded.config)
226
+ if (loaded.warning === null) return result
227
+ return { ...result, stdout: withWarning(inv.host, result.stdout, loaded.warning), stderr: `${loaded.warning}\n${result.stderr}` }
228
+ }
229
+
230
+ /**
231
+ * Carry the config WARN to the model, not only to stderr: a hook that exits 0
232
+ * never shows its stderr to Claude Code. Each host's channel, from its own docs
233
+ * (docs/architecture/adl-config.md rule 8 cites each URL and field):
234
+ * - claude: PreToolUse `hookSpecificOutput.additionalContext` (context for Claude)
235
+ * and the universal `systemMessage` (shown to the user).
236
+ * - codex: the same two fields, both documented for PreToolUse.
237
+ * - cursor: `user_message` / `agent_message` (its documented hook output; no additional_context).
238
+ * - kimi: non-empty stdout on exit 0 is added to context, so an allowed call's `{}` becomes the line.
239
+ * - opencode: `advice`, the shape its briefing hook emits; no hook output contract is documented for it.
240
+ * The decision itself (allow, deny, rewritten input) is untouched.
241
+ */
242
+ function withWarning(host: HookInvocation['host'], stdout: string, warning: string): string {
243
+ // Every result's stdout is one JSON object from `renderFor`/`renderRewrite`; a parse failure is a bug and throws loudly.
244
+ const out = JSON.parse(stdout) as Record<string, unknown>
245
+ if (host === 'kimi') return Object.keys(out).length === 0 ? `${warning}\n` : stdout
246
+ if (host === 'cursor') return `${JSON.stringify({ ...out, user_message: warning, agent_message: warning })}\n`
247
+ if (host === 'opencode') return `${JSON.stringify({ ...out, advice: warning })}\n`
248
+ const specific = isRecord(out.hookSpecificOutput) ? out.hookSpecificOutput : { hookEventName: 'PreToolUse' }
249
+ const merged = { ...out, hookSpecificOutput: { ...specific, additionalContext: warning } }
250
+ return `${JSON.stringify({ ...merged, systemMessage: warning })}\n`
251
+ }
228
252
 
253
+ async function decideWithConfig(inv: HookInvocation, configPath: string, config: AdlRepoConfig): Promise<HookResult> {
229
254
  // The invocation's own environment, not the handler process's ambient one:
230
255
  // `main.ts` passes `process.env` here in production, and the identity rules
231
256
  // (`adl.run-required-for-writes`, `adl.git-push-branch-policy`,
@@ -10,13 +10,15 @@
10
10
  * Fails loud: a missing assets dir/target repo or an invalid profile all
11
11
  * throw. There is no partial-success return value.
12
12
  */
13
+ import { assertSafeName, safeRepoPath } from "./safe-path.js";
14
+ import { createHash } from "node:crypto";
13
15
  import { existsSync, mkdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
14
16
  import { join } from "node:path";
15
17
  import { extensionFor, renderAgent } from "./agent-render.js";
16
18
  import { loadAgentSources, type AgentDef } from "./agent-toml.js";
17
19
  import { legacyFileTakeover, type LegacyLockDoc, readLegacyLock, stripLegacyOwnership } from "./legacy-lock.js";
18
20
  import { agentOwned, readLock, writeLock } from "./lock.js";
19
- import { type DeployProfile, loadProfile } from "./profile.js";
21
+ import { type AgentSurface, type DeployProfile, loadProfile } from "./profile.js";
20
22
 
21
23
  export interface DeployAgentsOptions {
22
24
  readonly assetsDir: string;
@@ -47,9 +49,17 @@ export interface DeployAgentsResult {
47
49
  readonly conflicts: readonly AgentConflict[];
48
50
  /** Unlocked same-name agent files whose content was exactly what deploy renders: taken over and locked, never a conflict. */
49
51
  readonly adopted: readonly string[];
52
+ /** Locked agent files left in place because their bytes no longer match what deploy wrote, or no hash can prove they do (az000): reported, never deleted. */
53
+ readonly kept: readonly string[];
54
+ /** Locked agent files that were already missing on disk: nothing to delete, counted apart from `removed` (az000 gap B). */
55
+ readonly absent: readonly string[];
50
56
  readonly lockPath: string;
51
57
  }
52
58
 
59
+ function sha256(text: string): string {
60
+ return createHash("sha256").update(text).digest("hex");
61
+ }
62
+
53
63
  export function deployAgents(options: DeployAgentsOptions): DeployAgentsResult {
54
64
  const { assetsDir, targetRepo } = options;
55
65
  const dryRun = options.dryRun === true;
@@ -63,9 +73,19 @@ export function deployAgents(options: DeployAgentsOptions): DeployAgentsResult {
63
73
 
64
74
  const profile = options.profile ?? loadProfile();
65
75
  const agents = options.agents ?? loadAgentSources(assetsDir);
66
- if (agents.length === 0) throw new Error(`agent-settings agents assets directory has no agents: ${assetsDir}`);
76
+ if (agents.length === 0 && options.agents === undefined) throw new Error(`agent-settings agents assets directory has no agents: ${assetsDir}`);
67
77
 
68
78
  const lock = readLock(targetRepo);
79
+ // A recorded or selected name is never trusted: validate every path before this run writes or deletes anything.
80
+ for (const def of agents) assertSafeName(def.name, "agent name");
81
+ for (const surface of profile.agents.surfaces) {
82
+ if (options.surfaceFilter !== undefined && surface.name !== options.surfaceFilter) continue;
83
+ for (const def of agents) safeRepoPath(targetRepo, `${surface.folder}/${def.name}.${extensionFor(surface)}`, "agent write target");
84
+ for (const name of lock.agents[surface.folder] ?? []) {
85
+ assertSafeName(name, "agent-settings lock agent name");
86
+ safeRepoPath(targetRepo, `${surface.folder}/${name}.${extensionFor(surface)}`, "agent-settings lock path");
87
+ }
88
+ }
69
89
  const legacyLockPath = profile.legacyLock !== undefined ? join(targetRepo, profile.legacyLock) : undefined;
70
90
  const legacyDoc: LegacyLockDoc | undefined = legacyLockPath !== undefined ? readLegacyLock(legacyLockPath) : undefined;
71
91
  const newAgentEntries: Record<string, readonly string[]> = {};
@@ -74,6 +94,15 @@ export function deployAgents(options: DeployAgentsOptions): DeployAgentsResult {
74
94
  const removed: string[] = [];
75
95
  const conflicts: AgentConflict[] = [];
76
96
  const adopted: string[] = [];
97
+ const keptUnverified: string[] = [];
98
+ const absent: string[] = [];
99
+ const newHashes: Record<string, string> = {};
100
+ let shippedDefs: readonly AgentDef[] | undefined;
101
+ const shippedHash = (surface: AgentSurface, name: string): string | undefined => {
102
+ shippedDefs ??= loadAgentSources(assetsDir);
103
+ const def = shippedDefs.find((candidate) => candidate.name === name);
104
+ return def === undefined ? undefined : sha256(renderAgent(surface, def));
105
+ };
77
106
  const legacyFileRemovals: string[] = [];
78
107
  let anyLegacyTakeover = false;
79
108
 
@@ -123,6 +152,7 @@ export function deployAgents(options: DeployAgentsOptions): DeployAgentsResult {
123
152
  written.push(relPath);
124
153
  }
125
154
  kept.push(def.name);
155
+ newHashes[relPath] = sha256(content);
126
156
  }
127
157
 
128
158
  const previouslyOwned = lock.agents[surface.folder] ?? [];
@@ -130,8 +160,18 @@ export function deployAgents(options: DeployAgentsOptions): DeployAgentsResult {
130
160
  if (kept.includes(name)) continue;
131
161
  const relPath = `${surface.folder}/${name}.${ext}`;
132
162
  const absPath = join(targetRepo, relPath);
133
- if (!dryRun && existsSync(absPath)) unlinkSync(absPath);
134
- removed.push(relPath);
163
+ if (existsSync(absPath)) {
164
+ // Only a file whose bytes still match what deploy wrote goes; a lock from before hashes existed falls back to what the shipped source renders today.
165
+ const expected = lock.agentHashes?.[relPath] ?? shippedHash(surface, name);
166
+ if (expected === undefined || sha256(readFileSync(absPath, "utf8")) !== expected) {
167
+ keptUnverified.push(relPath);
168
+ continue;
169
+ }
170
+ if (!dryRun) unlinkSync(absPath);
171
+ removed.push(relPath);
172
+ } else {
173
+ absent.push(relPath);
174
+ }
135
175
  }
136
176
 
137
177
  newAgentEntries[surface.folder] = kept.sort();
@@ -144,7 +184,8 @@ export function deployAgents(options: DeployAgentsOptions): DeployAgentsResult {
144
184
  const lockAgents = options.surfaceFilter === undefined
145
185
  ? newAgentEntries
146
186
  : { ...lock.agents, ...newAgentEntries };
147
- if (!dryRun) writeLock(targetRepo, { schema: 1, mcp: lock.mcp, agents: lockAgents });
187
+ const lockHashes = options.surfaceFilter === undefined ? newHashes : { ...lock.agentHashes, ...newHashes };
188
+ if (!dryRun) writeLock(targetRepo, { schema: 1, mcp: lock.mcp, agents: lockAgents, agentHashes: lockHashes });
148
189
 
149
190
  // Once anything was actually taken over, this package's own footprint in
150
191
  // the legacy lock's `files` section for these exact agent paths is stale:
@@ -161,6 +202,8 @@ export function deployAgents(options: DeployAgentsOptions): DeployAgentsResult {
161
202
  removed: removed.sort(),
162
203
  conflicts: conflicts.sort((a, b) => `${a.folder}/${a.agent}`.localeCompare(`${b.folder}/${b.agent}`)),
163
204
  adopted: adopted.sort(),
205
+ kept: keptUnverified.sort(),
206
+ absent: absent.sort(),
164
207
  lockPath: join(targetRepo, ".agents/agent-settings.lock.json"),
165
208
  };
166
209
  }
@@ -0,0 +1,22 @@
1
+ /** What a previous deploy wrote, from the lock: a named, additive deploy keeps these (Tarun, 2026-10-25). */
2
+ import { readLock } from "./lock.js";
3
+ import { readDeployedMcpServerNames } from "./mcp-inspect.js";
4
+ import type { DeployProfile } from "./profile.js";
5
+
6
+ /** Agent names the lock records across every surface folder, sorted. */
7
+ export function deployedAgentNames(targetRepo: string): readonly string[] {
8
+ return [...new Set(Object.values(readLock(targetRepo).agents).flat())].sort();
9
+ }
10
+
11
+ /** MCP server names a previous deploy owns: the lock's servers for a JSON surface, every server in an owned managed block. Sorted. */
12
+ export function deployedMcpServerNames(targetRepo: string, profile: DeployProfile): readonly string[] {
13
+ const lock = readLock(targetRepo);
14
+ const names = new Set<string>();
15
+ for (const surface of profile.mcp.surfaces) {
16
+ const entry = lock.mcp[surface.file];
17
+ if (entry === undefined) continue;
18
+ if (entry.kind === "json") for (const name of entry.servers) names.add(name);
19
+ else for (const name of readDeployedMcpServerNames(targetRepo, surface)) names.add(name);
20
+ }
21
+ return [...names].sort();
22
+ }