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