@nowcrew/daemon 0.6.91-beta.4 → 0.6.91-beta.5
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/execution-journal.js +1 -3
- package/dist/execution-protocol.js +1 -1
- package/dist/execution-runner.js +1 -3
- package/dist/local-execution-prompt.js +3 -8
- package/dist/local-executor.js +35 -14
- package/dist/local-memory/index-budget.js +3 -9
- package/dist/local-memory/prompt.js +4 -20
- package/dist/local-memory/read-cli.js +1 -36
- package/dist/local-memory/rollout.js +8 -53
- package/dist/local-memory/runtime.js +2 -5
- package/dist/local-memory/write.js +17 -108
- package/dist/machine-info.js +0 -3
- package/dist/message-file-preview.js +1 -11
- package/dist/prompt.js +1 -5
- package/dist/runner.js +1 -1
- package/dist/serve.js +3 -36
- package/dist/token.js +0 -1
- package/dist/workspace-control-handler.js +3 -16
- package/package.json +1 -1
- package/dist/local-memory/execution-workspace.js +0 -36
- package/dist/local-memory/full-index-search.js +0 -47
- package/dist/local-memory/migration-access.js +0 -118
- package/dist/local-memory/migration-cli.js +0 -54
- package/dist/local-memory/migration-io.js +0 -199
- package/dist/local-memory/migration-plan.js +0 -278
- package/dist/local-memory/migration-schema.js +0 -55
- package/dist/local-memory/migration-store.js +0 -424
- package/dist/local-memory/migration-tool-entry.js +0 -21
- package/dist/local-memory/storage-format.js +0 -152
- package/dist/memory-migration-controller.js +0 -84
- package/dist/memory-migration-inspect.js +0 -74
- package/dist/memory-migration-journal.js +0 -14
- package/dist/memory-migration-protocol.js +0 -14
- package/dist/memory-migration-runtime.js +0 -305
|
@@ -1,118 +0,0 @@
|
|
|
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 { readMemoryInventorySource, inventoryLimits } from "./inventory-source.js";
|
|
10
|
-
const StateGate = z.object({
|
|
11
|
-
schemaVersion: z.literal(1), migrationId: z.string().min(1),
|
|
12
|
-
phase: z.enum(["prepared", "applying", "committed", "rolled_back", "repair_required"]),
|
|
13
|
-
}).passthrough();
|
|
14
|
-
async function checkedDirectory(parent, name) {
|
|
15
|
-
const directory = join(parent, name);
|
|
16
|
-
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
17
|
-
const stat = await lstat(directory);
|
|
18
|
-
if (!stat.isDirectory() || stat.isSymbolicLink() || await realpath(directory) !== directory) {
|
|
19
|
-
throw new Error("memory_migration_path_invalid");
|
|
20
|
-
}
|
|
21
|
-
return directory;
|
|
22
|
-
}
|
|
23
|
-
export async function assertMemoryAccessAllowed(agentDir) {
|
|
24
|
-
let state = null;
|
|
25
|
-
try {
|
|
26
|
-
const source = await readMemoryInventorySource(agentDir, ".crew/memory/migration.v1.json", inventoryLimits.fileBytes);
|
|
27
|
-
state = StateGate.parse(JSON.parse(source.content));
|
|
28
|
-
if (state.phase === "applying" || state.phase === "repair_required")
|
|
29
|
-
throw new Error("memory_migration_in_progress");
|
|
30
|
-
}
|
|
31
|
-
catch (error) {
|
|
32
|
-
if (error instanceof Error && error.message === "memory_migration_in_progress")
|
|
33
|
-
throw error;
|
|
34
|
-
if (error.code !== "ENOENT")
|
|
35
|
-
throw new Error("memory_migration_state_invalid");
|
|
36
|
-
}
|
|
37
|
-
let source;
|
|
38
|
-
try {
|
|
39
|
-
source = await readMemoryInventorySource(agentDir, "MEMORY.md", inventoryLimits.fileBytes);
|
|
40
|
-
}
|
|
41
|
-
catch (error) {
|
|
42
|
-
if (error.code === "ENOENT" && state === null)
|
|
43
|
-
return;
|
|
44
|
-
if (error instanceof Error && error.message === "read_limit_exceeded")
|
|
45
|
-
throw new Error("memory_file_too_large");
|
|
46
|
-
throw error;
|
|
47
|
-
}
|
|
48
|
-
const version = detectLocalMemoryStorageVersion(source.content);
|
|
49
|
-
if (version === 2 || state?.phase === "committed") {
|
|
50
|
-
if (!state)
|
|
51
|
-
throw new Error("memory_migration_state_missing");
|
|
52
|
-
const verified = MigrationStateSchema.parse(state);
|
|
53
|
-
if (verified.phase !== "committed" || verified.storageVersion !== 2 || version !== 2
|
|
54
|
-
|| verified.identity.rootFingerprint !== createHash("sha256").update(await realpath(agentDir)).digest("hex")) {
|
|
55
|
-
throw new Error("memory_migration_state_invalid");
|
|
56
|
-
}
|
|
57
|
-
parseFullMemoryIndex(source.content);
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
/** 复用现有进程身份锁;仅保护一次本地IO,不持锁等待模型,避免子CLI自锁。 */
|
|
61
|
-
export async function withMemoryAccess(agentDir, operation, options = {}) {
|
|
62
|
-
let created = false;
|
|
63
|
-
if (options.create) {
|
|
64
|
-
created = await lstat(agentDir).then(() => false, (e) => { if (e.code === "ENOENT")
|
|
65
|
-
return true; throw e; });
|
|
66
|
-
await mkdir(agentDir, { recursive: true, mode: 0o700 });
|
|
67
|
-
}
|
|
68
|
-
const root = await realpath(agentDir);
|
|
69
|
-
if ((await lstat(agentDir)).isSymbolicLink())
|
|
70
|
-
throw new Error("memory_migration_path_invalid");
|
|
71
|
-
const crew = await checkedDirectory(root, ".crew");
|
|
72
|
-
const memory = await checkedDirectory(crew, "memory");
|
|
73
|
-
const directory = await checkedDirectory(memory, "access.lock");
|
|
74
|
-
const lease = createJournalLease({ directory, currentPid: process.pid,
|
|
75
|
-
captureCurrentIdentity: async () => {
|
|
76
|
-
const identity = await defaultProcessController.inspectIdentity(process.pid);
|
|
77
|
-
if (!identity)
|
|
78
|
-
throw new Error("memory_migration_process_unknown");
|
|
79
|
-
return identity;
|
|
80
|
-
},
|
|
81
|
-
inspectIdentity: pid => defaultProcessController.inspectIdentity(pid),
|
|
82
|
-
registry: createJournalLeaseRegistry(),
|
|
83
|
-
syncDirectory: async (path) => {
|
|
84
|
-
if (process.platform === "win32")
|
|
85
|
-
return;
|
|
86
|
-
const handle = await open(path, "r");
|
|
87
|
-
try {
|
|
88
|
-
await handle.sync();
|
|
89
|
-
}
|
|
90
|
-
finally {
|
|
91
|
-
await handle.close();
|
|
92
|
-
}
|
|
93
|
-
},
|
|
94
|
-
});
|
|
95
|
-
const deadline = Date.now() + (options.waitMs ?? 2000);
|
|
96
|
-
for (;;) {
|
|
97
|
-
try {
|
|
98
|
-
await lease.acquire();
|
|
99
|
-
break;
|
|
100
|
-
}
|
|
101
|
-
catch (error) {
|
|
102
|
-
if (!(error instanceof JournalLockedError))
|
|
103
|
-
throw error;
|
|
104
|
-
if (Date.now() >= deadline)
|
|
105
|
-
throw new Error("memory_migration_access_busy");
|
|
106
|
-
await new Promise(resolve => setTimeout(resolve, 25));
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
try {
|
|
110
|
-
if (!options.maintenance)
|
|
111
|
-
await assertMemoryAccessAllowed(root);
|
|
112
|
-
lease.assertUsable();
|
|
113
|
-
return await operation({ created });
|
|
114
|
-
}
|
|
115
|
-
finally {
|
|
116
|
-
await lease.close();
|
|
117
|
-
}
|
|
118
|
-
}
|
|
@@ -1,54 +0,0 @@
|
|
|
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();
|
|
@@ -1,199 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,278 +0,0 @@
|
|
|
1
|
-
import { digest } from './migration-io.js';
|
|
2
|
-
import { MigrationError, MigrationRecordMappingSchema } from './migration-schema.js';
|
|
3
|
-
import { assertLocalMemoryStorageSize, detectLocalMemoryStorageVersion, LOCAL_MEMORY_GENERATED_INDEX_PATTERN, LOCAL_MEMORY_NOTE_BYTE_CAP, LOCAL_MEMORY_READ_BYTE_CAP, parseFullMemoryIndex, renderFullMemoryIndex, selectLocalMemoryPreview } from './storage-format.js';
|
|
4
|
-
import { memorySeed } from '../workspace.js';
|
|
5
|
-
/** Reproduce the current workspace seed with its original handle and Role before accepting it as pristine. */
|
|
6
|
-
export function initializeExactWorkspaceSeed(bytes) {
|
|
7
|
-
const memory = bytes.toString('utf8');
|
|
8
|
-
const prefix = /^# ([^\r\n]+)\n\n## Role\n/u.exec(memory);
|
|
9
|
-
if (!prefix)
|
|
10
|
-
return null;
|
|
11
|
-
const template = memorySeed(prefix[1]);
|
|
12
|
-
const tail = template.slice(template.indexOf('\n\n## Core Goals\n'));
|
|
13
|
-
if (!memory.endsWith(tail))
|
|
14
|
-
return null;
|
|
15
|
-
const role = memory.slice(prefix[0].length, memory.length - tail.length);
|
|
16
|
-
if (!bytes.equals(Buffer.from(memorySeed(prefix[1], role))))
|
|
17
|
-
return null;
|
|
18
|
-
const heading = '\n## Knowledge Index\n';
|
|
19
|
-
const insertion = memory.length - tail.length + tail.indexOf(heading) + heading.length;
|
|
20
|
-
return Buffer.from(`${memory.slice(0, insertion)}${renderFullMemoryIndex([])}\n${memory.slice(insertion)}`);
|
|
21
|
-
}
|
|
22
|
-
const categories = /^(?:preferences|project-rules|testing|debugging|git|incidents|lessons)$/u;
|
|
23
|
-
const blockPattern = /<!--\s*NOWWORK:MEMORY_ENTRY:BEGIN\s+id=([A-Za-z0-9_-]+)\s+revision=([1-9][0-9]*)\s*-->([\s\S]*?)<!--\s*NOWWORK:MEMORY_ENTRY:END\s+id=\1\s*-->/gu;
|
|
24
|
-
const controlMarker = /<!--\s*NOWWORK:MEMORY_/u;
|
|
25
|
-
const harmless = (text) => !text.replace(/<!--[\s\S]*?-->/gu, '').replace(/^#{1,2}[^\n]*$/gmu, '').trim();
|
|
26
|
-
export function validateMigrationTarget(files) {
|
|
27
|
-
let totalBytes = 0;
|
|
28
|
-
for (const [path, bytes] of files) {
|
|
29
|
-
totalBytes += bytes.length;
|
|
30
|
-
if (bytes.length > LOCAL_MEMORY_NOTE_BYTE_CAP || totalBytes > LOCAL_MEMORY_READ_BYTE_CAP)
|
|
31
|
-
throw new MigrationError('migration_target_resource_limit', [{ path, reason: 'target_bytes_exceeded' }]);
|
|
32
|
-
}
|
|
33
|
-
const memory = files.get('MEMORY.md')?.toString('utf8');
|
|
34
|
-
if (!memory)
|
|
35
|
-
throw new MigrationError('migration_memory_missing');
|
|
36
|
-
const entries = parseFullMemoryIndex(memory);
|
|
37
|
-
selectLocalMemoryPreview(memory);
|
|
38
|
-
for (const entry of entries) {
|
|
39
|
-
const content = files.get(entry.file)?.toString('utf8') ?? '';
|
|
40
|
-
const blocks = [...content.matchAll(blockPattern)].filter(match => match[1] === entry.id);
|
|
41
|
-
if (blocks.length !== 1 || Number(blocks[0][2]) > entry.revision)
|
|
42
|
-
throw new MigrationError('migration_detail_invalid', [{ path: entry.file, reason: `missing_or_newer_detail:${entry.id}` }]);
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
/** Pure conversion; every source range is measured in UTF-16 offsets in the exact UTF-8 decoded source. */
|
|
46
|
-
export function planMemoryMigration(identity, files, supplied = []) {
|
|
47
|
-
for (const [path, bytes] of files) {
|
|
48
|
-
if ((path === 'MEMORY.md' || path.startsWith('notes/')) && !Buffer.from(bytes.toString('utf8')).equals(bytes)) {
|
|
49
|
-
throw new MigrationError('migration_source_encoding_invalid', [{ path, reason: 'invalid_utf8' }]);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
const memory = files.get('MEMORY.md')?.toString('utf8');
|
|
53
|
-
if (memory === undefined)
|
|
54
|
-
throw new MigrationError('migration_memory_missing');
|
|
55
|
-
assertLocalMemoryStorageSize(memory);
|
|
56
|
-
if (detectLocalMemoryStorageVersion(memory) !== identity.sourceStorageVersion)
|
|
57
|
-
throw new MigrationError('migration_source_version_mismatch');
|
|
58
|
-
const confirmedMappings = supplied.map(value => MigrationRecordMappingSchema.parse(value));
|
|
59
|
-
const mappingSourceDigests = new Map();
|
|
60
|
-
for (const mapping of confirmedMappings) {
|
|
61
|
-
if (mapping.sourceSha256 === undefined)
|
|
62
|
-
continue;
|
|
63
|
-
const source = files.get(mapping.sourceFile);
|
|
64
|
-
const actual = source === undefined ? undefined : mappingSourceDigests.get(mapping.sourceFile) ?? digest(source);
|
|
65
|
-
if (actual !== undefined)
|
|
66
|
-
mappingSourceDigests.set(mapping.sourceFile, actual);
|
|
67
|
-
if (actual !== mapping.sourceSha256) {
|
|
68
|
-
throw new MigrationError('migration_source_changed', [{ path: mapping.sourceFile, reason: 'mapping_source_digest_mismatch', start: mapping.start, end: mapping.end }]);
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
const output = new Map(files);
|
|
72
|
-
const issues = [];
|
|
73
|
-
let mappings = [];
|
|
74
|
-
if (identity.sourceStorageVersion === 1) {
|
|
75
|
-
const upgraded = memory.replace(LOCAL_MEMORY_GENERATED_INDEX_PATTERN, block => block.replace(/schema=1(?=\s*-->)/u, 'schema=2'));
|
|
76
|
-
const entries = parseFullMemoryIndex(upgraded);
|
|
77
|
-
const existingIds = new Set(entries.map(entry => entry.id));
|
|
78
|
-
const additions = confirmedMappings.map(mapping => ({ ...mapping, targetId: mapping.targetId
|
|
79
|
-
?? `mem_${digest(`${identity.migrationId}:${mapping.sourceFile}:${mapping.start}:${mapping.end}`).slice(0, 24)}` }));
|
|
80
|
-
const retainedHistory = new Map();
|
|
81
|
-
for (const mapping of additions) {
|
|
82
|
-
const body = files.get(mapping.sourceFile)?.toString('utf8');
|
|
83
|
-
if (!mapping.sourceFile.startsWith('notes/') || body === undefined || mapping.end > body.length)
|
|
84
|
-
issues.push({ path: mapping.sourceFile, reason: 'mapping_range_not_unindexed_notes', start: mapping.start, end: mapping.end });
|
|
85
|
-
if (existingIds.has(mapping.targetId))
|
|
86
|
-
issues.push({ path: mapping.sourceFile, reason: 'mapping_target_id_conflict' });
|
|
87
|
-
existingIds.add(mapping.targetId);
|
|
88
|
-
}
|
|
89
|
-
for (const [path, bytes] of files) {
|
|
90
|
-
if (!path.startsWith('notes/'))
|
|
91
|
-
continue;
|
|
92
|
-
const content = bytes.toString('utf8');
|
|
93
|
-
const blocks = [...content.matchAll(blockPattern)];
|
|
94
|
-
const ranges = additions.filter(mapping => mapping.sourceFile === path);
|
|
95
|
-
for (const block of blocks) {
|
|
96
|
-
const entry = entries.find(entry => entry.file === path && entry.id === block[1]);
|
|
97
|
-
if (!entry) {
|
|
98
|
-
const mapping = ranges.find(value => value.start === block.index && value.end === block.index + block[0].length);
|
|
99
|
-
// schema1 归档/替代会移除索引而保留正文。只接入确认过的完整历史块,不重包或推断其状态。
|
|
100
|
-
if (mapping?.sourceSha256 && mapping.targetId === block[1] && path === `notes/${mapping.category}.md`
|
|
101
|
-
&& mapping.status !== 'active' && mapping.status !== 'pinned' && !controlMarker.test(block[3]))
|
|
102
|
-
retainedHistory.set(mapping.targetId, { revision: Number(block[2]), body: block[3] });
|
|
103
|
-
else
|
|
104
|
-
issues.push({ path, reason: 'unindexed_detail', start: block.index, end: block.index + block[0].length });
|
|
105
|
-
}
|
|
106
|
-
else
|
|
107
|
-
mappings.push({ sourceFile: path, start: block.index, end: block.index + block[0].length, scope: `agent:${identity.agentId}`, category: path.slice(6, -3), targetId: entry.id, title: entry.title, status: entry.status });
|
|
108
|
-
}
|
|
109
|
-
const covered = [...blocks.map(block => ({ start: block.index, end: block.index + block[0].length })),
|
|
110
|
-
...ranges.filter(mapping => !retainedHistory.has(mapping.targetId))].sort((a, b) => a.start - b.start);
|
|
111
|
-
let cursor = 0, remainder = '';
|
|
112
|
-
for (const range of covered) {
|
|
113
|
-
if (range.start < cursor)
|
|
114
|
-
issues.push({ path, reason: 'mapping_overlaps_controlled_or_confirmed_range', start: range.start, end: range.end });
|
|
115
|
-
remainder += content.slice(cursor, range.start);
|
|
116
|
-
cursor = Math.max(cursor, range.end);
|
|
117
|
-
}
|
|
118
|
-
remainder += content.slice(cursor);
|
|
119
|
-
if (!harmless(remainder))
|
|
120
|
-
issues.push({ path, reason: 'unindexed_text_requires_mapping' });
|
|
121
|
-
}
|
|
122
|
-
for (const mapping of additions) {
|
|
123
|
-
const body = files.get(mapping.sourceFile)?.toString('utf8').slice(mapping.start, mapping.end) ?? '';
|
|
124
|
-
if (!retainedHistory.has(mapping.targetId) && controlMarker.test(body))
|
|
125
|
-
issues.push({ path: mapping.sourceFile, reason: 'mapping_contains_control_marker', start: mapping.start, end: mapping.end });
|
|
126
|
-
}
|
|
127
|
-
if (issues.length)
|
|
128
|
-
throw new MigrationError('migration_needs_review', issues);
|
|
129
|
-
const appended = new Map();
|
|
130
|
-
const replacements = new Map();
|
|
131
|
-
const newEntries = additions.map(mapping => ({ id: mapping.targetId, title: mapping.title,
|
|
132
|
-
file: `notes/${mapping.category}.md`, type: 'semantic', status: mapping.status,
|
|
133
|
-
summary: (retainedHistory.get(mapping.targetId)?.body ?? files.get(mapping.sourceFile).toString('utf8').slice(mapping.start, mapping.end)).replace(/\s+/gu, ' ').slice(0, 180),
|
|
134
|
-
triggers: [], priority: 'medium', updated: '1970-01-01', anchor: mapping.targetId, revision: retainedHistory.get(mapping.targetId)?.revision ?? 1, reviewAfter: null }));
|
|
135
|
-
for (const mapping of additions) {
|
|
136
|
-
if (retainedHistory.has(mapping.targetId))
|
|
137
|
-
continue;
|
|
138
|
-
const body = files.get(mapping.sourceFile).toString('utf8').slice(mapping.start, mapping.end);
|
|
139
|
-
const file = `notes/${mapping.category}.md`;
|
|
140
|
-
const block = `<!-- NOWWORK:MEMORY_ENTRY:BEGIN id=${mapping.targetId} revision=1 -->\n## ${mapping.title}\n\nScope: ${mapping.scope}\n\n${body}\n<!-- NOWWORK:MEMORY_ENTRY:END id=${mapping.targetId} -->\n`;
|
|
141
|
-
if (mapping.sourceFile === file)
|
|
142
|
-
replacements.set(file, [...(replacements.get(file) ?? []), { start: mapping.start, end: mapping.end, block }]);
|
|
143
|
-
else
|
|
144
|
-
appended.set(file, [...(appended.get(file) ?? []), block]);
|
|
145
|
-
}
|
|
146
|
-
for (const path of new Set([...replacements.keys(), ...appended.keys()])) {
|
|
147
|
-
let content = files.get(path)?.toString('utf8') ?? '';
|
|
148
|
-
for (const replacement of (replacements.get(path) ?? []).sort((a, b) => b.start - a.start))
|
|
149
|
-
content = content.slice(0, replacement.start) + replacement.block + content.slice(replacement.end);
|
|
150
|
-
const blocks = appended.get(path);
|
|
151
|
-
if (blocks)
|
|
152
|
-
content += '\n' + blocks.join('\n');
|
|
153
|
-
output.set(path, Buffer.from(content));
|
|
154
|
-
}
|
|
155
|
-
mappings.push(...additions);
|
|
156
|
-
const target = upgraded.replace(LOCAL_MEMORY_GENERATED_INDEX_PATTERN, () => renderFullMemoryIndex([...entries, ...newEntries]));
|
|
157
|
-
output.set('MEMORY.md', Buffer.from(target));
|
|
158
|
-
}
|
|
159
|
-
else {
|
|
160
|
-
const knownMetadata = new Map();
|
|
161
|
-
mappings = confirmedMappings;
|
|
162
|
-
if (mappings.length > 0) {
|
|
163
|
-
const heading = /^## Knowledge Index\s*$/mu.exec(memory);
|
|
164
|
-
if (heading?.index !== undefined) {
|
|
165
|
-
const start = heading.index + heading[0].length;
|
|
166
|
-
const tail = memory.slice(start);
|
|
167
|
-
const next = /^## (?!#)/mu.exec(tail);
|
|
168
|
-
const end = next?.index === undefined ? memory.length : start + next.index;
|
|
169
|
-
let uncovered = memory.slice(start, end);
|
|
170
|
-
for (const mapping of mappings.filter(value => value.sourceFile === 'MEMORY.md').sort((a, b) => b.start - a.start)) {
|
|
171
|
-
if (mapping.start < start || mapping.end > end) {
|
|
172
|
-
issues.push({ path: 'MEMORY.md', reason: 'mapping_crosses_identity_or_index_boundary' });
|
|
173
|
-
continue;
|
|
174
|
-
}
|
|
175
|
-
uncovered = uncovered.slice(0, mapping.start - start) + ' '.repeat(mapping.end - mapping.start) + uncovered.slice(mapping.end - start);
|
|
176
|
-
}
|
|
177
|
-
uncovered = uncovered.replace(/^[-*]\s+\[[^\]]+\]\((notes\/[^)]+)\)\s*$/gmu, (line, path) => mappings.some(value => value.sourceFile === path) ? '' : line);
|
|
178
|
-
if (uncovered.trim())
|
|
179
|
-
issues.push({ path: 'MEMORY.md', reason: 'index_text_requires_mapping', start, end });
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
// Known complete cards may declare their exact scope and unique whole-file body.
|
|
183
|
-
if (mappings.length === 0) {
|
|
184
|
-
const section = /^## Knowledge Index\s*\n([\s\S]*?)(?=^## (?!#)|$(?![\s\S]))/mu.exec(memory);
|
|
185
|
-
const content = section?.[1] ?? '';
|
|
186
|
-
const cards = [...content.matchAll(/^### (.+)\r?\n([\s\S]*?)(?=^### |$(?![\s\S]))/gmu)];
|
|
187
|
-
if (content.slice(0, cards[0]?.index ?? content.length).trim())
|
|
188
|
-
issues.push({ path: 'MEMORY.md', reason: 'index_text_requires_mapping' });
|
|
189
|
-
const seenFiles = new Set();
|
|
190
|
-
for (const card of cards) {
|
|
191
|
-
const fieldMatches = [...card[2].matchAll(/^- ([a-z_]+):[^\S\r\n]*(.*)$/gmu)];
|
|
192
|
-
const fields = Object.fromEntries(fieldMatches.map(match => [match[1], match[2].trim()]));
|
|
193
|
-
const allowedFields = new Set(['file', 'scope', 'type', 'status', 'summary', 'priority', 'updated', 'triggers', 'review_after', 'id', 'anchor', 'revision']);
|
|
194
|
-
if (card[2].replace(/^- ([a-z_]+):[^\S\r\n]*(.*)$/gmu, '').trim() || fieldMatches.length !== Object.keys(fields).length || Object.keys(fields).some(key => !allowedFields.has(key))) {
|
|
195
|
-
issues.push({ path: 'MEMORY.md', reason: 'card_contains_unmapped_text', start: card.index });
|
|
196
|
-
continue;
|
|
197
|
-
}
|
|
198
|
-
const path = fields.file ?? '';
|
|
199
|
-
const category = /^notes\/(.+)\.md$/u.exec(path)?.[1] ?? '';
|
|
200
|
-
const body = files.get(path)?.toString('utf8');
|
|
201
|
-
if (!fields.scope || !categories.test(category) || !body?.trim() || seenFiles.has(path)
|
|
202
|
-
|| !fields.summary || !['procedural', 'semantic', 'episodic', 'preference'].includes(fields.type ?? '') || !fields.status || !['high', 'medium', 'low'].includes(fields.priority ?? '') || !fields.updated) {
|
|
203
|
-
issues.push({ path: 'MEMORY.md', reason: 'card_mapping_unconfirmed', start: card.index });
|
|
204
|
-
continue;
|
|
205
|
-
}
|
|
206
|
-
seenFiles.add(path);
|
|
207
|
-
const parsed = MigrationRecordMappingSchema.safeParse({ sourceFile: path, start: 0, end: body.length, scope: fields.scope, category, title: card[1], status: fields.status });
|
|
208
|
-
if (!parsed.success)
|
|
209
|
-
issues.push({ path, reason: 'card_metadata_invalid' });
|
|
210
|
-
else {
|
|
211
|
-
mappings.push(parsed.data);
|
|
212
|
-
knownMetadata.set(path, { type: fields.type, summary: fields.summary, priority: fields.priority, updated: fields.updated,
|
|
213
|
-
triggers: (fields.triggers ?? '').split(/[,,、]/u).map(value => value.trim()).filter(Boolean), reviewAfter: fields.review_after ?? null });
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
if (!cards.length)
|
|
217
|
-
issues.push({ path: 'MEMORY.md', reason: 'legacy_source_requires_mapping' });
|
|
218
|
-
}
|
|
219
|
-
const entries = [];
|
|
220
|
-
for (const mapping of mappings) {
|
|
221
|
-
const body = files.get(mapping.sourceFile)?.toString('utf8');
|
|
222
|
-
if (body === undefined || mapping.end > body.length) {
|
|
223
|
-
issues.push({ path: mapping.sourceFile, reason: 'range_out_of_bounds' });
|
|
224
|
-
continue;
|
|
225
|
-
}
|
|
226
|
-
const id = mapping.targetId ?? `mem_${digest(`${identity.migrationId}:${mapping.sourceFile}:${mapping.start}:${mapping.end}`).slice(0, 24)}`;
|
|
227
|
-
entries.push({ id, title: mapping.title, file: `notes/${mapping.category}.md`, type: 'semantic', status: mapping.status, summary: body.slice(mapping.start, mapping.end).replace(/\s+/gu, ' ').slice(0, 180),
|
|
228
|
-
triggers: [], priority: 'medium', updated: '1970-01-01', anchor: id, revision: 1, reviewAfter: null, ...knownMetadata.get(mapping.sourceFile) });
|
|
229
|
-
}
|
|
230
|
-
for (const [path, bytes] of files) {
|
|
231
|
-
if (!path.startsWith('notes/') && path !== 'MEMORY.md')
|
|
232
|
-
continue;
|
|
233
|
-
const text = bytes.toString('utf8');
|
|
234
|
-
const ranges = mappings.filter(mapping => mapping.sourceFile === path).sort((a, b) => a.start - b.start);
|
|
235
|
-
if (path === 'MEMORY.md')
|
|
236
|
-
continue; // Retained identity stays byte-for-byte; replaced index coverage is checked above.
|
|
237
|
-
let cursor = 0;
|
|
238
|
-
for (const range of ranges) {
|
|
239
|
-
if (range.start < cursor || text.slice(cursor, range.start).trim())
|
|
240
|
-
issues.push({ path, reason: 'mapping_gap_or_overlap', start: cursor, end: range.start });
|
|
241
|
-
cursor = range.end;
|
|
242
|
-
}
|
|
243
|
-
if (text.slice(cursor).trim())
|
|
244
|
-
issues.push({ path, reason: 'unmapped_source_text', start: cursor, end: text.length });
|
|
245
|
-
}
|
|
246
|
-
if (issues.length)
|
|
247
|
-
throw new MigrationError('migration_needs_review', issues);
|
|
248
|
-
// Retain original files (external references may exist); only same-path fully covered sources are rewritten.
|
|
249
|
-
const targets = new Map();
|
|
250
|
-
mappings.forEach((mapping, index) => {
|
|
251
|
-
const entry = entries[index];
|
|
252
|
-
const body = files.get(mapping.sourceFile).toString('utf8').slice(mapping.start, mapping.end);
|
|
253
|
-
const blocks = targets.get(entry.file) ?? [];
|
|
254
|
-
targets.set(entry.file, [...blocks, `<!-- NOWWORK:MEMORY_ENTRY:BEGIN id=${entry.id} revision=1 -->\n## ${entry.title}\n\nScope: ${mapping.scope}\n\n${body}\n<!-- NOWWORK:MEMORY_ENTRY:END id=${entry.id} -->\n`]);
|
|
255
|
-
});
|
|
256
|
-
for (const [path, blocks] of targets) {
|
|
257
|
-
const existing = files.get(path);
|
|
258
|
-
if (existing && !mappings.some(mapping => mapping.sourceFile === path))
|
|
259
|
-
throw new MigrationError('migration_needs_review', [{ path, reason: 'target_contains_unmapped_text' }]);
|
|
260
|
-
output.set(path, Buffer.from(blocks.join('\n')));
|
|
261
|
-
}
|
|
262
|
-
const index = renderFullMemoryIndex(entries);
|
|
263
|
-
const heading = /^## Knowledge Index\s*$/mu.exec(memory);
|
|
264
|
-
let target;
|
|
265
|
-
if (heading?.index !== undefined) {
|
|
266
|
-
const start = heading.index + heading[0].length;
|
|
267
|
-
const tail = memory.slice(start);
|
|
268
|
-
const next = /^## (?!#)/mu.exec(tail);
|
|
269
|
-
target = memory.slice(0, start) + `\n${index}\n` + (next?.index === undefined ? '' : tail.slice(next.index));
|
|
270
|
-
}
|
|
271
|
-
else
|
|
272
|
-
target = `${memory}\n\n## Knowledge Index\n${index}\n`;
|
|
273
|
-
output.set('MEMORY.md', Buffer.from(target));
|
|
274
|
-
mappings = mappings.map((mapping, index) => ({ ...mapping, targetId: entries[index].id }));
|
|
275
|
-
}
|
|
276
|
-
validateMigrationTarget(output);
|
|
277
|
-
return { files: output, recordMappings: mappings };
|
|
278
|
-
}
|