@inventarch/cli 1.2.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 (125) hide show
  1. package/README.md +20 -5
  2. package/SPEC.md +86 -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/bundled-base.d.ts +18 -0
  21. package/dist/bundled-base.d.ts.map +1 -0
  22. package/dist/bundled-base.js +44 -0
  23. package/dist/bundled-base.js.map +1 -0
  24. package/dist/capture.d.ts +41 -6
  25. package/dist/capture.d.ts.map +1 -1
  26. package/dist/capture.js +132 -43
  27. package/dist/capture.js.map +1 -1
  28. package/dist/commands.d.ts +30 -8
  29. package/dist/commands.d.ts.map +1 -1
  30. package/dist/commands.js +287 -35
  31. package/dist/commands.js.map +1 -1
  32. package/dist/compile.d.ts +3 -4
  33. package/dist/compile.d.ts.map +1 -1
  34. package/dist/compile.js +28 -72
  35. package/dist/compile.js.map +1 -1
  36. package/dist/consumer.d.ts +11 -2
  37. package/dist/consumer.d.ts.map +1 -1
  38. package/dist/consumer.js +103 -20
  39. package/dist/consumer.js.map +1 -1
  40. package/dist/distribute.d.ts +30 -8
  41. package/dist/distribute.d.ts.map +1 -1
  42. package/dist/distribute.js +112 -60
  43. package/dist/distribute.js.map +1 -1
  44. package/dist/doctor-authority.d.ts +3 -0
  45. package/dist/doctor-authority.d.ts.map +1 -0
  46. package/dist/doctor-authority.js +65 -0
  47. package/dist/doctor-authority.js.map +1 -0
  48. package/dist/doctor-mounts.d.ts +4 -0
  49. package/dist/doctor-mounts.d.ts.map +1 -0
  50. package/dist/doctor-mounts.js +32 -0
  51. package/dist/doctor-mounts.js.map +1 -0
  52. package/dist/doctor.d.ts.map +1 -1
  53. package/dist/doctor.js +327 -79
  54. package/dist/doctor.js.map +1 -1
  55. package/dist/format.d.ts.map +1 -1
  56. package/dist/format.js +2 -1
  57. package/dist/format.js.map +1 -1
  58. package/dist/host-projection.d.ts +131 -6
  59. package/dist/host-projection.d.ts.map +1 -1
  60. package/dist/host-projection.js +663 -42
  61. package/dist/host-projection.js.map +1 -1
  62. package/dist/host.d.ts +154 -32
  63. package/dist/host.d.ts.map +1 -1
  64. package/dist/host.js +393 -142
  65. package/dist/host.js.map +1 -1
  66. package/dist/init.d.ts +296 -38
  67. package/dist/init.d.ts.map +1 -1
  68. package/dist/init.js +1303 -203
  69. package/dist/init.js.map +1 -1
  70. package/dist/main.d.ts +1 -6
  71. package/dist/main.d.ts.map +1 -1
  72. package/dist/main.js +4 -7
  73. package/dist/main.js.map +1 -1
  74. package/dist/migration-journal.d.ts +35 -0
  75. package/dist/migration-journal.d.ts.map +1 -0
  76. package/dist/migration-journal.js +205 -0
  77. package/dist/migration-journal.js.map +1 -0
  78. package/dist/next.d.ts +21 -0
  79. package/dist/next.d.ts.map +1 -0
  80. package/dist/next.js +216 -0
  81. package/dist/next.js.map +1 -0
  82. package/dist/operation-help.d.ts.map +1 -1
  83. package/dist/operation-help.js +15 -4
  84. package/dist/operation-help.js.map +1 -1
  85. package/dist/pack.d.ts.map +1 -1
  86. package/dist/pack.js +24 -2
  87. package/dist/pack.js.map +1 -1
  88. package/dist/position.d.ts +22 -0
  89. package/dist/position.d.ts.map +1 -0
  90. package/dist/position.js +244 -0
  91. package/dist/position.js.map +1 -0
  92. package/dist/preview.d.ts +145 -0
  93. package/dist/preview.d.ts.map +1 -0
  94. package/dist/preview.js +962 -0
  95. package/dist/preview.js.map +1 -0
  96. package/dist/profile.d.ts +118 -0
  97. package/dist/profile.d.ts.map +1 -0
  98. package/dist/profile.js +362 -0
  99. package/dist/profile.js.map +1 -0
  100. package/dist/project.d.ts +45 -0
  101. package/dist/project.d.ts.map +1 -0
  102. package/dist/project.js +263 -0
  103. package/dist/project.js.map +1 -0
  104. package/dist/read.d.ts +12 -2
  105. package/dist/read.d.ts.map +1 -1
  106. package/dist/read.js +32 -18
  107. package/dist/read.js.map +1 -1
  108. package/dist/render.d.ts +24 -2
  109. package/dist/render.d.ts.map +1 -1
  110. package/dist/render.js +171 -4
  111. package/dist/render.js.map +1 -1
  112. package/dist/session.d.ts +39 -12
  113. package/dist/session.d.ts.map +1 -1
  114. package/dist/session.js +55 -11
  115. package/dist/session.js.map +1 -1
  116. package/dist/user-host.d.ts +3 -3
  117. package/dist/user-host.js +10 -10
  118. package/dist/user-host.js.map +1 -1
  119. package/dist/validate.d.ts +28 -16
  120. package/dist/validate.d.ts.map +1 -1
  121. package/dist/validate.js +245 -23
  122. package/dist/validate.js.map +1 -1
  123. package/package.json +6 -6
  124. package/assets/base/0305ca741b1dfec97ff35fbeb36d4a66a0c9c0614b730fe14fcdac0f1565e28a.ia.tgz +0 -0
  125. package/assets/host/c5fb2bfbba619cbd558ecc1e94dd2c16e37aa8599b4e423f1f59ed01f2074e03.tgz +0 -0
@@ -1,19 +1,39 @@
1
1
  /**
2
2
  * Host registration spec §6: a workspace's projection for one host, rendered from its own admitted records.
3
3
  *
4
- * docs/specs/host-registration/README.md §6.1 makes the renderer a pure function in `@inventarch/compliance`;
5
- * this module is the composition root that feeds it — the admitted records, their revision-bound membership, the
6
- * launcher modes from `@inventarch/distribution/host-modes`, the installed lock's packages and the nine legacy operations.
7
- * One function feeds `ia host` and, in later tasks, `ia doctor`'s drift rows and the install/update/remove refresh,
8
- * so no two of them can disagree about what the projection should contain.
9
- */
10
- import { systemMember } from '@inventarch/db';
11
- import { renderWorkspaceProjection } from '@inventarch/compliance';
12
- import { HOST_MODES, launcherInvocation } from '@inventarch/distribution/host-modes';
13
- import { readInstalledState } from '@inventarch/distribution/services';
14
- import { LEGACY_OPERATIONS } from './commands.js';
4
+ * Milestone position-packet task replace-renderers (plan amendments B9, B11 and B12): the projection is the position
5
+ * packet (`renderPacket`, runtime R19) rendered by the host's adapter for the consumer target (`renderHost`, R20), with
6
+ * the command catalog this CLI tags (`packetCatalog`). One render feeds `ia host`, `ia doctor`'s projection rows and the
7
+ * install/update/remove refresh, so no two of them can disagree about what the projection should contain.
8
+ *
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.
20
+ */
21
+ import { accessSync, closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readFileSync, } from 'node:fs';
22
+ import { join, resolve } from 'node:path';
23
+ import { pathKey } from '@inventarch/db';
24
+ import { renderHost, renderPacket, PACKET_MARKER } from '@inventarch/runtime';
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';
30
+ import { DistributionError, json, readWorkspaceFile, readWorkspaceJson, replace, sha256, } from '@inventarch/distribution/services';
31
+ import { packetCatalog } from './commands.js';
15
32
  import { Refusal } from './consumer.js';
16
- import { openSession } from './session.js';
33
+ import { refusedPath, SETTINGS, skillFolderOf, STATE } from './host.js';
34
+ import { codeOf, openSession } from './session.js';
35
+ /** This CLI's id@version, which the receipt records and only the applying CLI knows (design item 12). */
36
+ const CLI = `@inventarch/cli@${JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version}`;
17
37
  /**
18
38
  * §4: the target must admit — zero error findings — before anything is rendered or registered. The refusal is the
19
39
  * CLI's own classification of the target, so it is IA-CLI-CONFLICT and names the command that shows the findings.
@@ -22,52 +42,653 @@ function requireAdmitted(session, root) {
22
42
  if (session.admission().status !== 'admitted')
23
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.');
24
44
  }
25
- /** §4's admission gate alone, for a removal, which renders nothing. */
26
- 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) {
27
65
  const session = openSession(root);
28
66
  try {
67
+ gate?.(session);
29
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
+ });
30
96
  }
31
97
  finally {
32
98
  session.close();
33
99
  }
34
100
  }
35
101
  /**
36
- * The same membership `tools/projections/generate.ts` builds for this repository: every admitted source path, with
37
- * the system folder `@inventarch/db` recognizes it under, authored or installed. The renderer refuses a membership that does
38
- * not cover every record, so nothing here filters.
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.
104
+ */
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}` });
115
+ }
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
+ }
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.
39
230
  */
40
- function membershipOf(session) {
41
- const records = session.reader.records(), revision = session.reader.revision;
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
+ }));
242
+ }
243
+ /**
244
+ * B11: whether this workspace holds a steward-guard registration an earlier release made, which the projection apply
245
+ * retires. Only Claude ever registered one; its ownership state is the registration, as `ia host` and `ia doctor`
246
+ * decide it.
247
+ */
248
+ export const ownsGuard = (root, host) => host === 'claude' && existsSync(resolve(root, STATE.hooks));
249
+ /**
250
+ * B11: the removal of the steward-guard registration this workspace owns, or null when it owns none. A refusal the
251
+ * mechanism does not locate at a file concerns the guard group in the settings file — a group changed by hand, or
252
+ * settings that do not parse — except a pending host journal, which is the journal's.
253
+ */
254
+ export function planRetirement(root, host) {
255
+ try {
256
+ if (host === 'claude')
257
+ assertRetirableGuard(root);
258
+ if (!ownsGuard(root, host))
259
+ return null;
260
+ return planGuardRegistration(root, { remove: HOST_REGISTRATION });
261
+ }
262
+ catch (error) {
263
+ const code = codeOf(error, '');
264
+ if (error instanceof Error &&
265
+ /^IA-/.test(code) &&
266
+ code !== 'IA-DIST-RECOVERY-REQUIRED' &&
267
+ refusedPath(error) === null)
268
+ throw new DistributionError(code, error.message, SETTINGS);
269
+ throw error;
270
+ }
271
+ }
272
+ /** The file plan `applyHostProjection` applies for `rendered`, or the removal of the owned set for null. */
273
+ export const planFiles = (root, host, rendered) => {
274
+ preflightReceipt(root, host);
275
+ return planProjection({ root, host, artifacts: rendered?.files ?? [], marker: PACKET_MARKER });
276
+ };
277
+ /** Check every destination ancestor and the opened destination without changing bytes. */
278
+ export function preflightReceipt(root, host) {
279
+ for (const path of [STATE.receipt(host), pendingPath(host)]) {
280
+ const parts = path.split('/'), ancestors = [];
281
+ const unsafe = (relative = path) => new DistributionError('IA-DIST-PATH-UNSAFE', 'Expected an unaliased receipt file and directory ancestors', relative);
282
+ for (let i = 1; i < parts.length; i++) {
283
+ const relative = parts.slice(0, i).join('/'), absolute = resolve(root, relative);
284
+ let stat;
285
+ try {
286
+ stat = lstatSync(absolute, { bigint: true });
287
+ }
288
+ catch (error) {
289
+ if (error.code === 'ENOENT')
290
+ break;
291
+ throw error;
292
+ }
293
+ if (stat.isSymbolicLink() || !stat.isDirectory())
294
+ throw unsafe(relative);
295
+ ancestors.push({ stat });
296
+ accessSync(absolute, constants.W_OK);
297
+ }
298
+ const checkAncestors = () => {
299
+ for (let i = 1; i < parts.length; i++) {
300
+ const relative = parts.slice(0, i).join('/'), current = lstatSync(resolve(root, relative), { bigint: true, throwIfNoEntry: false }), before = ancestors[i - 1]?.stat;
301
+ if (!current) {
302
+ if (before)
303
+ throw unsafe(relative);
304
+ break;
305
+ }
306
+ if (!current.isDirectory() ||
307
+ current.isSymbolicLink() ||
308
+ (before && (current.dev !== before.dev || current.ino !== before.ino)))
309
+ throw unsafe(relative);
310
+ }
311
+ };
312
+ const absolute = resolve(root, path);
313
+ let fd;
314
+ try {
315
+ // No pathname precheck: validate the handle actually opened. O_NOFOLLOW protects the leaf where supported;
316
+ // the identity checks below also cover Windows and ancestor replacement. No creation or truncation occurs.
317
+ fd = openSync(absolute, constants.O_RDWR | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
318
+ }
319
+ catch (error) {
320
+ // A bad kind may itself prevent opening (directories on Windows, or a dangling link). Preserve its path remedy.
321
+ const named = lstatSync(absolute, { bigint: true, throwIfNoEntry: false });
322
+ if (named && (!named.isFile() || named.isSymbolicLink() || named.nlink !== 1n))
323
+ throw unsafe();
324
+ if (error.code === 'ENOENT' && !named) {
325
+ checkAncestors();
326
+ continue;
327
+ }
328
+ throw error;
329
+ }
330
+ try {
331
+ // Windows file IDs can exceed Number.MAX_SAFE_INTEGER; retain every bit when comparing identities.
332
+ const opened = fstatSync(fd, { bigint: true }), named = lstatSync(absolute, { bigint: true });
333
+ if (!opened.isFile() ||
334
+ opened.nlink !== 1n ||
335
+ !named.isFile() ||
336
+ named.isSymbolicLink() ||
337
+ named.nlink !== 1n ||
338
+ opened.dev !== named.dev ||
339
+ opened.ino !== named.ino)
340
+ throw unsafe();
341
+ checkAncestors();
342
+ }
343
+ finally {
344
+ closeSync(fd);
345
+ }
346
+ }
347
+ readPending(root, host);
348
+ }
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;
357
+ function readPending(root, host) {
358
+ const path = pendingPath(host);
359
+ if (!existsSync(resolve(root, path)))
360
+ return null;
361
+ let value;
362
+ try {
363
+ value = readWorkspaceJson({ root, path });
364
+ }
365
+ catch (error) {
366
+ throw new DistributionError(codeOf(error, 'IA-CLI-FAILED'), error instanceof Error ? error.message : String(error), path);
367
+ }
368
+ const { digest, ...body } = value ?? {};
369
+ if (value === null ||
370
+ typeof value !== 'object' ||
371
+ Array.isArray(value) ||
372
+ value.format !== 'ia.packet-receipt-pending.v1' ||
373
+ value.host !== host ||
374
+ typeof value.guard !== 'boolean' ||
375
+ !digests(value.removed) ||
376
+ value.removed.some((file) => !projectionOwnable(host, file.path)) ||
377
+ (value.receipt !== undefined && !HEX.test(value.receipt)) ||
378
+ (value.removedHooks !== undefined && (!hookDigests(value.removedHooks) || value.removedHooks.length === 0)) ||
379
+ Object.keys(body).sort().join(',') !==
380
+ [
381
+ 'format',
382
+ 'guard',
383
+ 'host',
384
+ ...(value.receipt === undefined ? [] : ['receipt']),
385
+ 'removed',
386
+ ...(value.removedHooks === undefined ? [] : ['removedHooks']),
387
+ ].join(',') ||
388
+ digest !== sha256(json(body)))
389
+ throw new DistributionError('IA-DIST-INPUT-INVALID', 'Invalid pending projection receipt evidence', path);
390
+ // The receipt committed but a kill left the pending cleanup undone: that was a successful last apply.
391
+ if (value.receipt !== undefined &&
392
+ existsSync(resolve(root, STATE.receipt(host))) &&
393
+ sha256(readWorkspaceFile({ root, path: STATE.receipt(host) })) === value.receipt)
394
+ return null;
395
+ return body;
396
+ }
397
+ /** Verified deletion provenance shared by projection apply and a migration's durable effect plan. */
398
+ export function projectionEvidence(root, host, actions, retirement, previous, hookRemovals = []) {
399
+ if (previous !== undefined &&
400
+ (JSON.stringify(readReceipt(root, host)) !== JSON.stringify(previous) ||
401
+ !previous.files.every((file) => sha256(readWorkspaceFile({ root, path: file.path })) === file.sha256) ||
402
+ !previous.removed.every((file) => !existsSync(resolve(root, file.path)))))
403
+ throw new DistributionError('IA-DIST-LOCAL-MODIFICATION', 'Completed projection differs from its receipt', STATE.receipt(host));
404
+ const removed = actions.flatMap((action) => action.action === 'remove' && existsSync(resolve(root, action.path))
405
+ ? [{ path: action.path, sha256: sha256(readWorkspaceFile({ root, path: action.path })) }]
406
+ : []);
407
+ const pending = readPending(root, host);
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
+ });
416
+ for (const file of removed) {
417
+ const recorded = prior?.removed.find((row) => row.path === file.path);
418
+ if (recorded !== undefined && recorded.sha256 !== file.sha256)
419
+ throw new DistributionError('IA-DIST-LOCAL-MODIFICATION', 'Pending removal evidence differs from the current owned bytes', file.path);
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));
42
428
  return {
43
- revision,
44
- members: [...new Set(records.map((record) => record.source.path))].sort().map((path) => {
45
- const member = systemMember(path);
46
- return { path, system: member?.name ?? null, root: member?.root ?? null };
47
- }),
429
+ format: 'ia.packet-receipt-pending.v1',
430
+ host,
431
+ guard: prior?.guard === true || retirement,
432
+ removed: [...new Map([...(prior?.removed ?? []), ...removed].map((file) => [file.path, file])).values()],
433
+ ...(removedHooks.length === 0 ? {} : { removedHooks }),
48
434
  };
49
435
  }
50
- /** §6.1. Artifacts carry the `ia host` marker line; `@inventarch/distribution/projection` refuses any that does not. */
51
- export function renderProjectionFor(root, host) {
52
- const session = openSession(root);
436
+ /**
437
+ * The one writer of projection files: B11, then the files, then B12. `rendered` is `renderProjectionFor`'s output,
438
+ * or null to remove the owned set. Both the guard retirement and the file plan are planned before anything is written,
439
+ * so a refusal either planner finds changes nothing; then the guard registration is removed (its group in
440
+ * `.claude/settings.local.json` and its ownership state), and only then are the files written and the owned 1.x
441
+ * steward files deleted. A failure past the retirement so leaves the guard retired and never the steward files
442
+ * deleted with the guard still registered; a rerun converges. The receipt (`<host>-receipt.json` beside the
443
+ * projection state) describes the files as an apply left them, so it is deleted, under the host lock, before any of
444
+ * them changes: an interrupted apply leaves none, which `ia doctor` reports as unknown, never as a hand edit. It is
445
+ * written last, under the host lock, with the legacy files deleted (`removed`), the foreign files left in place, the
446
+ * retirement, this CLI's id@version and the time; a removal leaves it deleted. `checkpoint` runs after the retirement
447
+ * (`guard`), at each of `applyProjection`'s own stages and after the receipt (`receipt`), which is where an
448
+ * interruption test cuts. A migration may supply its verified previous receipt to refresh host notes while retaining
449
+ * that operation's retirement and deletion evidence; ordinary applies omit it and keep last-apply semantics.
450
+ */
451
+ export function applyHostProjection(root, host, rendered, checkpoint = () => { }, previous, cache = null) {
452
+ // A pending host journal refuses every host write, as it refuses the plan (§8).
453
+ assertHostRegistrationIdle(root);
454
+ const retirement = planRetirement(root, host), hooks = planHookStep(root, host, rendered, cache), plan = planFiles(root, host, rendered);
455
+ const writeEvidence = (path, value) => {
456
+ const unlock = acquireHostRegistrationLock(root);
457
+ try {
458
+ replace(root, path, value === null ? null : Buffer.from(json(value)));
459
+ }
460
+ finally {
461
+ unlock();
462
+ }
463
+ };
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);
470
+ // Evidence precedes retirement and every deletion; it survives failure and the projection state's collapse.
471
+ writeEvidence(pendingPath(host), { ...evidence, digest: sha256(json(evidence)) });
472
+ checkpoint('evidence');
473
+ if (retirement !== null)
474
+ applyGuardRegistration(retirement);
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');
483
+ // The last apply's receipt goes before any projection file changes (B12).
484
+ writeEvidence(STATE.receipt(host), null);
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));
488
+ const receipt = rendered === null
489
+ ? null
490
+ : {
491
+ ...rendered.receipt,
492
+ cli: CLI,
493
+ removed: evidence.removed.filter((file) => !existsSync(resolve(root, file.path))),
494
+ foreign: plan.actions.filter((action) => action.action === 'foreign').map((action) => action.path),
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),
506
+ writtenAt: new Date().toISOString(),
507
+ };
508
+ if (receipt !== null) {
509
+ const completed = { ...evidence, receipt: sha256(json(receipt)) };
510
+ writeEvidence(pendingPath(host), { ...completed, digest: sha256(json(completed)) });
511
+ }
512
+ writeEvidence(STATE.receipt(host), receipt);
513
+ writeEvidence(pendingPath(host), null);
514
+ checkpoint('receipt');
515
+ return {
516
+ status: rendered !== null ? 'projected' : result.removed > 0 ? 'projection-removed' : 'absent',
517
+ guard,
518
+ receipt,
519
+ };
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) {
53
544
  try {
54
- requireAdmitted(session, root);
55
- const records = session.reader.records(), revision = session.reader.revision;
56
- const lock = readInstalledState({ root }).lock;
57
- const rendered = renderWorkspaceProjection(records, revision, membershipOf(session), {
58
- host,
59
- modes: HOST_MODES.map((row) => ({ invocation: launcherInvocation(row), meaning: row.meaning })),
60
- distributions: (lock?.packages ?? []).map((pkg) => ({ id: pkg.id, version: pkg.version })),
61
- operations: [...LEGACY_OPERATIONS],
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 },
62
597
  });
63
- // Contract §4.1 lists IA-COMP-* as finding codes. This is a CLI refusal carrying the renderer's finding code
64
- // unchanged, because the renderer's assessment is the only thing that knows why the projection cannot exist.
65
- if (rendered.assessment.outcome !== 'pass')
66
- throw new Refusal('IA-COMP-PROJECTION-INVALID', rendered.assessment.findings.map((finding) => finding.message).join('; '), 3, { path: root }, 'Fix each system\'s steward declaration named above, then run "ia validate" to confirm the workspace admits.');
67
- return rendered.artifacts;
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);
68
609
  }
69
- finally {
70
- session.close();
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
+ }
642
+ const HEX = /^[a-f0-9]{64}$/;
643
+ const digests = (value) => Array.isArray(value) &&
644
+ value.every((row) => row !== null &&
645
+ typeof row === 'object' &&
646
+ typeof row.path === 'string' &&
647
+ HEX.test(String(row.sha256)));
648
+ /**
649
+ * B12: the receipt `applyHostProjection` wrote for `host`, or null when there is none — a 1.x registration, or one
650
+ * whose receipt was deleted. A receipt that cannot be read, or that lacks the fields `ia doctor` checks, refuses at
651
+ * its own path.
652
+ */
653
+ export function readReceipt(root, host) {
654
+ const path = STATE.receipt(host);
655
+ if (!existsSync(resolve(root, path)))
656
+ return null;
657
+ let value;
658
+ try {
659
+ value = readWorkspaceJson({ root, path });
660
+ }
661
+ catch (error) {
662
+ if (error instanceof Error && 'code' in error && typeof error.code === 'string')
663
+ throw new DistributionError(error.code, error.message, path);
664
+ throw error;
71
665
  }
666
+ const row = value;
667
+ if (row === null ||
668
+ typeof row !== 'object' ||
669
+ Array.isArray(row) ||
670
+ row.format !== 'ia.packet-receipt.v1' ||
671
+ row.host !== host ||
672
+ !HEX.test(String(row.packetDigest)) ||
673
+ !digests(row.files) ||
674
+ !digests(row.removed) ||
675
+ !Array.isArray(row.foreign) ||
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)))
691
+ throw new DistributionError('IA-DIST-INPUT-INVALID', 'Invalid projection receipt', path);
692
+ return row;
72
693
  }
73
694
  //# sourceMappingURL=host-projection.js.map