@wjarka/cezarion 0.17.0-dev.5447 → 0.17.0-dev.5474

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 (92) hide show
  1. package/dist/artifacts/cli.js +17 -4
  2. package/dist/artifacts/cli.js.map +1 -1
  3. package/dist/artifacts/reports-index.d.ts +1 -1
  4. package/dist/artifacts/reports-index.js +1 -6
  5. package/dist/artifacts/reports-index.js.map +1 -1
  6. package/dist/automations/coordinator.d.ts +1 -1
  7. package/dist/automations/coordinator.js +1 -1
  8. package/dist/automations/coordinator.js.map +1 -1
  9. package/dist/automations/schedule-runner.d.ts +6 -2
  10. package/dist/automations/schedule-runner.js +35 -27
  11. package/dist/automations/schedule-runner.js.map +1 -1
  12. package/dist/automations/scheduler.js +3 -14
  13. package/dist/automations/scheduler.js.map +1 -1
  14. package/dist/automations/store.d.ts +2 -2
  15. package/dist/automations/store.js +11 -13
  16. package/dist/automations/store.js.map +1 -1
  17. package/dist/automations/task-template.js +5 -6
  18. package/dist/automations/task-template.js.map +1 -1
  19. package/dist/cli-dispatch.js +14 -8
  20. package/dist/cli-dispatch.js.map +1 -1
  21. package/dist/delegation/routes.js +2 -2
  22. package/dist/delegation/routes.js.map +1 -1
  23. package/dist/delegation/transport.d.ts +12 -12
  24. package/dist/preview/browser-launch.d.ts +0 -1
  25. package/dist/preview/browser-launch.js +12 -1
  26. package/dist/preview/browser-launch.js.map +1 -1
  27. package/dist/preview/host.d.ts +0 -6
  28. package/dist/preview/host.js +3 -17
  29. package/dist/preview/host.js.map +1 -1
  30. package/dist/project-migration/answer.d.ts +19 -0
  31. package/dist/project-migration/answer.js +33 -0
  32. package/dist/project-migration/answer.js.map +1 -0
  33. package/dist/project-migration/auto.d.ts +73 -0
  34. package/dist/project-migration/auto.js +157 -0
  35. package/dist/project-migration/auto.js.map +1 -0
  36. package/dist/project-migration/cli.d.ts +18 -0
  37. package/dist/project-migration/cli.js +55 -0
  38. package/dist/project-migration/cli.js.map +1 -0
  39. package/dist/project-migration/containment.d.ts +52 -0
  40. package/dist/project-migration/containment.js +200 -0
  41. package/dist/project-migration/containment.js.map +1 -0
  42. package/dist/project-migration/engine.d.ts +9 -11
  43. package/dist/project-migration/engine.js +14 -8
  44. package/dist/project-migration/engine.js.map +1 -1
  45. package/dist/project-migration/live.d.ts +47 -0
  46. package/dist/project-migration/live.js +137 -0
  47. package/dist/project-migration/live.js.map +1 -0
  48. package/dist/project-migration/offline.d.ts +25 -0
  49. package/dist/project-migration/offline.js +54 -0
  50. package/dist/project-migration/offline.js.map +1 -0
  51. package/dist/project-migration/plan.d.ts +7 -0
  52. package/dist/project-migration/plan.js +34 -24
  53. package/dist/project-migration/plan.js.map +1 -1
  54. package/dist/project-migration/recovery.d.ts +28 -0
  55. package/dist/project-migration/recovery.js +78 -0
  56. package/dist/project-migration/recovery.js.map +1 -0
  57. package/dist/project-migration/steps.js +27 -0
  58. package/dist/project-migration/steps.js.map +1 -1
  59. package/dist/project-paths.d.ts +7 -0
  60. package/dist/project-paths.js +19 -0
  61. package/dist/project-paths.js.map +1 -1
  62. package/dist/runs/webhook.js +2 -3
  63. package/dist/runs/webhook.js.map +1 -1
  64. package/dist/self-update/checkouts.js +13 -1
  65. package/dist/self-update/checkouts.js.map +1 -1
  66. package/dist/serve-command.d.ts +4 -0
  67. package/dist/serve-command.js +8 -1
  68. package/dist/serve-command.js.map +1 -1
  69. package/dist/server/archive-on-merge.js +1 -1
  70. package/dist/server/archive-on-merge.js.map +1 -1
  71. package/dist/server/cockpit-ownership.d.ts +18 -34
  72. package/dist/server/cockpit-ownership.js +38 -120
  73. package/dist/server/cockpit-ownership.js.map +1 -1
  74. package/dist/server/live-routes.js +1 -1
  75. package/dist/server/live-routes.js.map +1 -1
  76. package/dist/server/project-context.d.ts +5 -14
  77. package/dist/server/project-context.js +14 -33
  78. package/dist/server/project-context.js.map +1 -1
  79. package/dist/server/reports-api.d.ts +2 -2
  80. package/dist/server/server.d.ts +182 -182
  81. package/dist/server/server.js +17 -13
  82. package/dist/server/server.js.map +1 -1
  83. package/dist/server/workspace-live-routes.d.ts +6 -6
  84. package/dist/server/workspace-projects.d.ts +1 -1
  85. package/dist/server/workspace-projects.js +4 -0
  86. package/dist/server/workspace-projects.js.map +1 -1
  87. package/dist/subcommands.js +5 -1
  88. package/dist/subcommands.js.map +1 -1
  89. package/package.json +3 -3
  90. package/dist/preview/project-exits.d.ts +0 -16
  91. package/dist/preview/project-exits.js +0 -36
  92. package/dist/preview/project-exits.js.map +0 -1
@@ -0,0 +1,55 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { commandText } from '../home/command.js';
5
+ import { getRepoInfo } from '../server/git.js';
6
+ import { migrationAnswerText } from './answer.js';
7
+ import { migrateProjectOffline } from './offline.js';
8
+ /**
9
+ * `migrate-project [--dry-run] [--repo <dir>]` (hearsay-tools/cezarion#3089): the offline project
10
+ * migration, run only by the user, registered only with the release switch.
11
+ */
12
+ const HELP = commandText(`Usage: cez migrate-project [--dry-run] [--repo <dir>]
13
+ Move this project's runtime state from .ai/cezar/ to .ai/squawk/, offline. Stop every
14
+ cockpit that serves the project and finish or cancel every task first; the command
15
+ names what it finds still running. It cannot see a cockpit of another home that
16
+ lists the project but never opened it: stop it yourself, and keep older binaries off
17
+ the project. Tracked files are never moved: the command prints the
18
+ git mv commands to run and commit.
19
+
20
+ --dry-run print every move, repair and rewrite; only an unfinished
21
+ migration is completed (and reported) first
22
+ --repo <dir> the project (default: the current directory)
23
+ -h, --help show this help`);
24
+ export async function runMigrateProjectCommand(argv, deps) {
25
+ let values;
26
+ try {
27
+ ({ values } = parseArgs({ args: argv, options: { 'dry-run': { type: 'boolean' }, repo: { type: 'string' }, help: { type: 'boolean', short: 'h' } }, strict: true, allowPositionals: false }));
28
+ }
29
+ catch (error) {
30
+ deps.error(`${error instanceof Error ? error.message : String(error)}\n\n${HELP}`);
31
+ return 1;
32
+ }
33
+ if (values.help) {
34
+ deps.log(HELP);
35
+ return 0;
36
+ }
37
+ try {
38
+ // A missing --repo is a refusal like any other: one line on stderr, exit 1.
39
+ const cwd = resolve(values.repo ?? deps.cwd());
40
+ const root = realpathSync((await deps.getRepoInfo(cwd))?.root ?? cwd);
41
+ deps.log(migrationAnswerText(await migrateProjectOffline(root, { homes: deps.homes, dryRun: values['dry-run'] === true, fault: deps.fault, self: deps.self })));
42
+ return 0;
43
+ }
44
+ catch (error) {
45
+ deps.error(error instanceof Error ? error.message : String(error));
46
+ return 1;
47
+ }
48
+ }
49
+ /** The runner the subcommand table registers. */
50
+ export function migrateProjectRunner(homes) {
51
+ return (argv, env) => runMigrateProjectCommand(argv, {
52
+ homes: homes(env), getRepoInfo, cwd: () => process.cwd(), log: line => console.log(line), error: line => console.error(line),
53
+ });
54
+ }
55
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../../src/project-migration/cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEjD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAGrD;;;GAGG;AAEH,MAAM,IAAI,GAAG,WAAW,CAAC;;;;;;;;;;;iCAWQ,CAAC,CAAC;AAenC,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAAC,IAAc,EAAE,IAAwB;IACrF,IAAI,MAA8D,CAAC;IACnE,IAAI,CAAC;QACH,CAAC,EAAE,MAAM,EAAE,GAAG,SAAS,CAA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KAAK,EAAE,CAAC;QACf,IAAI,CAAC,KAAK,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QACnE,OAAO,CAAC,CAAC;IACX,CAAC;AACH,CAAC;AAED,iDAAiD;AACjD,MAAM,UAAU,oBAAoB,CAAC,KAAkD;IACrF,OAAO,CAAC,IAAc,EAAE,GAAsB,EAAE,EAAE,CAAC,wBAAwB,CAAC,IAAI,EAAE;QAChF,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC;KAC7H,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,52 @@
1
+ import type { ProjectMigrationJournal } from './journal.ts';
2
+ /**
3
+ * What a project migration journal may name (hearsay-tools/cezarion#3089). A journal is read back
4
+ * from disk before a resume, so it is untrusted input: every path it names is checked before any
5
+ * step runs, and each step checks its write target again right before it writes.
6
+ *
7
+ * - `source` and `destination` are exactly `<root>/.ai/cezar` and `<root>/.ai/squawk`, and
8
+ * `<root>/.ai` is a real directory.
9
+ * - A move goes from inside `source` to the same place inside `destination`; so does a worktree.
10
+ * - A receipt or cleanup checkpoint lies in `<git common dir>/cezar-owned-workspaces/`; every other
11
+ * rewritten file lies in `<destination>/runs/`.
12
+ * - A rewritten value moves a path from a form of the project root's `.ai/cezar` to the same place
13
+ * under `.ai/squawk`; a tracked file is a relative `.ai/cezar/...` path printed as a `git mv`.
14
+ * - No existing directory on the way to a checked path resolves elsewhere (a symlink out), and a
15
+ * file the engine opens or rewrites in place (the run store and its `-wal` and `-shm`, each
16
+ * rewritten JSON file, each receipt) is a regular file, never a symlink. A moved item may be a
17
+ * symlink: a rename moves the link itself.
18
+ * - The journal file itself is a regular file of at most `MAX_JOURNAL_BYTES` that Git does not
19
+ * track (the shared excludes keep it out of every ordinary add), checked before it is read.
20
+ */
21
+ export declare class ProjectMigrationJournalRefusedError extends Error {
22
+ readonly journal: string;
23
+ constructor(journal: string, detail: string);
24
+ }
25
+ /**
26
+ * Why `path` may not be written as part of `root`: not a normalized absolute path, outside `root`
27
+ * by its letters, or an existing directory on its way (from `root` down) that resolves elsewhere.
28
+ * Undefined when it may. The last component itself is not followed: a move renames a link, and a
29
+ * rewrite replaces a file by rename.
30
+ */
31
+ export declare function outsideOf(root: string, path: string): string | undefined;
32
+ /** Why `path`, when it exists, may not be opened or rewritten in place: it is a symlink or not a file. */
33
+ export declare function notRegularFile(path: string): string | undefined;
34
+ /** The run store the run-store step opens, and the sidecars SQLite opens with it. */
35
+ export declare function runStoreFiles(directory: string): string[];
36
+ /**
37
+ * The largest journal a resume reads. A journal holds the plan, a few hundred bytes per path
38
+ * rewrite: 100,000 runs with several rewritten fields each stay well under it. Anything larger
39
+ * is not a journal this engine wrote.
40
+ */
41
+ export declare const MAX_JOURNAL_BYTES: number;
42
+ /**
43
+ * Accept the journal file at `path` before it is read: false when there is none; refused when it
44
+ * is a symlink or not a regular file, larger than `MAX_JOURNAL_BYTES`, tracked by Git (only a
45
+ * forced add or a clone tracks it; one Git call, only when a journal exists), or when that Git
46
+ * check cannot finish. Nothing is read.
47
+ */
48
+ export declare function assertJournalFile(path: string, repoRoot: string): Promise<boolean>;
49
+ /** The repository's receipt directory, where receipt and cleanup checkpoint rewrites must lie. */
50
+ export declare function receiptDirectory(repoRoot: string): Promise<string>;
51
+ /** Refuse `journal` before any step when it names anything outside the project's own state. */
52
+ export declare function assertJournalContained(path: string, journal: ProjectMigrationJournal): Promise<void>;
@@ -0,0 +1,200 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { lstatSync, realpathSync } from 'node:fs';
3
+ import { promisify } from 'node:util';
4
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
+ import { gitCommonDir } from '../delegation/workspace.js';
6
+ import { MIGRATION_JOURNAL_FILE } from '../server/cockpit-ownership.js';
7
+ import { pathPresent } from '../project-paths.js';
8
+ import { RUNS_DB_FILE } from '../runs/run-database.js';
9
+ /**
10
+ * What a project migration journal may name (hearsay-tools/cezarion#3089). A journal is read back
11
+ * from disk before a resume, so it is untrusted input: every path it names is checked before any
12
+ * step runs, and each step checks its write target again right before it writes.
13
+ *
14
+ * - `source` and `destination` are exactly `<root>/.ai/cezar` and `<root>/.ai/squawk`, and
15
+ * `<root>/.ai` is a real directory.
16
+ * - A move goes from inside `source` to the same place inside `destination`; so does a worktree.
17
+ * - A receipt or cleanup checkpoint lies in `<git common dir>/cezar-owned-workspaces/`; every other
18
+ * rewritten file lies in `<destination>/runs/`.
19
+ * - A rewritten value moves a path from a form of the project root's `.ai/cezar` to the same place
20
+ * under `.ai/squawk`; a tracked file is a relative `.ai/cezar/...` path printed as a `git mv`.
21
+ * - No existing directory on the way to a checked path resolves elsewhere (a symlink out), and a
22
+ * file the engine opens or rewrites in place (the run store and its `-wal` and `-shm`, each
23
+ * rewritten JSON file, each receipt) is a regular file, never a symlink. A moved item may be a
24
+ * symlink: a rename moves the link itself.
25
+ * - The journal file itself is a regular file of at most `MAX_JOURNAL_BYTES` that Git does not
26
+ * track (the shared excludes keep it out of every ordinary add), checked before it is read.
27
+ */
28
+ export class ProjectMigrationJournalRefusedError extends Error {
29
+ journal;
30
+ constructor(journal, detail) {
31
+ super(`The project migration journal ${journal} is refused: ${detail}. Nothing was changed. `
32
+ + 'The journal stays for inspection; remove it only if no migration of this project ran');
33
+ this.journal = journal;
34
+ this.name = 'ProjectMigrationJournalRefusedError';
35
+ }
36
+ }
37
+ function within(parent, path) {
38
+ const inside = relative(parent, path);
39
+ return inside === '' || (!isAbsolute(inside) && inside !== '..' && !inside.startsWith(`..${sep}`));
40
+ }
41
+ /**
42
+ * Why `path` may not be written as part of `root`: not a normalized absolute path, outside `root`
43
+ * by its letters, or an existing directory on its way (from `root` down) that resolves elsewhere.
44
+ * Undefined when it may. The last component itself is not followed: a move renames a link, and a
45
+ * rewrite replaces a file by rename.
46
+ */
47
+ export function outsideOf(root, path) {
48
+ if (!isAbsolute(path) || resolve(path) !== path)
49
+ return `${path} is not a normalized absolute path`;
50
+ if (path === root || !within(root, path))
51
+ return `${path} is not inside ${root}`;
52
+ let existing = dirname(path);
53
+ while (!pathPresent(existing) && existing !== dirname(existing))
54
+ existing = dirname(existing);
55
+ try {
56
+ if (realpathSync(existing) !== existing)
57
+ return `${existing} resolves to ${realpathSync(existing)}, outside the project`;
58
+ }
59
+ catch (error) {
60
+ return `${existing} cannot be resolved: ${error.message}`;
61
+ }
62
+ return undefined;
63
+ }
64
+ /** Why `path`, when it exists, may not be opened or rewritten in place: it is a symlink or not a file. */
65
+ export function notRegularFile(path) {
66
+ if (!pathPresent(path))
67
+ return undefined;
68
+ const info = lstatSync(path);
69
+ return info.isSymbolicLink() ? `${path} is a symbolic link` : info.isFile() ? undefined : `${path} is not a regular file`;
70
+ }
71
+ /** The run store the run-store step opens, and the sidecars SQLite opens with it. */
72
+ export function runStoreFiles(directory) {
73
+ const database = join(directory, RUNS_DB_FILE);
74
+ return [database, `${database}-wal`, `${database}-shm`];
75
+ }
76
+ /** `path` inside `from`, carried to the same place inside `to`. */
77
+ function carried(from, to, path) {
78
+ return outsideOf(from, path.from) ?? outsideOf(to, path.to)
79
+ ?? (path.to === to + path.from.slice(from.length) ? undefined : `${path.to} is not where ${path.from} goes`);
80
+ }
81
+ const execFileAsync = promisify(execFile);
82
+ const LEGACY = `${sep}.ai${sep}cezar`;
83
+ const MIGRATED = `${sep}.ai${sep}squawk`;
84
+ /** A stored value: under some form of the project root's `.ai/cezar`, mapped to the same place under `.ai/squawk`. */
85
+ function valueMoved(repoRoot, real, value) {
86
+ for (let at = value.from.indexOf(LEGACY); at > 0; at = value.from.indexOf(LEGACY, at + 1)) {
87
+ const rest = value.from.slice(at + LEGACY.length);
88
+ if (rest !== '' && !rest.startsWith(sep))
89
+ continue;
90
+ const prefix = value.from.slice(0, at);
91
+ if (real(prefix) === repoRoot && value.to === prefix + MIGRATED + rest)
92
+ return undefined;
93
+ }
94
+ return `the value ${value.from} -> ${value.to} does not move a path of this project from .ai/cezar to .ai/squawk`;
95
+ }
96
+ /** A tracked file: relative, `.ai/cezar/...` to the same `.ai/squawk/...`, no `..`. */
97
+ function trackedMoved(file) {
98
+ const parts = file.from.split('/');
99
+ const ok = parts.length > 2 && parts[0] === '.ai' && parts[1] === 'cezar' && !parts.some(part => part === '' || part === '.' || part === '..')
100
+ && !file.from.includes('\\') && file.to === `.ai/squawk/${parts.slice(2).join('/')}`;
101
+ return ok ? undefined : `the tracked file ${file.from} -> ${file.to} is not a path under .ai/cezar`;
102
+ }
103
+ /** The first refusal `check` gives for any of `items`. */
104
+ function firstRefusal(items, check) {
105
+ for (const item of items) {
106
+ const refusal = check(item);
107
+ if (refusal)
108
+ return refusal;
109
+ }
110
+ return undefined;
111
+ }
112
+ /** The directories, moves, worktrees and tracked files of `journal`. */
113
+ function layoutRefusal(journal) {
114
+ const ai = join(journal.repoRoot, '.ai');
115
+ if (journal.source !== join(ai, 'cezar') || journal.destination !== join(ai, 'squawk'))
116
+ return `its directories are not ${join(ai, 'cezar')} and ${join(ai, 'squawk')}`;
117
+ // `<root>/.ai` itself must be a real directory of the root.
118
+ return outsideOf(journal.repoRoot, journal.source)
119
+ ?? firstRefusal([...journal.moves, ...journal.worktrees], item => carried(journal.source, journal.destination, item))
120
+ ?? firstRefusal(journal.tracked, trackedMoved);
121
+ }
122
+ /** Every rewrite of `journal`: the file it rewrites in place, the run store it opens, the value it moves. */
123
+ async function rewritesRefusal(journal) {
124
+ const isReceipt = (rewrite) => rewrite.kind === 'receipt' || rewrite.kind === 'cleanup-checkpoint';
125
+ const receipts = journal.rewrites.some(isReceipt) ? await receiptDirectory(journal.repoRoot) : undefined;
126
+ const runs = join(journal.destination, 'runs');
127
+ const reals = new Map();
128
+ const real = (prefix) => {
129
+ if (!reals.has(prefix)) {
130
+ try {
131
+ reals.set(prefix, realpathSync(prefix));
132
+ }
133
+ catch {
134
+ reals.set(prefix, undefined);
135
+ }
136
+ }
137
+ return reals.get(prefix);
138
+ };
139
+ // The run store the run-store step opens: before the move it is the source's, after it the destination's.
140
+ const stores = journal.rewrites.some(rewrite => rewrite.kind === 'run-row') ? [...runStoreFiles(journal.source), ...runStoreFiles(journal.destination)] : [];
141
+ const fileRefusal = (rewrite) => {
142
+ if (!('file' in rewrite))
143
+ return undefined;
144
+ return outsideOf(isReceipt(rewrite) ? receipts : runs, rewrite.file) ?? notRegularFile(rewrite.file);
145
+ };
146
+ return firstRefusal(journal.rewrites, (rewrite) => { return fileRefusal(rewrite) ?? valueMoved(journal.repoRoot, real, rewrite); })
147
+ ?? firstRefusal(stores, notRegularFile);
148
+ }
149
+ /** The first reason `journal` may not run, checked before any step; undefined when it may. */
150
+ async function journalRefusal(path, journal) {
151
+ return layoutRefusal(journal) ?? await rewritesRefusal(journal);
152
+ }
153
+ /**
154
+ * The largest journal a resume reads. A journal holds the plan, a few hundred bytes per path
155
+ * rewrite: 100,000 runs with several rewritten fields each stay well under it. Anything larger
156
+ * is not a journal this engine wrote.
157
+ */
158
+ export const MAX_JOURNAL_BYTES = 64 * 1024 * 1024;
159
+ /**
160
+ * Why Git tracking refuses the journal of the project at `repoRoot` (a real path): tracked, or the
161
+ * check could not finish. A directory outside any Git repository tracks nothing. The pathspec is
162
+ * the journal's canonical place, whatever form the caller's path has.
163
+ */
164
+ async function trackedJournalRefusal(repoRoot) {
165
+ try {
166
+ const { stdout } = await execFileAsync('git', ['ls-files', '-z', '--', `.ai/${MIGRATION_JOURNAL_FILE}`], { cwd: repoRoot, encoding: 'utf8', timeout: 60_000 });
167
+ return stdout ? 'Git tracks it; a migration journal is never committed' : undefined;
168
+ }
169
+ catch (error) {
170
+ if (/not a git repository/i.test(String(error.stderr ?? '')))
171
+ return undefined;
172
+ return `Git could not tell whether it tracks the journal: ${error.message.split('\n')[0]}`;
173
+ }
174
+ }
175
+ /**
176
+ * Accept the journal file at `path` before it is read: false when there is none; refused when it
177
+ * is a symlink or not a regular file, larger than `MAX_JOURNAL_BYTES`, tracked by Git (only a
178
+ * forced add or a clone tracks it; one Git call, only when a journal exists), or when that Git
179
+ * check cannot finish. Nothing is read.
180
+ */
181
+ export async function assertJournalFile(path, repoRoot) {
182
+ if (!pathPresent(path))
183
+ return false;
184
+ const refusal = notRegularFile(path) ?? (lstatSync(path).size > MAX_JOURNAL_BYTES ? `it is larger than ${MAX_JOURNAL_BYTES} bytes` : undefined)
185
+ ?? await trackedJournalRefusal(repoRoot);
186
+ if (refusal)
187
+ throw new ProjectMigrationJournalRefusedError(path, refusal);
188
+ return true;
189
+ }
190
+ /** The repository's receipt directory, where receipt and cleanup checkpoint rewrites must lie. */
191
+ export async function receiptDirectory(repoRoot) {
192
+ return join(await gitCommonDir(repoRoot), 'cezar-owned-workspaces');
193
+ }
194
+ /** Refuse `journal` before any step when it names anything outside the project's own state. */
195
+ export async function assertJournalContained(path, journal) {
196
+ const refusal = await journalRefusal(path, journal);
197
+ if (refusal)
198
+ throw new ProjectMigrationJournalRefusedError(path, refusal);
199
+ }
200
+ //# sourceMappingURL=containment.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"containment.js","sourceRoot":"","sources":["../../src/project-migration/containment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC9E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gC;IACzF,MAAM,OAAO,GAAG,MAAM,cAAc,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IACpD,IAAI,OAAO;QAAE,MAAM,IAAI,mCAAmC,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AAC5E,CAAC"}
@@ -4,14 +4,14 @@ import { type ProjectMigrationPlan } from './plan.ts';
4
4
  import { type MigrationFault } from './steps.ts';
5
5
  /**
6
6
  * The project state migration engine (P4b2, hearsay-tools/cezarion#3088): it moves a project's
7
- * runtime state from `.ai/cezar/` to `.ai/squawk/` under the exclusive project fence (P4b1). It is
8
- * internal: no command, route or boot hook calls it until P4b3 wires it and P5 enables it.
7
+ * runtime state from `.ai/cezar/` to `.ai/squawk/` under the exclusive project fence. A migration
8
+ * runs offline (hearsay-tools/cezarion#3089): no cockpit serves the project and no task is live.
9
9
  *
10
- * Order: the caller takes the fence (`fenceProject` or `fenceProjectContext`); the engine checks
11
- * that this process holds it, runs the holder duty (`closeProject`: dispose the project's context
12
- * and close its store), plans, writes the journal, runs each step and marks it done, and removes
13
- * the journal last. The caller releases the fence afterwards, also after a failure: the journal
14
- * then keeps the project blocked until a resume completes it.
10
+ * Order: the caller takes the fence (`fenceProject`); the engine checks that this process holds
11
+ * it, runs as its holder (`asFenceHolder`), closes the store the caller opened (`closeProject`),
12
+ * plans, writes the journal, runs each step and marks it done, and removes the journal last. The
13
+ * caller releases the fence afterwards, also after a failure: the journal then keeps the project
14
+ * blocked until a resume completes it.
15
15
  */
16
16
  export interface ProjectMigrationOptions {
17
17
  /** The project root, in the form the project is registered with. */
@@ -37,10 +37,8 @@ export declare class ProjectMigrationRefusedError extends Error {
37
37
  /** Complete an unfinished journal, for P4b3's recovery before any project read; undefined without one. */
38
38
  export declare function resumeProjectMigration(options: ProjectMigrationOptions): Promise<ProjectMigrationResult | undefined>;
39
39
  /**
40
- * Migrate the project, or finish its unfinished journal first. `closeProject` is the holder duty
41
- * after the drain and before the first move: an owning cockpit disposes the project's context
42
- * (`ProjectContexts.dispose(id, { releasePreviews: false })`, previews were released in the drain),
43
- * which closes its store; a CLI closes the store it opened. A refused plan writes nothing.
40
+ * Migrate the project, or finish its unfinished journal first. `closeProject` runs before the
41
+ * plan: the CLI closes the store it opened for its live-task check. A refused plan writes nothing.
44
42
  */
45
43
  export declare function migrateProject(options: ProjectMigrationOptions & {
46
44
  closeProject?: () => void | Promise<void>;
@@ -1,11 +1,12 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { realpathSync } from 'node:fs';
3
3
  import { join, resolve } from 'node:path';
4
- import { holdProjectWork, holdsProjectFence, migrationFencePaths } from '../server/cockpit-ownership.js';
4
+ import { asFenceHolder, holdsProjectFence, migrationFencePaths } from '../server/cockpit-ownership.js';
5
5
  import { PROJECT_MIGRATION_STEPS, readProjectMigrationJournal, removeProjectMigrationJournal, writeProjectMigrationJournal, } from './journal.js';
6
6
  import { gitMvCommands, LEGACY_PROJECT_DIR, planProjectMigration } from './plan.js';
7
7
  import { GIT_MIGRATION_STEPS, MIGRATION_STEP_RUNNERS } from './steps.js';
8
8
  import { withWorktreeMutation } from '../git-worktree-lock.js';
9
+ import { assertJournalContained, assertJournalFile } from './containment.js';
9
10
  /** The plan had conflicts or blockers: nothing was written and no journal exists. */
10
11
  export class ProjectMigrationRefusedError extends Error {
11
12
  plan;
@@ -53,27 +54,30 @@ async function runJournal(path, start, resumed, fault) {
53
54
  export async function resumeProjectMigration(options) {
54
55
  const dataDir = legacyDataDir(options.repoRoot);
55
56
  assertHeldFence(dataDir, options.fence);
56
- return holdProjectWork(dataDir, async () => resumeHeld(options));
57
+ return asFenceHolder(options.fence, async () => resumeHeld(options));
57
58
  }
58
59
  async function resumeHeld(options) {
60
+ const root = realpathSync(resolve(options.repoRoot));
61
+ // The file is accepted before anything reads it: a symlink, a huge file or a committed one is refused.
62
+ if (!await assertJournalFile(options.fence.journal, root))
63
+ return undefined;
59
64
  const journal = readProjectMigrationJournal(options.fence.journal);
60
65
  if (!journal)
61
66
  return undefined;
62
- const root = realpathSync(resolve(options.repoRoot));
63
67
  if (journal.repoRoot !== root)
64
68
  throw new Error(`The migration journal ${options.fence.journal} belongs to ${journal.repoRoot}, not ${root}`);
69
+ // Read back from disk, so untrusted: nothing outside the project's own state may be named in it.
70
+ await assertJournalContained(options.fence.journal, journal);
65
71
  return runJournal(options.fence.journal, journal, true, options.fault ?? (() => undefined));
66
72
  }
67
73
  /**
68
- * Migrate the project, or finish its unfinished journal first. `closeProject` is the holder duty
69
- * after the drain and before the first move: an owning cockpit disposes the project's context
70
- * (`ProjectContexts.dispose(id, { releasePreviews: false })`, previews were released in the drain),
71
- * which closes its store; a CLI closes the store it opened. A refused plan writes nothing.
74
+ * Migrate the project, or finish its unfinished journal first. `closeProject` runs before the
75
+ * plan: the CLI closes the store it opened for its live-task check. A refused plan writes nothing.
72
76
  */
73
77
  export async function migrateProject(options) {
74
78
  const dataDir = legacyDataDir(options.repoRoot);
75
79
  assertHeldFence(dataDir, options.fence);
76
- return holdProjectWork(dataDir, async () => {
80
+ return asFenceHolder(options.fence, async () => {
77
81
  await options.closeProject?.();
78
82
  const unfinished = await resumeHeld(options);
79
83
  if (unfinished)
@@ -85,6 +89,8 @@ export async function migrateProject(options) {
85
89
  version: 1, id: randomUUID(), createdAt: new Date().toISOString(), repoRoot: plan.repoRoot, source: plan.source,
86
90
  destination: plan.destination, done: [], moves: plan.moves, tracked: plan.tracked, worktrees: plan.worktrees, rewrites: plan.rewrites,
87
91
  };
92
+ // The same rule as a resume, before the journal exists, so a refused plan leaves nothing behind.
93
+ await assertJournalContained(plan.journal, journal);
88
94
  const fault = options.fault ?? (() => undefined);
89
95
  fault('journal:before');
90
96
  writeProjectMigrationJournal(plan.journal, journal);
@@ -1 +1 @@
1
- {"version":3,"file":"engine.js","sourceRoot":"","sources":["../../src/project-migration/engine.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,MAA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,MAAM,oBAAoB,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QAC1D,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC;YAAE,MAAM,IAAI,4BAA4B,CAAC,IAAI,CAAC,CAAC;QACxG,MAAM,OAAO,GAA4B;YACvC,OAAO,EAAE,CAAC,EAAE,EAAE,EAAE,UAAU,EAAE,EAAE,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM;YAC/G,WAAW,EAAE,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ;SACtI,CAAC;QACF,iGAAiG;QACjG,MAAM,sBAAsB,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACpD,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QACjD,KAAK,CAAC,gBAAgB,CAAC,CAAC;QACxB,4BAA4B,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACpD,KAAK,CAAC,iBAAiB,CAAC,CAAC;QACzB,OAAO,UAAU,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,47 @@
1
+ import type { Home } from '../home/home.ts';
2
+ import { type RunStore } from '../runs/store.ts';
3
+ import { type LiveProjectTask } from '../server/cockpit-ownership.ts';
4
+ /**
5
+ * Whether anything is live for a project (hearsay-tools/cezarion#3089). A project migration runs
6
+ * offline: it refuses while a cockpit serves the project or a task of it is live, and names what to
7
+ * stop. Shared by every caller that starts a migration.
8
+ *
9
+ * Seen: the cockpit that owns the project's `cockpit.lock` (any home), every live cockpit of the
10
+ * given homes whose registry lists the project (their presence leases, `home/leases.ts`), and live
11
+ * tasks: rows not terminal in either project directory, and families another live process (a
12
+ * headless run, another binary) claims in `run_claims`. An agent process belongs to a live task.
13
+ * Not seen: a cockpit of another home that lists the project but never opened it; the write
14
+ * backstop and admission stop its writes during a move.
15
+ */
16
+ /** A cockpit that serves the project: the `cockpit.lock` owner, or a live cockpit whose registry lists it. */
17
+ export interface ProjectCockpit {
18
+ pid: number;
19
+ url?: string;
20
+ port?: number;
21
+ instance?: string;
22
+ home?: string;
23
+ }
24
+ /** Something live serves the project: nothing was claimed, moved or written. */
25
+ export declare class ProjectInUseError extends Error {
26
+ readonly project: string;
27
+ readonly cockpits: readonly ProjectCockpit[];
28
+ readonly tasks: readonly LiveProjectTask[];
29
+ constructor(project: string, cockpits: readonly ProjectCockpit[], tasks: readonly LiveProjectTask[]);
30
+ }
31
+ /**
32
+ * The cockpits other than process `self` that serve the project at `root`: the `cockpit.lock` owner
33
+ * and every live cockpit of `homes` whose registry lists `root`. A home that cannot be read has no
34
+ * cockpit to report.
35
+ */
36
+ export declare function projectCockpits(root: string, homes: readonly Home[], self?: number): Promise<ProjectCockpit[]>;
37
+ /**
38
+ * The project's runs as `projectLiveTasks` reads them, read without writing anything: each run
39
+ * store read-only (`readQuiescentRunDatabase`), and a `runs.json` no store imported yet read as
40
+ * JSON. The legacy directory wins an id both hold. Live: rows not terminal, and the runs of
41
+ * families a live process claims. Throws when a live id's record cannot be read.
42
+ */
43
+ export declare function readLiveTaskView(root: string): Pick<RunStore, 'listRuns' | 'persistedLiveRunIds' | 'getRun'>;
44
+ /** Refuse when a cockpit serves the project; live tasks are checked under the fence (`fenceProject`). */
45
+ export declare function assertNoProjectCockpit(root: string, homes: readonly Home[], self?: number): Promise<void>;
46
+ /** The project's live tasks, read without writing anything: the fence's live-task check. */
47
+ export declare function projectLiveTasksOffline(root: string): LiveProjectTask[];
@@ -0,0 +1,137 @@
1
+ import { readFileSync, realpathSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { readCockpitLeases } from '../home/leases.js';
4
+ import { pathPresent, projectPaths } from '../project-paths.js';
5
+ import { claimOwnerLive } from '../runs/run-claims.js';
6
+ import { RUNS_DB_FILE } from '../runs/run-database.js';
7
+ import { parseRunRecords } from '../runs/store.js';
8
+ import { isLiveRecord } from '../runs/run-row.js';
9
+ import { anotherCockpitOwner } from '../server/cockpit-ownership.js';
10
+ import { projectLiveTasks } from '../server/project-context.js';
11
+ import { loadWorkspaceConfig } from '../workspace/config.js';
12
+ import { readQuiescentRunDatabase } from './plan.js';
13
+ /** Something live serves the project: nothing was claimed, moved or written. */
14
+ export class ProjectInUseError extends Error {
15
+ project;
16
+ cockpits;
17
+ tasks;
18
+ constructor(project, cockpits, tasks) {
19
+ const lines = [
20
+ ...cockpits.map(cockpit => `- cockpit pid ${cockpit.pid}${cockpit.url ? ` at ${cockpit.url}` : cockpit.port ? ` on port ${cockpit.port}` : ''}`
21
+ + `${cockpit.instance ? `, instance ${cockpit.instance}` : ''}${cockpit.home ? `, home ${cockpit.home}` : ''}: stop it`),
22
+ ...tasks.map(task => `- task ${task.id} ${task.title} (${task.state}): finish or cancel it`),
23
+ ];
24
+ super(`Cannot migrate ${project} while it is in use. Stop what is listed, then retry:\n${lines.join('\n')}`);
25
+ this.project = project;
26
+ this.cockpits = cockpits;
27
+ this.tasks = tasks;
28
+ this.name = 'ProjectInUseError';
29
+ }
30
+ }
31
+ function realRoot(path) {
32
+ try {
33
+ return realpathSync(path);
34
+ }
35
+ catch {
36
+ return path;
37
+ }
38
+ }
39
+ /**
40
+ * The cockpits other than process `self` that serve the project at `root`: the `cockpit.lock` owner
41
+ * and every live cockpit of `homes` whose registry lists `root`. A home that cannot be read has no
42
+ * cockpit to report.
43
+ */
44
+ export async function projectCockpits(root, homes, self = process.pid) {
45
+ const found = new Map();
46
+ const owner = anotherCockpitOwner(projectPaths(root).write);
47
+ if (owner && owner.pid !== self)
48
+ found.set(owner.pid, owner);
49
+ const real = realRoot(root);
50
+ for (const home of homes) {
51
+ let listed;
52
+ try {
53
+ listed = (await loadWorkspaceConfig(home.workspaceConfig)).projects.some(project => realRoot(project.root) === real);
54
+ }
55
+ catch {
56
+ continue;
57
+ }
58
+ if (!listed)
59
+ continue;
60
+ let leases;
61
+ try {
62
+ leases = readCockpitLeases(home);
63
+ }
64
+ catch {
65
+ continue;
66
+ }
67
+ for (const lease of leases) {
68
+ if (lease.pid === self || found.has(lease.pid))
69
+ continue;
70
+ found.set(lease.pid, { pid: lease.pid, port: lease.port, instance: lease.instance, home: home.root });
71
+ }
72
+ }
73
+ return [...found.values()];
74
+ }
75
+ /** One stored record, or nothing when it does not parse. */
76
+ function record(value) {
77
+ const parsed = parseRunRecords([value]);
78
+ return parsed.success ? parsed.data[0] : undefined;
79
+ }
80
+ /**
81
+ * The project's runs as `projectLiveTasks` reads them, read without writing anything: each run
82
+ * store read-only (`readQuiescentRunDatabase`), and a `runs.json` no store imported yet read as
83
+ * JSON. The legacy directory wins an id both hold. Live: rows not terminal, and the runs of
84
+ * families a live process claims. Throws when a live id's record cannot be read.
85
+ */
86
+ export function readLiveTaskView(root) {
87
+ const runs = new Map();
88
+ const live = new Set(), foreign = new Set();
89
+ const add = (run) => { if (run && !runs.has(run.id))
90
+ runs.set(run.id, run); };
91
+ for (const directory of projectPaths(root).reads) {
92
+ const database = join(directory, RUNS_DB_FILE);
93
+ if (pathPresent(database)) {
94
+ readQuiescentRunDatabase(database, (db) => {
95
+ for (const row of db.listAll())
96
+ add(record(JSON.parse(row.data)));
97
+ for (const row of db.listLive())
98
+ live.add(row.id);
99
+ for (const claim of db.listClaims(true)) {
100
+ if (!claimOwnerLive(claim))
101
+ continue;
102
+ for (const id of [claim.family, ...db.listIdsByParent(claim.family)])
103
+ foreign.add(id);
104
+ }
105
+ });
106
+ continue;
107
+ }
108
+ const index = join(directory, 'runs.json');
109
+ if (!pathPresent(index))
110
+ continue;
111
+ const entries = JSON.parse(readFileSync(index, 'utf8'));
112
+ for (const entry of Array.isArray(entries) ? entries : []) {
113
+ const run = record(entry);
114
+ add(run);
115
+ if (run && isLiveRecord(run))
116
+ live.add(run.id);
117
+ }
118
+ }
119
+ // A live task whose record cannot be read is still live: the check refuses what it cannot prove safe.
120
+ const unreadable = [...new Set([...live, ...foreign])].filter(id => !runs.has(id));
121
+ if (unreadable.length > 0) {
122
+ throw new Error(`Cannot migrate ${root}: these tasks are marked live but their records cannot be read: ${unreadable.join(', ')}. `
123
+ + 'Open the project with the binary that wrote them, finish or cancel each one, then retry');
124
+ }
125
+ return { listRuns: () => [], persistedLiveRunIds: () => ({ live: [...live], foreign: [...foreign] }), getRun: (id) => runs.get(id) };
126
+ }
127
+ /** Refuse when a cockpit serves the project; live tasks are checked under the fence (`fenceProject`). */
128
+ export async function assertNoProjectCockpit(root, homes, self = process.pid) {
129
+ const cockpits = await projectCockpits(root, homes, self);
130
+ if (cockpits.length > 0)
131
+ throw new ProjectInUseError(root, cockpits, []);
132
+ }
133
+ /** The project's live tasks, read without writing anything: the fence's live-task check. */
134
+ export function projectLiveTasksOffline(root) {
135
+ return projectLiveTasks(readLiveTaskView(root));
136
+ }
137
+ //# sourceMappingURL=live.js.map