@inventarch/cli 2.0.0 → 3.0.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 (108) hide show
  1. package/README.md +11 -3
  2. package/SPEC.md +54 -11
  3. package/assets/base/08eaab3e1a6215d78283b82a94a0228367ac7bd78d0a746c56db79c8d7546c3a.ia.tgz +0 -0
  4. package/assets/base.json +3 -3
  5. package/assets/host/d7722e32fd0511df2a6dfdf2353e621fdff1cf559d5c8b7ac256c7eceac0452f.tgz +0 -0
  6. package/assets/host.json +4 -4
  7. package/assets/vocabulary.json +11 -3
  8. package/dist/adopt.d.ts +8 -0
  9. package/dist/adopt.d.ts.map +1 -0
  10. package/dist/adopt.js +60 -0
  11. package/dist/adopt.js.map +1 -0
  12. package/dist/author.d.ts +32 -0
  13. package/dist/author.d.ts.map +1 -0
  14. package/dist/author.js +226 -0
  15. package/dist/author.js.map +1 -0
  16. package/dist/briefing.d.ts +2 -0
  17. package/dist/briefing.d.ts.map +1 -1
  18. package/dist/briefing.js +15 -3
  19. package/dist/briefing.js.map +1 -1
  20. package/dist/capture.d.ts +12 -4
  21. package/dist/capture.d.ts.map +1 -1
  22. package/dist/capture.js +33 -19
  23. package/dist/capture.js.map +1 -1
  24. package/dist/commands.d.ts +7 -7
  25. package/dist/commands.d.ts.map +1 -1
  26. package/dist/commands.js +129 -39
  27. package/dist/commands.js.map +1 -1
  28. package/dist/compile.d.ts +3 -3
  29. package/dist/compile.d.ts.map +1 -1
  30. package/dist/compile.js +9 -12
  31. package/dist/compile.js.map +1 -1
  32. package/dist/consumer.d.ts +11 -2
  33. package/dist/consumer.d.ts.map +1 -1
  34. package/dist/consumer.js +94 -18
  35. package/dist/consumer.js.map +1 -1
  36. package/dist/distribute.d.ts +6 -4
  37. package/dist/distribute.d.ts.map +1 -1
  38. package/dist/distribute.js +40 -11
  39. package/dist/distribute.js.map +1 -1
  40. package/dist/doctor-authority.d.ts +3 -0
  41. package/dist/doctor-authority.d.ts.map +1 -0
  42. package/dist/doctor-authority.js +65 -0
  43. package/dist/doctor-authority.js.map +1 -0
  44. package/dist/doctor-mounts.d.ts +4 -0
  45. package/dist/doctor-mounts.d.ts.map +1 -0
  46. package/dist/doctor-mounts.js +32 -0
  47. package/dist/doctor-mounts.js.map +1 -0
  48. package/dist/doctor.d.ts.map +1 -1
  49. package/dist/doctor.js +218 -23
  50. package/dist/doctor.js.map +1 -1
  51. package/dist/host-projection.d.ts +67 -9
  52. package/dist/host-projection.d.ts.map +1 -1
  53. package/dist/host-projection.js +401 -38
  54. package/dist/host-projection.js.map +1 -1
  55. package/dist/host.d.ts +58 -6
  56. package/dist/host.d.ts.map +1 -1
  57. package/dist/host.js +181 -45
  58. package/dist/host.js.map +1 -1
  59. package/dist/init.d.ts +18 -5
  60. package/dist/init.d.ts.map +1 -1
  61. package/dist/init.js +77 -21
  62. package/dist/init.js.map +1 -1
  63. package/dist/main.d.ts +1 -6
  64. package/dist/main.d.ts.map +1 -1
  65. package/dist/main.js +1 -6
  66. package/dist/main.js.map +1 -1
  67. package/dist/next.d.ts +1 -1
  68. package/dist/next.d.ts.map +1 -1
  69. package/dist/next.js +14 -8
  70. package/dist/next.js.map +1 -1
  71. package/dist/operation-help.js +1 -1
  72. package/dist/position.d.ts +1 -1
  73. package/dist/position.d.ts.map +1 -1
  74. package/dist/position.js +10 -8
  75. package/dist/position.js.map +1 -1
  76. package/dist/preview.d.ts +145 -0
  77. package/dist/preview.d.ts.map +1 -0
  78. package/dist/preview.js +962 -0
  79. package/dist/preview.js.map +1 -0
  80. package/dist/profile.d.ts +118 -0
  81. package/dist/profile.d.ts.map +1 -0
  82. package/dist/profile.js +362 -0
  83. package/dist/profile.js.map +1 -0
  84. package/dist/project.d.ts +8 -5
  85. package/dist/project.d.ts.map +1 -1
  86. package/dist/project.js +47 -16
  87. package/dist/project.js.map +1 -1
  88. package/dist/read.d.ts.map +1 -1
  89. package/dist/read.js +3 -0
  90. package/dist/read.js.map +1 -1
  91. package/dist/render.d.ts +16 -2
  92. package/dist/render.d.ts.map +1 -1
  93. package/dist/render.js +156 -5
  94. package/dist/render.js.map +1 -1
  95. package/dist/session.d.ts +31 -10
  96. package/dist/session.d.ts.map +1 -1
  97. package/dist/session.js +31 -3
  98. package/dist/session.js.map +1 -1
  99. package/dist/user-host.d.ts +3 -3
  100. package/dist/user-host.js +10 -10
  101. package/dist/user-host.js.map +1 -1
  102. package/dist/validate.d.ts +28 -16
  103. package/dist/validate.d.ts.map +1 -1
  104. package/dist/validate.js +245 -23
  105. package/dist/validate.js.map +1 -1
  106. package/package.json +6 -6
  107. package/assets/base/0305ca741b1dfec97ff35fbeb36d4a66a0c9c0614b730fe14fcdac0f1565e28a.ia.tgz +0 -0
  108. package/assets/host/3d2c8530db8d14755410b17be8228a230d88de96f9dc78f953979d3ca7c6ea62.tgz +0 -0
@@ -6,23 +6,31 @@
6
6
  * the command catalog this CLI tags (`packetCatalog`). One render feeds `ia host`, `ia doctor`'s projection rows and the
7
7
  * install/update/remove refresh, so no two of them can disagree about what the projection should contain.
8
8
  *
9
- * `applyHostProjection` is the only writer of projection files. Before any of them changes it retires a steward-guard
10
- * registration an earlier release made (B11): with no per-system steward agent left to satisfy it, the guard would deny
11
- * every edit under `.ia/src/systems/<name>/`, so it stays retired until milestone generation-binding re-keys it to
12
- * `@mandate` scope (task generation-hook-governance). It then applies the planned files through
13
- * `@inventarch/distribution/projection`, which deletes the owned 1.x steward files and leaves foreign ones (B9), and
14
- * writes the receipt beside the projection state (B12).
9
+ * Milestone generation-binding task host-consumes-generated-set (plan amendments C4, C5, C9 and C12): the render also
10
+ * holds the host set workspace-runtime generates from the workspace's authored records, computed once
11
+ * (`generateHostSet`): the agent and skill files beside the packet's, the `@hook` declarations whose groups the writer
12
+ * registers, the operation and harness definitions, and a row for each authored record the host does not take.
13
+ *
14
+ * `applyHostProjection` is the only writer of projection files and hook groups. Before any file changes it retires a
15
+ * steward-guard registration an earlier release made (B11), then registers the hook groups of the authored `@hook`
16
+ * records (distribution's guard-registration, owned by exact match through their own state), then applies the planned
17
+ * files through `@inventarch/distribution/projection`, which owns packet and generated files alike through the
18
+ * projection state, deletes the owned 1.x steward files and obsolete generated files and leaves foreign ones (B9), and
19
+ * writes the receipt beside the projection state last (B12). Ownership is the states', never the receipt's.
15
20
  */
16
21
  import { accessSync, closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readFileSync, } from 'node:fs';
17
- import { resolve } from 'node:path';
22
+ import { join, resolve } from 'node:path';
23
+ import { pathKey } from '@inventarch/db';
18
24
  import { renderHost, renderPacket, PACKET_MARKER } from '@inventarch/runtime';
19
- import { applyGuardRegistration, assertRetirableGuard, planGuardRegistration, } from '@inventarch/distribution/guard-registration';
20
- import { acquireHostRegistrationLock, assertHostRegistrationIdle, HOST_REGISTRATION, } from '@inventarch/distribution/host';
21
- import { applyProjection, planProjection } from '@inventarch/distribution/projection';
25
+ import { ProjectionError } from '@inventarch/workspace-runtime/projections';
26
+ import { generateHostSet } from '@inventarch/workspace-runtime/internal/generate';
27
+ import { applyGuardRegistration, applyHookRegistration, assertRetirableGuard, assertRemovableHooks, hookGroupDigest, hooksDisabledBy, planGuardRegistration, planHookRegistration, planHooksFor, observeHookRegistration, readHookRegistration, } from '@inventarch/distribution/guard-registration';
28
+ import { acquireHostRegistrationLock, assertHostRegistrationIdle, HOST_REGISTRATION, verifyHostCache, } from '@inventarch/distribution/host';
29
+ import { applyProjection, planProjection, projectionOwnable } from '@inventarch/distribution/projection';
22
30
  import { DistributionError, json, readWorkspaceFile, readWorkspaceJson, replace, sha256, } from '@inventarch/distribution/services';
23
31
  import { packetCatalog } from './commands.js';
24
32
  import { Refusal } from './consumer.js';
25
- import { refusedPath, SETTINGS, STATE } from './host.js';
33
+ import { refusedPath, SETTINGS, skillFolderOf, STATE } from './host.js';
26
34
  import { codeOf, openSession } from './session.js';
27
35
  /** This CLI's id@version, which the receipt records and only the applying CLI knows (design item 12). */
28
36
  const CLI = `@inventarch/cli@${JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version}`;
@@ -34,31 +42,203 @@ function requireAdmitted(session, root) {
34
42
  if (session.admission().status !== 'admitted')
35
43
  throw new Refusal('IA-CLI-CONFLICT', 'The workspace does not admit; host registration needs a workspace with zero error findings', 3, { path: root }, 'Run "ia validate" and fix the reported errors.');
36
44
  }
37
- /** §4's admission gate alone, for a removal, which renders nothing. */
38
- export function checkAdmitted(root) {
45
+ /**
46
+ * A host-generation refusal (workspace-runtime's ProjectionError, which carries its code in `diagnostic`) as this CLI's
47
+ * refusal: its IA-PROJECTION-* code and message, located at the workspace, naming the command that shows the records.
48
+ * Generation reports a record it cannot render as an unsupported row, so this is a refusal of the whole render.
49
+ */
50
+ function generationRefusal(error, root) {
51
+ if (!(error instanceof ProjectionError))
52
+ return error;
53
+ return new Refusal(error.diagnostic.code, error.diagnostic.message, 3, { path: root }, 'Correct the record the message names, then run "ia validate".');
54
+ }
55
+ /**
56
+ * §6.1: the packet over the whole workspace, through the session's own scope, rendered by `host`'s adapter for the
57
+ * consumer target, and the host set generated from the workspace's authored records through the same scope: the
58
+ * packet's files, then the generated agent and skill files, each carrying `PACKET_MARKER`; the `@hook` declarations
59
+ * (`hooks`, claude only); and the receipt the render fills (B12), whose `files` list every file with its SHA-256,
60
+ * `generated` the generated ones with their records, `definitions` the operation and harness definitions and
61
+ * `unsupported` each authored record the host does not take. Its `hooks` rows are the applying caller's. `gate`, when given,
62
+ * judges the session before anything is read from it (review C2-N3).
63
+ */
64
+ export function renderProjectionFor(root, host, gate) {
39
65
  const session = openSession(root);
40
66
  try {
67
+ gate?.(session);
41
68
  requireAdmitted(session, root);
69
+ const within = session.reader.resolveScope().token;
70
+ const { packet, digest, hostNote } = renderPacket(session.reader, within, packetCatalog());
71
+ const output = renderHost(host, packet, digest, hostNote, 'consumer');
72
+ let set;
73
+ try {
74
+ set = generateHostSet(session.reader, within, host);
75
+ }
76
+ catch (error) {
77
+ throw generationRefusal(error, root);
78
+ }
79
+ const generated = set.files.map(({ identity, word, path, text }) => ({
80
+ identity,
81
+ word,
82
+ path,
83
+ sha256: sha256(text),
84
+ }));
85
+ return Object.freeze({
86
+ files: Object.freeze([...output.files, ...set.files.map(({ path, text }) => Object.freeze({ path, text }))]),
87
+ receipt: Object.freeze({
88
+ ...output.receipt,
89
+ files: Object.freeze([...output.receipt.files, ...generated.map(({ path, sha256 }) => ({ path, sha256 }))]),
90
+ generated: Object.freeze(generated),
91
+ definitions: set.definitions,
92
+ unsupported: set.unsupported,
93
+ }),
94
+ hooks: set.hooks,
95
+ });
42
96
  }
43
97
  finally {
44
98
  session.close();
45
99
  }
46
100
  }
47
101
  /**
48
- * §6.1: the packet over the whole workspace, through the session's own scope, rendered by `host`'s adapter for the
49
- * consumer target: its files, each carrying `PACKET_MARKER`, and the receipt the render fills (B12). No agent file is
50
- * rendered for any host.
102
+ * Why an obsolete owned group is still in the settings (review finding F1): with hooks disabled, the groups kept beside it
103
+ * are re-planned against the payload they were registered against, and that payload is gone.
51
104
  */
52
- export function renderProjectionFor(root, host) {
53
- const session = openSession(root);
54
- try {
55
- requireAdmitted(session, root);
56
- const { packet, digest, hostNote } = renderPacket(session.reader, session.reader.resolveScope().token, packetCatalog());
57
- return renderHost(host, packet, digest, hostNote, 'consumer');
105
+ export const HOOK_KEPT = 'Kept: no registrable hook claims this group any more, but it stays until hooks are back on or the payload it was registered against is materialized again';
106
+ /**
107
+ * The records a host does not take, one row per identity (review finding N3): generation's rows, then the hook step's;
108
+ * where both report an identity (an unsupported authored hook whose group is kept), one row carries both reasons.
109
+ */
110
+ export function notTaken(generated, step) {
111
+ const rows = new Map(generated.map((row) => [`${row.word} ${row.identity}`, row]));
112
+ for (const row of step) {
113
+ const key = `${row.word} ${row.identity}`, first = rows.get(key);
114
+ rows.set(key, first === undefined ? row : { ...first, reason: `${first.reason}; ${row.reason}` });
58
115
  }
59
- finally {
60
- session.close();
116
+ return [...rows.values()];
117
+ }
118
+ /** Why a declared hook is not registered when no host payload is known: `ia host` materializes one. */
119
+ export const HOOKS_NEED_HOST = 'Not registered: a hook group runs the guard in the host payload "ia host claude --apply" materializes; run it to register this hook';
120
+ /**
121
+ * The hook groups `rendered` declares, planned for `host` (claude only; Codex hooks are unsupported, C12): with no
122
+ * declared hook, the removal of every owned group; else their registration against `cache`, or against the payload the
123
+ * owned registration recorded; with neither, none, and each declared hook comes back unregistered. A removal
124
+ * (`rendered` null) removes every owned group. Reads only.
125
+ */
126
+ export function planHooks(root, host, rendered, cache) {
127
+ if (host !== 'claude')
128
+ return { plan: null, unregistered: [] };
129
+ if (rendered === null)
130
+ assertRemovableHooks(root);
131
+ const rows = (rendered?.hooks ?? []).map(({ identity, tools, paths }) => ({ identity, tools, paths }));
132
+ const prior = readHookRegistration(root);
133
+ if (rows.length === 0)
134
+ return {
135
+ plan: prior === null ? null : planHookRegistration(root, { remove: HOST_REGISTRATION }),
136
+ unregistered: [],
137
+ };
138
+ // Hooks turned off by disableAllHooks: no group is registered, each declared hook is reported, and every other part of
139
+ // the host applies as it does without hooks (review finding H-N12). Groups already owned stay as they are.
140
+ const disabled = hooksDisabledBy(root);
141
+ if (disabled !== null) {
142
+ // Review finding A-F1: a group owned for a hook still declared stays as registered, and is no unsupported row; an
143
+ // obsolete owned group is removed; a hook with no group is reported, naming the file.
144
+ const owned = new Map((prior?.groups ?? []).map((group) => [group.hook, group.paths])), declared = new Set(rows.map((row) => row.identity));
145
+ // A group changed or duplicated by hand refuses, and so does one deleted by hand whose hook is still declared, as
146
+ // with hooks on (H-R1); a deleted group of a hook no longer declared only loses its ownership (review finding N4).
147
+ const drift = prior === null ? [] : observeHookRegistration(root);
148
+ const handEditedRow = drift.find((row) => row.drift === 'modified' || (row.drift === 'missing' && declared.has(row.hook)));
149
+ if (handEditedRow !== undefined)
150
+ throw handEdited(handEditedRow);
151
+ const gone = new Set(drift.filter((row) => row.drift === 'missing').map((row) => row.hook));
152
+ const kept = rows
153
+ .filter((row) => owned.has(row.identity))
154
+ .map((row) => ({ ...row, paths: owned.get(row.identity) }));
155
+ const unregistered = rows
156
+ .filter((row) => !owned.has(row.identity))
157
+ .map((row) => ({
158
+ identity: row.identity,
159
+ word: 'hook',
160
+ reason: `Not registered: hooks are disabled by disableAllHooks in ${disabled}`,
161
+ }));
162
+ if (prior === null || kept.length === owned.size)
163
+ return { plan: null, unregistered };
164
+ if (kept.length === 0)
165
+ return { plan: planHookRegistration(root, { remove: HOST_REGISTRATION }), unregistered };
166
+ // The kept groups are re-planned as recorded, so nothing is written for them. That needs the payload they were
167
+ // registered against: the one this apply materializes when it is that payload (review finding N1, so a plan and its
168
+ // apply agree), else the recorded one, which must still verify. Without it nothing is planned: the obsolete groups
169
+ // stay, reported as kept rather than listed as registered, and a group already deleted by hand is no kept group but
170
+ // stays owned until such a plan runs (review finding F1), which doctor reports as a missing group.
171
+ // The same directory is the same payload however its path is spelled (review finding F2: an IA_HOST_HOME in another
172
+ // letter case), compared as the volume compares names; the kept groups are planned against the recorded spelling, so
173
+ // their bytes are the ones registered and the dry run and the apply agree.
174
+ const given = cache === null ? undefined : 'expected' in cache ? cache.expected.directory : cache.verified;
175
+ if (cache !== null && given !== undefined && pathKey(resolve(given)) === pathKey(resolve(prior.cache)))
176
+ return {
177
+ plan: 'expected' in cache
178
+ ? planHooksFor(root, { ...cache.expected, directory: prior.cache, launcher: join(prior.cache, 'scripts/ia.mjs') }, kept)
179
+ : planHookRegistration(root, { cache: prior.cache, hooks: kept }),
180
+ unregistered,
181
+ };
182
+ try {
183
+ verifyHostCache(prior.cache);
184
+ }
185
+ catch {
186
+ return {
187
+ plan: null,
188
+ unregistered: [
189
+ ...unregistered,
190
+ ...[...owned.keys()]
191
+ .filter((hook) => !declared.has(hook) && !gone.has(hook))
192
+ .map((hook) => ({ identity: hook, word: 'hook', reason: HOOK_KEPT })),
193
+ ],
194
+ };
195
+ }
196
+ return { plan: planHookRegistration(root, { cache: prior.cache, hooks: kept }), unregistered };
197
+ }
198
+ if (cache !== null && 'expected' in cache)
199
+ return { plan: planHooksFor(root, cache.expected, rows), unregistered: [] };
200
+ const directory = cache?.verified ?? prior?.cache;
201
+ if (directory === undefined)
202
+ return {
203
+ plan: null,
204
+ unregistered: rows.map((row) => ({ identity: row.identity, word: 'hook', reason: HOOKS_NEED_HOST })),
205
+ };
206
+ if (cache === null && prior !== null) {
207
+ // Against the payload the registration recorded (review finding H-R4): with the same hooks and selections owned,
208
+ // nothing is written and that payload is not read, so its absence never blocks an unrelated apply; a change needs it,
209
+ // and a payload gone or changed refuses there, naming `ia host`, which materializes one and registers against it.
210
+ const owned = new Map(prior.groups.map((group) => [group.hook, json(group.paths)]));
211
+ if (owned.size === rows.length && rows.every((row) => owned.get(row.identity) === json(row.paths))) {
212
+ // Still a group deleted, changed or duplicated by hand refuses, as a registration would (H-R1, H-R3).
213
+ const drift = observeHookRegistration(root).find((row) => row.drift !== 'foreign');
214
+ if (drift !== undefined)
215
+ throw handEdited(drift);
216
+ return { plan: null, unregistered: [] };
217
+ }
218
+ try {
219
+ verifyHostCache(directory);
220
+ }
221
+ catch (error) {
222
+ throw Object.assign(new DistributionError(codeOf(error, 'IA-DIST-ARTIFACT-UNAVAILABLE'), `The host payload the hook registration recorded cannot be used: ${error instanceof Error ? error.message : String(error)}`, directory), { hookRefusal: { payload: directory } });
223
+ }
61
224
  }
225
+ return { plan: planHookRegistration(root, { cache: directory, hooks: rows }), unregistered: [] };
226
+ }
227
+ /**
228
+ * The hook groups the workspace owns now, as a receipt lists them: one row per `@hook`, keyed by identity, with the
229
+ * tools the hook declares (every group matches every edit tool, so its matcher does not say them) and the group's digest.
230
+ */
231
+ function hookRows(root, declared) {
232
+ const tools = new Map(declared.map((hook) => [hook.identity, hook.tools]));
233
+ // Only the groups of declared hooks are registered ones: an obsolete group kept while hooks are disabled is reported
234
+ // as kept instead (review finding F1).
235
+ return (readHookRegistration(root)?.groups ?? [])
236
+ .filter(({ hook }) => tools.has(hook))
237
+ .map(({ hook, group }) => ({
238
+ identity: hook,
239
+ tools: [...tools.get(hook)],
240
+ sha256: hookGroupDigest(group),
241
+ }));
62
242
  }
63
243
  /**
64
244
  * B11: whether this workspace holds a steward-guard registration an earlier release made, which the projection apply
@@ -167,6 +347,13 @@ export function preflightReceipt(root, host) {
167
347
  readPending(root, host);
168
348
  }
169
349
  const pendingPath = (host) => `.ia/distributions/hosts/${host}-receipt-pending.json`;
350
+ /** Rows `{identity, sha256}` of removed hook groups, each identity once. */
351
+ const hookDigests = (value) => Array.isArray(value) &&
352
+ value.every((row) => row !== null &&
353
+ typeof row === 'object' &&
354
+ typeof row.identity === 'string' &&
355
+ HEX.test(String(row.sha256))) &&
356
+ new Set(value.map((row) => row.identity)).size === value.length;
170
357
  function readPending(root, host) {
171
358
  const path = pendingPath(host);
172
359
  if (!existsSync(resolve(root, path)))
@@ -186,16 +373,18 @@ function readPending(root, host) {
186
373
  value.host !== host ||
187
374
  typeof value.guard !== 'boolean' ||
188
375
  !digests(value.removed) ||
189
- value.removed.some((file) => !/^\.claude\/agents\/[a-z][a-z0-9-]*\.md$/.test(file.path) &&
190
- ![
191
- '.claude/rules/ia-workspace.md',
192
- '.claude/skills/ia-authoring/SKILL.md',
193
- 'AGENTS.md',
194
- '.agents/skills/ia-authoring/SKILL.md',
195
- ].includes(file.path)) ||
376
+ value.removed.some((file) => !projectionOwnable(host, file.path)) ||
196
377
  (value.receipt !== undefined && !HEX.test(value.receipt)) ||
378
+ (value.removedHooks !== undefined && (!hookDigests(value.removedHooks) || value.removedHooks.length === 0)) ||
197
379
  Object.keys(body).sort().join(',') !==
198
- (value.receipt === undefined ? 'format,guard,host,removed' : 'format,guard,host,receipt,removed') ||
380
+ [
381
+ 'format',
382
+ 'guard',
383
+ 'host',
384
+ ...(value.receipt === undefined ? [] : ['receipt']),
385
+ 'removed',
386
+ ...(value.removedHooks === undefined ? [] : ['removedHooks']),
387
+ ].join(',') ||
199
388
  digest !== sha256(json(body)))
200
389
  throw new DistributionError('IA-DIST-INPUT-INVALID', 'Invalid pending projection receipt evidence', path);
201
390
  // The receipt committed but a kill left the pending cleanup undone: that was a successful last apply.
@@ -206,7 +395,7 @@ function readPending(root, host) {
206
395
  return body;
207
396
  }
208
397
  /** Verified deletion provenance shared by projection apply and a migration's durable effect plan. */
209
- export function projectionEvidence(root, host, actions, retirement, previous) {
398
+ export function projectionEvidence(root, host, actions, retirement, previous, hookRemovals = []) {
210
399
  if (previous !== undefined &&
211
400
  (JSON.stringify(readReceipt(root, host)) !== JSON.stringify(previous) ||
212
401
  !previous.files.every((file) => sha256(readWorkspaceFile({ root, path: file.path })) === file.sha256) ||
@@ -216,17 +405,32 @@ export function projectionEvidence(root, host, actions, retirement, previous) {
216
405
  ? [{ path: action.path, sha256: sha256(readWorkspaceFile({ root, path: action.path })) }]
217
406
  : []);
218
407
  const pending = readPending(root, host);
219
- const prior = pending ?? (previous === undefined ? null : { guard: previous.guard === 'retired', removed: previous.removed });
408
+ const prior = pending ??
409
+ (previous === undefined
410
+ ? null
411
+ : {
412
+ guard: previous.guard === 'retired',
413
+ removed: previous.removed,
414
+ ...(previous.removedHooks === undefined ? {} : { removedHooks: previous.removedHooks }),
415
+ });
220
416
  for (const file of removed) {
221
417
  const recorded = prior?.removed.find((row) => row.path === file.path);
222
418
  if (recorded !== undefined && recorded.sha256 !== file.sha256)
223
419
  throw new DistributionError('IA-DIST-LOCAL-MODIFICATION', 'Pending removal evidence differs from the current owned bytes', file.path);
224
420
  }
421
+ // A hook group an interrupted earlier apply removed stays listed with the digest it recorded then (H-R5).
422
+ const removedHooks = [
423
+ ...new Map([...hookRemovals, ...(prior?.removedHooks ?? [])].map((row) => [
424
+ row.identity,
425
+ { identity: row.identity, sha256: row.sha256 },
426
+ ])).values(),
427
+ ].sort((a, b) => (a.identity < b.identity ? -1 : a.identity > b.identity ? 1 : 0));
225
428
  return {
226
429
  format: 'ia.packet-receipt-pending.v1',
227
430
  host,
228
431
  guard: prior?.guard === true || retirement,
229
432
  removed: [...new Map([...(prior?.removed ?? []), ...removed].map((file) => [file.path, file])).values()],
433
+ ...(removedHooks.length === 0 ? {} : { removedHooks }),
230
434
  };
231
435
  }
232
436
  /**
@@ -244,10 +448,10 @@ export function projectionEvidence(root, host, actions, retirement, previous) {
244
448
  * interruption test cuts. A migration may supply its verified previous receipt to refresh host notes while retaining
245
449
  * that operation's retirement and deletion evidence; ordinary applies omit it and keep last-apply semantics.
246
450
  */
247
- export function applyHostProjection(root, host, rendered, checkpoint = () => { }, previous) {
451
+ export function applyHostProjection(root, host, rendered, checkpoint = () => { }, previous, cache = null) {
248
452
  // A pending host journal refuses every host write, as it refuses the plan (§8).
249
453
  assertHostRegistrationIdle(root);
250
- const retirement = planRetirement(root, host), plan = planFiles(root, host, rendered);
454
+ const retirement = planRetirement(root, host), hooks = planHookStep(root, host, rendered, cache), plan = planFiles(root, host, rendered);
251
455
  const writeEvidence = (path, value) => {
252
456
  const unlock = acquireHostRegistrationLock(root);
253
457
  try {
@@ -257,16 +461,30 @@ export function applyHostProjection(root, host, rendered, checkpoint = () => { }
257
461
  unlock();
258
462
  }
259
463
  };
260
- const evidence = projectionEvidence(root, host, plan.actions, retirement !== null, previous);
464
+ // The groups this apply removes, each with the digest the ownership state recorded for it (H-R5).
465
+ const recorded = new Map((readHookRegistration(root)?.groups ?? []).map((row) => [row.hook, hookGroupDigest(row.group)]));
466
+ const hookRemovals = (hooks.plan?.hooks ?? [])
467
+ .filter((row) => row.action === 'remove' && recorded.has(row.hook))
468
+ .map((row) => ({ identity: row.hook, sha256: recorded.get(row.hook) }));
469
+ const evidence = projectionEvidence(root, host, plan.actions, retirement !== null, previous, hookRemovals);
261
470
  // Evidence precedes retirement and every deletion; it survives failure and the projection state's collapse.
262
471
  writeEvidence(pendingPath(host), { ...evidence, digest: sha256(json(evidence)) });
263
472
  checkpoint('evidence');
264
473
  if (retirement !== null)
265
474
  applyGuardRegistration(retirement);
266
475
  checkpoint('guard');
476
+ // The hook groups next, through their own journal and lock; a plan that changes nothing writes nothing. A retirement
477
+ // rewrote the settings the first plan read, so the groups are planned again against what it left: the first plan
478
+ // only refused, before anything was written, what this one would.
479
+ const registration = retirement === null ? hooks : planHookStep(root, host, rendered, cache);
480
+ if (registration.plan !== null)
481
+ applyHookRegistration(registration.plan);
482
+ checkpoint('hooks');
267
483
  // The last apply's receipt goes before any projection file changes (B12).
268
484
  writeEvidence(STATE.receipt(host), null);
269
485
  const result = applyProjection(plan, checkpoint), guard = evidence.guard ? 'retired' : 'none';
486
+ // The groups owned now, and those removed: this apply's and an interrupted earlier one's, not registered again (H-R5).
487
+ const owned = host === 'claude' && rendered !== null ? hookRows(root, rendered.hooks ?? []) : [], registered = new Set(owned.map((row) => row.identity));
270
488
  const receipt = rendered === null
271
489
  ? null
272
490
  : {
@@ -275,6 +493,16 @@ export function applyHostProjection(root, host, rendered, checkpoint = () => { }
275
493
  removed: evidence.removed.filter((file) => !existsSync(resolve(root, file.path))),
276
494
  foreign: plan.actions.filter((action) => action.action === 'foreign').map((action) => action.path),
277
495
  guard,
496
+ ...(host === 'claude'
497
+ ? {
498
+ hooks: owned,
499
+ removedHooks: (evidence.removedHooks ?? []).filter((row) => !registered.has(row.identity)),
500
+ }
501
+ : {}),
502
+ ...(rendered.receipt.definitions === undefined
503
+ ? {}
504
+ : { definitions: appliedDefinitions(rendered.receipt.definitions, rendered.receipt.files, registered) }),
505
+ unsupported: notTaken(rendered.receipt.unsupported ?? [], registration.unregistered),
278
506
  writtenAt: new Date().toISOString(),
279
507
  };
280
508
  if (receipt !== null) {
@@ -290,6 +518,127 @@ export function applyHostProjection(root, host, rendered, checkpoint = () => { }
290
518
  receipt,
291
519
  };
292
520
  }
521
+ /**
522
+ * The definitions as this apply left them (review finding H-R7): each harness registers only the agent and skill files
523
+ * the receipt lists and the hook groups the workspace owns after the apply, so a hook an apply did not register (no host
524
+ * payload known, or disabled hooks) is never listed as registered.
525
+ */
526
+ function appliedDefinitions(definitions, files, registered) {
527
+ const written = new Set(files.map((file) => file.path));
528
+ return definitions.map((row) => row.word !== 'harness'
529
+ ? row
530
+ : {
531
+ ...row,
532
+ definition: {
533
+ ...row.definition,
534
+ registrations: {
535
+ agents: row.definition.registrations.agents.filter((agent) => written.has(agent.path)),
536
+ skills: row.definition.registrations.skills.filter((skill) => written.has(skill.path)),
537
+ hooks: row.definition.registrations.hooks.filter((hook) => registered.has(hook.identity)),
538
+ },
539
+ },
540
+ });
541
+ }
542
+ /** `planHooks`, a refusal it does not locate at a file located at the settings the hook groups live in. */
543
+ export function planHookStep(root, host, rendered, cache) {
544
+ try {
545
+ return planHooks(root, host, rendered, cache);
546
+ }
547
+ catch (error) {
548
+ if (error instanceof DistributionError && 'unownedHook' in error) {
549
+ const unowned = error.unownedHook;
550
+ throw Object.assign(error, {
551
+ hookRefusal: { drift: 'foreign', hook: unowned.hook, path: unowned.path },
552
+ });
553
+ }
554
+ const code = codeOf(error, '');
555
+ if (error instanceof Error &&
556
+ /^IA-/.test(code) &&
557
+ code !== 'IA-DIST-RECOVERY-REQUIRED' &&
558
+ refusedPath(error) === null) {
559
+ const located = new DistributionError(code, error.message, SETTINGS), hookRefusal = code === 'IA-DIST-LOCAL-MODIFICATION' ? handEditedGroup(root) : undefined;
560
+ throw hookRefusal === undefined ? located : Object.assign(located, { hookRefusal });
561
+ }
562
+ throw error;
563
+ }
564
+ }
565
+ /** An owned hook group's drift as the hook planner refuses it, with the planner's own wording (guard review G-N2). */
566
+ function handEdited(drift) {
567
+ return new DistributionError('IA-DIST-LOCAL-MODIFICATION', drift.drift === 'missing'
568
+ ? `Owned hook group for ${drift.hook} was deleted by hand; remove the registration ("ia host claude --remove --apply") and register it again`
569
+ : `Owned hook group for ${drift.hook} changed or was duplicated; delete only that group from ${SETTINGS}, then remove the registration ("ia host claude --remove --apply") and register it again`);
570
+ }
571
+ /**
572
+ * What the hook step of a later apply would refuse, found before anything is written (review finding H-R3): an install,
573
+ * update or remove checks it before its first install write, and a migration before it plans. With a hook registration
574
+ * owned, the step is planned against the workspace's current records when they render: a group deleted, changed or
575
+ * duplicated by hand refuses with the recovery doctor names, and so does a recorded payload a change of hooks would need.
576
+ * When the records do not render, only a changed or duplicated group is refused, since a removal refuses it too.
577
+ */
578
+ export function preflightHooks(root, host, given) {
579
+ if (host !== 'claude' || readHookRegistration(root) === null)
580
+ return;
581
+ let rendered;
582
+ try {
583
+ rendered = given === undefined ? renderProjectionFor(root, host) : given;
584
+ }
585
+ catch {
586
+ // Records that do not render refuse the refresh itself, with their own next action.
587
+ rendered = null;
588
+ }
589
+ if (rendered !== null) {
590
+ planHookStep(root, host, rendered, null);
591
+ return;
592
+ }
593
+ const changed = observeHookRegistration(root).find((row) => row.drift === 'modified');
594
+ if (changed !== undefined)
595
+ throw Object.assign(new DistributionError('IA-DIST-LOCAL-MODIFICATION', handEdited(changed).message, SETTINGS), {
596
+ hookRefusal: { drift: 'modified', hook: changed.hook },
597
+ });
598
+ }
599
+ /**
600
+ * What a refresh's file plan would refuse, and its hook step, found before an install, update or remove writes anything
601
+ * (review finding F4, the H-R3 class): the files are planned against the current records, rendered once, so a generated
602
+ * skill refused at a populated folder of the user's refuses here (any other file refusal is left to the refresh, as
603
+ * before); then `preflightHooks` runs on the same render.
604
+ */
605
+ export function preflightProjection(root, host) {
606
+ let rendered;
607
+ try {
608
+ rendered = renderProjectionFor(root, host);
609
+ }
610
+ catch {
611
+ // Records that do not render refuse the refresh itself, with their own next action.
612
+ rendered = null;
613
+ }
614
+ // Only the populated skill folder refuses here: every other file refusal stays the refresh's after the install
615
+ // commits, naming the applied install (host registration §6.3), as before.
616
+ if (rendered !== null)
617
+ try {
618
+ planFiles(root, host, rendered);
619
+ }
620
+ catch (error) {
621
+ if (skillFolderOf(error) !== undefined)
622
+ throw error;
623
+ }
624
+ preflightHooks(root, host, rendered);
625
+ }
626
+ /**
627
+ * The owned hook group a hook-registration refusal concerns, by its drift (review finding H-R1), so the refusal names the
628
+ * recovery `hookRepair` words: a changed or duplicated group first, else a deleted one. Undefined when no owned group
629
+ * drifted (an unmanaged identical one), which the settings repair covers.
630
+ */
631
+ function handEditedGroup(root) {
632
+ let drift;
633
+ try {
634
+ drift = observeHookRegistration(root);
635
+ }
636
+ catch {
637
+ return undefined;
638
+ }
639
+ const found = drift.find((row) => row.drift === 'modified') ?? drift.find((row) => row.drift === 'missing');
640
+ return found === undefined ? undefined : { drift: found.drift, hook: found.hook };
641
+ }
293
642
  const HEX = /^[a-f0-9]{64}$/;
294
643
  const digests = (value) => Array.isArray(value) &&
295
644
  value.every((row) => row !== null &&
@@ -324,7 +673,21 @@ export function readReceipt(root, host) {
324
673
  !digests(row.files) ||
325
674
  !digests(row.removed) ||
326
675
  !Array.isArray(row.foreign) ||
327
- !row.foreign.every((item) => typeof item === 'string'))
676
+ !row.foreign.every((item) => typeof item === 'string') ||
677
+ (row.generated !== undefined &&
678
+ (!digests(row.generated) ||
679
+ !row.generated.every((item) => typeof item.identity === 'string' &&
680
+ ['agent-profile', 'playbook'].includes(String(item.word))))) ||
681
+ (row.hooks !== undefined &&
682
+ (!Array.isArray(row.hooks) ||
683
+ !row.hooks.every((item) => item !== null &&
684
+ typeof item === 'object' &&
685
+ typeof item.identity === 'string' &&
686
+ Array.isArray(item.tools) &&
687
+ HEX.test(String(item.sha256))))) ||
688
+ (row.removedHooks !== undefined && !hookDigests(row.removedHooks)) ||
689
+ (row.unsupported !== undefined && !Array.isArray(row.unsupported)) ||
690
+ (row.definitions !== undefined && !Array.isArray(row.definitions)))
328
691
  throw new DistributionError('IA-DIST-INPUT-INVALID', 'Invalid projection receipt', path);
329
692
  return row;
330
693
  }