@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
package/dist/init.js CHANGED
@@ -1,74 +1,227 @@
1
+ import { registryWorkspace } from './adopt.js';
2
+ import { adoptedBindings } from '@inventarch/db';
3
+ import { adoptionId, planAdoption, applyAdoption } from '@inventarch/distribution/registry';
4
+ import { readBase, PIN_PATH, PACKAGE_ID, DAMAGED } from './bundled-base.js';
5
+ export { readBase, PIN_PATH, baseArchivePath, PACKAGE_ID } from './bundled-base.js';
1
6
  /**
2
7
  * `ia init`: docs/specs/consumer-cli-contract/README.md §2.1, implementing
3
8
  * docs/specs/workspace-initialization-apply/README.md (M5.2) to reach the end state
4
9
  * docs/specs/workspace-initialization/README.md (M5.1) fixes.
5
10
  *
6
- * Without `--apply` it prints the reviewable plan: the five owned paths, the target's classification (M5.2 §4.1),
7
- * the conflicts detected now, the starter it would write, the bundled base pin and the four steps. It exits 0
8
- * whether or not conflicts were found, because reporting them is the command's job.
11
+ * Without `--apply` it prints the reviewable plan: the owned paths, the target's classification (M5.2 §4.1), the
12
+ * conflicts detected now, the starter it would write, the bundled base pin and the steps. It exits 0 whether or not
13
+ * conflicts were found, because reporting them is the command's job.
9
14
  *
10
- * With `--apply` it runs M5.2 §3.1 in order — verify the pin, install the bundled base unless it is already
11
- * installed as planned, write `system.ia`, write `records/workspace.ia`, admit and read the `@distribution`
12
- * identity from the compiled graph, write `.ia/release.json` last — through the shared install services and
13
- * `createFile`. No journal is written: a rerun derives from the workspace which steps are done (§4.2). No step
14
- * performs a network request. `<directory>` is the only way to name the target: this verb never performs root
15
- * discovery, and `--root` is refused by the grammar rather than silently ignored.
15
+ * Milestone position-packet task init-three-records (position-and-projection §3; plan amendments B7 and B13;
16
+ * decisions local-system-at-init and identity-namespace): the starter is three authored records in
17
+ * `.ia/src/workspace.ia` — the `@workspace`, its participant `@agent` and that participant's `@mandate` — and a
18
+ * create-only `.ia/.gitignore`. No local `@system` and no `@distribution` are written unless `--system` asks for
19
+ * them, inside `.ia/src/systems/<name>/`, where the packer finds a release's records; without them the release
20
+ * descriptor names no distribution, so `ia pack` refuses until one is authored.
16
21
  *
17
- * `--host claude` or `--host codex` (docs/specs/host-registration/README.md §4 "init --host") adds one
18
- * step after the four: once the workspace is initialized, the `ia host <host> --apply` path runs under the question
19
- * already answered here, so it never asks a second one. The plan names that step and writes nothing for it — the
20
- * host plan needs `.ia/release.json`, which only the apply writes. A host step that refuses leaves the workspace
21
- * initialized: the refusal keeps the service's code, message and location, and its next action names the rerun.
22
+ * With `--apply` it runs the steps in order — verify the pin, install the bundled base unless it is already
23
+ * installed as planned, author the starter create-only, admit and read the authored identities from the compiled
24
+ * graph, write `.ia/release.json`, the completion point — through the shared install services and `createFile`.
25
+ * No journal is written: a rerun derives from the workspace which steps are done (§4.2). No step performs a network
26
+ * request. `<directory>` is the only way to name the target: this verb never performs root discovery, and `--root`
27
+ * is refused by the grammar rather than silently ignored. Two effects follow the completion point and are reported
28
+ * apart (design §3): the capture, through db's `writeCapture` as `ia capture` writes it, and, only with `--host`, the
29
+ * projection. A later step that fails leaves every earlier result in place and says so, naming its own command.
30
+ *
31
+ * `--host claude` or `--host codex` (docs/specs/host-registration/README.md §4 "init --host") is the project effect:
32
+ * once the workspace is initialized, after the capture, the `ia host <host> --apply` path runs under the question
33
+ * already answered here, so it never asks a second one, and its projection is written by `applyHostProjection`, the
34
+ * one writer of projection files. It reads the live revision rather than the capture (plan amendment B8), so a capture
35
+ * that fails does not keep it from running; the capture's refusal then says the projection is written. The plan names
36
+ * that step and writes nothing for it — the host plan needs `.ia/release.json`, which only the apply writes. A host
37
+ * step that refuses leaves the workspace initialized: the refusal keeps the service's code, message and location, and
38
+ * its next action names the rerun.
39
+ *
40
+ * `--migrate` (milestone position-packet task init-migrate-flag; plan amendments B7, B9 and B11) takes a workspace a
41
+ * 1.1.0 `ia init` wrote instead: one local system folder, `.ia/src/systems/<name>/`, whose `system.ia` holds exactly the
42
+ * starter `@system <name>`, registering no word, and `@agent <name>-steward`, and whose `records/workspace.ia` holds
43
+ * exactly `@workspace <name>` and `@distribution <name>-distribution`. It rewrites it into the three starter records:
44
+ * each other record file moves from the folder's `records/` to `.ia/src/`, where a record's word, not its folder,
45
+ * decides its system, so its identity is unchanged; the local system folder goes and the descriptor names no
46
+ * distribution, unless `--system` keeps the `@system` and its steward and re-roots the `@distribution` at the system.
47
+ * It plans by default, and plan and apply alike refuse a workspace of any other shape before anything is written. The
48
+ * three records use fields only the base this CLI bundles declares, so the apply first installs that base where the
49
+ * workspace has another, as `ia init` installs it; it then captures and re-projects each host whose projection the
50
+ * workspace owns through `applyHostProjection`, which retires the 1.x steward guard and deletes the owned steward agent
51
+ * files (`collectMigration`, `applyMigration`).
22
52
  */
53
+ import { readMigrationJournal, beginMigrationJournal, applyMigrationFiles, finishMigrationJournal, completeMigrationProjection, reopenMigrationProjection, } from './migration-journal.js';
23
54
  import { spawnSync } from 'node:child_process';
24
55
  import { accessSync, constants, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, unlinkSync, } from 'node:fs';
25
56
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
26
- import { DISTRIBUTION_ENGINE_VERSION, INSTALL_PATHS } from '@inventarch/db/distribution';
57
+ import { inertCommandRoot } from '@inventarch/runtime';
58
+ import { decodeReleaseDescriptor, deriveGenerationInputs, generationDigest, installationWorkspace, readExpandedBundle, DISTRIBUTION_ENGINE_VERSION, INSTALL_PATHS, sha256, } from '@inventarch/db/distribution';
27
59
  import { verifyArchive } from '@inventarch/distribution/archive';
60
+ import { assertHostRegistrationIdle } from '@inventarch/distribution/host';
28
61
  import { assertHomeOutsideWorkspace } from '@inventarch/distribution/host-home';
29
62
  import { applyInstallation, cacheArchive, planInstallation } from '@inventarch/distribution/install';
30
63
  import { resolveReleases } from '@inventarch/distribution/resolve';
31
- import { createFile, openWorkspaceSession, readInstalledState, resolveCatalog, } from '@inventarch/distribution/services';
64
+ import { createFile, openWorkspaceSession, readInstalledState, readWorkspaceFile, readWorkspaceJson, resolveCatalog, } from '@inventarch/distribution/services';
32
65
  import { parseArguments, UsageError } from './args.js';
66
+ import { captureFailure, collectCapture, CURRENT } from './capture.js';
33
67
  import { findCommand } from './commands.js';
34
68
  import { confirm, iaHomeOf, Interrupted, Refusal, refusalOf, respell } from './consumer.js';
35
69
  import { clearDecline, runDecline } from './decline.js';
36
- import { CONFIRMATION } from './distribute.js';
37
- import { applyHostSet, collectHost, hostNotes, recoverCommand, rootedNext, THEN_RERUN } from './host.js';
70
+ import { CONFIRMATION, registeredProjections } from './distribute.js';
71
+ import { applyHostSet, collectHost, GUARD_RETIRED, hostNotes, JOURNALS, projectionRepair, recoverCommand, refusedPath, rootedNext, SETTINGS, STATE, THEN_RERUN, } from './host.js';
72
+ import { applyHostProjection, planFiles, planRetirement, preflightHooks, readReceipt, renderProjectionFor, } from './host-projection.js';
38
73
  import { located } from './home-remedy.js';
39
74
  import { findProgram, programEnv, programHome } from './program.js';
40
- import { codeOf } from './session.js';
41
- import { atom, document, entry, fieldRows, headerLine, quote, sectionLabel, truncateDigest, words } from './render.js';
75
+ import { codeOf, openSession } from './session.js';
76
+ import { atom, blockSymbolWidth, document, entry, fieldRows, headerLine, quote, safeRootAdvice, sectionLabel, truncateDigest, words, } from './render.js';
42
77
  /**
43
78
  * Relative to the `@inventarch/cli` package root, as `assets/vocabulary.json` is (vocabulary.ts CATALOGUE_PATH). The base
44
79
  * package's id is read from this pin and appears nowhere in this source: M5.1 §3.2 makes the pin the only authority.
45
80
  */
46
- export const PIN_PATH = 'assets/base.json';
47
- export const baseArchivePath = (digest) => `assets/base/${digest}.ia.tgz`;
48
81
  export const DESCRIPTOR_PATH = '.ia/release.json';
49
82
  export const STARTER_VERSION = '0.1.0';
50
83
  /** The installer's lock, `acquire()` at apps/distribution/src/install.ts:70; `INSTALL_PATHS` does not name it. */
51
84
  export const INSTALL_LOCK = '.ia/distributions/install-lock.json';
52
85
  const cachePath = (digest) => `.ia/distributions/cache/${digest}.ia.tgz`;
53
86
  const systemFolder = (name) => `.ia/src/systems/${name}`;
54
- const systemPath = (name) => `${systemFolder(name)}/system.ia`;
55
- const recordsPath = (name) => `${systemFolder(name)}/records/workspace.ia`;
87
+ /** Plan amendment C20: where `ia author system <name>` writes a local system, as `ia init --system` does. */
88
+ export const systemPath = (name) => `${systemFolder(name)}/system.ia`;
89
+ const distributionPath = (name) => `${systemFolder(name)}/records/distribution.ia`;
90
+ /** Position-and-projection §3: the one file the three starter records share, at the root of the authored source. */
91
+ export const WORKSPACE_PATH = '.ia/src/workspace.ia';
92
+ /** Create-only: the local working state each clone makes for itself, never the authored records or the lock. */
93
+ export const IGNORE_PATH = '.ia/.gitignore';
94
+ export const IGNORE_TEXT = 'work/\ndistributions/\n';
95
+ export function migrationIgnoreText(root) {
96
+ const result = gitIn(root, process.env)(['ls-files', '-z', '--', '.ia/distributions']);
97
+ return result === null || result.status === null || (result.status === 0 && result.stdout.length > 0)
98
+ ? 'work/\n'
99
+ : IGNORE_TEXT;
100
+ }
101
+ /** Enumerate the exact store and generation inventory the installer will make active, without caching or writing. */
102
+ function migrationPayloadPaths(root, base, current) {
103
+ const replacing = current.packages.find((pkg) => pkg.id === base.pin.id).archive !== base.pin.archive;
104
+ const resolved = replacing
105
+ ? resolveReleases([{ id: base.pin.id, range: `^${base.pin.version}` }], [
106
+ {
107
+ release: verifyArchive(base.bytes, base.pin.archive),
108
+ location: `sha256:${base.pin.archive}`,
109
+ withdrawn: false,
110
+ },
111
+ ], DISTRIBUTION_ENGINE_VERSION)
112
+ : null;
113
+ const lock = resolved?.lock ?? current;
114
+ const releases = resolved?.releases ?? new Map(lock.packages.map((pkg) => [pkg.id, readExpandedBundle(root, pkg)]));
115
+ const inputs = deriveGenerationInputs(lock, releases);
116
+ const workspace = installationWorkspace(lock, inputs, releases);
117
+ const generation = `${INSTALL_PATHS.generations}/${generationDigest(lock, inputs, workspace)}`;
118
+ return [
119
+ INSTALL_PATHS.lock,
120
+ INSTALL_PATHS.active,
121
+ `${generation}/lock.json`,
122
+ `${generation}/inputs.json`,
123
+ ...(workspace === null ? [] : [`${generation}/workspace.ia`]),
124
+ ...lock.packages.flatMap((pkg) => [
125
+ `${INSTALL_PATHS.store}/${pkg.archive}/distribution.json`,
126
+ ...releases.get(pkg.id).manifest.files.map((file) => `${INSTALL_PATHS.store}/${pkg.archive}/${file.path}`),
127
+ ]),
128
+ ];
129
+ }
130
+ function migrationGitConflict(root, base, lock) {
131
+ const git = gitIn(root, process.env);
132
+ const tracked = git(['ls-files', '-z', '--', '.ia/distributions']);
133
+ if (tracked === null || tracked.status === null || tracked.status !== 0) {
134
+ for (let at = root;; at = dirname(at)) {
135
+ if (existsSync(resolve(at, '.git')))
136
+ return {
137
+ path: '.ia/distributions',
138
+ reason: 'Git tracking could not be verified; make Git available before migrating this checkout',
139
+ };
140
+ if (dirname(at) === at)
141
+ break;
142
+ }
143
+ return null;
144
+ }
145
+ if (tracked.status !== 0 || tracked.stdout.length === 0)
146
+ return null;
147
+ const probes = migrationPayloadPaths(root, base, lock);
148
+ // NUL-delimited bounded batches preserve exact paths and avoid Windows argument/output limits.
149
+ const query = (args) => {
150
+ let stdout = '', status = 1;
151
+ for (let at = 0; at < probes.length; at += 128) {
152
+ const result = git(args, probes.slice(at, at + 128).join('\0') + '\0');
153
+ if (result === null || result.status === null || result.status > 1)
154
+ return result;
155
+ stdout += result.stdout;
156
+ if (result.status === 0)
157
+ status = 0;
158
+ }
159
+ return { status, stdout };
160
+ };
161
+ const attributes = query(['check-attr', '-z', '--stdin', 'text', 'eol', 'filter', 'working-tree-encoding']);
162
+ const conversion = git(['config', '--get', 'core.autocrlf']);
163
+ if (attributes?.status !== 0 || conversion === null)
164
+ return {
165
+ path: '.gitattributes',
166
+ reason: 'Git byte-conversion rules could not be verified for tracked installation payload; repair Git before migrating',
167
+ };
168
+ const fields = attributes.stdout.split('\0');
169
+ const settings = new Map();
170
+ for (let index = 0; index + 2 < fields.length; index += 3) {
171
+ const values = settings.get(fields[index]) ?? {};
172
+ values[fields[index + 1]] = fields[index + 2];
173
+ settings.set(fields[index], values);
174
+ }
175
+ const transforms = [...settings.values()].some((values) => (values['filter'] !== 'unspecified' && values['filter'] !== 'unset') ||
176
+ (values['working-tree-encoding'] !== 'unspecified' && values['working-tree-encoding'] !== 'unset') ||
177
+ (values['text'] !== 'unset' &&
178
+ (values['text'] !== 'unspecified' ||
179
+ values['eol'] !== 'unspecified' ||
180
+ ['true', 'input'].includes(conversion.stdout.trim()))));
181
+ if (settings.size !== probes.length || transforms)
182
+ return {
183
+ path: '.gitattributes',
184
+ reason: 'Git may rewrite tracked immutable installation bytes; add .ia/distributions/** -text and .ia/distributions.lock.json -text to .gitattributes and remove any filters or encoding conversion for those paths before migrating',
185
+ };
186
+ const ignored = query(['check-ignore', '-v', '-z', '--no-index', '--stdin']);
187
+ if (ignored?.status === 1)
188
+ return null;
189
+ if (ignored?.status === 0) {
190
+ const fields = ignored.stdout.split('\0');
191
+ for (let at = 0; at + 3 < fields.length; at += 4) {
192
+ const [source, line, pattern, path] = fields.slice(at, at + 4);
193
+ if (pattern.startsWith('!'))
194
+ continue;
195
+ return {
196
+ path: '.ia/distributions',
197
+ reason: `Tracked installation payload ${path} would be hidden by an existing Git ignore rule: ${source}:${line}:${pattern}; adjust that rule to include this required file before migrating`,
198
+ };
199
+ }
200
+ return null;
201
+ }
202
+ return {
203
+ path: '.ia/distributions',
204
+ reason: 'Git ignore rules could not be verified for tracked installation payload; repair Git before migrating',
205
+ };
206
+ }
56
207
  /** `packages/db/src/distribution/codec.ts` packageId and identifier: the id rule and the system-name ceiling. */
57
- export const PACKAGE_ID = /^[a-z][a-z0-9.-]*\/[a-z][a-z0-9-]*$/;
58
208
  const NAME = /^[a-z][a-z0-9-]*$/;
59
209
  const NAME_LIMIT = 64;
210
+ /** A local system name `ia init --system` and `ia author system` accept: the id rule and the system-name ceiling. */
211
+ export const isSystemName = (name) => NAME.test(name) && name.length <= NAME_LIMIT;
60
212
  /** M5.2 §4.3: `createFile`'s temporary name, `<target>.<randomUUID()>.tmp` (apps/distribution/src/files.ts:76). */
61
- export const LEFTOVER = /^(system\.ia|workspace\.ia|release\.json)\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp$/;
213
+ export const LEFTOVER = /^(system\.ia|workspace\.ia|distribution\.ia|release\.json|\.gitignore)\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp$/;
62
214
  /** The installation, not the target, is at fault; `ia doctor` names the channel a reinstall goes through. */
63
- const DAMAGED = 'The ia installation is damaged; run "ia doctor" for its install channel and reinstall @inventarch/cli through it.';
64
- /** M5.1 §2.1: the three M4 paths plus the starter system folder and the release descriptor. */
65
- export function ownedPaths(name) {
215
+ /** M5.1 §2.1's paths: the authored source, the ignore file, the descriptor, the install state and the capture. */
216
+ export function ownedPaths(name, system = false) {
66
217
  return [
67
218
  { path: '.ia/src/', purpose: 'authored records' },
68
- { path: `${systemFolder(name ?? '<name>')}/`, purpose: 'the starter system, written once' },
219
+ ...(system ? [{ path: `${systemFolder(name ?? '<name>')}/`, purpose: 'the local system, written once' }] : []),
220
+ { path: IGNORE_PATH, purpose: 'ignores work/ and distributions/; written once, only if absent' },
69
221
  { path: DESCRIPTOR_PATH, purpose: 'the release descriptor, written once' },
70
222
  { path: INSTALL_PATHS.lock, purpose: 'direct requests and resolved versions' },
71
223
  { path: '.ia/distributions/', purpose: 'install state, store and generations' },
224
+ { path: '.ia/work/snapshot/', purpose: 'the capture taken once the workspace is initialized' },
72
225
  ];
73
226
  }
74
227
  /**
@@ -104,44 +257,17 @@ const writable = (path) => {
104
257
  * has no digest to verify against and is the CLI's own failure. Either way the next action says the installation is
105
258
  * damaged, because nothing the user did to the target can cause it.
106
259
  */
107
- export function readBase(packageRoot) {
108
- const pinPath = resolve(packageRoot, PIN_PATH);
109
- let pin;
110
- try {
111
- const value = JSON.parse(readFileSync(pinPath, 'utf8'));
112
- const keys = Object.keys(value).sort().join(',');
113
- if (keys !== 'archive,id,manifest,version' ||
114
- !Object.values(value).every((item) => typeof item === 'string') ||
115
- !PACKAGE_ID.test(String(value['id'])))
116
- throw new Error('unexpected fields');
117
- if (!/^[a-f0-9]{64}$/.test(String(value['archive'])) || !/^[a-f0-9]{64}$/.test(String(value['manifest'])))
118
- throw new Error('malformed digest');
119
- pin = value;
120
- }
121
- catch (error) {
122
- throw new Refusal('IA-CLI-FAILED', `The bundled base package pin cannot be read: ${error instanceof Error ? error.message : String(error)}`, 3, { path: pinPath }, DAMAGED);
123
- }
124
- const archivePath = resolve(packageRoot, baseArchivePath(pin.archive));
125
- const bytes = existsSync(archivePath) ? readFileSync(archivePath) : Buffer.alloc(0);
126
- try {
127
- const verified = verifyArchive(bytes, pin.archive);
128
- if (verified.manifestDigest !== pin.manifest ||
129
- verified.manifest.id !== pin.id ||
130
- verified.manifest.version !== pin.version)
131
- throw new Refusal('IA-CLI-FAILED', 'The bundled base archive does not carry the pinned manifest', 3, { path: archivePath }, DAMAGED);
132
- return { pin, bytes, systems: verified.manifest.systems.map((system) => system.name) };
133
- }
134
- catch (error) {
135
- if (error instanceof Refusal)
136
- throw error;
137
- throw new Refusal(codeOf(error, 'IA-CLI-FAILED'), error instanceof Error ? error.message : String(error), 3, { path: archivePath }, DAMAGED);
138
- }
139
- }
140
260
  /** M5.1 §2.3's normalization: lowercase, every run outside `[a-z0-9-]` becomes `-`, no leading or trailing `-`. */
141
- export const normalizeName = (directory) => directory
142
- .toLowerCase()
143
- .replace(/[^a-z0-9-]+/g, '-')
144
- .replace(/^-+|-+$/g, '');
261
+ export const normalizeName = (directory) => {
262
+ const normalized = directory.toLowerCase().replace(/[^a-z0-9-]+/g, '-');
263
+ let start = 0, end = normalized.length;
264
+ // Scan each edge once: an unanchored trailing-hyphen regex retries at every internal hyphen.
265
+ while (start < end && normalized[start] === '-')
266
+ start++;
267
+ while (end > start && normalized[end - 1] === '-')
268
+ end--;
269
+ return normalized.slice(start, end);
270
+ };
145
271
  /** M5.1 §2.3: valid only if the name, the full id and the public-system rule all hold. Nothing is invented. */
146
272
  export function starterIdentity(root, supplied, systems) {
147
273
  const name = supplied === undefined ? normalizeName(basename(root)) : supplied.slice(supplied.indexOf('/') + 1);
@@ -157,9 +283,10 @@ export function starterIdentity(root, supplied, systems) {
157
283
  return { name, id, conflict: null };
158
284
  }
159
285
  /**
160
- * M5.1 §2.2, verbatim in shape: the steward needs `agent-system`, and `governance` is required. `work-system` is
161
- * required so a fresh workspace can author `@plan`, `@milestone`, `@task` and `@decision` records with no edit: a
162
- * system may use only words owned by systems it directly requires (operator decision, 2026-09-25).
286
+ * `--system`'s local system, the 1.x starter system unchanged (M5.1 §2.2, verbatim in shape): the steward needs
287
+ * `agent-system`, and `governance` is required. `work-system` is required so the system folder can hold `@plan`,
288
+ * `@milestone`, `@task` and `@decision` records with no edit: a system may use only words owned by systems it directly
289
+ * requires (operator decision, 2026-09-25).
163
290
  */
164
291
  export function starterSystem(name) {
165
292
  return [
@@ -184,8 +311,14 @@ export function starterSystem(name) {
184
311
  '',
185
312
  ].join('\n');
186
313
  }
187
- /** M5.1 §2.2: the workspace composes every installed system, so nothing installed is unreachable. */
188
- export function starterRecords(name, systems) {
314
+ /**
315
+ * Position-and-projection §3's three records, at placement authored (band 100), with only the fields their schemas
316
+ * declare (plan amendment B13). The `@workspace` composes every installed system, so nothing installed is unreachable
317
+ * (M5.1 §2.2), declares the authored root its records are captured under and names the participant as its steward.
318
+ * The participant `@agent` implies no host permission, and its `@mandate` grants it closed moves over that workspace;
319
+ * the mandate's one prose clause claims nothing. Every name is the workspace's (decision identity-namespace).
320
+ */
321
+ export function starterRecords(name, systems, sources = []) {
189
322
  return [
190
323
  '#! ia 1.0',
191
324
  '',
@@ -195,16 +328,77 @@ export function starterRecords(name, systems) {
195
328
  ' answers "Which systems does this workspace compose?"',
196
329
  ' composition',
197
330
  ` systems [${systems.map((system) => `@system ${system}`).join(', ')}]`,
331
+ ` sources [${['.ia/src @authored', ...sources].map((source) => JSON.stringify(source)).join(', ')}]`,
332
+ ` steward @agent ${name}`,
333
+ '',
334
+ `@agent ${name}`,
335
+ ' meaning',
336
+ ` says "The IDE agent operating in the ${name} workspace, any vendor."`,
337
+ ` answers "Which participant acts in the ${name} workspace?"`,
338
+ ' governance',
339
+ ' applies []',
340
+ '',
341
+ `@mandate ${name}-mandate`,
342
+ ' meaning',
343
+ ` says "The bounded authority of the ${name} participant in the ${name} workspace."`,
344
+ ` answers "Which moves may the ${name} participant make, and in which workspace?"`,
345
+ ' governance',
346
+ ' requires "Claim no host permission or execution from this mandate."',
347
+ ' authority',
348
+ ` participant @agent ${name}`,
349
+ ' moves [Observation, Verification, Synthesis, Delegation, Execution]',
350
+ ` scope [@workspace ${name}]`,
351
+ '',
352
+ ].join('\n');
353
+ }
354
+ /**
355
+ * `--system`'s release root (position-and-projection §2 case 3: a distribution's roots are system registrations). It
356
+ * sits in the system folder, so the closure from it stays inside folders the packer can release
357
+ * (apps/distribution/src/snapshot.ts, "Release roots must belong to native system folders").
358
+ */
359
+ export function starterDistribution(name) {
360
+ return [
361
+ '#! ia 1.0',
198
362
  '',
199
363
  `@distribution ${name}-distribution`,
200
364
  ' meaning',
201
- ` says "The release root of the ${name} workspace."`,
365
+ ` says "The release root of the ${name} system."`,
202
366
  ' answers "Which records does this release ship?"',
203
367
  ' distribution',
204
- ` records [@workspace ${name}]`,
368
+ ` records [@system ${name}]`,
205
369
  '',
206
370
  ].join('\n');
207
371
  }
372
+ /**
373
+ * The authored files in the order the author step writes them, and the records they hold, in file order. With
374
+ * `--system` the `@workspace` composes the local system after `systems` (position-and-projection §2 case 2: a
375
+ * repository that owns vocabulary composes its own system), so the packet renders a pointer line for it.
376
+ */
377
+ export function starterFiles(name, systems, system, sources = []) {
378
+ return {
379
+ files: [
380
+ { path: WORKSPACE_PATH, text: starterRecords(name, system ? [...systems, name] : systems, sources) },
381
+ ...(system
382
+ ? [
383
+ { path: systemPath(name), text: starterSystem(name) },
384
+ { path: distributionPath(name), text: starterDistribution(name) },
385
+ ]
386
+ : []),
387
+ ],
388
+ records: [
389
+ { word: 'workspace', name, path: WORKSPACE_PATH },
390
+ { word: 'agent', name, path: WORKSPACE_PATH },
391
+ { word: 'mandate', name: `${name}-mandate`, path: WORKSPACE_PATH },
392
+ ...(system
393
+ ? [
394
+ { word: 'system', name, path: systemPath(name) },
395
+ { word: 'agent', name: `${name}-steward`, path: systemPath(name) },
396
+ { word: 'distribution', name: `${name}-distribution`, path: distributionPath(name) },
397
+ ]
398
+ : []),
399
+ ],
400
+ };
401
+ }
208
402
  /**
209
403
  * Git as a child process, with the host's environment rather than this process's, so the probe is a function of the
210
404
  * same explicit host every verb receives. `core.fsmonitor` is disabled because it is the configured command a
@@ -212,7 +406,7 @@ export function starterRecords(name, systems) {
212
406
  * The target is a repository the user may not trust, so git is found on the host's qualified PATH entries only
213
407
  * and runs by absolute path from the home directory, with `-C` naming the target (src/program.ts).
214
408
  */
215
- export const gitIn = (cwd, env) => (args) => {
409
+ export const gitIn = (cwd, env) => (args, input) => {
216
410
  const git = findProgram('git', env);
217
411
  if (git === null)
218
412
  return null;
@@ -220,6 +414,7 @@ export const gitIn = (cwd, env) => (args) => {
220
414
  cwd: programHome(),
221
415
  env: programEnv(env),
222
416
  encoding: 'utf8',
417
+ input,
223
418
  timeout: 10_000,
224
419
  windowsHide: true,
225
420
  });
@@ -279,16 +474,23 @@ const MISSING = {
279
474
  commit: 'the checkout has no commit',
280
475
  'https-remote': 'the checkout has no HTTPS remote',
281
476
  };
282
- /** M5.1 §2.3's table. `distribution` stays null until the compiled record is read (§3.1 step 6). */
283
- export function starterDescriptor(id, name, base, provenance, distribution = null) {
477
+ /** The descriptor's one dependency row: the bundled base, at a caret range of its version, and the systems it carries. */
478
+ const baseDependencies = (base) => [
479
+ { id: base.pin.id, range: `^${base.pin.version}`, systems: base.systems },
480
+ ];
481
+ /**
482
+ * M5.1 §2.3's table. With `--system`, `distribution` stays null until the compiled record is read (§3.1 step 6);
483
+ * without it, `undefined` leaves the key out, because a default starter authors no `@distribution` (plan amendment B7).
484
+ */
485
+ export function starterDescriptor(id, name, base, provenance, distribution) {
284
486
  return {
285
487
  formatVersion: 1,
286
488
  id,
287
489
  version: STARTER_VERSION,
288
- distribution,
490
+ ...(distribution === undefined ? {} : { distribution }),
289
491
  engine: `^${DISTRIBUTION_ENGINE_VERSION}`,
290
492
  language: ['1.0'],
291
- dependencies: [{ id: base.pin.id, range: `^${base.pin.version}`, systems: base.systems }],
493
+ dependencies: baseDependencies(base),
292
494
  assets: [],
293
495
  license: 'UNLICENSED',
294
496
  description: `The ${name} workspace.`,
@@ -328,10 +530,11 @@ function filesBelow(root, path) {
328
530
  }
329
531
  /**
330
532
  * M5.2 §4.1. The starter bytes compared are what this invocation would write for its resolved id: they depend only
331
- * on the name and the bundled manifest, so they are recomputed on every run instead of being journaled.
533
+ * on the name, `--system` and the bundled manifest, so they are recomputed on every run instead of being journaled.
332
534
  */
333
535
  export function collectInit(request) {
334
536
  const { root, host } = request;
537
+ const system = request.system === true;
335
538
  const base = readBase(request.packageRoot);
336
539
  const conflicts = [];
337
540
  const present = existsSync(root);
@@ -341,12 +544,19 @@ export function collectInit(request) {
341
544
  conflicts.push(identity.conflict);
342
545
  const { name, id } = identity;
343
546
  const provenance = readProvenance(request.git);
344
- const files = name === null
345
- ? []
346
- : [
347
- { path: systemPath(name), text: starterSystem(name) },
348
- { path: recordsPath(name), text: starterRecords(name, base.systems) },
349
- ];
547
+ const sources = present
548
+ ? adoptedBindings(root).map((binding) => `${binding.tree}/.ia/src @${binding.placement ?? 'adopted'}`)
549
+ : [];
550
+ if (request.adoption) {
551
+ const source = `.ia/open/${adoptionId(request.adoption.id)}/${request.adoption.release.revision}/.ia/src @open`;
552
+ if (!sources.includes(source))
553
+ sources.push(source);
554
+ }
555
+ const { files, records } = name === null ? { files: [], records: [] } : starterFiles(name, base.systems, system, sources);
556
+ // M5.2 §4.3: a temporary file `createFile` left beside one of this initialization's own targets.
557
+ const targets = new Set([...files.map((file) => file.path), IGNORE_PATH, DESCRIPTOR_PATH]);
558
+ // `.<uuid>.tmp` is 41 characters: the dot, a 36-character UUID and `.tmp`.
559
+ const leftover = (path) => LEFTOVER.test(basename(path)) && targets.has(path.slice(0, -41));
350
560
  const leftovers = [];
351
561
  const written = new Set();
352
562
  let lock = false, installed = false;
@@ -357,7 +567,7 @@ export function collectInit(request) {
357
567
  const installation = [];
358
568
  // M5.2 §4.1: a held or abandoned install lock is recovery-required too. A process killed inside
359
569
  // applyInstallation skips the `finally` that releases it (apps/distribution/src/install.ts:67-97), before
360
- // `pending` exists and after it is removed. `ia-distribution recover` clears a dead holder's lock and refuses a
570
+ // `pending` exists and after it is removed. `ia recover installation` clears a dead holder's lock and refuses a
361
571
  // live one (`acquire(root, true)`, install.ts:71), so it is the remedy whether or not a journal exists; the
362
572
  // journal case keeps the reader's own refusal below.
363
573
  if (!existsSync(resolve(root, INSTALL_PATHS.pending)) && existsSync(resolve(root, INSTALL_LOCK)))
@@ -381,11 +591,6 @@ export function collectInit(request) {
381
591
  // Any other unreadable installation state is a conflict the plan reports, with the reader's own words.
382
592
  installation.push({ path: '.ia/distributions/', reason: message });
383
593
  }
384
- const leftoverDirectories = new Set([
385
- '.ia',
386
- ...(name === null ? [] : [systemFolder(name), `${systemFolder(name)}/records`]),
387
- ]);
388
- const leftover = (path) => leftoverDirectories.has(dirname(path)) && LEFTOVER.test(basename(path));
389
594
  if (existsSync(resolve(root, '.ia')))
390
595
  for (const entry of readdirSync(resolve(root, '.ia')).sort())
391
596
  if (leftover(`.ia/${entry}`))
@@ -402,7 +607,7 @@ export function collectInit(request) {
402
607
  }
403
608
  else if (leftover(path))
404
609
  leftovers.push(path);
405
- else if (name !== null && path.startsWith(`${systemFolder(name)}/`))
610
+ else if (system && name !== null && path.startsWith(`${systemFolder(name)}/`))
406
611
  conflicts.push({ path, reason: 'A file this initialization does not write' });
407
612
  else
408
613
  foreign.push(path);
@@ -430,32 +635,37 @@ export function collectInit(request) {
430
635
  });
431
636
  const untouched = !existsSync(resolve(root, '.ia/src')) && !lock && !installed && !existsSync(resolve(root, DESCRIPTOR_PATH));
432
637
  const state = conflicts.length > 0 ? 'conflict' : untouched && leftovers.length === 0 ? 'fresh' : 'resumable';
638
+ // Create-only and never a conflict: an existing ignore file is the target's own, so it is left and reported.
639
+ const ignore = existsSync(resolve(root, IGNORE_PATH)) ? 'present' : 'create';
433
640
  const steps = [
434
- { id: 'install', status: installed ? 'done' : 'pending', path: INSTALL_PATHS.lock },
641
+ { id: 'install', status: installed ? 'done' : 'pending', paths: [INSTALL_PATHS.lock] },
435
642
  {
436
- id: 'system',
437
- status: name !== null && written.has(systemPath(name)) ? 'done' : 'pending',
438
- path: name === null ? '' : systemPath(name),
643
+ id: 'author',
644
+ status: name !== null && files.every((file) => written.has(file.path)) && ignore === 'present' ? 'done' : 'pending',
645
+ paths: name === null ? [] : [...files.map((file) => file.path), IGNORE_PATH],
439
646
  },
440
- {
441
- id: 'records',
442
- status: name !== null && written.has(recordsPath(name)) ? 'done' : 'pending',
443
- path: name === null ? '' : recordsPath(name),
444
- },
445
- { id: 'descriptor', status: 'pending', path: DESCRIPTOR_PATH },
647
+ { id: 'admission', status: 'pending', paths: [] },
648
+ { id: 'descriptor', status: 'pending', paths: [DESCRIPTOR_PATH] },
649
+ { id: 'capture', status: 'pending', paths: [CURRENT] },
650
+ ...(host === 'none' ? [] : [{ id: 'project', status: 'pending', paths: [] }]),
446
651
  ];
447
652
  return {
653
+ ...(request.adoption ? { adoption: request.adoption } : {}),
448
654
  root,
449
- owns: ownedPaths(name),
655
+ owns: ownedPaths(name, system),
450
656
  state,
451
657
  conflicts,
452
658
  leftovers: leftovers.sort(),
659
+ present: files.filter((file) => written.has(file.path)).map((file) => file.path),
660
+ ignore,
453
661
  steps,
454
662
  starter: {
455
663
  name,
456
664
  id,
665
+ system,
457
666
  files,
458
- descriptor: id === null || name === null ? null : starterDescriptor(id, name, base, provenance),
667
+ records,
668
+ descriptor: id === null || name === null ? null : starterDescriptor(id, name, base, provenance, system ? null : undefined),
459
669
  base: base.pin,
460
670
  systems: base.systems,
461
671
  provenance,
@@ -467,9 +677,22 @@ export function collectInit(request) {
467
677
  };
468
678
  }
469
679
  /**
470
- * M5.2 §3.1 steps 2–7, in that order. Each step either completes or leaves a state `collectInit` classifies as
471
- * resumable or recovery-required. The signal is observed at step boundaries (§5): before the first write it is the
472
- * plain interruption and the target is byte-identical; after one, the interruption names the rerun that finishes.
680
+ * The sentence the next action of a step that fails or is interrupted once the descriptor is written opens with:
681
+ * initialization is complete, so running `ia init` again refuses the target, and each effect is finished by its own
682
+ * command (design §3). The project effect's also says whether the capture before it was taken.
683
+ */
684
+ const INITIALIZED = 'The workspace is initialized.';
685
+ const CAPTURED = 'The workspace is initialized and captured.';
686
+ const UNCAPTURED = 'The workspace is initialized but not captured.';
687
+ /**
688
+ * M5.2 §3.1's steps, in position-and-projection §3's order. Each step before the descriptor either completes or leaves
689
+ * a state `collectInit` classifies as resumable or recovery-required. The signal is observed at step boundaries (§5):
690
+ * before the first write it is the plain interruption and the target is byte-identical; after one, the interruption
691
+ * names the rerun that finishes. Two effects follow the completion point, each reported apart, and each that fails or
692
+ * is interrupted leaves the workspace initialized and names its own command: the capture, `ia capture`, and, only when
693
+ * `options.project` is given (`--host`), the project effect, `ia host`. The project effect reads the live revision,
694
+ * never the capture (plan amendment B8), so it runs after a capture that failed too, and that failure is then refused
695
+ * with the capture's own repair, after a sentence saying the projection is written.
473
696
  */
474
697
  export async function applyInit(view, options) {
475
698
  const { root, starter } = view;
@@ -495,64 +718,54 @@ export async function applyInit(view, options) {
495
718
  for (const path of view.leftovers)
496
719
  unlinkSync(resolve(root, path));
497
720
  const step = (id) => view.steps.find((row) => row.id === id);
498
- // Step 3: M5.1 §4's three calls, offline, resolved the way `ia install` resolves (distribute.ts collectPlan).
499
- if (step('install').status === 'pending') {
721
+ // Step 3: the bundled base, installed as the workspace's one request.
722
+ if (step('install').status === 'pending')
723
+ await installBase(root, base, 'install', { signal: options.signal, checkpoint }, resume);
724
+ boundary('install');
725
+ if (view.adoption)
726
+ applyAdoption(planAdoption(root, view.adoption.id, view.adoption.release, false));
727
+ // Step 4, author: create-only, so a starter file already present with these bytes is skipped and nothing is ever
728
+ // rewritten. The ignore file is written only where none exists; one the target already holds is its own.
729
+ for (const file of starter.files)
730
+ if (!view.present.includes(file.path))
731
+ createFile(root, file.path, Buffer.from(file.text));
732
+ const ignore = existsSync(resolve(root, IGNORE_PATH)) ? 'present' : 'written';
733
+ if (ignore === 'written')
734
+ createFile(root, IGNORE_PATH, Buffer.from(IGNORE_TEXT));
735
+ boundary('author');
736
+ // Step 5, admission: the identities are read from the compiled graph, never string-constructed (M5.1 §2.3).
737
+ const { compiled } = admitStarter(root, starter.records, 'initialized', '');
738
+ const authored = compiled.map((record) => record.identity), distribution = compiled.find((record) => record.discriminator === 'distribution')?.identity ?? null;
739
+ boundary('admission');
740
+ // Step 6, the completion point (§4.1). A default starter's descriptor names no distribution (plan amendment B7).
741
+ createFile(root, DESCRIPTOR_PATH, Buffer.from(descriptorText(starterDescriptor(id, name, base, starter.provenance, distribution ?? undefined))));
742
+ checkpoint('init:descriptor');
743
+ const installed = readInstalledState({ root });
744
+ // Step 7, the capture effect: `ia capture` on the workspace just initialized, written through db's writeCapture. A
745
+ // failure is refused as `ia capture` refuses it, located and with its repair (`captureFailure`), for this root.
746
+ const recapture = `ia capture --root ${quote(root)}`;
747
+ let capture, failed;
748
+ if (options.signal?.aborted) {
749
+ if (options.project === undefined)
750
+ throw new Interrupted(`${INITIALIZED} Run "${recapture}" to capture it.`);
751
+ }
752
+ else
500
753
  try {
501
- cacheArchive(root, base.bytes, base.pin.archive);
502
- const choices = await resolveCatalog({
503
- root,
504
- entries: [{ path: cachePath(base.pin.archive), withdrawn: false }],
505
- offline: true,
506
- signal: options.signal,
507
- });
508
- options.signal?.throwIfAborted();
509
- const lock = resolveReleases([{ id: base.pin.id, range: `^${base.pin.version}` }], choices, DISTRIBUTION_ENGINE_VERSION).lock;
510
- applyInstallation(planInstallation(root, lock, 'install'), { checkpoint });
754
+ const written = collectCapture(root, root);
755
+ capture = { revision: written.snapshot.revision, records: written.snapshot.counts.records };
511
756
  }
512
757
  catch (error) {
513
- if (options.signal?.aborted)
514
- throw resume;
515
- // collectInit already refuses a lock present at planning time; this is another installer taking it between
516
- // planning and apply. The installer's code is kept (§4.1 of the contract); the next action names the recovery
517
- // that clears the lock if that installer has since died.
518
- if (codeOf(error, '') === 'IA-DIST-INSTALL-BUSY')
519
- throw new Refusal('IA-DIST-INSTALL-BUSY', error instanceof Error ? error.message : String(error), 3, { path: root }, `If no installer is running, an interrupted one left its lock: run "${recoverCommand('recover', root)}", then apply again.`);
520
- throw error;
758
+ failed = refusalOf(captureFailure(error, root, recapture));
521
759
  }
522
- }
523
- boundary('install');
524
- // Steps 4 and 5: create-only, so an existing byte-equal file is skipped and nothing is ever rewritten.
525
- for (const [id, text] of [
526
- ['system', starter.files[0].text],
527
- ['records', starter.files[1].text],
528
- ]) {
529
- if (step(id).status === 'pending')
530
- createFile(root, step(id).path, Buffer.from(text));
531
- boundary(id);
532
- }
533
- // Step 6: the identity is read from the compiled graph, never string-constructed (M5.1 §2.3).
534
- const session = openWorkspaceSession({ root });
535
- let distribution;
536
- try {
537
- const errors = session.admission().findings.filter((finding) => finding.severity === 'error');
538
- if (errors.length > 0)
539
- throw new Refusal('IA-CLI-FAILED', `The initialized workspace failed admission with ${errors.length} error findings; first: ${errors[0].code}`, 3, { path: root }, `Run "ia validate --root ${quote(root)}" for the findings.`);
540
- const record = session.reader
541
- .records()
542
- .find((node) => node.discriminator === 'distribution' &&
543
- node.name === `${name}-distribution` &&
544
- node.source.path === recordsPath(name));
545
- if (record === undefined)
546
- throw new Refusal('IA-CLI-FAILED', `The compiled workspace has no @distribution ${name}-distribution in ${recordsPath(name)}`, 3, { path: root }, `Run "ia inspect --path ${recordsPath(name)} --root ${quote(root)}" for the records that file admitted.`);
547
- distribution = record.identity;
548
- }
549
- finally {
550
- session.close();
551
- }
552
- // Step 7, the completion point (§4.1).
553
- createFile(root, DESCRIPTOR_PATH, Buffer.from(descriptorText(starterDescriptor(id, name, base, starter.provenance, distribution))));
554
- checkpoint('init:descriptor');
555
- const installed = readInstalledState({ root });
760
+ if (capture !== undefined)
761
+ checkpoint('init:capture');
762
+ // Step 8, the project effect, only with `--host`: after a capture that failed too. A signal the capture stopped for,
763
+ // it observes itself, naming `ia host`, the effect this invocation asked for, after saying the capture was not taken.
764
+ const projected = options.project?.(capture === undefined ? UNCAPTURED : CAPTURED);
765
+ if (failed !== undefined)
766
+ throw new Refusal(failed.code, failed.message, 3, failed.where, `${projected === undefined ? INITIALIZED : `The workspace is initialized and its ${projected.effect.host} projection is written.`} ${failed.next ?? `Run "${recapture}" to capture it.`}`);
767
+ if (capture === undefined)
768
+ throw new Interrupted(`${INITIALIZED} Run "${recapture}" to capture it.`);
556
769
  return {
557
770
  status: 'initialized',
558
771
  resumed: view.state === 'resumable',
@@ -560,14 +773,53 @@ export async function applyInit(view, options) {
560
773
  distribution,
561
774
  generation: installed.pointer.generation,
562
775
  counter: installed.pointer.counter,
776
+ authored,
777
+ ignore,
778
+ effects: { capture, project: projected?.effect ?? 'skipped' },
779
+ ...(projected === undefined ? {} : { host: projected.host }),
563
780
  };
564
781
  }
782
+ /**
783
+ * M5.1 §4's three calls, offline, resolved the way `ia install` resolves (distribute.ts collectPlan): the bundled base
784
+ * is cached, resolved from that one archive and installed as the workspace's one request, by `ia init` into a new
785
+ * workspace and by `ia init --migrate` in place of a 1.x base. A signal during it is `resume`.
786
+ */
787
+ async function installBase(root, base, operation, options, resume) {
788
+ try {
789
+ cacheArchive(root, base.bytes, base.pin.archive);
790
+ const choices = await resolveCatalog({
791
+ root,
792
+ entries: [{ path: cachePath(base.pin.archive), withdrawn: false }],
793
+ offline: true,
794
+ signal: options.signal,
795
+ });
796
+ options.signal?.throwIfAborted();
797
+ const lock = resolveReleases([{ id: base.pin.id, range: `^${base.pin.version}` }], choices, DISTRIBUTION_ENGINE_VERSION).lock;
798
+ applyInstallation(planInstallation(root, lock, operation), { checkpoint: options.checkpoint });
799
+ }
800
+ catch (error) {
801
+ if (options.signal?.aborted)
802
+ throw resume;
803
+ // collectInit already refuses a lock present at planning time; this is another installer taking it between
804
+ // planning and apply. The installer's code is kept (§4.1 of the contract); the next action names the recovery
805
+ // that clears the lock if that installer has since died.
806
+ if (codeOf(error, '') === 'IA-DIST-INSTALL-BUSY')
807
+ throw new Refusal('IA-DIST-INSTALL-BUSY', error instanceof Error ? error.message : String(error), 3, { path: root }, `If no installer is running, an interrupted one left its lock: run "${recoverCommand('recover', root)}", then apply again.`);
808
+ throw error;
809
+ }
810
+ }
811
+ /** The refusal's message for `conflicts`: the one conflict at its path, or every conflict with its reason. */
812
+ const conflictMessage = (conflicts, blocked) => conflicts.length === 1
813
+ ? `${conflicts[0].reason}: ${conflicts[0].path}`
814
+ : `${conflicts.length} conflicts block ${blocked}: ${conflicts.map((row) => `${row.path} (${row.reason})`).join('; ')}`;
565
815
  /** M5.2 §4.1: every conflict is listed; `--apply` refuses at class 3 and writes nothing. */
816
+ function initializedNext(view) {
817
+ if (!view.conflicts.some((row) => row.path === DESCRIPTOR_PATH && row.reason === 'The target is already initialized'))
818
+ return null;
819
+ return safeRootAdvice(`${existsSync(resolve(view.root, WORKSPACE_PATH)) || existsSync(resolve(view.root, SYSTEMS)) ? '' : 'Restore the authored .ia/src/workspace.ia from source control first. '}Run "ia position --root ${quote(view.root)}" to inspect this initialized workspace.`, [view.root]);
820
+ }
566
821
  function conflictRefusal(view) {
567
- const message = view.conflicts.length === 1
568
- ? `${view.conflicts[0].reason}: ${view.conflicts[0].path}`
569
- : `${view.conflicts.length} conflicts block initialization: ${view.conflicts.map((row) => `${row.path} (${row.reason})`).join('; ')}`;
570
- return new Refusal('IA-CLI-CONFLICT', message, 3, { path: view.root }, `Run "${view.invocation}" to review the plan and its conflicts.`);
822
+ return new Refusal('IA-CLI-CONFLICT', conflictMessage(view.conflicts, 'initialization'), 3, { path: view.root }, initializedNext(view) ?? `Run "${view.invocation}" to review the plan and its conflicts.`);
571
823
  }
572
824
  export function initEnvelope(view, apply, applied = null) {
573
825
  const { starter } = view;
@@ -577,14 +829,30 @@ export function initEnvelope(view, apply, applied = null) {
577
829
  root: view.root,
578
830
  apply,
579
831
  plan: {
832
+ ...(view.adoption
833
+ ? {
834
+ adoption: {
835
+ id: view.adoption.id,
836
+ version: view.adoption.release.version,
837
+ revision: view.adoption.release.revision,
838
+ placement: 'open',
839
+ band: 50,
840
+ files: view.adoption.release.files.map((file) => file.path),
841
+ },
842
+ }
843
+ : {}),
580
844
  state: view.state,
845
+ ...(initializedNext(view) === null ? {} : { next: initializedNext(view) }),
581
846
  owns: view.owns.map((row) => row.path),
582
847
  conflicts: view.conflicts.map((row) => ({ path: row.path, reason: row.reason })),
583
848
  leftovers: view.leftovers.map((path) => ({ path, reason: 'leftover temporary file' })),
584
849
  steps: view.steps.map((row) => ({ id: row.id, status: row.status })),
585
850
  starter: {
586
851
  id: starter.id,
852
+ system: starter.system,
587
853
  paths: [...starter.files.map((file) => file.path), ...(starter.descriptor === null ? [] : [DESCRIPTOR_PATH])],
854
+ records: starter.records.map((record) => `@${record.word} ${record.name}`),
855
+ ignore: { path: IGNORE_PATH, status: view.ignore },
588
856
  descriptor: starter.descriptor,
589
857
  base: starter.base,
590
858
  provenance: {
@@ -605,17 +873,27 @@ const settled = (view) => view.directory === 'absent'
605
873
  : `None. The target directory holds ${view.entries} ${view.entries === 1 ? 'entry' : 'entries'}, none of them conflicting.`;
606
874
  const STEP_LABEL = {
607
875
  install: 'Install',
608
- system: 'System',
609
- records: 'Records',
876
+ author: 'Author',
877
+ admission: 'Admission',
610
878
  descriptor: 'Descriptor',
879
+ capture: 'Capture',
880
+ project: 'Project',
611
881
  };
612
882
  const stepValue = (view, step) => {
613
883
  const pin = view.starter.base;
614
884
  const what = step.id === 'install'
615
885
  ? `${pin.id} ${pin.version} from the bundled archive`
616
- : step.path === ''
617
- ? 'needs a valid name'
618
- : step.path;
886
+ : step.id === 'admission'
887
+ ? 'zero error findings before the descriptor is written'
888
+ : step.id === 'project'
889
+ ? `the ${view.host} projection, through ia host ${view.host}`
890
+ : step.paths.length === 0
891
+ ? 'needs a valid name'
892
+ : step.id === 'author' && view.ignore === 'present'
893
+ ? `${step.paths.slice(0, -1).join(', ')}; ${IGNORE_PATH} exists and is left as it is`
894
+ : step.id === 'capture'
895
+ ? `${step.paths[0]}, as ia capture writes it`
896
+ : step.paths.join(', ');
619
897
  return step.status === 'done' ? `${what}; already present` : what;
620
898
  };
621
899
  const stepRows = (view, symbol, caps) => [
@@ -638,12 +916,21 @@ const starterRows = (view, caps) => {
638
916
  {
639
917
  symbol: 'info',
640
918
  label: 'Starter records',
641
- value: words(`@system ${starter.name} and its steward; @workspace ${starter.name} composing ${starter.systems.length} systems; @distribution ${starter.name}-distribution`),
919
+ value: words(`@workspace ${starter.name} composing ${starter.systems.length} systems${starter.system ? ` and @system ${starter.name}` : ''}; its participant @agent ${starter.name}; @mandate ${starter.name}-mandate`),
642
920
  },
921
+ ...(starter.system
922
+ ? [
923
+ {
924
+ symbol: 'info',
925
+ label: 'Local system',
926
+ value: words(`@system ${starter.name} and its steward; @distribution ${starter.name}-distribution rooted at it`),
927
+ },
928
+ ]
929
+ : []),
643
930
  {
644
931
  symbol: 'info',
645
932
  label: 'Release',
646
- value: words(`${starter.id} ${STARTER_VERSION}, requiring ${pin.id} ^${pin.version}`),
933
+ value: words(`${starter.id} ${STARTER_VERSION}, requiring ${pin.id} ^${pin.version}${starter.system ? '' : '; no distribution, so ia pack refuses until one is authored'}`),
647
934
  },
648
935
  { symbol: 'info', label: 'Provenance', value: words(provenanceText(starter.provenance)) },
649
936
  ];
@@ -704,14 +991,29 @@ const planBlocks = (view, caps) => {
704
991
  ],
705
992
  ];
706
993
  };
707
- export function renderInit(view, caps) {
708
- const next = view.state === 'conflict'
709
- ? `Resolve the conflicts above, then run "${view.invocation} --apply --yes".`
710
- : `Apply with "${view.invocation} --apply --yes".${view.state === 'resumable' ? ' Completed steps are skipped.' : ''}`;
994
+ export function renderInit(view, caps, supplied, advice) {
995
+ const next = safeRootAdvice(view.state === 'conflict'
996
+ ? (initializedNext(view) ?? `Resolve the conflicts above, then run "${view.invocation} --apply --yes".`)
997
+ : `Apply with "${view.invocation} --apply --yes".${view.state === 'resumable' ? ' Completed steps are skipped.' : ''}`, [view.root, supplied], advice);
711
998
  return document([
712
999
  headerLine('Plan', 'init', [{ text: view.root, column: 50 }], caps),
713
1000
  entry([words('This is a preview. Nothing has been written.')], { depth: 1 }, caps),
1001
+ ...(view.adoption
1002
+ ? [
1003
+ entry([
1004
+ words(`Adopt ${view.adoption.id}@${view.adoption.release.version}, pinned ${view.adoption.release.revision}, as source-only material at @open (band 50).`),
1005
+ ], { depth: 1 }, caps),
1006
+ ]
1007
+ : []),
714
1008
  ...planBlocks(view, caps),
1009
+ ...(view.directory === 'absent' &&
1010
+ (!inertCommandRoot(view.root) || (supplied !== undefined && !inertCommandRoot(supplied)))
1011
+ ? [
1012
+ entry([
1013
+ words('Create the target directory without pasting its path into a shell, then enter it before running the suggested command.'),
1014
+ ], { depth: 0 }, caps),
1015
+ ]
1016
+ : []),
715
1017
  entry([words(next)], { depth: 0, symbol: 'step' }, caps),
716
1018
  ], { leadingBlank: true });
717
1019
  }
@@ -719,6 +1021,25 @@ export function renderInit(view, caps) {
719
1021
  export const renderInitSummary = (view, caps) => document([headerLine('Plan', 'init', [{ text: view.root, column: 50 }], caps), ...planBlocks(view, caps)], {
720
1022
  leadingBlank: true,
721
1023
  });
1024
+ /**
1025
+ * The report rows `ia init` and `ia init --migrate` share, each from one function so the two verbs word them alike:
1026
+ * the records authored and the ignore file, the capture effect, and the closing next step.
1027
+ */
1028
+ const authoredEntry = (applied, caps, ignored = 'work/ and distributions/') => entry([
1029
+ words(`Authored ${applied.authored.length} records:`),
1030
+ ...applied.authored.map((identity) => [atom(identity, null, 0)]),
1031
+ words(applied.ignore === 'written'
1032
+ ? `Wrote ${IGNORE_PATH}, ignoring ${ignored}.`
1033
+ : `${IGNORE_PATH} already exists and is left as it is.`),
1034
+ ], { depth: 1, symbol: 'success' }, caps);
1035
+ const capturedEntry = (capture, caps) => entry([
1036
+ words(`Captured ${capture.records} records at revision ${truncateDigest(capture.revision, caps.ascii)} to ${CURRENT}.`),
1037
+ ], { depth: 1, symbol: 'success' }, caps);
1038
+ const closingEntry = (distribution, caps) => entry([
1039
+ words(distribution === null
1040
+ ? 'Run "ia validate" to check the workspace, or "ia position" for the position body an agent starts from.'
1041
+ : 'Run "ia validate" to check the workspace, or "ia pack --descriptor .ia/release.json" to build its release.'),
1042
+ ], { depth: 0, symbol: 'step' }, caps);
722
1043
  export function renderApplied(view, applied, caps) {
723
1044
  return document([
724
1045
  headerLine('Init', applied.id, [{ text: view.root, column: 50 }], caps),
@@ -726,30 +1047,43 @@ export function renderApplied(view, applied, caps) {
726
1047
  words(`${applied.resumed ? 'Finished initializing' : 'Initialized'} ${applied.id}; release descriptor ${DESCRIPTOR_PATH}.`),
727
1048
  words(`Installed generation ${truncateDigest(applied.generation, caps.ascii)}, counter ${applied.counter}.`),
728
1049
  ], { depth: 1, symbol: 'success' }, caps),
729
- // Host registration spec §4: written is all this can say; `ia doctor` reports what is observed.
730
- ...(applied.host === undefined
731
- ? []
732
- : [
733
- entry([words(`Registered with ${view.host}; written, not observed answering.`)], { depth: 1, symbol: 'success' }, caps),
734
- ]),
1050
+ // Position-and-projection §3: the records authored, then each effect, reported apart.
1051
+ authoredEntry(applied, caps),
1052
+ capturedEntry(applied.effects.capture, caps),
1053
+ applied.effects.project === 'skipped'
1054
+ ? entry([words('Project skipped: no host was selected.')], { depth: 1, symbol: 'info' }, caps)
1055
+ : entry([
1056
+ words(`Projected the position packet for ${applied.effects.project.host}:`),
1057
+ ...applied.effects.project.files.map((file) => [atom(file.path, 'cyan', 0)]),
1058
+ words(`Receipt ${applied.effects.project.receipt}.`),
1059
+ // Host registration spec §4: written is all this can say; `ia doctor` reports what is observed.
1060
+ words(`Registered with ${view.host}; written, not observed answering.`),
1061
+ ], { depth: 1, symbol: 'success' }, caps),
735
1062
  stepRows(view, () => 'success', caps),
736
1063
  // Spec §5.3 and §5.4: the notes `ia host` prints after a registration, from the same function.
737
1064
  ...(applied.host === undefined || view.host === 'none' ? [] : hostNotes(view.host, caps)),
738
- entry([
739
- words('Run "ia validate" to check the workspace, or "ia pack --descriptor .ia/release.json" to build its release.'),
740
- ], { depth: 0, symbol: 'step' }, caps),
1065
+ closingEntry(applied.distribution, caps),
741
1066
  ], { leadingBlank: true });
742
1067
  }
743
- const renderDeclined = (view, caps) => document([
1068
+ const renderDeclined = (view, caps, supplied, advice) => document([
744
1069
  entry([words('Nothing was applied.')], { depth: 0, symbol: 'info' }, caps),
745
- entry([words(`Apply with "${view.invocation} --apply --yes".`)], { depth: 0, symbol: 'step' }, caps),
1070
+ entry([words(safeRootAdvice(`Apply with "${view.invocation} --apply --yes".`, [view.root, supplied], advice))], { depth: 0, symbol: 'step' }, caps),
746
1071
  ], { leadingBlank: true });
747
1072
  function invocationOf(context) {
748
1073
  const { args } = context;
749
1074
  const parts = ['ia init', ...args.positionals.map(quote)];
750
1075
  const id = args.value('id'), host = args.value('host');
1076
+ for (const option of ['adopt', 'registry']) {
1077
+ const value = args.value(option);
1078
+ if (value !== undefined)
1079
+ parts.push(`--${option}`, quote(value));
1080
+ }
751
1081
  if (id !== undefined)
752
1082
  parts.push('--id', quote(id));
1083
+ if (args.flag('migrate'))
1084
+ parts.push('--migrate');
1085
+ if (args.flag('system'))
1086
+ parts.push('--system');
753
1087
  if (host !== undefined && host !== 'none')
754
1088
  parts.push('--host', host);
755
1089
  return parts.join(' ');
@@ -757,6 +1091,8 @@ function invocationOf(context) {
757
1091
  export async function runInit(context) {
758
1092
  const { args, host } = context;
759
1093
  const id = args.value('id');
1094
+ if (args.value('registry') !== undefined && args.value('adopt') === undefined)
1095
+ throw new UsageError('ia init --registry requires --adopt');
760
1096
  // A malformed identity is usage (§3), decided before the target is read.
761
1097
  if (id !== undefined && (!PACKAGE_ID.test(id) || id.includes('..')))
762
1098
  throw new UsageError(`--id must be <provider/name>; got ${id}`);
@@ -786,13 +1122,18 @@ async function initialize(context, root, id) {
786
1122
  const iaHome = iaHomeOf(host.env);
787
1123
  if (iaHome !== undefined)
788
1124
  located(root, `Set IA_HOME to an absolute directory outside ${root}, then run "${invocationOf(context)}".`, () => assertHomeOutsideWorkspace(iaHome, root));
1125
+ if (args.flag('migrate'))
1126
+ return migrate(context, root);
789
1127
  const selected = (args.value('host') ?? 'none');
790
1128
  const apply = args.flag('apply');
791
1129
  const existing = statSync(root, { throwIfNoEntry: false }) === undefined ? dirname(root) : root;
1130
+ const adoption = args.value('adopt') === undefined ? undefined : await registryWorkspace(context, root, args.value('adopt'));
792
1131
  const view = collectInit({
1132
+ ...(adoption ? { adoption } : {}),
793
1133
  root,
794
1134
  host: selected,
795
1135
  id,
1136
+ system: args.flag('system'),
796
1137
  packageRoot: host.packageRoot,
797
1138
  git: gitIn(existing, host.env),
798
1139
  invocation: invocationOf(context),
@@ -801,7 +1142,7 @@ async function initialize(context, root, id) {
801
1142
  ? { exitCode: 0, stdout: JSON.stringify(initEnvelope(view, apply, applied)) + '\n', stderr: '' }
802
1143
  : {
803
1144
  exitCode: 0,
804
- stdout: applied === null ? renderInit(view, caps) : renderApplied(view, applied, caps),
1145
+ stdout: applied === null ? renderInit(view, caps, args.positionals[0], host) : renderApplied(view, applied, caps),
805
1146
  stderr: '',
806
1147
  };
807
1148
  // §2.1: conflicts are reported inside the plan and are not an error class, so a plan is always exit 0.
@@ -811,12 +1152,18 @@ async function initialize(context, root, id) {
811
1152
  throw conflictRefusal(view);
812
1153
  // §2.8 rule 3, as `ia install` asks it: parsing already refused every `--apply` whose question cannot be answered.
813
1154
  if (!args.flag('yes') && !(await confirm(host.interaction, renderInitSummary(view, caps), CONFIRMATION)))
814
- return { exitCode: 0, stdout: renderDeclined(view, caps), stderr: '' };
815
- const initialized = await applyInit(view, { packageRoot: host.packageRoot, signal: host.signal });
816
- clearDecline(host.env, root);
817
- if (selected === 'none')
818
- return rendered(initialized);
819
- return rendered({ ...initialized, host: registerHost(context, selected, root) });
1155
+ return { exitCode: 0, stdout: renderDeclined(view, caps, args.positionals[0], host), stderr: '' };
1156
+ // The project effect, last (position-and-projection §3): the `ia host` path, whose apply writes the receipt.
1157
+ const project = selected === 'none' ? undefined : (done) => registerHost(context, selected, root, done);
1158
+ try {
1159
+ return rendered(await applyInit(view, { packageRoot: host.packageRoot, signal: host.signal, project }));
1160
+ }
1161
+ finally {
1162
+ // Once the descriptor, the completion point, is written, the target is initialized whatever an effect after it
1163
+ // did, so its recorded decline is forgotten (`clearDecline`).
1164
+ if (existsSync(resolve(root, DESCRIPTOR_PATH)))
1165
+ clearDecline(host.env, root);
1166
+ }
820
1167
  }
821
1168
  /**
822
1169
  * Host registration spec §4 "init --host": the `ia host <host> --apply` path over the workspace just initialized.
@@ -825,23 +1172,27 @@ async function initialize(context, root, id) {
825
1172
  * the step never asks a second question. Every failure here happens after initialization completed: the workspace
826
1173
  * stays initialized, and each refusal keeps the service's code, message and location (contract §4.1).
827
1174
  *
828
- * Its next action is `ia host`'s own remedy for that refusal, after a sentence saying initialization completed. Every
829
- * `ia host` command the remedy names gains `--root <root>`, because `<directory>` may be relative to a cwd that
830
- * is not the workspace, and `ia host` would otherwise discover a different root or none. A failure `ia host` gives
831
- * no remedy for falls back to the rerun that finishes registration. A recovery followed by "rerun" would send the user
832
- * back to this init, which now refuses as initialized, so it names `ia host` instead, which names that recovery itself.
1175
+ * Its next action is `ia host`'s own remedy for that refusal, after `done`, the sentence saying what initialization
1176
+ * completed, the capture included or not. Every `ia host` command the remedy names gains `--root <root>`, because
1177
+ * `<directory>` may be relative to a cwd that is not the workspace, and `ia host` would otherwise discover a different
1178
+ * root or none. A failure `ia host` gives no remedy for falls back to the rerun that finishes registration. A recovery
1179
+ * followed by "rerun" would send the user back to this init, which now refuses as initialized, so it names `ia host`
1180
+ * instead, which names that recovery itself. The effect is read from the receipt the projection apply just wrote.
833
1181
  */
834
- function registerHost(context, selected, root) {
1182
+ function registerHost(context, selected, root, done) {
835
1183
  const host = `ia host ${selected} --root ${quote(root)} --apply`;
836
1184
  const finish = `Run "${host}" to finish host registration.`, recover = `Run "${host}" for the recovery it names, then run it again to finish host registration.`;
837
- const composed = (next) => `The workspace is initialized. ${next === null ? finish : next.endsWith(THEN_RERUN) ? recover : rootedNext(next, selected, root)}`;
1185
+ const composed = (next) => `${done} ${next === null ? finish : next.endsWith(THEN_RERUN) ? recover : rootedNext(next, selected, root)}`;
838
1186
  // M5.2 §5: a signal observed after the last init write interrupts a command that has written, so it names the rerun.
839
1187
  if (context.host.signal?.aborted)
840
1188
  throw new Interrupted(composed(null));
841
1189
  const command = findCommand('host');
842
1190
  const args = parseArguments([selected, '--root', root, '--apply', '--yes'], command.grammar);
843
1191
  try {
844
- return applyHostSet(collectHost({ ...context, command, args }), context.host.packageRoot, context.host.signal);
1192
+ const applied = applyHostSet(collectHost({ ...context, command, args }), context.host.packageRoot, context.host.signal);
1193
+ // A host apply that returns has projected, and `applyHostProjection` wrote the receipt (B12) before it returned.
1194
+ const receipt = readReceipt(root, selected);
1195
+ return { effect: { host: selected, files: receipt.files, receipt: STATE.receipt(selected) }, host: applied };
845
1196
  }
846
1197
  catch (error) {
847
1198
  if (error instanceof Interrupted)
@@ -851,6 +1202,755 @@ function registerHost(context, selected, root) {
851
1202
  throw new Refusal(refusal.code, refusal.message, refusal.exit, refusal.where, composed(error instanceof Refusal ? refusal.next : null));
852
1203
  }
853
1204
  }
1205
+ /** The release whose starter `ia init --migrate` rewrites. */
1206
+ export const MIGRATES_FROM = '1.1.0';
1207
+ const SYSTEMS = '.ia/src/systems';
1208
+ /** The 1.x starter file beside the user's record files: its `@workspace` and the `@distribution` rooted at it. */
1209
+ const legacyRecordsPath = (name) => `${systemFolder(name)}/records/workspace.ia`;
1210
+ const spelled = (record) => `@${record.discriminator} ${record.name}`;
1211
+ /** A descriptor's dependency rows, compared as text: each id, range and the systems it externalizes. */
1212
+ const spelledRows = (rows) => rows.map((row) => `${row.id} ${row.range} ${row.systems.join(',')}`).join('; ');
1213
+ /**
1214
+ * The one refusal for a target `--migrate` does not recognize. Its message names what was found and the shape a 1.1.0
1215
+ * starter has there; its next action names the help for the forms the verb takes.
1216
+ */
1217
+ const unshaped = (reason, path) => new Refusal('IA-CLI-CONFLICT', `The target is not a ${MIGRATES_FROM} starter workspace: ${reason}`, 3, { path }, 'Run "ia init --help" for the forms this verb takes.');
1218
+ const entriesOf = (root, path) => readdirSync(resolve(root, path), { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
1219
+ const directory = (root, path) => lstatSync(resolve(root, path), { throwIfNoEntry: false })?.isDirectory() === true;
1220
+ /**
1221
+ * The preflight's folder half, read without following a link: `.ia/src/systems/` holds one folder, the local system,
1222
+ * and it holds only `system.ia` and `records/*.ia`, with `records/workspace.ia` among them. Its name and the user's
1223
+ * record files beside the starter's, sorted.
1224
+ */
1225
+ function starterFolder(root) {
1226
+ if (!directory(root, SYSTEMS))
1227
+ throw unshaped(`${SYSTEMS}/ is absent, so it has no local system`, root);
1228
+ const folders = entriesOf(root, SYSTEMS);
1229
+ if (folders.length !== 1 || !folders[0].isDirectory() || !NAME.test(folders[0].name))
1230
+ throw unshaped(`${SYSTEMS}/ holds ${folders.length === 0 ? 'nothing' : folders.map((entry) => entry.name).join(', ')}, where a ${MIGRATES_FROM} starter holds one folder, its local system`, SYSTEMS);
1231
+ const name = folders[0].name, folder = systemFolder(name);
1232
+ const foreign = (path) => unshaped(`${path} is not part of one, whose system folder holds only system.ia and records/*.ia`, path);
1233
+ for (const entry of entriesOf(root, folder))
1234
+ if (!(entry.name === 'system.ia' && entry.isFile()) && !(entry.name === 'records' && entry.isDirectory()))
1235
+ throw foreign(`${folder}/${entry.name}`);
1236
+ if (!existsSync(resolve(root, systemPath(name))))
1237
+ throw unshaped(`${systemPath(name)} is absent`, folder);
1238
+ if (!directory(root, `${folder}/records`))
1239
+ throw unshaped(`${legacyRecordsPath(name)} is absent`, folder);
1240
+ const files = [];
1241
+ for (const entry of entriesOf(root, `${folder}/records`)) {
1242
+ if (!entry.isFile() || !entry.name.endsWith('.ia'))
1243
+ throw foreign(`${folder}/records/${entry.name}`);
1244
+ if (entry.name !== 'workspace.ia')
1245
+ files.push(entry.name);
1246
+ }
1247
+ if (!existsSync(resolve(root, legacyRecordsPath(name))))
1248
+ throw unshaped(`${legacyRecordsPath(name)} is absent`, folder);
1249
+ return { name, files };
1250
+ }
1251
+ /**
1252
+ * The preflight (plan and `--apply` alike), before anything is written. Unrecognized, it refuses naming
1253
+ * `ia init --help`: no descriptor naming the starter's distribution, a system folder holding anything else, a
1254
+ * `system.ia` or `records/workspace.ia` holding any record but the starter's, a local `@system` that registers words,
1255
+ * or a base to replace in a lock that holds more than that base. A workspace that does not admit is refused naming
1256
+ * `ia validate`, because the migrated one must admit for its effects; so is a pending host journal, naming its
1257
+ * recovery. A destination that already exists, a record that already holds the word and name of a starter record the
1258
+ * migration authors anew, and a registered projection whose guard retirement or file plan the planners refuse, are
1259
+ * listed as conflicts, which the plan reports and `--apply` refuses. The three records use fields only the base this
1260
+ * CLI bundles declares, so the apply installs it first unless the workspace has it installed already, as `ia init`
1261
+ * does. The registered hosts are the ones the install refresh re-projects after an update, as the base install is
1262
+ * (`registeredProjections`): those whose projection state exists, as `ia host` and `ia doctor` read ownership.
1263
+ */
1264
+ export function collectMigration(request) {
1265
+ const { root } = request, system = request.system === true;
1266
+ if (!existsSync(resolve(root, DESCRIPTOR_PATH)))
1267
+ throw unshaped(`${DESCRIPTOR_PATH} is absent, so no initialization completed here`, root);
1268
+ const recovery = readMigrationJournal(root, system, readBase(request.packageRoot).pin);
1269
+ if (recovery !== null) {
1270
+ const installed = readInstalledState({ root }).lock?.packages.find((row) => row.id === recovery.view.base.pin.id);
1271
+ return {
1272
+ ...recovery.view,
1273
+ steps: installed?.archive === recovery.view.base.pin.archive
1274
+ ? recovery.view.steps.filter((step) => step !== 'install')
1275
+ : recovery.view.steps,
1276
+ invocation: request.invocation ?? recovery.view.invocation,
1277
+ };
1278
+ }
1279
+ const { name, files: others } = starterFolder(root);
1280
+ let raw, descriptor;
1281
+ try {
1282
+ raw = readWorkspaceJson({ root, path: DESCRIPTOR_PATH });
1283
+ descriptor = decodeReleaseDescriptor(raw);
1284
+ }
1285
+ catch (error) {
1286
+ throw unshaped(`${DESCRIPTOR_PATH} is not a release descriptor (${error instanceof Error ? error.message : String(error)})`, DESCRIPTOR_PATH);
1287
+ }
1288
+ if (descriptor.distribution === undefined)
1289
+ throw unshaped(`${DESCRIPTOR_PATH} names no distribution, where a ${MIGRATES_FROM} starter's names its own`, DESCRIPTOR_PATH);
1290
+ const session = openSession(root);
1291
+ let records, admitted;
1292
+ try {
1293
+ records = session.reader.records();
1294
+ admitted = session.admission().status === 'admitted';
1295
+ }
1296
+ finally {
1297
+ session.close();
1298
+ }
1299
+ if (!admitted)
1300
+ throw new Refusal('IA-CLI-CONFLICT', 'The workspace does not admit; migrating it needs zero error findings', 3, { path: root }, `Run "ia validate --root ${quote(root)}" and fix the reported errors.`);
1301
+ const at = (path) => records.filter((record) => record.source.path === path);
1302
+ const identities = (path) => at(path)
1303
+ .map((record) => record.identity)
1304
+ .sort();
1305
+ /** The records `path` holds, which must be exactly `expected`. */
1306
+ const holds = (path, expected) => {
1307
+ const found = at(path);
1308
+ if (found.length !== expected.length ||
1309
+ !expected.every(([word, named]) => found.some((record) => record.discriminator === word && record.name === named)))
1310
+ throw unshaped(`${path} holds ${found.length === 0 ? 'no record' : found.map(spelled).join(', ')}, where a ${MIGRATES_FROM} starter's holds exactly ${expected.map(([word, named]) => `@${word} ${named}`).join(' and ')}`, path);
1311
+ return found;
1312
+ };
1313
+ const local = holds(systemPath(name), [
1314
+ ['system', name],
1315
+ ['agent', `${name}-steward`],
1316
+ ]);
1317
+ const starter = holds(legacyRecordsPath(name), [
1318
+ ['workspace', name],
1319
+ ['distribution', `${name}-distribution`],
1320
+ ]);
1321
+ const registered = local
1322
+ .find((record) => record.discriminator === 'system')
1323
+ .sections.find((section) => section.name === 'discriminators')
1324
+ ?.fields.flatMap((child) => ('key' in child ? [child.key] : []));
1325
+ if (registered !== undefined && registered.length > 0)
1326
+ throw unshaped(`its local @system ${name} registers ${registered.join(', ')}, where a ${MIGRATES_FROM} starter's registers no word`, systemPath(name));
1327
+ const distribution = starter.find((record) => record.discriminator === 'distribution').identity;
1328
+ if (descriptor.distribution !== distribution)
1329
+ throw unshaped(`${DESCRIPTOR_PATH} names ${descriptor.distribution}, where a ${MIGRATES_FROM} starter's names ${distribution}`, DESCRIPTOR_PATH);
1330
+ // The base the three records need. A 1.x base declares neither `composition.sources` and `composition.steward` nor
1331
+ // the `@mandate`'s `authority`, so another archive than the bundled one is replaced, which only a lock holding that
1332
+ // one base allows: a replacement resolved from the bundled archive alone would drop every other package.
1333
+ const base = readBase(request.packageRoot);
1334
+ const state = readInstalledState({ root });
1335
+ const lock = state.status === 'installed' ? state.lock : undefined;
1336
+ const locked = lock?.packages.find((pkg) => pkg.id === base.pin.id);
1337
+ const bundled = (pkg) => pkg.archive === base.pin.archive && pkg.manifest === base.pin.manifest;
1338
+ if (locked === undefined ||
1339
+ (!bundled(locked) &&
1340
+ (lock.packages.length !== 1 || lock.requests.length !== 1 || lock.requests[0].id !== base.pin.id)))
1341
+ throw unshaped(`${INSTALL_PATHS.lock} locks ${lock === undefined || lock.packages.length === 0 ? 'nothing' : lock.packages.map((pkg) => `${pkg.id} ${pkg.version}`).join(', ')}, where a ${MIGRATES_FROM} starter's locks only ${base.pin.id}, which the migration replaces with the archive this CLI bundles`, INSTALL_PATHS.lock);
1342
+ // The new @workspace keeps the 1.x one's composition, less the local system, which only `--system` composes.
1343
+ const field = starter
1344
+ .find((record) => record.discriminator === 'workspace')
1345
+ .sections.find((section) => section.name === 'composition')
1346
+ ?.fields.find((child) => 'key' in child && child.key === 'systems');
1347
+ const value = field === undefined || !('value' in field) ? undefined : field.value;
1348
+ const kept = (value === undefined ? [] : value.kind === 'list' ? value.items : [value]).flatMap((item) => item.kind === 'ref' && item.discriminator === 'system' && item.name !== name ? [item.name] : []);
1349
+ const planned = starterFiles(name, kept, system);
1350
+ const moves = others.map((file) => {
1351
+ const from = `${systemFolder(name)}/records/${file}`;
1352
+ return { from, to: `.ia/src/${file}`, identities: identities(from) };
1353
+ });
1354
+ const removes = [
1355
+ { path: legacyRecordsPath(name), identities: identities(legacyRecordsPath(name)) },
1356
+ ...(system
1357
+ ? []
1358
+ : [
1359
+ { path: systemPath(name), identities: identities(systemPath(name)) },
1360
+ ...[`${systemFolder(name)}/records/`, `${systemFolder(name)}/`, `${SYSTEMS}/`].map((path) => ({
1361
+ path,
1362
+ identities: [],
1363
+ })),
1364
+ ]),
1365
+ ];
1366
+ // The preflight's destination half: neither the starter file nor any moved file's destination may exist.
1367
+ const gitConflict = migrationGitConflict(root, base, lock);
1368
+ const conflicts = gitConflict === null ? [] : [gitConflict];
1369
+ const legacyText = readWorkspaceFile({ root, path: legacyRecordsPath(name) })
1370
+ .toString('utf8')
1371
+ .replace(/\r\n/g, '\n');
1372
+ const stockWorkspace = starterRecords(name, kept)
1373
+ .split(`\n@agent ${name}\n`)[0]
1374
+ .replace(' sources [".ia/src @authored"]\n', '')
1375
+ .replace(` steward @agent ${name}\n`, '');
1376
+ const stockDistribution = starterDistribution(name)
1377
+ .replace('#! ia 1.0\n\n', '')
1378
+ .replace(`The release root of the ${name} system.`, `The release root of the ${name} workspace.`)
1379
+ .replace(`records [@system ${name}]`, `records [@workspace ${name}]`);
1380
+ const normalizeSystems = (text) => text.replace(/^ systems \[[^\n]*\]$/m, ' systems []');
1381
+ if (normalizeSystems(legacyText) !== normalizeSystems(stockWorkspace + '\n' + stockDistribution))
1382
+ conflicts.push({
1383
+ path: legacyRecordsPath(name),
1384
+ reason: 'Authored workspace or distribution text differs from the 1.1.0 starter; preserve these edits in an explicit migration before removing this file',
1385
+ });
1386
+ const occupied = (path) => lstatSync(resolve(root, path), { throwIfNoEntry: false }) !== undefined;
1387
+ if (occupied(WORKSPACE_PATH))
1388
+ conflicts.push({ path: WORKSPACE_PATH, reason: 'Exists where the migration writes the three starter records' });
1389
+ for (const move of moves)
1390
+ if (occupied(move.to))
1391
+ conflicts.push({ path: move.to, reason: `Exists where the migration moves ${move.from}` });
1392
+ // Its identity half: a word and name compile to one identity wherever they are written, so a record the workspace
1393
+ // keeps with a starter record's word and name would tie with the one the migration authors. A starter record found
1394
+ // at a path the migration deletes is the one it replaces; one at the planned record's own path, `--system`'s
1395
+ // `system.ia`, is kept.
1396
+ const deleted = new Set(removes.map((removal) => removal.path));
1397
+ for (const record of planned.records)
1398
+ for (const found of records)
1399
+ if (found.discriminator === record.word &&
1400
+ found.name === record.name &&
1401
+ found.source.path !== record.path &&
1402
+ !deleted.has(found.source.path))
1403
+ conflicts.push({
1404
+ path: found.source.path,
1405
+ reason: `Holds @${record.word} ${record.name}, which the migration authors in ${record.path}`,
1406
+ });
1407
+ // Spec §8: a pending host journal refuses the whole verb and names the recovery that clears it, as `ia host` does.
1408
+ if (!system) {
1409
+ const removedRecords = [...local, ...starter.filter((record) => record.discriminator === 'distribution')];
1410
+ const references = (value, word, name, identity) => {
1411
+ if (value === null || typeof value !== 'object')
1412
+ return false;
1413
+ if (Array.isArray(value))
1414
+ return value.some((child) => references(child, word, name, identity));
1415
+ const item = value;
1416
+ // The language preserves authored reference spelling but resolves names case-insensitively.
1417
+ if (item['kind'] === 'ref' &&
1418
+ item['discriminator'] === word &&
1419
+ typeof item['name'] === 'string' &&
1420
+ item['name'].toLowerCase() === name.toLowerCase())
1421
+ return true;
1422
+ if (item['kind'] === 'identity' && item['identity'] === identity)
1423
+ return true;
1424
+ return Object.values(item).some((child) => references(child, word, name, identity));
1425
+ };
1426
+ for (const record of records)
1427
+ if (!deleted.has(record.source.path))
1428
+ for (const removed of removedRecords)
1429
+ if (references(record, removed.discriminator, removed.name, removed.identity))
1430
+ conflicts.push({
1431
+ path: record.source.path,
1432
+ reason: `${spelled(record)} references ${removed.identity}, which the migration deletes; use --system to retain it`,
1433
+ });
1434
+ }
1435
+ const hosts = [], projected = registeredProjections(root, 'update');
1436
+ if (projected.length > 0)
1437
+ try {
1438
+ assertHostRegistrationIdle(root);
1439
+ }
1440
+ catch (error) {
1441
+ const refusal = refusalOf(error), [journal, command] = JOURNALS.find(([path]) => existsSync(resolve(root, path))) ?? JOURNALS[0];
1442
+ throw new Refusal(refusal.code, refusal.message, 3, { path: journal }, `Run "${recoverCommand(command, root)}"${THEN_RERUN}`);
1443
+ }
1444
+ for (const host of projected)
1445
+ try {
1446
+ const guard = planRetirement(root, host) === null ? 'none' : 'retire';
1447
+ // The hook step the projection effect runs (review finding H-R3), found before the migration plans its writes.
1448
+ preflightHooks(root, host);
1449
+ hosts.push({ host, guard, files: migratedFiles(root, host) });
1450
+ }
1451
+ catch (error) {
1452
+ const refusal = refusalOf(error);
1453
+ conflicts.push({
1454
+ path: refusedPath(error) ?? STATE.projection(host),
1455
+ reason: refusal.message,
1456
+ host,
1457
+ code: refusal.code,
1458
+ });
1459
+ }
1460
+ // The descriptor depends on the bundled base, as `ia init` writes it, in place of its row for the installed base, and
1461
+ // keeps every other row; it names no distribution without `--system`. Rows stay sorted by id, as the decoder requires.
1462
+ const dependencies = [
1463
+ ...descriptor.dependencies.filter((row) => row.id !== base.pin.id),
1464
+ ...baseDependencies(base),
1465
+ ].sort((a, b) => (a.id < b.id ? -1 : 1));
1466
+ const text = `${JSON.stringify(Object.fromEntries(Object.entries(raw)
1467
+ .filter(([key]) => system || key !== 'distribution')
1468
+ .map(([key, item]) => [key, key === 'dependencies' ? dependencies : item])), null, 2)}\n`;
1469
+ return {
1470
+ root,
1471
+ id: descriptor.id,
1472
+ name,
1473
+ system,
1474
+ base: { pin: base.pin, installed: { version: locked.version, archive: locked.archive } },
1475
+ conflicts,
1476
+ moves,
1477
+ files: planned.files.filter((file) => file.path !== systemPath(name)),
1478
+ records: planned.records,
1479
+ systems: system ? [...kept, name] : kept,
1480
+ removes,
1481
+ ignore: existsSync(resolve(root, IGNORE_PATH)) ? 'present' : 'create',
1482
+ descriptor: {
1483
+ before: distribution,
1484
+ after: system ? distribution : null,
1485
+ dependencies: { before: descriptor.dependencies, after: dependencies },
1486
+ },
1487
+ // Without `--system` the distribution goes, so the descriptor is always rewritten; with it, only a new base row
1488
+ // rewrites it, so one that differs from these bytes in formatting alone, such as its line endings, is left as it is.
1489
+ rewrite: system && spelledRows(descriptor.dependencies) === spelledRows(dependencies) ? null : text,
1490
+ hosts,
1491
+ steps: [
1492
+ ...(bundled(locked) ? [] : ['install']),
1493
+ 'move',
1494
+ 'author',
1495
+ 'remove',
1496
+ 'descriptor',
1497
+ 'admission',
1498
+ 'capture',
1499
+ ...(hosts.length === 0 ? [] : ['project']),
1500
+ ],
1501
+ invocation: request.invocation ?? `ia init ${quote(root)} --migrate${system ? ' --system' : ''}`,
1502
+ };
1503
+ }
1504
+ /**
1505
+ * A registered host's file plan for the migrated records, before they exist. Every file the adapter renders carries
1506
+ * the workspace revision, which the migration changes, so the apply rewrites each one this render leaves unchanged:
1507
+ * that one is planned with a text that differs from its bytes, as the apply's will, which the planner reads as an
1508
+ * update of an owned file or refuses as one this workspace does not own. Every other action, and every refusal,
1509
+ * depends on the files on disk alone.
1510
+ */
1511
+ function migratedFiles(root, host) {
1512
+ const rendered = renderProjectionFor(root, host), { actions } = planFiles(root, host, rendered), unchanged = new Set(actions.filter((row) => row.action === 'unchanged').map((row) => row.path));
1513
+ if (unchanged.size === 0)
1514
+ return actions;
1515
+ return planFiles(root, host, {
1516
+ ...rendered,
1517
+ files: rendered.files.map((file) => (unchanged.has(file.path) ? { ...file, text: `${file.text}\n` } : file)),
1518
+ }).actions;
1519
+ }
1520
+ /**
1521
+ * `--apply`'s refusal of a plan with conflicts, before anything is written. A file in a destination's way, or a record
1522
+ * holding a starter record's word and name, is the migration's own conflict, so it names the plan, which lists each
1523
+ * one; a registered projection the planner refuses alone names that host's plan, which names each file it refuses
1524
+ * with its repair.
1525
+ */
1526
+ function migrationRefusal(view) {
1527
+ const collisions = view.conflicts.filter((row) => row.host === undefined);
1528
+ if (collisions.length === 0) {
1529
+ const first = view.conflicts[0];
1530
+ return new Refusal(first.code ?? 'IA-CLI-CONFLICT', first.reason, 3, { path: first.path }, `Run "ia host ${first.host} --root ${quote(view.root)}" for its projection plan, which names each file it refuses.`);
1531
+ }
1532
+ return new Refusal('IA-CLI-CONFLICT', conflictMessage(view.conflicts, 'the migration'), 3, { path: view.root }, `Run "${view.invocation}" to review the plan and its conflicts.`);
1533
+ }
1534
+ /**
1535
+ * The sentence each refusal after the file steps opens its next action with: the records are in the new shape, and,
1536
+ * once the capture effect has run or failed, whether it was taken, as `ia init`'s say it.
1537
+ */
1538
+ const MIGRATED = 'The workspace is migrated.';
1539
+ const MIGRATED_CAPTURED = 'The workspace is migrated and captured.';
1540
+ const MIGRATED_UNCAPTURED = 'The workspace is migrated but not captured.';
1541
+ /**
1542
+ * The admission step `ia init` and `ia init --migrate` share: zero error findings, then each planned starter record as
1543
+ * the compiled graph holds it at its path, never string-constructed (M5.1 §2.3), with every record the graph holds.
1544
+ * `done` opens each refusal's next action with what the command completed before it, if anything.
1545
+ */
1546
+ function admitStarter(root, planned, what, done) {
1547
+ const session = openWorkspaceSession({ root });
1548
+ try {
1549
+ const errors = session.admission().findings.filter((finding) => finding.severity === 'error');
1550
+ if (errors.length > 0)
1551
+ throw new Refusal('IA-CLI-FAILED', `The ${what} workspace failed admission with ${errors.length} error findings; first: ${errors[0].code}`, 3, { path: root }, `${done}Run "ia validate --root ${quote(root)}" for the findings.`);
1552
+ const records = session.reader.records();
1553
+ const compiled = planned.map((starter) => {
1554
+ const record = records.find((node) => node.discriminator === starter.word && node.name === starter.name && node.source.path === starter.path);
1555
+ if (record === undefined)
1556
+ throw new Refusal('IA-CLI-FAILED', `The compiled workspace has no @${starter.word} ${starter.name} in ${starter.path}`, 3, { path: root }, `${done}Run "ia inspect --path ${starter.path} --root ${quote(root)}" for the records that file admitted.`);
1557
+ return record;
1558
+ });
1559
+ return { compiled, records };
1560
+ }
1561
+ finally {
1562
+ session.close();
1563
+ }
1564
+ }
1565
+ /**
1566
+ * Apply the exact migration plan through a durable operation journal. File mutations are resumed only from their
1567
+ * recorded before/after digests. Capture and each host projection follow admission; a completed host receipt is
1568
+ * verified and retained on resume, including the window before its journal completion marker was published.
1569
+ * Every interrupted effect names the same migration command, after a pending host transaction is recovered.
1570
+ */
1571
+ export async function applyMigration(view, options) {
1572
+ if (view.conflicts.length > 0)
1573
+ throw migrationRefusal(view);
1574
+ const { root } = view;
1575
+ // Rebuild from the verified operation options so the retry is rooted even when the original target was relative.
1576
+ const resume = `ia init ${quote(root)} --migrate${view.system ? ' --system' : ''} --apply --yes`;
1577
+ const checkpoint = (name) => {
1578
+ try {
1579
+ options.checkpoint?.(name);
1580
+ }
1581
+ catch (error) {
1582
+ const refusal = refusalOf(error);
1583
+ throw new Refusal(refusal.code, refusal.message, 3, refusal.where, `The migration is recorded in .ia/migration.json. Run "${resume}" again to finish migrating.`);
1584
+ }
1585
+ };
1586
+ const base = readBase(options.packageRoot);
1587
+ if (base.pin.archive !== view.base.pin.archive || base.pin.manifest !== view.base.pin.manifest)
1588
+ throw new Refusal('IA-CLI-FAILED', 'The bundled base package changed while planning', 3, { path: resolve(options.packageRoot, PIN_PATH) }, DAMAGED);
1589
+ options.signal?.throwIfAborted();
1590
+ const existingJournal = readMigrationJournal(root, view.system, base.pin);
1591
+ if (existingJournal === null) {
1592
+ const fresh = collectMigration({
1593
+ root,
1594
+ system: view.system,
1595
+ packageRoot: options.packageRoot,
1596
+ invocation: view.invocation,
1597
+ });
1598
+ if (fresh.conflicts.length > 0)
1599
+ throw migrationRefusal(fresh);
1600
+ if (JSON.stringify(fresh) !== JSON.stringify(view))
1601
+ throw new Refusal('IA-CLI-CONFLICT', 'The migration inputs changed after planning', 3, { path: root }, `Run "${view.invocation}" again to review the current plan.`);
1602
+ }
1603
+ const journal = existingJournal ?? beginMigrationJournal(view, migrationIgnoreText(root));
1604
+ const install = view.steps.includes('install');
1605
+ if (install &&
1606
+ readInstalledState({ root }).lock?.packages.find((row) => row.id === base.pin.id)?.archive !== base.pin.archive) {
1607
+ const interrupted = new Interrupted(`Run "${resume}" again to finish migrating.`);
1608
+ await installBase(root, base, 'update', { signal: options.signal, checkpoint }, interrupted);
1609
+ checkpoint('migrate:install');
1610
+ if (options.signal?.aborted)
1611
+ throw interrupted;
1612
+ }
1613
+ const ignore = view.ignore === 'create' ? 'written' : 'present';
1614
+ const removed = view.removes.map((row) => row.path);
1615
+ try {
1616
+ applyMigrationFiles(journal, checkpoint, options.signal);
1617
+ }
1618
+ catch (error) {
1619
+ const refusal = refusalOf(error);
1620
+ throw new Refusal(refusal.code, refusal.message, 3, refusal.where ?? { path: root }, `The migration is recorded in .ia/migration.json; nothing was rolled back. Repair the reported filesystem problem, then run "${resume}" again to finish migrating.`);
1621
+ }
1622
+ // Neither effect has run, so the refusal says so before the one command it names.
1623
+ const { compiled, records } = admitStarter(root, view.records, 'migrated', view.hosts.length === 0
1624
+ ? `${MIGRATED_UNCAPTURED} `
1625
+ : 'The workspace is migrated but neither captured nor projected. ');
1626
+ const moved = view.moves.map((move) => ({
1627
+ ...move,
1628
+ identities: records
1629
+ .filter((record) => record.source.path === move.to)
1630
+ .map((record) => record.identity)
1631
+ .sort(),
1632
+ }));
1633
+ checkpoint('migrate:admission');
1634
+ // The capture effect, as `ia init` takes it: refused as `ia capture` refuses, with its repair, for this root.
1635
+ const recapture = `ia capture --root ${quote(root)}`;
1636
+ let capture, failed;
1637
+ if (options.signal?.aborted) {
1638
+ if (view.hosts.length === 0)
1639
+ throw new Interrupted(`${MIGRATED} Run "${resume}" to finish migrating.`);
1640
+ }
1641
+ else
1642
+ try {
1643
+ const written = collectCapture(root, root);
1644
+ capture = { revision: written.snapshot.revision, records: written.snapshot.counts.records };
1645
+ }
1646
+ catch (error) {
1647
+ failed = refusalOf(captureFailure(error, root, recapture));
1648
+ }
1649
+ if (capture !== undefined)
1650
+ checkpoint('migrate:capture');
1651
+ // The project effect: each registered host, through the one writer of projection files.
1652
+ const captured = capture === undefined ? MIGRATED_UNCAPTURED : MIGRATED_CAPTURED;
1653
+ const projected = [], refused = [];
1654
+ for (const { host } of view.hosts) {
1655
+ const finish = resume;
1656
+ if (options.signal?.aborted)
1657
+ throw new Interrupted(`${captured} Run "${finish}" to finish migrating.`);
1658
+ try {
1659
+ const rendered = renderProjectionFor(root, host);
1660
+ const prior = readReceipt(root, host);
1661
+ const priorDigest = prior === null ? null : sha256(readWorkspaceFile({ root, path: STATE.receipt(host) }));
1662
+ const completed = prior !== null &&
1663
+ priorDigest !== journal.receiptsBefore[host] &&
1664
+ prior.packetDigest === rendered.receipt.packetDigest &&
1665
+ prior.revision === rendered.receipt.revision &&
1666
+ prior.bodyDigest === rendered.receipt.bodyDigest &&
1667
+ prior.guard ===
1668
+ (journal.view.hosts.find((row) => row.host === host).guard === 'retire' ? 'retired' : 'none') &&
1669
+ JSON.stringify(prior.removed) === JSON.stringify(journal.removals[host]) &&
1670
+ prior.adapter === rendered.receipt.adapter &&
1671
+ JSON.stringify(prior.files.map((file) => file.path)) ===
1672
+ JSON.stringify(rendered.receipt.files.map((file) => file.path)) &&
1673
+ prior.files.every((file) => sha256(readWorkspaceFile({ root, path: file.path })) === file.sha256) &&
1674
+ prior.removed.every((file) => !existsSync(resolve(root, file.path))) &&
1675
+ planRetirement(root, host) === null &&
1676
+ planFiles(root, host, {
1677
+ ...rendered,
1678
+ files: prior.files.map((file) => ({
1679
+ path: file.path,
1680
+ text: readWorkspaceFile({ root, path: file.path }).toString('utf8'),
1681
+ })),
1682
+ }).actions.every((action) => action.action === 'unchanged' || action.action === 'foreign');
1683
+ if (journal.completed[host] !== undefined && !completed)
1684
+ throw new Refusal('IA-CLI-CONFLICT', 'Completed migration projection differs from its receipt', 3, { path: STATE.receipt(host) }, `Restore the projected files to their receipt digests, then run "${resume}".`);
1685
+ const refresh = completed && JSON.stringify(prior.files) !== JSON.stringify(rendered.receipt.files);
1686
+ if (refresh)
1687
+ reopenMigrationProjection(journal, host);
1688
+ const applied = completed && !refresh
1689
+ ? { receipt: prior, guard: prior.guard }
1690
+ : applyHostProjection(root, host, rendered, undefined, refresh ? prior : undefined);
1691
+ // Receipt publication is itself recoverable before the journal completion marker advances.
1692
+ checkpoint(`migrate:project:${host}:receipt`);
1693
+ completeMigrationProjection(journal, host);
1694
+ const receipt = applied.receipt;
1695
+ projected.push({
1696
+ host,
1697
+ files: receipt.files,
1698
+ receipt: STATE.receipt(host),
1699
+ guard: applied.guard,
1700
+ removed: receipt.removed.map((file) => file.path),
1701
+ });
1702
+ checkpoint(`migrate:project:${host}`);
1703
+ }
1704
+ catch (error) {
1705
+ const refusal = refusalOf(error), path = refusedPath(error);
1706
+ refused.push(new Refusal(refusal.code, refusal.message, 3, path === null ? refusal.where : { path }, `${captured} ${JOURNALS.some(([journal]) => existsSync(resolve(root, journal))) ? `Run "${recoverCommand(JOURNALS.find(([journal]) => existsSync(resolve(root, journal)))[1], root)}" first, then rerun this migration with the same target and options to finish.` : path === null ? `Repair the reported filesystem problem, then run "${resume}" to finish migrating.` : projectionRepair(host, path, resume, refusal.code)}`));
1707
+ }
1708
+ }
1709
+ if (projected.length > 0)
1710
+ checkpoint('migrate:project');
1711
+ const first = refused[0];
1712
+ if (first !== undefined)
1713
+ throw new Refusal(first.code, refused.length > 1
1714
+ ? `${first.message}. ${refused.length} registered host projections were not written; this is the first.`
1715
+ : first.message, 3, first.where, first.next);
1716
+ if (failed !== undefined)
1717
+ throw new Refusal(failed.code, failed.message, 3, failed.where, `${projected.length === 0
1718
+ ? MIGRATED
1719
+ : `The workspace is migrated and its ${projected.map((row) => row.host).join(' and ')} ${projected.length === 1 ? 'projection is' : 'projections are'} written.`} ${failed.next?.replace(`"${recapture}"`, `"${resume}"`) ?? `Run "${resume}" to finish migrating.`}`);
1720
+ if (capture === undefined)
1721
+ throw new Interrupted(`${MIGRATED} Run "${resume}" to finish migrating.`);
1722
+ checkpoint('migrate:complete');
1723
+ finishMigrationJournal(root);
1724
+ return {
1725
+ status: 'migrated',
1726
+ id: view.id,
1727
+ base: install ? 'installed' : 'present',
1728
+ distribution: compiled.find((record) => record.discriminator === 'distribution')?.identity ?? null,
1729
+ authored: compiled.map((record) => record.identity),
1730
+ moved,
1731
+ removed,
1732
+ ignore,
1733
+ effects: { capture, project: projected },
1734
+ };
1735
+ }
1736
+ export function migrationEnvelope(view, apply, applied = null) {
1737
+ return {
1738
+ version: 1,
1739
+ command: 'init',
1740
+ root: view.root,
1741
+ apply,
1742
+ plan: {
1743
+ migrate: MIGRATES_FROM,
1744
+ id: view.id,
1745
+ name: view.name,
1746
+ system: view.system,
1747
+ base: {
1748
+ id: view.base.pin.id,
1749
+ installed: view.base.installed,
1750
+ bundled: { version: view.base.pin.version, archive: view.base.pin.archive },
1751
+ },
1752
+ conflicts: view.conflicts,
1753
+ steps: view.steps,
1754
+ moves: view.moves,
1755
+ writes: view.files.map((file) => file.path),
1756
+ records: view.records.map((record) => `@${record.word} ${record.name}`),
1757
+ systems: view.systems,
1758
+ removes: view.removes,
1759
+ ignore: { path: IGNORE_PATH, status: view.ignore },
1760
+ descriptor: { path: DESCRIPTOR_PATH, ...view.descriptor },
1761
+ hosts: view.hosts,
1762
+ },
1763
+ ...(applied === null ? {} : { applied }),
1764
+ };
1765
+ }
1766
+ /** One row per file: its path, then what the migration does to it, each row on one content column (§6.4 rule 2). */
1767
+ const fileRows = (rows, caps) => {
1768
+ const symbolWidth = blockSymbolWidth(rows.map((row) => row.symbol), caps.ascii);
1769
+ return rows.flatMap((row) => entry([[atom(row.path, 'cyan', 0), ...words(row.text, null, 2)]], { depth: 1, symbol: row.symbol, symbolWidth }, caps));
1770
+ };
1771
+ const migrationBlocks = (view, caps) => {
1772
+ const { name } = view, { pin } = view.base, { dependencies } = view.descriptor;
1773
+ // Only the base's row changes; every other row is kept as it is.
1774
+ const was = dependencies.before.find((row) => row.id === pin.id), now = dependencies.after.find((row) => row.id === pin.id);
1775
+ const conflicts = view.conflicts.map((row) => ({
1776
+ symbol: 'warning',
1777
+ label: row.path,
1778
+ value: words(row.host === undefined ? row.reason : `the ${row.host} projection: ${row.code} ${row.reason}`),
1779
+ }));
1780
+ const project = view.hosts.map((planned) => ({
1781
+ symbol: 'added',
1782
+ label: `Project ${planned.host}`,
1783
+ value: words([
1784
+ ...(planned.guard === 'retire' ? [`first retires the steward guard registered in ${SETTINGS}`] : []),
1785
+ ...planned.files.map((file) => `${file.path} ${file.action === 'foreign' ? 'foreign, left in place' : file.action}`),
1786
+ ].join('; ')),
1787
+ }));
1788
+ return [
1789
+ [
1790
+ sectionLabel('Conflicts', caps),
1791
+ ...(conflicts.length === 0
1792
+ ? entry([
1793
+ words("None. No destination exists, no record holds a starter record's word and name, and every registered projection plans."),
1794
+ ], { depth: 1, symbol: 'success' }, caps)
1795
+ : fieldRows(conflicts, { depth: 1 }, caps)),
1796
+ ],
1797
+ [
1798
+ sectionLabel('Base', caps),
1799
+ ...fieldRows([
1800
+ view.steps.includes('install')
1801
+ ? {
1802
+ symbol: 'added',
1803
+ label: 'Install',
1804
+ value: words(`${pin.id} ${pin.version} from the bundled archive, sha256 ${truncateDigest(pin.archive, caps.ascii)}, in place of the installed ${view.base.installed.version}, sha256 ${truncateDigest(view.base.installed.archive, caps.ascii)}, which may not declare the fields the three records use`),
1805
+ }
1806
+ : {
1807
+ symbol: 'info',
1808
+ label: 'Base package',
1809
+ value: words(`${pin.id} ${pin.version} from the bundled archive, already installed`),
1810
+ },
1811
+ ], { depth: 1 }, caps),
1812
+ ],
1813
+ [
1814
+ sectionLabel('Records', caps),
1815
+ ...fileRows([
1816
+ ...view.moves.map((move) => ({
1817
+ symbol: 'updated',
1818
+ path: move.from,
1819
+ text: `moves to ${move.to}${move.identities.length === 0 ? '' : `, holding ${move.identities.join(', ')}`}`,
1820
+ })),
1821
+ {
1822
+ symbol: 'added',
1823
+ path: WORKSPACE_PATH,
1824
+ text: `@workspace ${name} composing ${view.systems.length} systems; its participant @agent ${name}; @mandate ${name}-mandate`,
1825
+ },
1826
+ ...(view.system
1827
+ ? [
1828
+ {
1829
+ symbol: 'added',
1830
+ path: distributionPath(name),
1831
+ text: `@distribution ${name}-distribution rooted at @system ${name}, in place of the one rooted at @workspace ${name}`,
1832
+ },
1833
+ { symbol: 'info', path: systemPath(name), text: `kept: @system ${name} and its steward` },
1834
+ ]
1835
+ : []),
1836
+ {
1837
+ symbol: view.ignore === 'create' ? 'added' : 'info',
1838
+ path: IGNORE_PATH,
1839
+ text: view.ignore === 'create'
1840
+ ? migrationIgnoreText(view.root) === IGNORE_TEXT
1841
+ ? 'ignores work/ and distributions/'
1842
+ : 'ignores work/; tracked distributions remain visible to Git'
1843
+ : 'exists and is left as it is',
1844
+ },
1845
+ ...view.removes.map((removal) => ({
1846
+ symbol: 'removed',
1847
+ path: removal.path,
1848
+ text: removal.path.endsWith('/') ? 'deleted once empty' : `deleted, with ${removal.identities.join(', ')}`,
1849
+ })),
1850
+ {
1851
+ symbol: view.rewrite === null ? 'info' : 'updated',
1852
+ path: DESCRIPTOR_PATH,
1853
+ text: `${view.descriptor.after === null
1854
+ ? `drops distribution ${view.descriptor.before}, so ia pack refuses until one is authored`
1855
+ : `keeps distribution ${view.descriptor.before}`}${spelledRows(dependencies.before) === spelledRows(dependencies.after)
1856
+ ? ''
1857
+ : `; depends on ${now.id} ${now.range}, the bundled base, ${was === undefined ? 'which it did not name' : `in place of ${was.id} ${was.range}`}`}`,
1858
+ },
1859
+ ], caps),
1860
+ ],
1861
+ [
1862
+ sectionLabel('Effects', caps),
1863
+ ...fieldRows([
1864
+ { symbol: 'added', label: 'Capture', value: words(`${CURRENT}, as ia capture writes it`) },
1865
+ ...(project.length === 0
1866
+ ? [
1867
+ {
1868
+ symbol: 'info',
1869
+ label: 'Project',
1870
+ value: words(view.conflicts.some((row) => row.host !== undefined)
1871
+ ? 'Not planned: each registered projection conflicts, as listed above'
1872
+ : 'No host projection is registered'),
1873
+ },
1874
+ ]
1875
+ : project),
1876
+ ], { depth: 1 }, caps),
1877
+ ],
1878
+ ];
1879
+ };
1880
+ const migrationHeader = (view, caps) => headerLine('Plan', `init --migrate from ${MIGRATES_FROM}`, [{ text: view.root, column: 50 }], caps);
1881
+ export function renderMigration(view, caps, supplied) {
1882
+ const next = safeRootAdvice(view.conflicts.length > 0
1883
+ ? `Resolve the conflicts above, then run "${view.invocation} --apply --yes".`
1884
+ : `Apply with "${view.invocation} --apply --yes".`, [view.root, supplied]);
1885
+ return document([
1886
+ migrationHeader(view, caps),
1887
+ entry([words('This is a preview. Nothing has been written.')], { depth: 1 }, caps),
1888
+ ...migrationBlocks(view, caps),
1889
+ entry([words(next)], { depth: 0, symbol: 'step' }, caps),
1890
+ ], { leadingBlank: true });
1891
+ }
1892
+ /** §2.8 rule 3's change summary: the plan's own blocks without the preview note or the footer. */
1893
+ const renderMigrationSummary = (view, caps) => document([migrationHeader(view, caps), ...migrationBlocks(view, caps)], { leadingBlank: true });
1894
+ export function renderMigrated(view, applied, caps) {
1895
+ return document([
1896
+ headerLine('Init', applied.id, [{ text: view.root, column: 50 }], caps),
1897
+ entry([
1898
+ words(`Migrated ${applied.id} from the ${MIGRATES_FROM} starter; release descriptor ${DESCRIPTOR_PATH}${applied.distribution === null ? ', which names no distribution' : `, naming ${applied.distribution}`}.`),
1899
+ words(applied.base === 'installed'
1900
+ ? `Installed ${view.base.pin.id} ${view.base.pin.version} from the bundled archive.`
1901
+ : `${view.base.pin.id} ${view.base.pin.version} from the bundled archive was already installed.`),
1902
+ ], { depth: 1, symbol: 'success' }, caps),
1903
+ authoredEntry(applied, caps, readFileSync(resolve(view.root, IGNORE_PATH), 'utf8').includes('distributions/')
1904
+ ? 'work/ and distributions/'
1905
+ : 'work/'),
1906
+ ...applied.moved.map((move) => entry([
1907
+ [atom(move.from, 'cyan', 0), ...words(`moved to ${move.to}`, null, 1)],
1908
+ ...(move.identities.length === 0 ? [] : [words(`It holds ${move.identities.join(', ')}.`)]),
1909
+ ], { depth: 1, symbol: 'success' }, caps)),
1910
+ entry([
1911
+ words(`Deleted ${applied.removed.join(', ')}.`),
1912
+ ...(view.system ? [words(`Kept @system ${view.name} and its steward in ${systemPath(view.name)}.`)] : []),
1913
+ ], { depth: 1, symbol: 'success' }, caps),
1914
+ capturedEntry(applied.effects.capture, caps),
1915
+ ...(applied.effects.project.length === 0
1916
+ ? [entry([words('Project skipped: no host projection is registered.')], { depth: 1, symbol: 'info' }, caps)]
1917
+ : applied.effects.project.map((projection) => entry([
1918
+ words(`Projected the position packet for ${projection.host}:`),
1919
+ ...projection.files.map((file) => [atom(file.path, 'cyan', 0)]),
1920
+ words(`Receipt ${projection.receipt}.`),
1921
+ ...(projection.removed.length === 0
1922
+ ? []
1923
+ : [words(`Deleted the 1.x projection files ${projection.removed.join(', ')}.`)]),
1924
+ ...(projection.guard === 'retired' ? [words(GUARD_RETIRED)] : []),
1925
+ ], { depth: 1, symbol: 'success' }, caps))),
1926
+ closingEntry(applied.distribution, caps),
1927
+ ], { leadingBlank: true });
1928
+ }
1929
+ /** `ia init --migrate`: the plan, which reports its conflicts, or once confirmed its apply. */
1930
+ async function migrate(context, root) {
1931
+ const { args, caps, json, host } = context;
1932
+ const apply = args.flag('apply');
1933
+ const view = collectMigration({
1934
+ root,
1935
+ system: args.flag('system'),
1936
+ packageRoot: host.packageRoot,
1937
+ invocation: invocationOf(context),
1938
+ });
1939
+ const rendered = (applied) => json
1940
+ ? { exitCode: 0, stdout: JSON.stringify(migrationEnvelope(view, apply, applied)) + '\n', stderr: '' }
1941
+ : {
1942
+ exitCode: 0,
1943
+ stdout: applied === null ? renderMigration(view, caps, args.positionals[0]) : renderMigrated(view, applied, caps),
1944
+ stderr: '',
1945
+ };
1946
+ if (!apply)
1947
+ return rendered(null);
1948
+ if (view.conflicts.length > 0)
1949
+ throw migrationRefusal(view);
1950
+ if (!args.flag('yes') && !(await confirm(host.interaction, renderMigrationSummary(view, caps), CONFIRMATION)))
1951
+ return { exitCode: 0, stdout: renderDeclined(view, caps, args.positionals[0]), stderr: '' };
1952
+ return rendered(await applyMigration(view, { packageRoot: host.packageRoot, signal: host.signal }));
1953
+ }
854
1954
  /**
855
1955
  * A finished git run's answer, or null when git is not really there: it could not start, or it is the macOS stub
856
1956
  * `/usr/bin/git`, which only asks for the Xcode Command Line Tools and fails; reading that as "not a Git checkout" would