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