@nowcrew/daemon 0.6.97-beta.1 → 0.6.97-beta.2
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.
- package/dist/cloud-report-upload.js +1 -10
- package/dist/execution-journal.js +3 -1
- package/dist/execution-protocol.js +1 -1
- package/dist/execution-runner.js +4 -1
- package/dist/local-execution-prompt.js +8 -3
- package/dist/local-executor.js +63 -39
- package/dist/local-memory/commit-telemetry.js +30 -0
- package/dist/local-memory/execution-workspace.js +62 -0
- package/dist/local-memory/full-index-search.js +47 -0
- package/dist/local-memory/index-budget.js +9 -3
- package/dist/local-memory/initialization-identity.js +36 -0
- package/dist/local-memory/inventory-cli.js +49 -8
- package/dist/local-memory/inventory-source.js +15 -8
- package/dist/local-memory/inventory-v2.js +361 -0
- package/dist/local-memory/legacy-adapter.js +233 -0
- package/dist/local-memory/migration-access.js +242 -0
- package/dist/local-memory/migration-cli.js +54 -0
- package/dist/local-memory/migration-io.js +199 -0
- package/dist/local-memory/migration-pending.js +9 -0
- package/dist/local-memory/migration-plan.js +317 -0
- package/dist/local-memory/migration-schema.js +55 -0
- package/dist/local-memory/migration-state-invariants.js +65 -0
- package/dist/local-memory/migration-store.js +414 -0
- package/dist/local-memory/migration-tool-entry.js +21 -0
- package/dist/local-memory/pending-query.js +5 -2
- package/dist/local-memory/pending-schema.js +1 -1
- package/dist/local-memory/pending.js +16 -2
- package/dist/local-memory/prompt.js +21 -5
- package/dist/local-memory/read-cli.js +98 -76
- package/dist/local-memory/rollout.js +79 -11
- package/dist/local-memory/runtime.js +181 -13
- package/dist/local-memory/storage-format.js +152 -0
- package/dist/local-memory/write.js +189 -21
- package/dist/local-memory/writer-mode.js +13 -0
- package/dist/local-memory-diagnostics.js +94 -13
- package/dist/local-memory-telemetry.js +19 -2
- package/dist/machine-info.js +3 -0
- package/dist/marketplace-protocol.js +1 -1
- package/dist/marketplace-remote.js +1 -1
- package/dist/marketplace-runner.js +1 -1
- package/dist/memory-migration-controller.js +86 -0
- package/dist/memory-migration-inspect.js +108 -0
- package/dist/memory-migration-journal.js +14 -0
- package/dist/memory-migration-protocol.js +14 -0
- package/dist/memory-migration-runtime.js +305 -0
- package/dist/memory-prune-diagnostics.js +60 -4
- package/dist/message-file-preview.js +11 -1
- package/dist/prompt.js +6 -2
- package/dist/runner.js +1 -1
- package/dist/runtimes/claude-thread-runner.js +25 -4
- package/dist/serve.js +38 -3
- package/dist/token.js +1 -0
- package/dist/workspace-control-handler.js +16 -3
- package/dist/workspace.js +13 -2
- package/package.json +1 -1
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { lstat, mkdir, open, readFile, realpath } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { createJournalLease, createJournalLeaseRegistry, JournalLockedError } from "../execution-journal-lock.js";
|
|
5
|
+
import { defaultProcessController } from "../execution-journal.js";
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { MigrationStateSchema } from "./migration-schema.js";
|
|
8
|
+
import { detectLocalMemoryStorageVersion, parseFullMemoryIndex } from "./storage-format.js";
|
|
9
|
+
import { inventoryLimits, readMemoryInventorySource, scanMemorySources } from "./inventory-source.js";
|
|
10
|
+
import { inspectV2MemoryInventory } from "./inventory-v2.js";
|
|
11
|
+
import { MEMORY_STATE_GUARD_CAPABILITY, MEMORY_STORAGE_V2_CAPABILITY } from "../memory-migration-protocol.js";
|
|
12
|
+
import { isLocalMemoryInitializationIdentity, localMemoryInitializationIdentity } from "./initialization-identity.js";
|
|
13
|
+
import { assertMigrationStateIntegrity } from "./migration-state-invariants.js";
|
|
14
|
+
export const LOCAL_MEMORY_V2_WRITER_CAPABILITIES = [MEMORY_STORAGE_V2_CAPABILITY, MEMORY_STATE_GUARD_CAPABILITY];
|
|
15
|
+
/**
|
|
16
|
+
* Keep an execution that started before migration from writing a committed V2
|
|
17
|
+
* catalog with the legacy result writer. Server-side daemon capability checks
|
|
18
|
+
* stop new work, but an already-running old process can still reach its local
|
|
19
|
+
* result commit after the migration has finished.
|
|
20
|
+
*/
|
|
21
|
+
export async function assertMemoryWriterAllowed(agentDir, capabilities = []) {
|
|
22
|
+
const root = await realpath(agentDir);
|
|
23
|
+
let state;
|
|
24
|
+
try {
|
|
25
|
+
const source = await readMemoryInventorySource(root, ".crew/memory/migration.v1.json", inventoryLimits.fileBytes);
|
|
26
|
+
state = StateGate.parse(JSON.parse(source.content));
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
if (error.code === "ENOENT") {
|
|
30
|
+
// A missing state file is only compatible with an old, unmarked store.
|
|
31
|
+
// Once MEMORY.md carries a schema2 index, absence of the state must fail closed.
|
|
32
|
+
try {
|
|
33
|
+
const memory = await readMemoryInventorySource(root, "MEMORY.md", inventoryLimits.fileBytes);
|
|
34
|
+
if (detectLocalMemoryStorageVersion(memory.content) === 2) {
|
|
35
|
+
throw new Error("memory_migration_state_missing");
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
catch (memoryError) {
|
|
39
|
+
if (memoryError.code === "ENOENT")
|
|
40
|
+
return;
|
|
41
|
+
throw memoryError;
|
|
42
|
+
}
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
if (error instanceof z.ZodError || error instanceof SyntaxError)
|
|
46
|
+
throw new Error("memory_migration_state_invalid");
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
if (state.phase === "applying" || state.phase === "repair_required" || state.phase === "prepared") {
|
|
50
|
+
throw new Error("memory_migration_in_progress");
|
|
51
|
+
}
|
|
52
|
+
if (state.phase !== "committed")
|
|
53
|
+
return;
|
|
54
|
+
// Reuse the committed-state integrity checks before admitting any writer;
|
|
55
|
+
// a truncated committed state must fail closed instead of looking legacy.
|
|
56
|
+
await assertMemoryAccessAllowed(root);
|
|
57
|
+
if (state.storageVersion !== 2)
|
|
58
|
+
return;
|
|
59
|
+
if (LOCAL_MEMORY_V2_WRITER_CAPABILITIES.some((capability) => !capabilities.includes(capability))) {
|
|
60
|
+
throw new Error("memory_v2_writer_capability_missing");
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Check the committed V2 catalog immediately before a write is persisted.
|
|
65
|
+
* Keep this separate from the boot/state gate so legacy writer-specific
|
|
66
|
+
* validation (size limits, entry limits, note limits) retains its established
|
|
67
|
+
* error precedence.
|
|
68
|
+
*/
|
|
69
|
+
export async function assertMemoryInventoryHealth(agentDir) {
|
|
70
|
+
const root = await realpath(agentDir);
|
|
71
|
+
let state;
|
|
72
|
+
try {
|
|
73
|
+
const source = await readMemoryInventorySource(root, ".crew/memory/migration.v1.json", inventoryLimits.fileBytes);
|
|
74
|
+
state = StateGate.parse(JSON.parse(source.content));
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
if (error.code === "ENOENT")
|
|
78
|
+
return;
|
|
79
|
+
if (error instanceof z.ZodError || error instanceof SyntaxError)
|
|
80
|
+
throw new Error("memory_migration_state_invalid");
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
// Legacy/schema1 writers do not need a V2 inventory scan. In particular,
|
|
84
|
+
// a large pending directory must keep the old writer's normal latency and
|
|
85
|
+
// budget behavior.
|
|
86
|
+
if (state.phase !== "committed" || state.storageVersion !== 2)
|
|
87
|
+
return;
|
|
88
|
+
const scan = await scanMemorySources(root, { includeOperationalFiles: false });
|
|
89
|
+
const health = await inspectV2MemoryInventory(root, scan.sources, scan.issues.length === 0);
|
|
90
|
+
const blockingNoteIssues = health.analysis.issues.filter(issue => issue.path.startsWith("notes/"));
|
|
91
|
+
if (scan.issues.length === 0
|
|
92
|
+
&& !health.analysis.issues.some(issue => issue.path === "MEMORY.md")
|
|
93
|
+
&& blockingNoteIssues.length > 0) {
|
|
94
|
+
throw new Error("memory_migration_inventory_invalid");
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const StateGate = z.object({
|
|
98
|
+
schemaVersion: z.literal(1), migrationId: z.string().min(1),
|
|
99
|
+
phase: z.enum(["prepared", "applying", "committed", "rolled_back", "repair_required"]),
|
|
100
|
+
storageVersion: z.union([z.literal(0), z.literal(1), z.literal(2)]).optional(),
|
|
101
|
+
}).passthrough();
|
|
102
|
+
async function checkedDirectory(parent, name) {
|
|
103
|
+
const directory = join(parent, name);
|
|
104
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
105
|
+
const stat = await lstat(directory);
|
|
106
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || await realpath(directory) !== directory) {
|
|
107
|
+
throw new Error("memory_migration_path_invalid");
|
|
108
|
+
}
|
|
109
|
+
return directory;
|
|
110
|
+
}
|
|
111
|
+
export async function assertMemoryAccessAllowed(agentDir, options = {}) {
|
|
112
|
+
let state = null;
|
|
113
|
+
try {
|
|
114
|
+
const source = await readMemoryInventorySource(agentDir, ".crew/memory/migration.v1.json", inventoryLimits.fileBytes);
|
|
115
|
+
state = StateGate.parse(JSON.parse(source.content));
|
|
116
|
+
if (state.phase === "prepared" || state.phase === "applying" || state.phase === "repair_required") {
|
|
117
|
+
if (options.pendingOnly && (state.phase === "prepared" || state.phase === "applying")) {
|
|
118
|
+
const fullState = MigrationStateSchema.parse(state);
|
|
119
|
+
assertMigrationStateIntegrity(fullState, fullState.identity);
|
|
120
|
+
// The migration inventory owns the pending directory while its journal
|
|
121
|
+
// is active. Allowing an execution to append a candidate here would
|
|
122
|
+
// make the next classify() see an unplanned file and force
|
|
123
|
+
// repair_required. Keep the journal fail-closed and let pending-only
|
|
124
|
+
// apply only to the marker-only legacy state (no active journal).
|
|
125
|
+
throw new Error("memory_migration_in_progress");
|
|
126
|
+
}
|
|
127
|
+
const recovery = options.initializedRecoveryIdentity;
|
|
128
|
+
if (recovery === undefined)
|
|
129
|
+
throw new Error("memory_migration_in_progress");
|
|
130
|
+
const fullState = MigrationStateSchema.parse(state);
|
|
131
|
+
assertMigrationStateIntegrity(fullState, fullState.identity);
|
|
132
|
+
const binding = recovery.workspaceId !== undefined && recovery.machineId !== undefined
|
|
133
|
+
? { workspaceId: recovery.workspaceId, machineId: recovery.machineId }
|
|
134
|
+
: undefined;
|
|
135
|
+
const identity = await localMemoryInitializationIdentity(agentDir, recovery.agentId, binding);
|
|
136
|
+
const legacyIdentity = binding === undefined
|
|
137
|
+
? identity
|
|
138
|
+
: await localMemoryInitializationIdentity(agentDir, recovery.agentId);
|
|
139
|
+
if (fullState.origin !== "initialized"
|
|
140
|
+
|| (fullState.phase === "prepared" && fullState.intentReceipt !== undefined)
|
|
141
|
+
|| (!isLocalMemoryInitializationIdentity(fullState.identity, identity)
|
|
142
|
+
&& !isLocalMemoryInitializationIdentity(fullState.identity, legacyIdentity))) {
|
|
143
|
+
throw new Error("memory_migration_in_progress");
|
|
144
|
+
}
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
if (error instanceof Error && error.message === "memory_migration_in_progress")
|
|
150
|
+
throw error;
|
|
151
|
+
if (error.code !== "ENOENT")
|
|
152
|
+
throw new Error("memory_migration_state_invalid");
|
|
153
|
+
}
|
|
154
|
+
let source;
|
|
155
|
+
try {
|
|
156
|
+
source = await readMemoryInventorySource(agentDir, "MEMORY.md", inventoryLimits.fileBytes);
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
if (error.code === "ENOENT" && state === null)
|
|
160
|
+
return;
|
|
161
|
+
if (error instanceof Error && error.message === "read_limit_exceeded")
|
|
162
|
+
throw new Error("memory_file_too_large");
|
|
163
|
+
throw error;
|
|
164
|
+
}
|
|
165
|
+
const version = detectLocalMemoryStorageVersion(source.content);
|
|
166
|
+
if (version === 2 || state?.phase === "committed") {
|
|
167
|
+
if (!state)
|
|
168
|
+
throw new Error("memory_migration_state_missing");
|
|
169
|
+
const verified = MigrationStateSchema.parse(state);
|
|
170
|
+
assertMigrationStateIntegrity(verified, verified.identity);
|
|
171
|
+
if (verified.phase !== "committed" || verified.storageVersion !== 2 || version !== 2
|
|
172
|
+
|| verified.identity.rootFingerprint !== createHash("sha256").update(await realpath(agentDir)).digest("hex")
|
|
173
|
+
|| verified.identity.ownerIdentity !== String((await lstat(agentDir)).uid)) {
|
|
174
|
+
throw new Error("memory_migration_state_invalid");
|
|
175
|
+
}
|
|
176
|
+
parseFullMemoryIndex(source.content);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
/** 复用现有进程身份锁;仅保护一次本地IO,不持锁等待模型,避免子CLI自锁。 */
|
|
180
|
+
export async function withMemoryAccess(agentDir, operation, options = {}) {
|
|
181
|
+
let created = false;
|
|
182
|
+
if (options.create) {
|
|
183
|
+
created = await lstat(agentDir).then(() => false, (e) => { if (e.code === "ENOENT")
|
|
184
|
+
return true; throw e; });
|
|
185
|
+
await mkdir(agentDir, { recursive: true, mode: 0o700 });
|
|
186
|
+
}
|
|
187
|
+
const root = await realpath(agentDir);
|
|
188
|
+
if ((await lstat(agentDir)).isSymbolicLink())
|
|
189
|
+
throw new Error("memory_migration_path_invalid");
|
|
190
|
+
const crew = await checkedDirectory(root, ".crew");
|
|
191
|
+
const memory = await checkedDirectory(crew, "memory");
|
|
192
|
+
const directory = await checkedDirectory(memory, "access.lock");
|
|
193
|
+
const lease = createJournalLease({ directory, currentPid: process.pid,
|
|
194
|
+
captureCurrentIdentity: async () => {
|
|
195
|
+
const identity = await defaultProcessController.inspectIdentity(process.pid);
|
|
196
|
+
if (!identity)
|
|
197
|
+
throw new Error("memory_migration_process_unknown");
|
|
198
|
+
return identity;
|
|
199
|
+
},
|
|
200
|
+
inspectIdentity: pid => defaultProcessController.inspectIdentity(pid),
|
|
201
|
+
registry: createJournalLeaseRegistry(),
|
|
202
|
+
syncDirectory: async (path) => {
|
|
203
|
+
if (process.platform === "win32")
|
|
204
|
+
return;
|
|
205
|
+
const handle = await open(path, "r");
|
|
206
|
+
try {
|
|
207
|
+
await handle.sync();
|
|
208
|
+
}
|
|
209
|
+
finally {
|
|
210
|
+
await handle.close();
|
|
211
|
+
}
|
|
212
|
+
},
|
|
213
|
+
});
|
|
214
|
+
const deadline = Date.now() + (options.waitMs ?? 2000);
|
|
215
|
+
for (;;) {
|
|
216
|
+
try {
|
|
217
|
+
await lease.acquire();
|
|
218
|
+
break;
|
|
219
|
+
}
|
|
220
|
+
catch (error) {
|
|
221
|
+
if (!(error instanceof JournalLockedError))
|
|
222
|
+
throw error;
|
|
223
|
+
if (Date.now() >= deadline)
|
|
224
|
+
throw new Error("memory_migration_access_busy");
|
|
225
|
+
await new Promise(resolve => setTimeout(resolve, 25));
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
try {
|
|
229
|
+
if (!options.maintenance)
|
|
230
|
+
await assertMemoryAccessAllowed(root, {
|
|
231
|
+
...(options.initializedRecoveryIdentity === undefined ? {} : {
|
|
232
|
+
initializedRecoveryIdentity: options.initializedRecoveryIdentity,
|
|
233
|
+
}),
|
|
234
|
+
...(options.pendingOnly ? { pendingOnly: true } : {}),
|
|
235
|
+
});
|
|
236
|
+
lease.assertUsable();
|
|
237
|
+
return await operation({ created });
|
|
238
|
+
}
|
|
239
|
+
finally {
|
|
240
|
+
await lease.close();
|
|
241
|
+
}
|
|
242
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { isAbsolute, resolve } from 'node:path';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { applyMemoryMigration, prepareMemoryMigration, recoverMemoryMigration, statusMemoryMigration } from './migration-store.js';
|
|
5
|
+
import { MigrationError, MigrationHistorySchema, MigrationIdentitySchema, MigrationIntentReceiptSchema, MigrationProcessStoppedReceiptSchema, MigrationRecordMappingSchema } from './migration-schema.js';
|
|
6
|
+
const base = z.object({ agentDir: z.string().refine(isAbsolute), identity: MigrationIdentitySchema });
|
|
7
|
+
export const MigrationCommandSchema = z.discriminatedUnion('command', [
|
|
8
|
+
base.extend({ command: z.literal('prepare'), serverHistory: MigrationHistorySchema, recordMappings: z.array(MigrationRecordMappingSchema).max(10000).optional() }).strict(),
|
|
9
|
+
base.extend({ command: z.literal('status') }).strict(),
|
|
10
|
+
base.extend({ command: z.literal('apply'), intentReceipt: MigrationIntentReceiptSchema }).strict(),
|
|
11
|
+
base.extend({ command: z.literal('recover'), serverHistory: MigrationHistorySchema.optional(), intentReceipt: MigrationIntentReceiptSchema.optional(), stoppedReceipt: MigrationProcessStoppedReceiptSchema.optional(), cancelled: z.boolean() }).strict(),
|
|
12
|
+
]);
|
|
13
|
+
export function summarizeMemoryMigration(state) {
|
|
14
|
+
return { migrationId: state?.migrationId ?? null, phase: state?.phase ?? null, storageVersion: state?.storageVersion ?? null, sourceDigest: state?.sourceDigest ?? null, planDigest: state?.planDigest ?? null,
|
|
15
|
+
issues: state?.issues ?? [], result: state === null ? 'missing' : state.phase === 'repair_required' ? 'repair_required' : 'success' };
|
|
16
|
+
}
|
|
17
|
+
/** The caller owns the execution/maintenance lease. This boundary never accepts or reads credentials. */
|
|
18
|
+
export async function runMemoryMigrationCommand(raw) {
|
|
19
|
+
let migrationId = null;
|
|
20
|
+
try {
|
|
21
|
+
const input = MigrationCommandSchema.parse(raw);
|
|
22
|
+
migrationId = input.identity.migrationId;
|
|
23
|
+
const state = input.command === 'prepare' ? await prepareMemoryMigration(input) : input.command === 'apply' ? await applyMemoryMigration(input)
|
|
24
|
+
: input.command === 'recover' ? await recoverMemoryMigration(input) : await statusMemoryMigration(input);
|
|
25
|
+
return summarizeMemoryMigration(state);
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
const reason = error instanceof MigrationError ? error.code : error instanceof z.ZodError ? 'migration_input_invalid' : 'migration_operation_failed';
|
|
29
|
+
return { ...summarizeMemoryMigration(null), migrationId, result: reason === 'migration_needs_review' ? 'needs_review' : reason.includes('repair_required') ? 'repair_required' : 'failed',
|
|
30
|
+
issues: error instanceof MigrationError && error.issues.length ? error.issues : [{ path: '', reason }] };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
async function main() {
|
|
34
|
+
try {
|
|
35
|
+
const chunks = [];
|
|
36
|
+
let bytes = 0;
|
|
37
|
+
for await (const chunk of process.stdin) {
|
|
38
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
39
|
+
bytes += buffer.length;
|
|
40
|
+
if (bytes > 8 * 1024 * 1024)
|
|
41
|
+
throw new Error('input_limit');
|
|
42
|
+
chunks.push(buffer);
|
|
43
|
+
}
|
|
44
|
+
const result = await runMemoryMigrationCommand(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
|
45
|
+
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
46
|
+
process.exitCode = result.result === 'success' || result.result === 'missing' ? 0 : 1;
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
process.stdout.write(`${JSON.stringify({ ...summarizeMemoryMigration(null), result: 'failed', issues: [{ path: '', reason: 'migration_input_invalid' }] })}\n`);
|
|
50
|
+
process.exitCode = 1;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url))
|
|
54
|
+
void main();
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { lstat, mkdir, open, opendir, realpath, rename, rm } from 'node:fs/promises';
|
|
4
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import { MigrationError, MigrationIdentitySchema } from './migration-schema.js';
|
|
6
|
+
import { LOCAL_MEMORY_NOTE_BYTE_CAP, LOCAL_MEMORY_READ_BYTE_CAP, LOCAL_MEMORY_STORAGE_BYTE_CAP } from './storage-format.js';
|
|
7
|
+
export const digest = (data) => createHash('sha256').update(data).digest('hex');
|
|
8
|
+
export const STATE_PATH = '.crew/memory/migration.v1.json';
|
|
9
|
+
export async function validateMigrationRoot(agentDir, raw) {
|
|
10
|
+
const identity = MigrationIdentitySchema.parse(raw);
|
|
11
|
+
if (!isAbsolute(agentDir) || resolve(agentDir) !== agentDir)
|
|
12
|
+
throw new MigrationError('migration_root_invalid');
|
|
13
|
+
// macOS /var -> /private/var is a trusted system alias; the agent root itself may not be a symlink.
|
|
14
|
+
const stat = await lstat(agentDir);
|
|
15
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || String(stat.uid) !== identity.ownerIdentity)
|
|
16
|
+
throw new MigrationError('migration_owner_invalid');
|
|
17
|
+
if (digest(await realpath(agentDir)) !== identity.rootFingerprint)
|
|
18
|
+
throw new MigrationError('migration_root_fingerprint_invalid');
|
|
19
|
+
return identity;
|
|
20
|
+
}
|
|
21
|
+
export async function safePath(root, path, createParents = false) {
|
|
22
|
+
const target = resolve(root, path);
|
|
23
|
+
const rel = relative(root, target);
|
|
24
|
+
if (!rel || rel.startsWith(`..${sep}`) || rel === '..' || isAbsolute(rel))
|
|
25
|
+
throw new MigrationError('migration_path_invalid', [{ path, reason: 'outside_root' }]);
|
|
26
|
+
const parts = rel.split(sep);
|
|
27
|
+
let current = root;
|
|
28
|
+
for (let i = 0; i < parts.length; i++) {
|
|
29
|
+
current = join(current, parts[i]);
|
|
30
|
+
let stat = await lstat(current).catch((error) => {
|
|
31
|
+
if (error.code === 'ENOENT')
|
|
32
|
+
return null;
|
|
33
|
+
throw error;
|
|
34
|
+
});
|
|
35
|
+
if (!stat && createParents && i < parts.length - 1) {
|
|
36
|
+
await mkdir(current, { mode: 0o700 });
|
|
37
|
+
stat = await lstat(current);
|
|
38
|
+
}
|
|
39
|
+
if (stat?.isSymbolicLink() || (stat && i < parts.length - 1 && !stat.isDirectory()))
|
|
40
|
+
throw new MigrationError('migration_path_unsafe', [{ path, reason: 'symlink_or_non_directory' }]);
|
|
41
|
+
}
|
|
42
|
+
return target;
|
|
43
|
+
}
|
|
44
|
+
export async function readBytes(root, path, cap = LOCAL_MEMORY_NOTE_BYTE_CAP) {
|
|
45
|
+
const target = await safePath(root, path);
|
|
46
|
+
const file = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW).catch((error) => {
|
|
47
|
+
if (error.code === 'ENOENT')
|
|
48
|
+
return null;
|
|
49
|
+
throw error;
|
|
50
|
+
});
|
|
51
|
+
if (!file)
|
|
52
|
+
return null;
|
|
53
|
+
try {
|
|
54
|
+
const stat = await file.stat();
|
|
55
|
+
if (!stat.isFile() || stat.size > cap)
|
|
56
|
+
throw new MigrationError('migration_read_limit', [{ path, reason: 'invalid_file_or_size' }]);
|
|
57
|
+
const data = Buffer.alloc(stat.size + 1);
|
|
58
|
+
const { bytesRead } = await file.read(data, 0, data.length, 0);
|
|
59
|
+
if (bytesRead !== stat.size || (await file.stat()).size !== stat.size)
|
|
60
|
+
throw new MigrationError('migration_source_changed', [{ path, reason: 'changed_during_read' }]);
|
|
61
|
+
return data.subarray(0, bytesRead);
|
|
62
|
+
}
|
|
63
|
+
finally {
|
|
64
|
+
await file.close();
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
export async function atomicBytes(root, path, data, options = {}) {
|
|
68
|
+
const target = await safePath(root, path, true);
|
|
69
|
+
const temporaryPath = options.temporaryPath ?? `${path}.tmp-${randomUUID()}`;
|
|
70
|
+
const temp = await safePath(root, temporaryPath, true);
|
|
71
|
+
if ((await lstat(dirname(target))).dev !== (await lstat(dirname(temp))).dev) {
|
|
72
|
+
throw new MigrationError('migration_publication_filesystem_mismatch');
|
|
73
|
+
}
|
|
74
|
+
const existing = options.temporaryPath ? await readBytes(root, temporaryPath) : null;
|
|
75
|
+
if (existing && digest(existing) !== digest(data)) {
|
|
76
|
+
throw new MigrationError('migration_publication_copy_unknown', [{ path: temporaryPath, reason: 'publication_hash_mismatch' }]);
|
|
77
|
+
}
|
|
78
|
+
if (!existing) {
|
|
79
|
+
// The plan-recognized name is only published after every byte is complete and synced.
|
|
80
|
+
// An interrupted unpublished file is never a recovery source and is preserved as evidence.
|
|
81
|
+
const writePath = options.temporaryPath
|
|
82
|
+
? `${dirname(dirname(temporaryPath))}/unpublished/${randomUUID()}.tmp`
|
|
83
|
+
: temporaryPath;
|
|
84
|
+
const unpublished = await safePath(root, writePath, true);
|
|
85
|
+
if ((await lstat(dirname(unpublished))).dev !== (await lstat(dirname(temp))).dev) {
|
|
86
|
+
throw new MigrationError('migration_publication_filesystem_mismatch');
|
|
87
|
+
}
|
|
88
|
+
const file = await open(unpublished, 'wx', 0o600);
|
|
89
|
+
try {
|
|
90
|
+
if (options.temporaryPath) {
|
|
91
|
+
for (let offset = 0; offset < data.length; offset += 64 * 1024) {
|
|
92
|
+
const end = Math.min(offset + 64 * 1024, data.length);
|
|
93
|
+
await file.writeFile(data.subarray(offset, end));
|
|
94
|
+
await options.afterWriteChunk?.(writePath, end, data.length);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
else
|
|
98
|
+
await file.writeFile(data);
|
|
99
|
+
await file.sync();
|
|
100
|
+
}
|
|
101
|
+
finally {
|
|
102
|
+
await file.close();
|
|
103
|
+
}
|
|
104
|
+
if (options.temporaryPath) {
|
|
105
|
+
const complete = await readBytes(root, writePath);
|
|
106
|
+
if (!complete || digest(complete) !== digest(data))
|
|
107
|
+
throw new MigrationError('migration_unpublished_copy_invalid');
|
|
108
|
+
const appeared = await readBytes(root, temporaryPath);
|
|
109
|
+
if (appeared && digest(appeared) !== digest(data))
|
|
110
|
+
throw new MigrationError('migration_publication_copy_unknown');
|
|
111
|
+
if (!appeared) {
|
|
112
|
+
await safePath(root, temporaryPath);
|
|
113
|
+
await rename(unpublished, temp);
|
|
114
|
+
await syncDirectory(dirname(temp));
|
|
115
|
+
await syncDirectory(dirname(unpublished));
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
try {
|
|
120
|
+
await options.beforeRename?.();
|
|
121
|
+
await safePath(root, path);
|
|
122
|
+
if (options.temporaryPath) {
|
|
123
|
+
const verified = await readBytes(root, temporaryPath);
|
|
124
|
+
if (!verified || digest(verified) !== digest(data))
|
|
125
|
+
throw new MigrationError('migration_publication_copy_unknown');
|
|
126
|
+
}
|
|
127
|
+
await rename(temp, target);
|
|
128
|
+
await syncDirectory(dirname(target));
|
|
129
|
+
}
|
|
130
|
+
finally {
|
|
131
|
+
// Controlled copies survive interruption; recovery verifies their plan-bound name and content before reuse.
|
|
132
|
+
if (!options.temporaryPath)
|
|
133
|
+
await rm(temp, { force: true });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
export async function syncDirectory(path) {
|
|
137
|
+
const fd = await open(path, 'r');
|
|
138
|
+
try {
|
|
139
|
+
await fd.sync();
|
|
140
|
+
}
|
|
141
|
+
finally {
|
|
142
|
+
await fd.close();
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
export async function inventory(root) {
|
|
146
|
+
const files = new Map();
|
|
147
|
+
const directories = [];
|
|
148
|
+
let bytes = 0;
|
|
149
|
+
let fileCount = 0;
|
|
150
|
+
let directoryCount = 0;
|
|
151
|
+
function reserveFile() {
|
|
152
|
+
if (++fileCount > 20000)
|
|
153
|
+
throw new MigrationError('migration_file_limit');
|
|
154
|
+
}
|
|
155
|
+
function reserveDirectory() {
|
|
156
|
+
if (++directoryCount > 10000)
|
|
157
|
+
throw new MigrationError('migration_directory_limit');
|
|
158
|
+
}
|
|
159
|
+
async function scan(path, reserved = false) {
|
|
160
|
+
const target = await safePath(root, path);
|
|
161
|
+
const stat = await lstat(target).catch((error) => {
|
|
162
|
+
if (error.code === 'ENOENT')
|
|
163
|
+
return null;
|
|
164
|
+
throw error;
|
|
165
|
+
});
|
|
166
|
+
if (!stat)
|
|
167
|
+
return;
|
|
168
|
+
if (stat.isDirectory()) {
|
|
169
|
+
if (!reserved)
|
|
170
|
+
reserveDirectory();
|
|
171
|
+
directories.push(path);
|
|
172
|
+
const children = [];
|
|
173
|
+
for await (const entry of await opendir(target)) {
|
|
174
|
+
if (entry.isDirectory())
|
|
175
|
+
reserveDirectory();
|
|
176
|
+
else
|
|
177
|
+
reserveFile();
|
|
178
|
+
children.push(entry.name);
|
|
179
|
+
}
|
|
180
|
+
for (const name of children.sort())
|
|
181
|
+
await scan(`${path}/${name}`, true);
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
if (!reserved)
|
|
185
|
+
reserveFile();
|
|
186
|
+
const content = await readBytes(root, path, path === 'MEMORY.md' ? LOCAL_MEMORY_STORAGE_BYTE_CAP : LOCAL_MEMORY_NOTE_BYTE_CAP);
|
|
187
|
+
if (content) {
|
|
188
|
+
bytes += content.length;
|
|
189
|
+
if (bytes > LOCAL_MEMORY_READ_BYTE_CAP)
|
|
190
|
+
throw new MigrationError('migration_read_limit');
|
|
191
|
+
files.set(path, content);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
await scan('MEMORY.md');
|
|
196
|
+
await scan('notes');
|
|
197
|
+
await scan('.crew/memory/pending');
|
|
198
|
+
return { files, directories: directories.sort() };
|
|
199
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { detectLocalMemoryStorageVersion } from "./storage-format.js";
|
|
2
|
+
export function shouldUseMigrationDeferredPending(input) {
|
|
3
|
+
return input.pruneTraceId !== null
|
|
4
|
+
&& input.writerMode === "blocked"
|
|
5
|
+
&& input.rolloutEnabled
|
|
6
|
+
&& input.legacyFallback !== true
|
|
7
|
+
&& input.failure !== "inspection_failed"
|
|
8
|
+
&& detectLocalMemoryStorageVersion(input.memory) === 1;
|
|
9
|
+
}
|