@inventarch/distribution 2.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +10 -0
  2. package/SPEC.md +19 -1
  3. package/dist/adoption.d.ts +21 -0
  4. package/dist/adoption.d.ts.map +1 -0
  5. package/dist/adoption.js +187 -0
  6. package/dist/adoption.js.map +1 -0
  7. package/dist/archive.d.ts.map +1 -1
  8. package/dist/archive.js +4 -1
  9. package/dist/archive.js.map +1 -1
  10. package/dist/command.d.ts.map +1 -1
  11. package/dist/command.js +22 -6
  12. package/dist/command.js.map +1 -1
  13. package/dist/files.d.ts.map +1 -1
  14. package/dist/files.js +30 -23
  15. package/dist/files.js.map +1 -1
  16. package/dist/guard-registration.d.ts +120 -5
  17. package/dist/guard-registration.d.ts.map +1 -1
  18. package/dist/guard-registration.js +419 -57
  19. package/dist/guard-registration.js.map +1 -1
  20. package/dist/host-modes.d.ts.map +1 -1
  21. package/dist/host-modes.js +2 -2
  22. package/dist/host-modes.js.map +1 -1
  23. package/dist/host-observe.d.ts +20 -1
  24. package/dist/host-observe.d.ts.map +1 -1
  25. package/dist/host-observe.js +18 -5
  26. package/dist/host-observe.js.map +1 -1
  27. package/dist/host.d.ts +7 -0
  28. package/dist/host.d.ts.map +1 -1
  29. package/dist/host.js +3 -0
  30. package/dist/host.js.map +1 -1
  31. package/dist/implementations.d.ts +181 -0
  32. package/dist/implementations.d.ts.map +1 -0
  33. package/dist/implementations.js +371 -0
  34. package/dist/implementations.js.map +1 -0
  35. package/dist/installation-core.d.ts.map +1 -1
  36. package/dist/installation-core.js +3 -3
  37. package/dist/installation-core.js.map +1 -1
  38. package/dist/lifecycle-registration.d.ts +6 -2
  39. package/dist/lifecycle-registration.d.ts.map +1 -1
  40. package/dist/lifecycle-registration.js +5 -1
  41. package/dist/lifecycle-registration.js.map +1 -1
  42. package/dist/minting.d.ts.map +1 -1
  43. package/dist/minting.js +2 -2
  44. package/dist/minting.js.map +1 -1
  45. package/dist/projection.d.ts +11 -2
  46. package/dist/projection.d.ts.map +1 -1
  47. package/dist/projection.js +78 -13
  48. package/dist/projection.js.map +1 -1
  49. package/dist/registry-build.d.ts +3 -0
  50. package/dist/registry-build.d.ts.map +1 -1
  51. package/dist/registry-build.js +20 -0
  52. package/dist/registry-build.js.map +1 -1
  53. package/dist/registry-collections.d.ts +32 -0
  54. package/dist/registry-collections.d.ts.map +1 -0
  55. package/dist/registry-collections.js +105 -0
  56. package/dist/registry-collections.js.map +1 -0
  57. package/dist/registry-resolve.d.ts +2 -0
  58. package/dist/registry-resolve.d.ts.map +1 -1
  59. package/dist/registry-resolve.js +23 -2
  60. package/dist/registry-resolve.js.map +1 -1
  61. package/dist/registry-source.d.ts +3 -0
  62. package/dist/registry-source.d.ts.map +1 -1
  63. package/dist/registry-source.js +15 -6
  64. package/dist/registry-source.js.map +1 -1
  65. package/dist/registry.d.ts +4 -0
  66. package/dist/registry.d.ts.map +1 -1
  67. package/dist/registry.js +2 -0
  68. package/dist/registry.js.map +1 -1
  69. package/dist/services.d.ts +89 -6
  70. package/dist/services.d.ts.map +1 -1
  71. package/dist/services.js +94 -4
  72. package/dist/services.js.map +1 -1
  73. package/dist/snapshot.d.ts +1 -1
  74. package/dist/snapshot.d.ts.map +1 -1
  75. package/dist/snapshot.js +30 -6
  76. package/dist/snapshot.js.map +1 -1
  77. package/package.json +16 -7
  78. package/references/registry-collections.md +15 -0
@@ -1,7 +1,8 @@
1
1
  import { isAbsolute, join, relative, sep } from 'node:path';
2
2
  import { decodeDistributionJson } from '@inventarch/db/distribution';
3
+ import { HOOK_LIMIT, HOOK_SELECTION_LIMIT, registrableHook, registrableSelection, } from '@inventarch/workspace-runtime/internal/generate';
3
4
  import { acquireHostRegistrationLock, assertHostRegistrationIdle, doorServer, HOST_REGISTRATION, verifyHostCache, } from './host.js';
4
- import { bytes, digest, fail, json, locate, object, replace, sha256, utf8, workspace } from './files.js';
5
+ import { bytes, digest, DistributionError, fail, json, locate, object, replace, sha256, utf8, workspace, } from './files.js';
5
6
  import { editJson, emptyJson, keptPaths, presentJson } from './json-edit.js';
6
7
  const area = '.ia/distributions/hosts', pendingPath = area + '/guard-pending.json', configPath = '.claude/settings.local.json', projectPath = '.claude/settings.json';
7
8
  const identity = (value) => {
@@ -28,22 +29,31 @@ function plain(value) {
28
29
  fail('INPUT-INVALID', 'Expected host settings object');
29
30
  return value;
30
31
  }
31
- /** Spec §5.1: explicit root, not claude-guard's CLAUDE_PROJECT_DIR, so the recorded root is the one run; on POSIX through `/bin/sh`, so a guard that cannot run denies (`FAIL_CLOSED`). */
32
- export function guardGroup(launcher, root, platform = process.platform) {
33
- const server = doorServer(launcher, ['guard', '--root', root]);
32
+ /**
33
+ * One group that runs the launcher's guard mode with `args` after it: the direct form on win32, and elsewhere through
34
+ * `/bin/sh` with `FAIL_CLOSED`. Every group IA registers for the guard, the retired steward guard's and each `@hook`'s,
35
+ * is this derivation, so `guardNode` reads both.
36
+ */
37
+ function fixedGroup(matcher, launcher, args, platform) {
38
+ const server = doorServer(launcher, ['guard', ...args]);
34
39
  return {
35
- matcher: GUARD_MATCHER,
40
+ matcher,
36
41
  hooks: [
37
42
  {
38
43
  type: 'command',
39
44
  ...(platform === 'win32'
40
45
  ? server
41
46
  : { command: '/bin/sh', args: ['-c', FAIL_CLOSED, server.command, ...server.args] }),
42
- timeout: 10,
47
+ timeout: GUARD_TIMEOUT,
43
48
  },
44
49
  ],
45
50
  };
46
51
  }
52
+ const GUARD_TIMEOUT = 10;
53
+ /** Spec §5.1: explicit root, not claude-guard's CLAUDE_PROJECT_DIR, so the recorded root is the one run; on POSIX through `/bin/sh`, so a guard that cannot run denies (`FAIL_CLOSED`). */
54
+ export function guardGroup(launcher, root, platform = process.platform) {
55
+ return fixedGroup(GUARD_MATCHER, launcher, ['--root', root], platform);
56
+ }
47
57
  /**
48
58
  * The retained group must be the fixed guard derivation for its cache and root, in either form (`guardNode`); the
49
59
  * recorded Node executable is kept as written. Exported for `host-observe.ts`, which reuses this real validator rather than a weaker local
@@ -80,19 +90,31 @@ export function saved(content, root, id, removal = false) {
80
90
  keptPaths(row['existing'], containers);
81
91
  return row;
82
92
  }
83
- /** Released direct and POSIX wrappers both contain this fixed launcher/verb/root argv sequence. */
84
- function referencesGuard(value) {
93
+ /**
94
+ * What a group's guard invocation names: undefined when no handler runs the launcher's guard mode, null when one does and
95
+ * names no `@hook` (the retired steward guard's), else the value after its `--hook`, as written. Released direct and
96
+ * POSIX wrappers both contain this fixed launcher/verb/root argv sequence; a `@hook`'s group follows it with
97
+ * `--hook <identity>`.
98
+ */
99
+ function guardInvocation(value) {
85
100
  if (value === null || typeof value !== 'object' || !('hooks' in value) || !Array.isArray(value.hooks))
86
- return false;
87
- return value.hooks.some((handler) => {
101
+ return undefined;
102
+ for (const handler of value.hooks) {
88
103
  if (handler === null || typeof handler !== 'object' || !('args' in handler) || !Array.isArray(handler.args))
89
- return false;
90
- return handler.args.some((arg, index, args) => typeof arg === 'string' &&
104
+ continue;
105
+ const args = handler.args;
106
+ const index = args.findIndex((arg, at) => typeof arg === 'string' &&
91
107
  /[/\\]scripts[/\\]ia\.mjs$/.test(arg) &&
92
- args[index + 1] === 'guard' &&
93
- args[index + 2] === '--root');
94
- });
108
+ args[at + 1] === 'guard' &&
109
+ args[at + 2] === '--root');
110
+ if (index < 0)
111
+ continue;
112
+ return args[index + 4] === '--hook' ? String(args[index + 5]) : null;
113
+ }
114
+ return undefined;
95
115
  }
116
+ /** Whether a group is the retired steward guard's: it runs the guard and names no `@hook` (B11 retires exactly these). */
117
+ const referencesGuard = (value) => guardInvocation(value) === null;
96
118
  /** Refuse an unowned guard before retiring the agents it depends on. Never alter unrelated hooks. */
97
119
  export function assertRetirableGuard(root) {
98
120
  const state = locate(statePath(HOST_REGISTRATION), () => saved(read(root, statePath(HOST_REGISTRATION)), root, HOST_REGISTRATION, true));
@@ -128,30 +150,86 @@ export function planGuardFor(rootInput, expected) {
128
150
  assertHostRegistrationIdle(root);
129
151
  return planGuardWith(root, expected, null);
130
152
  }
131
- function planGuardWith(root, cache, removeId) {
153
+ /**
154
+ * The settings file whose `disableAllHooks: true` turns Claude Code's hooks off for this workspace, as registration
155
+ * reads it (`.claude/settings.local.json` first, then `.claude/settings.json` when the local file does not set it), or
156
+ * null when hooks are on or a file cannot be read, which the plan itself then refuses (review finding H-N12).
157
+ */
158
+ export function hooksDisabledBy(rootInput) {
159
+ const root = workspace(rootInput);
160
+ try {
161
+ const local = read(root, configPath), config = local === null ? {} : plain(decodeDistributionJson(local));
162
+ if (config['disableAllHooks'] === true)
163
+ return configPath;
164
+ if (config['disableAllHooks'] !== undefined)
165
+ return null;
166
+ const shared = read(root, projectPath), project = shared === null ? {} : plain(decodeDistributionJson(shared));
167
+ return project['disableAllHooks'] === true ? projectPath : null;
168
+ }
169
+ catch {
170
+ return null;
171
+ }
172
+ }
173
+ /**
174
+ * The preamble the retired steward guard's plan (removal, and the 1.x registration its fixtures still make) and the hook
175
+ * groups' plan share (guard review finding G-N9): a Claude-compatible cache outside the root, the settings and the
176
+ * ownership state read once, a removal refused when nothing is owned, hooks explicitly disabled refused when the plan
177
+ * would register a group, and a bounded PreToolUse array.
178
+ */
179
+ function readSettings(root, cache, removeId, what, stateOf, validate, writing) {
132
180
  if (cache && cache.host !== null && cache.host !== 'claude')
133
- fail('HOST-UNSUPPORTED', 'Guard registration requires a Claude-compatible cache');
181
+ fail('HOST-UNSUPPORTED', `${what} registration requires a Claude-compatible cache`);
134
182
  if (cache) {
135
183
  const path = relative(cache.directory, root);
136
184
  if (!isAbsolute(path) && path !== '..' && !path.startsWith('..' + sep))
137
185
  fail('PATH-UNSAFE', 'Consumer root cannot be inside its immutable host cache');
138
186
  }
139
- const id = cache ? HOST_REGISTRATION : identity(removeId);
187
+ const id = cache ? HOST_REGISTRATION : identity(removeId), stateFile = stateOf(id);
140
188
  const before = {
141
189
  config: read(root, configPath),
142
- state: locate(statePath(id), () => read(root, statePath(id))),
143
- }, prior = locate(statePath(id), () => saved(before.state, root, id, cache === null));
190
+ state: locate(stateFile, () => read(root, stateFile)),
191
+ }, prior = locate(stateFile, () => validate(before.state, id, cache === null));
144
192
  if (!cache && !prior)
145
- fail('INPUT-INVALID', 'Guard registration is not owned');
193
+ fail('INPUT-INVALID', `${what} registration is not owned`);
146
194
  const config = before.config === null ? {} : plain(decodeDistributionJson(before.config)), hooks = config['hooks'] === undefined ? {} : plain(config['hooks']);
147
195
  const projectText = read(root, projectPath), project = projectText === null ? {} : plain(decodeDistributionJson(projectText));
148
- if (cache &&
149
- (config['disableAllHooks'] === true ||
150
- (config['disableAllHooks'] === undefined && project['disableAllHooks'] === true)))
196
+ const disabled = config['disableAllHooks'] === true ||
197
+ (config['disableAllHooks'] === undefined && project['disableAllHooks'] === true);
198
+ if (writing && disabled)
151
199
  fail('HOST-UNSUPPORTED', 'Project hooks are explicitly disabled by disableAllHooks');
152
200
  const rows = hooks['PreToolUse'] === undefined ? [] : hooks['PreToolUse'];
153
201
  if (!Array.isArray(rows) || rows.length > 256)
154
202
  fail('INPUT-INVALID', 'Expected a bounded PreToolUse hook array');
203
+ return { id, before, prior, rows, projectText, disabled };
204
+ }
205
+ /**
206
+ * The journaled publication both registrations share (G-N9), under the host lock the caller holds: the journal first
207
+ * (`guard-pending.json`, which every host write waits on), the settings, then the ownership state (the commit), then
208
+ * the journal cleared; a concurrent change of either file, the project settings or the cache refuses.
209
+ */
210
+ function publish(root, plan, stateFile, pendingFormat, what, checkpoint) {
211
+ const now = () => ({ config: read(root, configPath), state: read(root, stateFile) });
212
+ const unchanged = (side) => {
213
+ if (json(now()) !== json(side))
214
+ fail('LOCAL-MODIFICATION', `${what} configuration or ownership changed during publication`);
215
+ };
216
+ const before = now();
217
+ write(root, pendingPath, json({ format: pendingFormat, id: plan.id, before, after: plan.after }));
218
+ checkpoint('pending');
219
+ unchanged(before);
220
+ write(root, configPath, plan.after.config);
221
+ checkpoint('config');
222
+ unchanged({ ...before, config: plan.after.config });
223
+ if (pin(read(root, projectPath)) !== plan.before.projectConfig ||
224
+ ('cache' in plan.request && verifyHostCache(plan.request.cache).release !== plan.release))
225
+ fail('PLAN-STALE', 'Project settings or host cache changed before registration commit');
226
+ write(root, stateFile, plan.after.state);
227
+ checkpoint('state');
228
+ write(root, pendingPath, null);
229
+ checkpoint('complete');
230
+ }
231
+ function planGuardWith(root, cache, removeId) {
232
+ const { id, before, prior, rows, projectText } = readSettings(root, cache, removeId, 'Guard', statePath, (content, owner, removal) => saved(content, root, owner, removal), cache !== null);
155
233
  const matching = prior
156
234
  ? rows.map((row, at) => (json(row) === json(prior.group) ? at : -1)).filter((at) => at >= 0)
157
235
  : [];
@@ -192,14 +270,6 @@ function planGuardWith(root, cache, removeId) {
192
270
  };
193
271
  return { ...body, digest: digest(body) };
194
272
  }
195
- const current = (root, id) => ({
196
- config: read(root, configPath),
197
- state: read(root, statePath(id)),
198
- });
199
- function same(root, id, side) {
200
- if (json(current(root, id)) !== json(side))
201
- fail('LOCAL-MODIFICATION', 'Guard configuration or ownership changed during publication');
202
- }
203
273
  const write = (root, path, content) => replace(root, path, content === null ? null : Buffer.from(content));
204
274
  export function applyGuardRegistration(input, checkpoint = () => { }) {
205
275
  const row = object(input, ['format', 'root', 'id', 'request', 'release', 'before', 'after', 'digest']);
@@ -210,26 +280,312 @@ export function applyGuardRegistration(input, checkpoint = () => { }) {
210
280
  const plan = planGuardRegistration(root, row['request']);
211
281
  if (json(plan) !== json(input))
212
282
  fail('PLAN-STALE', 'Guard plan no longer matches its current inputs');
213
- const before = current(root, plan.id);
214
- write(root, pendingPath, json({ format: 'ia.guard-registration-pending.v1', id: plan.id, before, after: plan.after }));
215
- checkpoint('pending');
216
- same(root, plan.id, before);
217
- write(root, configPath, plan.after.config);
218
- checkpoint('config');
219
- same(root, plan.id, { ...before, config: plan.after.config });
220
- if (pin(read(root, projectPath)) !== plan.before.projectConfig ||
221
- ('cache' in plan.request && verifyHostCache(plan.request.cache).release !== plan.release))
222
- fail('PLAN-STALE', 'Project settings or host cache changed before registration commit');
223
- write(root, statePath(plan.id), plan.after.state);
224
- checkpoint('state');
225
- write(root, pendingPath, null);
226
- checkpoint('complete');
283
+ publish(root, plan, statePath(plan.id), 'ia.guard-registration-pending.v1', 'Guard', checkpoint);
227
284
  return { status: 'cache' in plan.request ? 'guard-registered' : 'guard-removed', id: plan.id };
228
285
  }
229
286
  finally {
230
287
  unlock();
231
288
  }
232
289
  }
290
+ /*
291
+ * Hook groups (milestone generation-binding, plan amendments C9 and C10). Each authored `@hook` becomes exactly one
292
+ * PreToolUse group in `.claude/settings.local.json`, which runs the launcher's guard mode for that hook,
293
+ * `guard --root <root> --hook <identity>`, through the derivation the retired steward guard's group used. A JSON entry
294
+ * cannot carry a marker line, so the groups are owned as that group was: by exact match against the group an ownership
295
+ * state records (`claude-hooks-<id>.json`, beside the guard's state), published under the host lock through the same
296
+ * journal (`guard-pending.json`, which every host write already waits on) and recovered by the same `recover-guard`.
297
+ * Every other group, key and byte of the file is kept. `@hook` gains no field: the record's `hook.paths` decide what the
298
+ * guard selects when it runs, and only its identity and tools reach the registration.
299
+ */
300
+ /** The edit tools a hook group can match, in matcher order. */
301
+ export const HOOK_TOOLS = ['Write', 'Edit', 'MultiEdit'];
302
+ // The bounds hook generation applies, so a hook beyond them is reported there, never refused here (H-N2).
303
+ const MAX_HOOKS = HOOK_LIMIT;
304
+ /** The ownership state of a registration's hook groups. */
305
+ export const hookStatePath = (id) => `${area}/claude-hooks-${identity(id)}.json`;
306
+ const order = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
307
+ function hookIdentity(value) {
308
+ // The identities hook generation registers, which the guard's --hook accepts (workspace-runtime registrableHook).
309
+ if (!registrableHook(value))
310
+ fail('INPUT-INVALID', 'Invalid hook identity');
311
+ return value;
312
+ }
313
+ function hookTools(value) {
314
+ if (!Array.isArray(value) ||
315
+ value.length === 0 ||
316
+ new Set(value).size !== value.length ||
317
+ value.some((tool) => !HOOK_TOOLS.includes(tool)))
318
+ fail('INPUT-INVALID', 'Hook tools must name Write, Edit or MultiEdit, each at most once');
319
+ return HOOK_TOOLS.filter((tool) => value.includes(tool));
320
+ }
321
+ /** A registered selection: one to 64 selections hook generation can register (`registrableSelection`). */
322
+ function hookPaths(value) {
323
+ if (!Array.isArray(value) ||
324
+ value.length === 0 ||
325
+ value.length > HOOK_SELECTION_LIMIT ||
326
+ value.some((path) => !registrableSelection(path)))
327
+ fail('INPUT-INVALID', 'Hook paths must be workspace-relative selections written with /');
328
+ return [...value];
329
+ }
330
+ /** A request's rows in identity order with tools in matcher order; a repeated identity is refused. */
331
+ function hookRows(value) {
332
+ if (!Array.isArray(value) || value.length > MAX_HOOKS)
333
+ fail('INPUT-INVALID', `Expected a list of at most ${MAX_HOOKS} hook rows`);
334
+ const rows = value
335
+ .map((item) => {
336
+ const row = object(item, ['identity', 'tools', 'paths']);
337
+ return {
338
+ identity: hookIdentity(row['identity']),
339
+ tools: hookTools(row['tools']),
340
+ paths: hookPaths(row['paths']),
341
+ };
342
+ })
343
+ .sort((a, b) => order(a.identity, b.identity));
344
+ if (new Set(rows.map((row) => row.identity)).size !== rows.length)
345
+ fail('INPUT-INVALID', 'Each hook is registered at most once');
346
+ return rows;
347
+ }
348
+ /**
349
+ * The group a `@hook` registers: the guard runs with this root and that identity for every edit tool (`Write|Edit|MultiEdit`,
350
+ * as the retired steward guard's group did), so the managed-state protection decides every edit; the hook's own tools
351
+ * apply only to its paths, which the guard reads from the record (guard review finding G-R2).
352
+ */
353
+ export function hookGroup(launcher, root, hook, platform = process.platform) {
354
+ hookTools(hook.tools);
355
+ return fixedGroup(GUARD_MATCHER, launcher, ['--root', root, '--hook', hookIdentity(hook.identity)], platform);
356
+ }
357
+ /**
358
+ * A hook ownership state, or null for none. Each recorded group must be `hookGroup`'s derivation for the state's cache,
359
+ * this root and its hook, in either form (`guardNode`), the recorded Node kept as written; a removal accepts the root
360
+ * the group records, so a moved workspace can still remove what it registered.
361
+ */
362
+ export function savedHooks(content, root, id, removal = false) {
363
+ if (content === null)
364
+ return null;
365
+ const value = plain(decodeDistributionJson(content)), row = object(value, [
366
+ 'format',
367
+ 'id',
368
+ 'cache',
369
+ 'release',
370
+ 'created',
371
+ 'groups',
372
+ ...(Object.hasOwn(value, 'existing') ? ['existing'] : []),
373
+ ]);
374
+ if (row['format'] !== 'ia.hook-registration-state.v1' ||
375
+ row['id'] !== id ||
376
+ typeof row['cache'] !== 'string' ||
377
+ !isAbsolute(row['cache']) ||
378
+ typeof row['created'] !== 'boolean' ||
379
+ !Array.isArray(row['groups']) ||
380
+ row['groups'].length === 0 ||
381
+ row['groups'].length > MAX_HOOKS)
382
+ fail('INPUT-INVALID', 'Invalid hook ownership state');
383
+ hash(row['release']);
384
+ const launcher = join(row['cache'], 'scripts/ia.mjs');
385
+ let previous = '';
386
+ for (const item of row['groups']) {
387
+ const owned = object(item, ['hook', 'group', 'paths']), hook = hookIdentity(owned['hook']);
388
+ hookPaths(owned['paths']);
389
+ if (hook <= previous)
390
+ fail('INPUT-INVALID', 'Hook ownership rows must be unique and in identity order');
391
+ previous = hook;
392
+ const group = object(owned['group'], ['matcher', 'hooks']);
393
+ if (typeof group['matcher'] !== 'string' ||
394
+ group['matcher'] !== GUARD_MATCHER ||
395
+ !Array.isArray(group['hooks']) ||
396
+ group['hooks'].length !== 1)
397
+ fail('INPUT-INVALID', 'Invalid owned hook group');
398
+ const handler = object(group['hooks'][0], ['type', 'command', 'args', 'timeout']), recorded = Array.isArray(handler['args']) ? handler['args'].at(-3) : null, fixedRoot = removal && typeof recorded === 'string' && isAbsolute(recorded) ? recorded : root, node = guardNode(handler, launcher, fixedRoot, hook);
399
+ if (handler['type'] !== 'command' ||
400
+ typeof node !== 'string' ||
401
+ !isAbsolute(node) ||
402
+ handler['timeout'] !== GUARD_TIMEOUT)
403
+ fail('INPUT-INVALID', 'Owned hook command differs from its fixed root');
404
+ }
405
+ keptPaths(row['existing'], containers);
406
+ return row;
407
+ }
408
+ /** Plan the registration of exactly `request.hooks`, or the removal of every owned group. Reads only; writes nothing. */
409
+ export function planHookRegistration(rootInput, request) {
410
+ const root = workspace(rootInput);
411
+ assertHostRegistrationIdle(root);
412
+ const remove = Object.hasOwn(plain(request), 'remove'), row = object(request, remove ? ['remove'] : ['cache', 'hooks']);
413
+ if (remove) {
414
+ assertRemovableHooks(root, identity(row['remove']));
415
+ return planHooksWith(root, null, [], row['remove']);
416
+ }
417
+ const hooks = hookRows(row['hooks']);
418
+ return planHooksWith(root, verifyHostCache(row['cache']), hooks, null);
419
+ }
420
+ /**
421
+ * Explicit removal must not report that protection was lifted while an unowned IA hook still runs. Check both settings
422
+ * locations, including after ownership was lost, and leave every byte untouched. A foreign group is never adopted.
423
+ */
424
+ export function assertRemovableHooks(rootInput, id = HOST_REGISTRATION) {
425
+ const root = workspace(rootInput), stateFile = hookStatePath(id), state = locate(stateFile, () => savedHooks(read(root, stateFile), root, id, true));
426
+ for (const path of [configPath, projectPath])
427
+ locate(path, () => {
428
+ const text = read(root, path);
429
+ if (text === null)
430
+ return;
431
+ const config = plain(decodeDistributionJson(text)), hooks = config['hooks'] === undefined ? {} : plain(config['hooks']), rows = hooks['PreToolUse'] ?? [];
432
+ if (!Array.isArray(rows) || rows.length > 256)
433
+ fail('INPUT-INVALID', 'Expected a bounded PreToolUse hook array');
434
+ for (const group of rows) {
435
+ const hook = guardInvocation(group);
436
+ if (typeof hook !== 'string')
437
+ continue;
438
+ // Existing modified/duplicate owned groups retain their own refusal and recovery.
439
+ if (path === configPath && state?.groups.some((row) => row.hook === hook))
440
+ continue;
441
+ throw Object.assign(new DistributionError('IA-DIST-LOCAL-MODIFICATION', `IA hook group for ${hook} has no matching ownership state; protection may remain active until that group is removed manually`, path), { unownedHook: { hook, path } });
442
+ }
443
+ });
444
+ }
445
+ /** `planHookRegistration` against an expected, unverified cache (`expectedHostCache`); apply re-plans with verification. */
446
+ export function planHooksFor(rootInput, expected, hooks) {
447
+ const root = workspace(rootInput);
448
+ assertHostRegistrationIdle(root);
449
+ return planHooksWith(root, expected, hookRows(hooks), null);
450
+ }
451
+ function planHooksWith(root, cache, desired, removeId) {
452
+ // With hooks turned off, a plan that only keeps or removes owned groups proceeds; one that would write a group refuses
453
+ // below (review finding A-F1).
454
+ const { id, before, prior, rows, projectText, disabled } = readSettings(root, cache, removeId, 'Hook', hookStatePath, (content, owner, removal) => savedHooks(content, root, owner, removal), false);
455
+ const wanted = new Map(desired.map((row) => [row.identity, hookGroup(cache.launcher, root, row)])), selections = new Map(desired.map((row) => [row.identity, row.paths]));
456
+ // Each owned group is found by exact match, exactly once. One the user already deleted, so that no group names its
457
+ // hook any more, has only its ownership dropped, and only when the hook is no longer wanted, as the guard's removal
458
+ // does; a changed or duplicated group refuses.
459
+ const owned = (prior?.groups ?? []).map(({ hook, group, paths }) => {
460
+ const at = rows.flatMap((row, index) => (json(row) === json(group) ? [index] : []));
461
+ const named = rows.some((row) => guardInvocation(row) === hook), gone = at.length === 0 && !named;
462
+ // Guard review finding G-N2: each refusal names the way out. A group deleted by hand is restored only through the
463
+ // removal, which drops its ownership, and a new registration.
464
+ if (gone && wanted.has(hook))
465
+ fail('LOCAL-MODIFICATION', `Owned hook group for ${hook} was deleted by hand; remove the registration ("ia host claude --remove --apply") and register it again`);
466
+ if (!gone && at.length !== 1)
467
+ fail('LOCAL-MODIFICATION', `Owned hook group for ${hook} changed or was duplicated; delete only that group from ${configPath}, then remove the registration ("ia host claude --remove --apply") and register it again`);
468
+ return { hook, group, paths, at: at[0] ?? null };
469
+ });
470
+ const claimed = new Set(owned.flatMap(({ at }) => (at === null ? [] : [at])));
471
+ for (const [hook, group] of wanted)
472
+ if (rows.some((row, index) => !claimed.has(index) && json(row) === json(group)))
473
+ fail('LOCAL-MODIFICATION', `An unmanaged identical hook group already exists for ${hook}`);
474
+ // In place (spec §5.1): replace each owned group whose derivation changed at its own index, append each new one in
475
+ // identity order, then remove the unwanted ones from the highest index down; every other byte is kept.
476
+ const existing = prior ? keptPaths(prior.existing, containers) : presentJson(before.config, containers);
477
+ let edited = before.config;
478
+ for (const { hook, group, at } of owned)
479
+ if (at !== null && wanted.has(hook) && json(group) !== json(wanted.get(hook)))
480
+ edited = editJson(edited, ['hooks', 'PreToolUse', at], wanted.get(hook), existing);
481
+ for (const [hook, group] of wanted)
482
+ if (!owned.some((row) => row.hook === hook))
483
+ edited = editJson(edited, ['hooks', 'PreToolUse', -1], group, existing);
484
+ const removed = owned.filter(({ hook, at }) => at !== null && !wanted.has(hook)).sort((a, b) => b.at - a.at);
485
+ for (const { at } of removed)
486
+ edited = editJson(edited, ['hooks', 'PreToolUse', at], undefined, existing);
487
+ const created = prior?.created ?? before.config === null;
488
+ const after = {
489
+ // A file the first registration created goes again once its last owned group is removed and it holds nothing else.
490
+ config: wanted.size === 0 && removed.length > 0 && created && emptyJson(edited) ? null : edited,
491
+ state: wanted.size === 0
492
+ ? null
493
+ : json({
494
+ format: 'ia.hook-registration-state.v1',
495
+ id,
496
+ cache: cache.directory,
497
+ release: cache.release,
498
+ created,
499
+ groups: [...wanted].map(([hook, group]) => ({ hook, group, paths: selections.get(hook) })),
500
+ ...(existing.length ? { existing } : {}),
501
+ }),
502
+ };
503
+ if (Buffer.byteLength(after.config ?? '') > 1024 * 1024 || Buffer.byteLength(after.state ?? '') > 1024 * 1024)
504
+ fail('LIMIT-EXCEEDED', 'Hook registration exceeds its publication bounds');
505
+ const actions = [
506
+ ...[...wanted].map(([hook, group]) => {
507
+ const prior = owned.find((row) => row.hook === hook);
508
+ return {
509
+ hook,
510
+ action: prior === undefined
511
+ ? 'create'
512
+ : json(prior.group) === json(group) && json(prior.paths) === json(selections.get(hook))
513
+ ? 'unchanged'
514
+ : 'update',
515
+ };
516
+ }),
517
+ ...owned.filter(({ hook }) => !wanted.has(hook)).map(({ hook }) => ({ hook, action: 'remove' })),
518
+ ].sort((a, b) => order(a.hook, b.hook));
519
+ if (disabled && actions.some((row) => row.action === 'create' || row.action === 'update'))
520
+ fail('HOST-UNSUPPORTED', 'Project hooks are explicitly disabled by disableAllHooks');
521
+ const body = {
522
+ format: 'ia.hook-registration-plan.v1',
523
+ root,
524
+ id,
525
+ request: cache ? { cache: cache.directory, hooks: [...desired] } : { remove: id },
526
+ release: cache?.release ?? null,
527
+ hooks: actions,
528
+ before: { config: pin(before.config), state: pin(before.state), projectConfig: pin(projectText) },
529
+ after,
530
+ };
531
+ return { ...body, digest: digest(body) };
532
+ }
533
+ /** The registration's hook ownership state as `savedHooks` reads it for this root, or null when it owns none. */
534
+ export function readHookRegistration(rootInput, id = HOST_REGISTRATION) {
535
+ const root = workspace(rootInput), stateFile = hookStatePath(id);
536
+ return locate(stateFile, () => savedHooks(read(root, stateFile), root, id));
537
+ }
538
+ /**
539
+ * Read-only drift of the hook groups (doctor): each owned group found exactly once is current and not listed. Reads the
540
+ * ownership state and `.claude/settings.local.json` as the planner does, so a file the planner would refuse to read
541
+ * refuses here too, located at that file. Writes nothing.
542
+ */
543
+ export function observeHookRegistration(rootInput, id = HOST_REGISTRATION) {
544
+ const root = workspace(rootInput), state = readHookRegistration(root, id), text = read(root, configPath);
545
+ const config = locate(configPath, () => (text === null ? {} : plain(decodeDistributionJson(text)))), hooks = config['hooks'] === undefined ? {} : plain(config['hooks']), rows = hooks['PreToolUse'] === undefined ? [] : hooks['PreToolUse'];
546
+ if (!Array.isArray(rows))
547
+ fail('INPUT-INVALID', 'Expected PreToolUse hook array');
548
+ const owned = state?.groups ?? [], drift = [];
549
+ for (const { hook, group } of owned) {
550
+ const exact = rows.filter((row) => json(row) === json(group)).length;
551
+ if (exact === 1)
552
+ continue;
553
+ drift.push({
554
+ hook,
555
+ drift: exact > 1 || rows.some((row) => guardInvocation(row) === hook) ? 'modified' : 'missing',
556
+ });
557
+ }
558
+ const ownedHooks = new Set(owned.map(({ hook }) => hook));
559
+ for (const hook of new Set(rows.map(guardInvocation)))
560
+ if (typeof hook === 'string' && !ownedHooks.has(hook))
561
+ drift.push({ hook, drift: 'foreign' });
562
+ return drift.sort((a, b) => order(a.hook, b.hook));
563
+ }
564
+ /** The canonical JSON digest of an owned group, as a receipt's hook row records it. */
565
+ export const hookGroupDigest = (group) => sha256(json(group));
566
+ /**
567
+ * Apply a hook plan under the host lock: re-plan, refuse a stale plan, journal, write the settings, then the ownership
568
+ * state (the commit), then clear the journal. A plan that changes nothing writes nothing. `checkpoint` runs after each
569
+ * write, where an interruption test cuts; `recoverGuardRegistration` finishes or rolls back an interrupted one.
570
+ */
571
+ export function applyHookRegistration(input, checkpoint = () => { }) {
572
+ const row = object(input, ['format', 'root', 'id', 'request', 'release', 'hooks', 'before', 'after', 'digest']);
573
+ if (row['format'] !== 'ia.hook-registration-plan.v1' || typeof row['root'] !== 'string')
574
+ fail('INPUT-INVALID', 'Invalid hook registration plan');
575
+ const root = workspace(row['root']), unlock = acquireHostRegistrationLock(root);
576
+ try {
577
+ const plan = planHookRegistration(root, row['request']);
578
+ if (json(plan) !== json(input))
579
+ fail('PLAN-STALE', 'Hook plan no longer matches its current inputs');
580
+ if (pin(plan.after.config) === plan.before.config && pin(plan.after.state) === plan.before.state)
581
+ return { status: 'hooks-unchanged', id: plan.id };
582
+ publish(root, plan, hookStatePath(plan.id), 'ia.hook-registration-pending.v1', 'Hook', checkpoint);
583
+ return { status: plan.after.state === null ? 'hooks-removed' : 'hooks-registered', id: plan.id };
584
+ }
585
+ finally {
586
+ unlock();
587
+ }
588
+ }
233
589
  export function recoverGuardRegistration(rootInput) {
234
590
  const root = workspace(rootInput), unlock = acquireHostRegistrationLock(root, true);
235
591
  try {
@@ -241,26 +597,32 @@ export function recoverGuardRegistration(rootInput) {
241
597
  if (content === null)
242
598
  return { status: 'current' };
243
599
  const row = object(decodeDistributionJson(content), ['format', 'id', 'before', 'after']);
244
- if (row['format'] !== 'ia.guard-registration-pending.v1')
600
+ // One journal serves both registrations this module publishes: the retired steward guard's and the hook groups'.
601
+ const hooks = row['format'] === 'ia.hook-registration-pending.v1';
602
+ if (row['format'] !== 'ia.guard-registration-pending.v1' && !hooks)
245
603
  fail('INPUT-INVALID', 'Unknown guard recovery format');
246
- const id = identity(row['id']);
604
+ const id = identity(row['id']), state = hooks ? hookStatePath(id) : statePath(id);
247
605
  const side = (value) => {
248
606
  const data = object(value, ['config', 'state']);
249
607
  for (const v of Object.values(data))
250
608
  if (!(v === null || (typeof v === 'string' && Buffer.byteLength(v) <= 1024 * 1024)))
251
609
  fail('INPUT-INVALID', 'Invalid guard recovery bytes');
252
610
  const result = data;
253
- saved(result.state, root, id, plain(row['after'])['state'] === null);
611
+ const removal = plain(row['after'])['state'] === null;
612
+ if (hooks)
613
+ savedHooks(result.state, root, id, removal);
614
+ else
615
+ saved(result.state, root, id, removal);
254
616
  if (result.config !== null)
255
617
  plain(decodeDistributionJson(result.config));
256
618
  return result;
257
619
  };
258
- const before = side(row['before']), after = side(row['after']), actual = current(root, id);
620
+ const before = side(row['before']), after = side(row['after']), actual = { config: read(root, configPath), state: read(root, state) };
259
621
  if (![before.config, after.config].includes(actual.config) || ![before.state, after.state].includes(actual.state))
260
622
  fail('LOCAL-MODIFICATION', 'Unexpected local guard edit must be reconciled');
261
623
  const desired = actual.state === after.state ? after : before;
262
624
  write(root, configPath, desired.config);
263
- write(root, statePath(id), desired.state);
625
+ write(root, state, desired.state);
264
626
  write(root, pendingPath, null);
265
627
  return { status: 'guard-recovered' };
266
628
  }
@@ -283,18 +645,18 @@ export const FAIL_CLOSED = '"$0" "$@" || { echo "IA steward guard could not run:
283
645
  */
284
646
  export const FAIL_CLOSED_ACCEPTED = [FAIL_CLOSED, '"$0" "$@" || exit 2'];
285
647
  /**
286
- * The Node a guard handler runs when its arguments are the fixed derivation for this launcher and root: the direct form's
287
- * command (win32, and registrations made before the POSIX form), or the POSIX form's `$0` under any accepted script. Null
288
- * for any other handler.
648
+ * The Node a guard handler runs when its arguments are the fixed derivation for this launcher and root, and for `hook`
649
+ * when one is given (a `@hook`'s group, `--hook <identity>` last): the direct form's command (win32, and registrations
650
+ * made before the POSIX form), or the POSIX form's `$0` under any accepted script. Null for any other handler.
289
651
  */
290
- export function guardNode(handler, launcher, root) {
291
- const direct = json([launcher, 'guard', '--root', root]), args = handler.args;
652
+ export function guardNode(handler, launcher, root, hook) {
653
+ const fixed = [launcher, 'guard', '--root', root, ...(hook === undefined ? [] : ['--hook', hook])], direct = json(fixed), args = handler.args;
292
654
  if (!Array.isArray(args))
293
655
  return null;
294
656
  if (json(args) === direct)
295
657
  return handler.command;
296
658
  return handler.command === '/bin/sh' &&
297
- args.length === 7 &&
659
+ args.length === 3 + fixed.length &&
298
660
  args[0] === '-c' &&
299
661
  FAIL_CLOSED_ACCEPTED.includes(args[1]) &&
300
662
  json(args.slice(3)) === direct