@nowcrew/daemon 0.6.93-beta.2 → 0.6.93-beta.4

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 (46) hide show
  1. package/dist/cloud-report-upload.js +10 -1
  2. package/dist/execution-journal.js +1 -3
  3. package/dist/execution-protocol.js +1 -1
  4. package/dist/execution-runner.js +1 -3
  5. package/dist/local-execution-prompt.js +3 -8
  6. package/dist/local-executor.js +35 -64
  7. package/dist/local-memory/index-budget.js +3 -9
  8. package/dist/local-memory/inventory-cli.js +1 -23
  9. package/dist/local-memory/inventory-source.js +8 -15
  10. package/dist/local-memory/prompt.js +4 -20
  11. package/dist/local-memory/read-cli.js +77 -75
  12. package/dist/local-memory/rollout.js +8 -54
  13. package/dist/local-memory/runtime.js +13 -148
  14. package/dist/local-memory/write.js +19 -125
  15. package/dist/local-memory-diagnostics.js +2 -41
  16. package/dist/local-memory-telemetry.js +2 -19
  17. package/dist/machine-info.js +0 -3
  18. package/dist/marketplace-protocol.js +1 -1
  19. package/dist/marketplace-remote.js +1 -1
  20. package/dist/marketplace-runner.js +1 -1
  21. package/dist/memory-prune-diagnostics.js +4 -60
  22. package/dist/message-file-preview.js +1 -11
  23. package/dist/prompt.js +1 -5
  24. package/dist/runner.js +1 -1
  25. package/dist/serve.js +3 -36
  26. package/dist/token.js +0 -1
  27. package/dist/workspace-control-handler.js +3 -16
  28. package/dist/workspace.js +2 -10
  29. package/package.json +1 -1
  30. package/dist/local-memory/execution-workspace.js +0 -55
  31. package/dist/local-memory/full-index-search.js +0 -47
  32. package/dist/local-memory/initialization-identity.js +0 -23
  33. package/dist/local-memory/legacy-adapter.js +0 -233
  34. package/dist/local-memory/migration-access.js +0 -184
  35. package/dist/local-memory/migration-cli.js +0 -54
  36. package/dist/local-memory/migration-io.js +0 -199
  37. package/dist/local-memory/migration-plan.js +0 -283
  38. package/dist/local-memory/migration-schema.js +0 -55
  39. package/dist/local-memory/migration-store.js +0 -429
  40. package/dist/local-memory/migration-tool-entry.js +0 -21
  41. package/dist/local-memory/storage-format.js +0 -152
  42. package/dist/memory-migration-controller.js +0 -84
  43. package/dist/memory-migration-inspect.js +0 -75
  44. package/dist/memory-migration-journal.js +0 -14
  45. package/dist/memory-migration-protocol.js +0 -14
  46. package/dist/memory-migration-runtime.js +0 -305
@@ -1,283 +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
- function migrationSummary(body, title) {
27
- const clean = (value) => value.replace(/<!--[\s\S]*?-->/gu, ' ')
28
- .replace(/[\u0000-\u001f\u007f]+/gu, ' ').replace(/\s+/gu, ' ').trim().slice(0, 180);
29
- return clean(body) || clean(title) || 'Migrated memory';
30
- }
31
- export function validateMigrationTarget(files) {
32
- let totalBytes = 0;
33
- for (const [path, bytes] of files) {
34
- totalBytes += bytes.length;
35
- if (bytes.length > LOCAL_MEMORY_NOTE_BYTE_CAP || totalBytes > LOCAL_MEMORY_READ_BYTE_CAP)
36
- throw new MigrationError('migration_target_resource_limit', [{ path, reason: 'target_bytes_exceeded' }]);
37
- }
38
- const memory = files.get('MEMORY.md')?.toString('utf8');
39
- if (!memory)
40
- throw new MigrationError('migration_memory_missing');
41
- const entries = parseFullMemoryIndex(memory);
42
- selectLocalMemoryPreview(memory);
43
- for (const entry of entries) {
44
- const content = files.get(entry.file)?.toString('utf8') ?? '';
45
- const blocks = [...content.matchAll(blockPattern)].filter(match => match[1] === entry.id);
46
- if (blocks.length !== 1 || Number(blocks[0][2]) > entry.revision)
47
- throw new MigrationError('migration_detail_invalid', [{ path: entry.file, reason: `missing_or_newer_detail:${entry.id}` }]);
48
- }
49
- }
50
- /** Pure conversion; every source range is measured in UTF-16 offsets in the exact UTF-8 decoded source. */
51
- export function planMemoryMigration(identity, files, supplied = []) {
52
- for (const [path, bytes] of files) {
53
- if ((path === 'MEMORY.md' || path.startsWith('notes/')) && !Buffer.from(bytes.toString('utf8')).equals(bytes)) {
54
- throw new MigrationError('migration_source_encoding_invalid', [{ path, reason: 'invalid_utf8' }]);
55
- }
56
- }
57
- const memory = files.get('MEMORY.md')?.toString('utf8');
58
- if (memory === undefined)
59
- throw new MigrationError('migration_memory_missing');
60
- assertLocalMemoryStorageSize(memory);
61
- if (detectLocalMemoryStorageVersion(memory) !== identity.sourceStorageVersion)
62
- throw new MigrationError('migration_source_version_mismatch');
63
- const confirmedMappings = supplied.map(value => MigrationRecordMappingSchema.parse(value));
64
- const mappingSourceDigests = new Map();
65
- for (const mapping of confirmedMappings) {
66
- if (mapping.sourceSha256 === undefined)
67
- continue;
68
- const source = files.get(mapping.sourceFile);
69
- const actual = source === undefined ? undefined : mappingSourceDigests.get(mapping.sourceFile) ?? digest(source);
70
- if (actual !== undefined)
71
- mappingSourceDigests.set(mapping.sourceFile, actual);
72
- if (actual !== mapping.sourceSha256) {
73
- throw new MigrationError('migration_source_changed', [{ path: mapping.sourceFile, reason: 'mapping_source_digest_mismatch', start: mapping.start, end: mapping.end }]);
74
- }
75
- }
76
- const output = new Map(files);
77
- const issues = [];
78
- let mappings = [];
79
- if (identity.sourceStorageVersion === 1) {
80
- const upgraded = memory.replace(LOCAL_MEMORY_GENERATED_INDEX_PATTERN, block => block.replace(/schema=1(?=\s*-->)/u, 'schema=2'));
81
- const entries = parseFullMemoryIndex(upgraded);
82
- const existingIds = new Set(entries.map(entry => entry.id));
83
- const additions = confirmedMappings.map(mapping => ({ ...mapping, targetId: mapping.targetId
84
- ?? `mem_${digest(`${identity.migrationId}:${mapping.sourceFile}:${mapping.start}:${mapping.end}`).slice(0, 24)}` }));
85
- const retainedHistory = new Map();
86
- for (const mapping of additions) {
87
- const body = files.get(mapping.sourceFile)?.toString('utf8');
88
- if (!mapping.sourceFile.startsWith('notes/') || body === undefined || mapping.end > body.length)
89
- issues.push({ path: mapping.sourceFile, reason: 'mapping_range_not_unindexed_notes', start: mapping.start, end: mapping.end });
90
- if (existingIds.has(mapping.targetId))
91
- issues.push({ path: mapping.sourceFile, reason: 'mapping_target_id_conflict' });
92
- existingIds.add(mapping.targetId);
93
- }
94
- for (const [path, bytes] of files) {
95
- if (!path.startsWith('notes/'))
96
- continue;
97
- const content = bytes.toString('utf8');
98
- const blocks = [...content.matchAll(blockPattern)];
99
- const ranges = additions.filter(mapping => mapping.sourceFile === path);
100
- for (const block of blocks) {
101
- const entry = entries.find(entry => entry.file === path && entry.id === block[1]);
102
- if (!entry) {
103
- const mapping = ranges.find(value => value.start === block.index && value.end === block.index + block[0].length);
104
- // schema1 归档/替代会移除索引而保留正文。只接入确认过的完整历史块,不重包或推断其状态。
105
- if (mapping?.sourceSha256 && mapping.targetId === block[1] && path === `notes/${mapping.category}.md`
106
- && mapping.status !== 'active' && mapping.status !== 'pinned' && !controlMarker.test(block[3]))
107
- retainedHistory.set(mapping.targetId, { revision: Number(block[2]), body: block[3] });
108
- else
109
- issues.push({ path, reason: 'unindexed_detail', start: block.index, end: block.index + block[0].length });
110
- }
111
- else
112
- 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 });
113
- }
114
- const covered = [...blocks.map(block => ({ start: block.index, end: block.index + block[0].length })),
115
- ...ranges.filter(mapping => !retainedHistory.has(mapping.targetId))].sort((a, b) => a.start - b.start);
116
- let cursor = 0, remainder = '';
117
- for (const range of covered) {
118
- if (range.start < cursor)
119
- issues.push({ path, reason: 'mapping_overlaps_controlled_or_confirmed_range', start: range.start, end: range.end });
120
- remainder += content.slice(cursor, range.start);
121
- cursor = Math.max(cursor, range.end);
122
- }
123
- remainder += content.slice(cursor);
124
- if (!harmless(remainder))
125
- issues.push({ path, reason: 'unindexed_text_requires_mapping' });
126
- }
127
- for (const mapping of additions) {
128
- const body = files.get(mapping.sourceFile)?.toString('utf8').slice(mapping.start, mapping.end) ?? '';
129
- if (!retainedHistory.has(mapping.targetId) && controlMarker.test(body))
130
- issues.push({ path: mapping.sourceFile, reason: 'mapping_contains_control_marker', start: mapping.start, end: mapping.end });
131
- }
132
- if (issues.length)
133
- throw new MigrationError('migration_needs_review', issues);
134
- const appended = new Map();
135
- const replacements = new Map();
136
- const newEntries = additions.map(mapping => ({ id: mapping.targetId, title: mapping.title,
137
- file: `notes/${mapping.category}.md`, type: 'semantic', status: mapping.status,
138
- summary: migrationSummary(retainedHistory.get(mapping.targetId)?.body ?? files.get(mapping.sourceFile).toString('utf8').slice(mapping.start, mapping.end), mapping.title),
139
- triggers: [], priority: 'medium', updated: '1970-01-01', anchor: mapping.targetId, revision: retainedHistory.get(mapping.targetId)?.revision ?? 1, reviewAfter: null }));
140
- for (const mapping of additions) {
141
- if (retainedHistory.has(mapping.targetId))
142
- continue;
143
- const body = files.get(mapping.sourceFile).toString('utf8').slice(mapping.start, mapping.end);
144
- const file = `notes/${mapping.category}.md`;
145
- 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`;
146
- if (mapping.sourceFile === file)
147
- replacements.set(file, [...(replacements.get(file) ?? []), { start: mapping.start, end: mapping.end, block }]);
148
- else
149
- appended.set(file, [...(appended.get(file) ?? []), block]);
150
- }
151
- for (const path of new Set([...replacements.keys(), ...appended.keys()])) {
152
- let content = files.get(path)?.toString('utf8') ?? '';
153
- for (const replacement of (replacements.get(path) ?? []).sort((a, b) => b.start - a.start))
154
- content = content.slice(0, replacement.start) + replacement.block + content.slice(replacement.end);
155
- const blocks = appended.get(path);
156
- if (blocks)
157
- content += '\n' + blocks.join('\n');
158
- output.set(path, Buffer.from(content));
159
- }
160
- mappings.push(...additions);
161
- const target = upgraded.replace(LOCAL_MEMORY_GENERATED_INDEX_PATTERN, () => renderFullMemoryIndex([...entries, ...newEntries]));
162
- output.set('MEMORY.md', Buffer.from(target));
163
- }
164
- else {
165
- const knownMetadata = new Map();
166
- mappings = confirmedMappings;
167
- if (mappings.length > 0) {
168
- const heading = /^## Knowledge Index\s*$/mu.exec(memory);
169
- if (heading?.index !== undefined) {
170
- const start = heading.index + heading[0].length;
171
- const tail = memory.slice(start);
172
- const next = /^## (?!#)/mu.exec(tail);
173
- const end = next?.index === undefined ? memory.length : start + next.index;
174
- let uncovered = memory.slice(start, end);
175
- for (const mapping of mappings.filter(value => value.sourceFile === 'MEMORY.md').sort((a, b) => b.start - a.start)) {
176
- if (mapping.start < start || mapping.end > end) {
177
- issues.push({ path: 'MEMORY.md', reason: 'mapping_crosses_identity_or_index_boundary' });
178
- continue;
179
- }
180
- uncovered = uncovered.slice(0, mapping.start - start) + ' '.repeat(mapping.end - mapping.start) + uncovered.slice(mapping.end - start);
181
- }
182
- uncovered = uncovered.replace(/^[-*]\s+\[[^\]]+\]\((notes\/[^)]+)\)\s*$/gmu, (line, path) => mappings.some(value => value.sourceFile === path) ? '' : line);
183
- if (uncovered.trim())
184
- issues.push({ path: 'MEMORY.md', reason: 'index_text_requires_mapping', start, end });
185
- }
186
- }
187
- // Known complete cards may declare their exact scope and unique whole-file body.
188
- if (mappings.length === 0) {
189
- const section = /^## Knowledge Index\s*\n([\s\S]*?)(?=^## (?!#)|$(?![\s\S]))/mu.exec(memory);
190
- const content = section?.[1] ?? '';
191
- const cards = [...content.matchAll(/^### (.+)\r?\n([\s\S]*?)(?=^### |$(?![\s\S]))/gmu)];
192
- if (content.slice(0, cards[0]?.index ?? content.length).trim())
193
- issues.push({ path: 'MEMORY.md', reason: 'index_text_requires_mapping' });
194
- const seenFiles = new Set();
195
- for (const card of cards) {
196
- const fieldMatches = [...card[2].matchAll(/^- ([a-z_]+):[^\S\r\n]*(.*)$/gmu)];
197
- const fields = Object.fromEntries(fieldMatches.map(match => [match[1], match[2].trim()]));
198
- const allowedFields = new Set(['file', 'scope', 'type', 'status', 'summary', 'priority', 'updated', 'triggers', 'review_after', 'id', 'anchor', 'revision']);
199
- 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))) {
200
- issues.push({ path: 'MEMORY.md', reason: 'card_contains_unmapped_text', start: card.index });
201
- continue;
202
- }
203
- const path = fields.file ?? '';
204
- const category = /^notes\/(.+)\.md$/u.exec(path)?.[1] ?? '';
205
- const body = files.get(path)?.toString('utf8');
206
- if (!fields.scope || !categories.test(category) || !body?.trim() || seenFiles.has(path)
207
- || !fields.summary || !['procedural', 'semantic', 'episodic', 'preference'].includes(fields.type ?? '') || !fields.status || !['high', 'medium', 'low'].includes(fields.priority ?? '') || !fields.updated) {
208
- issues.push({ path: 'MEMORY.md', reason: 'card_mapping_unconfirmed', start: card.index });
209
- continue;
210
- }
211
- seenFiles.add(path);
212
- const parsed = MigrationRecordMappingSchema.safeParse({ sourceFile: path, start: 0, end: body.length, scope: fields.scope, category, title: card[1], status: fields.status });
213
- if (!parsed.success)
214
- issues.push({ path, reason: 'card_metadata_invalid' });
215
- else {
216
- mappings.push(parsed.data);
217
- knownMetadata.set(path, { type: fields.type, summary: fields.summary, priority: fields.priority, updated: fields.updated,
218
- triggers: (fields.triggers ?? '').split(/[,,、]/u).map(value => value.trim()).filter(Boolean), reviewAfter: fields.review_after ?? null });
219
- }
220
- }
221
- if (!cards.length)
222
- issues.push({ path: 'MEMORY.md', reason: 'legacy_source_requires_mapping' });
223
- }
224
- const entries = [];
225
- for (const mapping of mappings) {
226
- const body = files.get(mapping.sourceFile)?.toString('utf8');
227
- if (body === undefined || mapping.end > body.length) {
228
- issues.push({ path: mapping.sourceFile, reason: 'range_out_of_bounds' });
229
- continue;
230
- }
231
- const id = mapping.targetId ?? `mem_${digest(`${identity.migrationId}:${mapping.sourceFile}:${mapping.start}:${mapping.end}`).slice(0, 24)}`;
232
- entries.push({ id, title: mapping.title, file: `notes/${mapping.category}.md`, type: 'semantic', status: mapping.status, summary: migrationSummary(body.slice(mapping.start, mapping.end), mapping.title),
233
- triggers: [], priority: 'medium', updated: '1970-01-01', anchor: id, revision: 1, reviewAfter: null, ...knownMetadata.get(mapping.sourceFile) });
234
- }
235
- for (const [path, bytes] of files) {
236
- if (!path.startsWith('notes/') && path !== 'MEMORY.md')
237
- continue;
238
- const text = bytes.toString('utf8');
239
- const ranges = mappings.filter(mapping => mapping.sourceFile === path).sort((a, b) => a.start - b.start);
240
- if (path === 'MEMORY.md')
241
- continue; // Retained identity stays byte-for-byte; replaced index coverage is checked above.
242
- let cursor = 0;
243
- for (const range of ranges) {
244
- if (range.start < cursor || text.slice(cursor, range.start).trim())
245
- issues.push({ path, reason: 'mapping_gap_or_overlap', start: cursor, end: range.start });
246
- cursor = range.end;
247
- }
248
- if (text.slice(cursor).trim())
249
- issues.push({ path, reason: 'unmapped_source_text', start: cursor, end: text.length });
250
- }
251
- if (issues.length)
252
- throw new MigrationError('migration_needs_review', issues);
253
- // Retain original files (external references may exist); only same-path fully covered sources are rewritten.
254
- const targets = new Map();
255
- mappings.forEach((mapping, index) => {
256
- const entry = entries[index];
257
- const body = files.get(mapping.sourceFile).toString('utf8').slice(mapping.start, mapping.end);
258
- const blocks = targets.get(entry.file) ?? [];
259
- 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`]);
260
- });
261
- for (const [path, blocks] of targets) {
262
- const existing = files.get(path);
263
- if (existing && !mappings.some(mapping => mapping.sourceFile === path))
264
- throw new MigrationError('migration_needs_review', [{ path, reason: 'target_contains_unmapped_text' }]);
265
- output.set(path, Buffer.from(blocks.join('\n')));
266
- }
267
- const index = renderFullMemoryIndex(entries);
268
- const heading = /^## Knowledge Index\s*$/mu.exec(memory);
269
- let target;
270
- if (heading?.index !== undefined) {
271
- const start = heading.index + heading[0].length;
272
- const tail = memory.slice(start);
273
- const next = /^## (?!#)/mu.exec(tail);
274
- target = memory.slice(0, start) + `\n${index}\n` + (next?.index === undefined ? '' : tail.slice(next.index));
275
- }
276
- else
277
- target = `${memory}\n\n## Knowledge Index\n${index}\n`;
278
- output.set('MEMORY.md', Buffer.from(target));
279
- mappings = mappings.map((mapping, index) => ({ ...mapping, targetId: entries[index].id }));
280
- }
281
- validateMigrationTarget(output);
282
- return { files: output, recordMappings: mappings };
283
- }
@@ -1,55 +0,0 @@
1
- import { z } from 'zod';
2
- const identifier = z.string().min(1).max(256).regex(/^[A-Za-z0-9_.:@-]+$/u);
3
- export const MigrationDigestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
4
- export const MigrationIdentitySchema = z.object({
5
- workspaceId: identifier, agentId: identifier, migrationId: identifier,
6
- sourceStorageVersion: z.union([z.literal(0), z.literal(1)]), targetStorageVersion: z.literal(2),
7
- rootFingerprint: MigrationDigestSchema, ownerIdentity: identifier, machineId: identifier, executionId: identifier,
8
- }).strict();
9
- export const MigrationIntentReceiptSchema = MigrationIdentitySchema.extend({
10
- kind: z.literal('server_write_intent'), sourceDigest: MigrationDigestSchema, planDigest: MigrationDigestSchema,
11
- intentVersion: z.number().int().positive(), confirmedAt: z.string().datetime(),
12
- }).strict();
13
- export const MigrationProcessStoppedReceiptSchema = z.object({
14
- kind: z.literal('migration_process_stopped'), migrationId: identifier, machineId: identifier,
15
- executionId: identifier, ownerIdentity: identifier, pid: z.number().int().positive().nullable(),
16
- stoppedAt: z.string().datetime(), proof: z.enum(['supervisor_exit', 'journal_reconciled', 'not_started']),
17
- }).strict().refine(value => value.proof === 'not_started' ? value.pid === null : value.proof === 'supervisor_exit' ? value.pid !== null : true, 'migration_stop_proof_invalid');
18
- export const MigrationPathSchema = z.string().max(512).refine(value => (value === 'MEMORY.md' || value === 'notes' || value === '.crew/memory/pending'
19
- || value.startsWith('notes/') || value.startsWith('.crew/memory/pending/'))
20
- && !/[\\\u0000-\u001f\u007f:]/u.test(value)
21
- && value.split('/').every(part => part !== '.' && part !== '..' && part.length > 0), 'migration_path_invalid');
22
- export const MigrationRecordMappingSchema = z.object({
23
- sourceFile: MigrationPathSchema.refine(value => value === 'MEMORY.md' || value.startsWith('notes/'), 'migration_pending_promotion_forbidden'), start: z.number().int().nonnegative(), end: z.number().int().positive(),
24
- sourceSha256: MigrationDigestSchema.optional(),
25
- scope: z.string().min(1).max(1000), category: z.enum(['preferences', 'project-rules', 'testing', 'debugging', 'git', 'incidents', 'lessons']),
26
- targetId: z.string().regex(/^[A-Za-z0-9_-]+$/u).optional(), title: z.string().min(1).max(300),
27
- status: z.enum(['active', 'pinned', 'candidate', 'stale', 'superseded', 'archived']).default('active'),
28
- }).strict().refine(value => value.end > value.start, 'migration_mapping_range_invalid');
29
- const image = z.discriminatedUnion('exists', [z.object({ exists: z.literal(false) }).strict(),
30
- z.object({ exists: z.literal(true), sha256: MigrationDigestSchema, ref: z.string().regex(/^\.crew\/memory\/migrations\/[A-Za-z0-9_.:@-]+\/(?:backup|staged)\/[a-f0-9]{64}$/u), bytes: z.number().int().nonnegative() }).strict()]);
31
- export const MigrationManifestSchema = z.object({
32
- directories: z.array(MigrationPathSchema).max(10000),
33
- files: z.array(z.object({ path: MigrationPathSchema, before: image, after: image }).strict()).max(20000),
34
- recordMappings: z.array(MigrationRecordMappingSchema).max(10000),
35
- }).strict();
36
- export const MigrationIssueSchema = z.object({ path: z.string(), reason: z.string(), start: z.number().optional(), end: z.number().optional() }).strict();
37
- export const MigrationStateSchema = z.object({
38
- schemaVersion: z.literal(1), identity: MigrationIdentitySchema,
39
- storageVersion: z.union([z.literal(0), z.literal(1), z.literal(2)]), targetStorageVersion: z.literal(2), origin: z.enum(['migrated', 'initialized']),
40
- migrationId: identifier, phase: z.enum(['prepared', 'applying', 'committed', 'rolled_back', 'repair_required']),
41
- sourceDigest: MigrationDigestSchema, planDigest: MigrationDigestSchema, manifest: MigrationManifestSchema,
42
- intentReceipt: MigrationIntentReceiptSchema.optional(), issues: z.array(MigrationIssueSchema),
43
- }).strict();
44
- export const MigrationHistorySchema = z.object({ kind: z.enum(['none', 'existing', 'unavailable']), migrationId: identifier.optional(), writeIntentConfirmed: z.boolean().optional(), isNewAgent: z.boolean().optional(),
45
- rolledBackOperations: z.array(z.object({ migrationId: identifier, sourceDigest: MigrationDigestSchema, planDigest: MigrationDigestSchema }).strict()).max(10000).optional(),
46
- }).strict();
47
- export class MigrationError extends Error {
48
- code;
49
- issues;
50
- constructor(code, issues = []) {
51
- super(code);
52
- this.code = code;
53
- this.issues = issues;
54
- }
55
- }