@nowcrew/daemon 0.6.87-beta.3 → 0.6.87-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.
Files changed (38) hide show
  1. package/README.md +22 -0
  2. package/dist/cloud-report-uploader.js +27 -25
  3. package/dist/execution-runner.js +6 -3
  4. package/dist/external-output.js +154 -68
  5. package/dist/local-execution-prompt.js +19 -25
  6. package/dist/local-executor.js +16 -44
  7. package/dist/local-memory/prompt.js +37 -0
  8. package/dist/local-memory/read-cli.js +232 -0
  9. package/dist/local-memory-diagnostics.js +79 -12
  10. package/dist/main.js +6 -2
  11. package/dist/prompt.js +24 -9
  12. package/dist/serve.js +17 -11
  13. package/dist/storage-identity.js +4 -1
  14. package/dist/storage-ownership.js +93 -5
  15. package/dist/storage-runtime-controller.js +40 -20
  16. package/dist/storage-runtime.js +38 -2
  17. package/dist/storage-serve-adapter.js +22 -5
  18. package/dist/workspace.js +15 -0
  19. package/package.json +1 -1
  20. package/dist/project-skills/capability.js +0 -109
  21. package/dist/project-skills/controller-convergence.js +0 -57
  22. package/dist/project-skills/projection-set-switch.js +0 -419
  23. package/dist/project-skills/projection-state-domain.js +0 -170
  24. package/dist/project-skills/projection-state-store.js +0 -842
  25. package/dist/project-skills/projection-state-transaction.js +0 -322
  26. package/dist/project-skills/projection-state.js +0 -3
  27. package/dist/project-skills/runtime-root-bootstrap.js +0 -47
  28. package/dist/project-skills/runtime-root-domain.js +0 -268
  29. package/dist/project-skills/runtime-root-gc.js +0 -293
  30. package/dist/project-skills/runtime-root-lease-artifact.js +0 -46
  31. package/dist/project-skills/runtime-root-leases.js +0 -487
  32. package/dist/project-skills/runtime-root-source-identity.js +0 -60
  33. package/dist/project-skills/runtime-root-startup.js +0 -49
  34. package/dist/project-skills/runtime-root-state-artifact-domain.js +0 -143
  35. package/dist/project-skills/runtime-root-state-index.js +0 -356
  36. package/dist/project-skills/runtime-root-store.js +0 -722
  37. package/dist/project-skills/serve-capability.js +0 -28
  38. package/dist/project-skills/serve-startup.js +0 -37
@@ -0,0 +1,232 @@
1
+ import { constants } from "node:fs";
2
+ import { open, realpath } from "node:fs/promises";
3
+ import { createHash } from "node:crypto";
4
+ import { isAbsolute, relative, resolve, sep } from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ import { parseArgs, TextDecoder } from "node:util";
7
+ import { z } from "zod";
8
+ const OUTPUT_BYTES = 12 * 1024;
9
+ const FILE_BYTES = 32 * 1024 * 1024;
10
+ const FileSchema = z.string().min(1).refine((file) => {
11
+ if (isAbsolute(file) || /[\\\u0000-\u001f\u007f]/u.test(file))
12
+ return false;
13
+ if (Buffer.byteLength(file, "utf8") > 1024)
14
+ return false;
15
+ const parts = file.split("/");
16
+ if (parts.some((part) => part === "" || part === "." || part === ".."))
17
+ return false;
18
+ return file === "MEMORY.md" || (parts[0] === "notes" && parts.length > 1 && file.endsWith(".md"));
19
+ }, "memory_path_invalid");
20
+ const Common = {
21
+ file: FileSchema.default("MEMORY.md"),
22
+ ifHash: z.string().regex(/^[a-f0-9]{64}$/u).optional(),
23
+ };
24
+ const CommandSchema = z.discriminatedUnion("command", [
25
+ z.object({
26
+ command: z.literal("search"), ...Common,
27
+ query: z.string().trim().min(1).max(256),
28
+ limit: z.coerce.number().int().min(1).max(40).default(10),
29
+ afterLine: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),
30
+ }).strict(),
31
+ z.object({
32
+ command: z.literal("read"), ...Common,
33
+ offset: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),
34
+ limit: z.coerce.number().int().min(1).max(4000).default(2000),
35
+ }).strict(),
36
+ ]);
37
+ const USAGE = `只读记忆工具,默认输出 JSON,不修改任何记忆文件。
38
+ crew-memory search --query <关键词> [--file MEMORY.md|notes/文件.md] [--limit 10] [--after-line 0]
39
+ crew-memory read [--file MEMORY.md|notes/文件.md] [--offset 0] [--limit 2000]
40
+ 搜索关键词按空白分隔,同一行须全部命中;返回完整文件中的行号和字符偏移。
41
+ 读取的 offset/limit 按 Unicode 字符计数;用 nextOffset 继续,eof=true 表示结束。
42
+ 后续页可传 --if-hash <前一页的 sha256>,文件变化时停止,避免混读不同版本。
43
+ 搜索结果是原始资料定位,不代表候选已生效;按当前有效索引读取明细,不扫描 pending。`;
44
+ function inside(root, path) {
45
+ const value = relative(root, path);
46
+ return value !== ".." && !value.startsWith(`..${sep}`) && !isAbsolute(value);
47
+ }
48
+ async function readSource(home, file) {
49
+ if (!home)
50
+ throw new Error("memory_home_missing");
51
+ const root = await realpath(home);
52
+ const path = await realpath(resolve(root, file));
53
+ if (!inside(root, path) || !FileSchema.safeParse(relative(root, path).split(sep).join("/")).success) {
54
+ throw new Error("memory_path_invalid");
55
+ }
56
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
57
+ try {
58
+ const stat = await handle.stat();
59
+ if (!stat.isFile())
60
+ throw new Error("memory_file_not_regular");
61
+ if (stat.size > FILE_BYTES)
62
+ throw new Error("memory_file_too_large");
63
+ // 允许读完整来源,但绝不能在文件并发增长时无界分配内存。
64
+ const chunks = [];
65
+ const chunk = Buffer.allocUnsafe(64 * 1024);
66
+ let bytes = 0;
67
+ for (;;) {
68
+ const { bytesRead } = await handle.read(chunk, 0, Math.min(chunk.length, FILE_BYTES + 1 - bytes), null);
69
+ if (bytesRead === 0)
70
+ break;
71
+ bytes += bytesRead;
72
+ if (bytes > FILE_BYTES)
73
+ throw new Error("memory_file_too_large");
74
+ chunks.push(Buffer.from(chunk.subarray(0, bytesRead)));
75
+ }
76
+ const buffer = Buffer.concat(chunks);
77
+ const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buffer);
78
+ return { text, sha256: createHash("sha256").update(buffer).digest("hex") };
79
+ }
80
+ finally {
81
+ await handle.close();
82
+ }
83
+ }
84
+ function characterCount(text) {
85
+ let count = 0;
86
+ for (const _character of text)
87
+ count += 1;
88
+ return count;
89
+ }
90
+ function excerpt(text, limit) {
91
+ let value = "";
92
+ let count = 0;
93
+ for (const character of text) {
94
+ if (count++ >= limit)
95
+ return `${value}...`;
96
+ value += character;
97
+ }
98
+ return value;
99
+ }
100
+ function originalLowercaseIndex(text, index) {
101
+ let originalIndex = 0;
102
+ let lowerIndex = 0;
103
+ for (const character of text) {
104
+ // 逐字符只累计小写长度;匹配仍用整行小写,保留长度不变的词尾 sigma 上下文规则。
105
+ lowerIndex += character.toLowerCase().length;
106
+ if (index < lowerIndex)
107
+ return originalIndex;
108
+ originalIndex += character.length;
109
+ }
110
+ return text.length;
111
+ }
112
+ function searchSource(text, sha256, command) {
113
+ const terms = command.query.toLowerCase().split(/\s+/u);
114
+ const matches = [];
115
+ let line = 0;
116
+ let offset = 0;
117
+ let heading = "";
118
+ let matchCount = 0;
119
+ let hasMore = false;
120
+ let remaining = OUTPUT_BYTES - Buffer.byteLength(JSON.stringify({ file: command.file, sha256 })) - 512;
121
+ for (const match of text.matchAll(/[^\n]*(?:\n|$)/gu)) {
122
+ if (match[0] === "")
123
+ break;
124
+ line += 1;
125
+ const raw = match[0];
126
+ const content = raw.replace(/\r?\n$/u, "");
127
+ const title = /^#{1,6}\s+(.+?)\s*$/u.exec(content)?.[1];
128
+ if (title !== undefined)
129
+ heading = excerpt(title, 96);
130
+ const lower = content.toLowerCase();
131
+ if (terms.every((term) => lower.includes(term))) {
132
+ matchCount += 1;
133
+ if (line > command.afterLine) {
134
+ let start = Math.max(0, originalLowercaseIndex(content, lower.indexOf(terms[0])) - 60);
135
+ if (start > 0 && /[\uDC00-\uDFFF]/u.test(content[start]))
136
+ start -= 1;
137
+ const item = { line, offset, heading, text: `${start > 0 ? "..." : ""}${excerpt(content.slice(start), 240)}` };
138
+ const bytes = Buffer.byteLength(JSON.stringify(item), "utf8") + 1;
139
+ if (hasMore || matches.length >= command.limit || bytes > remaining) {
140
+ hasMore = true;
141
+ }
142
+ else {
143
+ matches.push(item);
144
+ remaining -= bytes;
145
+ }
146
+ }
147
+ }
148
+ offset += characterCount(raw);
149
+ }
150
+ return {
151
+ file: command.file, sha256, matches, matchCount, hasMore,
152
+ nextAfterLine: hasMore ? matches.at(-1)?.line ?? null : null,
153
+ };
154
+ }
155
+ function readPage(text, sha256, command) {
156
+ const metadata = { file: command.file, sha256, offset: command.offset, nextOffset: Number.MAX_SAFE_INTEGER, eof: false, content: "" };
157
+ let remaining = OUTPUT_BYTES - Buffer.byteLength(JSON.stringify(metadata), "utf8");
158
+ let position = 0;
159
+ let offset = 0;
160
+ while (position < text.length && offset < command.offset) {
161
+ position += text.codePointAt(position) > 0xffff ? 2 : 1;
162
+ offset += 1;
163
+ }
164
+ let content = "";
165
+ let count = 0;
166
+ while (position < text.length && count < command.limit) {
167
+ const character = String.fromCodePoint(text.codePointAt(position));
168
+ const bytes = Buffer.byteLength(JSON.stringify(character), "utf8") - 2;
169
+ if (bytes > remaining)
170
+ break;
171
+ remaining -= bytes;
172
+ content += character;
173
+ position += character.length;
174
+ offset += 1;
175
+ count += 1;
176
+ }
177
+ const eof = position === text.length;
178
+ return { ...metadata, content, eof, nextOffset: eof ? null : offset };
179
+ }
180
+ export async function runMemoryReadCommand(argv, io) {
181
+ let command;
182
+ try {
183
+ const { values, positionals } = parseArgs({
184
+ args: [...argv], allowPositionals: true,
185
+ options: {
186
+ query: { type: "string", short: "q" }, file: { type: "string" },
187
+ limit: { type: "string" }, offset: { type: "string" },
188
+ "after-line": { type: "string" }, "if-hash": { type: "string" },
189
+ json: { type: "boolean" }, help: { type: "boolean", short: "h" },
190
+ },
191
+ });
192
+ if (values.help) {
193
+ io.out(USAGE);
194
+ return 0;
195
+ }
196
+ if (positionals.length !== 1)
197
+ throw new Error("memory_command_invalid");
198
+ const { help: _help, json: _json, "after-line": afterLine, "if-hash": ifHash, ...options } = values;
199
+ command = CommandSchema.parse({
200
+ command: positionals[0], ...options,
201
+ ...(afterLine === undefined ? {} : { afterLine }),
202
+ ...(ifHash === undefined ? {} : { ifHash }),
203
+ });
204
+ }
205
+ catch {
206
+ io.err(`memory_arguments_invalid: 参数不合法。\n${USAGE}`);
207
+ return 2;
208
+ }
209
+ try {
210
+ const source = await readSource(io.env.CREW_HOME, command.file);
211
+ if (command.ifHash !== undefined && command.ifHash !== source.sha256)
212
+ throw new Error("memory_file_changed");
213
+ const result = command.command === "search"
214
+ ? searchSource(source.text, source.sha256, command)
215
+ : readPage(source.text, source.sha256, command);
216
+ io.out(JSON.stringify(result));
217
+ return 0;
218
+ }
219
+ catch (error) {
220
+ const code = error.code;
221
+ const known = error instanceof Error && /^memory_[a-z_]+$/u.test(error.message) ? error.message : code ?? "memory_read_failed";
222
+ io.err(JSON.stringify({ error: known, message: "记忆读取未完成;检查路径、文件版本或大小,不要将此错误当作没有记忆。" }));
223
+ return 1;
224
+ }
225
+ }
226
+ if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
227
+ void runMemoryReadCommand(process.argv.slice(2), {
228
+ env: process.env,
229
+ out: (text) => process.stdout.write(`${text}\n`),
230
+ err: (text) => process.stderr.write(`${text}\n`),
231
+ }).then((code) => { process.exitCode = code; });
232
+ }
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { readFile, stat } from "node:fs/promises";
3
3
  import { isAbsolute, join, normalize, relative, resolve } from "node:path";
4
+ import { parseArgs } from "node:util";
4
5
  import { capMemoryForInject, MEMORY_INJECT_CAP } from "./prompt.js";
5
6
  const INJECTION_MARKERS = [
6
7
  "## Injected MEMORY.md (bounded local context)\n",
@@ -172,10 +173,58 @@ function commandOperation(command) {
172
173
  ? "read"
173
174
  : null;
174
175
  }
176
+ function crewMemoryReadAccess(command, paths) {
177
+ if (!/^\s*crew-memory(?:\s|$)/u.test(command))
178
+ return null;
179
+ const args = [];
180
+ let remaining = command.trim();
181
+ // Only complete literal arguments are supported; shell expansion and concatenated quoting are not inferred.
182
+ while (remaining !== "") {
183
+ const match = /^(?:"([^"\\$`]*)"|'([^']*)'|([^\s"'\\$`<>;|&()\[\]{}*?!#]+))(?=\s|$)\s*/u.exec(remaining);
184
+ if (match === null)
185
+ return null;
186
+ args.push(match[1] ?? match[2] ?? match[3]);
187
+ remaining = remaining.slice(match[0].length);
188
+ }
189
+ try {
190
+ const { values, positionals } = parseArgs({
191
+ args: args.slice(1),
192
+ allowPositionals: true,
193
+ options: {
194
+ file: { type: "string" }, query: { type: "string", short: "q" },
195
+ limit: { type: "string" }, offset: { type: "string" },
196
+ "after-line": { type: "string" }, "if-hash": { type: "string" },
197
+ json: { type: "boolean" }, help: { type: "boolean", short: "h" },
198
+ },
199
+ });
200
+ if (values.help || positionals.length !== 1)
201
+ return null;
202
+ const operation = positionals[0];
203
+ if (operation === "search") {
204
+ if (!values.query?.trim() || values.offset !== undefined)
205
+ return null;
206
+ }
207
+ else if (operation !== "read" || values.query !== undefined || values["after-line"] !== undefined) {
208
+ return null;
209
+ }
210
+ const file = values.file ?? "MEMORY.md";
211
+ if (file !== "MEMORY.md" && !/^notes\/[^/\\\u0000-\u001f\u007f]+\.md$/u.test(file))
212
+ return null;
213
+ const classified = classifyExplicitPath(resolve(paths.homeDir, file), paths);
214
+ return classified === null ? null : { ...classified, operation: "read" };
215
+ }
216
+ catch {
217
+ return null;
218
+ }
219
+ }
175
220
  function commandAccesses(command, paths) {
176
221
  if (/[;|&\n]/.test(command))
177
222
  return [];
178
223
  const accesses = new Map();
224
+ const memoryRead = crewMemoryReadAccess(command, paths);
225
+ if (memoryRead !== null) {
226
+ accesses.set(`${memoryRead.target}:${memoryRead.relative_path ?? ""}:read`, memoryRead);
227
+ }
179
228
  const expanded = command
180
229
  .replaceAll("${CREW_HOME}", paths.homeDir)
181
230
  .replaceAll("$CREW_HOME", paths.homeDir)
@@ -243,26 +292,41 @@ export function createLocalMemoryAccessObserver(options) {
243
292
  for (const block of blocks) {
244
293
  if (block.type !== "tool_use" || typeof block.id !== "string" || typeof block.name !== "string")
245
294
  continue;
295
+ if (block.name === "Bash") {
296
+ const input = block.input && typeof block.input === "object" && !Array.isArray(block.input)
297
+ ? block.input
298
+ : null;
299
+ const accesses = typeof input?.command === "string" ? commandAccesses(input.command, paths) : [];
300
+ if (accesses.length > 0)
301
+ pending.set(block.id, { accesses, evidence: "shell_command" });
302
+ continue;
303
+ }
246
304
  const operation = toolOperation(block.name);
247
305
  const path = toolPath(block.input);
248
306
  const classified = operation === null || path === null ? null : classifyExplicitPath(path, paths);
249
- if (operation !== null && classified !== null)
250
- pending.set(block.id, { operation, ...classified });
307
+ if (operation !== null && classified !== null) {
308
+ pending.set(block.id, {
309
+ accesses: [{ operation, ...classified }],
310
+ evidence: "structured_tool",
311
+ });
312
+ }
251
313
  }
252
314
  }
253
315
  if (record.type === "user") {
254
316
  for (const block of blocks) {
255
317
  if (block.type !== "tool_result" || typeof block.tool_use_id !== "string")
256
318
  continue;
257
- const access = pending.get(block.tool_use_id);
319
+ const toolAccess = pending.get(block.tool_use_id);
258
320
  pending.delete(block.tool_use_id);
259
- if (access === undefined)
321
+ if (toolAccess === undefined)
260
322
  continue;
261
- recordObservation(observations, counts, {
262
- ...access,
263
- outcome: block.is_error === true ? "failed" : "succeeded",
264
- evidence: "structured_tool",
265
- });
323
+ for (const access of toolAccess.accesses) {
324
+ recordObservation(observations, counts, {
325
+ ...access,
326
+ outcome: block.is_error === true ? "failed" : "succeeded",
327
+ evidence: toolAccess.evidence,
328
+ });
329
+ }
266
330
  }
267
331
  }
268
332
  if (record.type === "kimi.acp.tool_call" && typeof record.id === "string") {
@@ -277,15 +341,18 @@ export function createLocalMemoryAccessObserver(options) {
277
341
  ? null
278
342
  : classifyExplicitPath(path, paths);
279
343
  if (fallbackOperation !== null && classified !== null) {
280
- pending.set(record.id, { operation: fallbackOperation, ...classified });
344
+ pending.set(record.id, {
345
+ accesses: [{ operation: fallbackOperation, ...classified }],
346
+ evidence: "structured_tool",
347
+ });
281
348
  }
282
349
  }
283
350
  if (record.type === "kimi.acp.tool_result" && typeof record.id === "string") {
284
351
  if (record.status !== "completed" && record.status !== "failed")
285
352
  return observations;
286
- const access = pending.get(record.id);
353
+ const toolAccess = pending.get(record.id);
287
354
  pending.delete(record.id);
288
- if (access !== undefined) {
355
+ for (const access of toolAccess?.accesses ?? []) {
289
356
  recordObservation(observations, counts, {
290
357
  ...access,
291
358
  outcome: record.status === "failed" ? "failed" : "succeeded",
package/dist/main.js CHANGED
@@ -24,7 +24,7 @@ import { formatDaemonStartupError } from "./daemon-startup-error.js";
24
24
  import { assertManagedServiceStartup } from "./managed-service-startup.js";
25
25
  import { daemonGlobalInstallation } from "./daemon-installation.js";
26
26
  import { acquireDaemonInstallationLease, runWithDaemonInstallationLease, } from "./daemon-installation-lease.js";
27
- import { loadStorageRuntime } from "./storage-runtime.js";
27
+ import { createStorageRuntimeOwnershipBinding, loadStorageRuntime } from "./storage-runtime.js";
28
28
  import { readStorageMigrationReceipt } from "./storage-migration-controller.js";
29
29
  import { storageMigrationStatusReplay } from "./storage-status-replay.js";
30
30
  import { runStorageWorkerCommand } from "./storage-worker-command.js";
@@ -160,6 +160,9 @@ async function main() {
160
160
  ...(process.getuid === undefined ? {} : { uid: process.getuid() }),
161
161
  environment: process.env,
162
162
  });
163
+ const targetStorageBinding = storageRuntime === null
164
+ ? null
165
+ : createStorageRuntimeOwnershipBinding(storageRuntime);
163
166
  const targetConfirmation = storageRuntime?.identity.storageMigrationId === undefined
164
167
  ? null
165
168
  : createStorageTargetConfirmationHandler({
@@ -172,7 +175,8 @@ async function main() {
172
175
  ? {
173
176
  ready: false,
174
177
  statusOutboxPath: join(storageRuntime.local.stateRoot, "storage-status-outbox.json"),
175
- identity: storageRuntime.identity,
178
+ identity: targetStorageBinding.identity,
179
+ bindServerIdentity: targetStorageBinding.bind,
176
180
  ...(targetConfirmation === null ? {} : { confirm: targetConfirmation.handle }),
177
181
  ...(storageRuntime.identity.storageMigrationId === undefined ? {} : {
178
182
  replayStatus: async (send) => {
package/dist/prompt.js CHANGED
@@ -67,10 +67,23 @@ export function capWorkLogForInject(workLog, cap = WORKLOG_INJECT_CAP) {
67
67
  const tail = workLog.slice(-WORKLOG_TAIL);
68
68
  return `${head}\n…(work-log 过长已截去中段,全文用 Read 读 $CREW_TASK_LOG)\n${tail}`;
69
69
  }
70
- export function capMemoryForInject(memory, cap = MEMORY_INJECT_CAP) {
71
- return memory.length > cap
72
- ? `${memory.slice(0, cap)}\n…(MEMORY.md 过长已截断,详情用 Read 读 $CREW_HOME/MEMORY.md;功能明细仅按索引中的 file 读取)`
73
- : memory;
70
+ export function capMemoryForInject(memory, cap = MEMORY_INJECT_CAP, maxBytes = Number.POSITIVE_INFINITY) {
71
+ if (memory.length <= cap && Buffer.byteLength(memory, "utf8") <= maxBytes)
72
+ return memory;
73
+ const notice = "[MEMORY.md preview truncated; use crew-memory search/read for more.]\n";
74
+ const noticeBytes = Buffer.byteLength(notice, "utf8");
75
+ if (notice.length > cap || noticeBytes > maxBytes)
76
+ return "";
77
+ let end = 0;
78
+ let bytes = noticeBytes;
79
+ for (const character of memory) {
80
+ const size = Buffer.byteLength(character, "utf8");
81
+ if (notice.length + end + character.length > cap || bytes + size > maxBytes)
82
+ break;
83
+ end += character.length;
84
+ bytes += size;
85
+ }
86
+ return notice + memory.slice(0, end);
74
87
  }
75
88
  export function buildSystemPrompt(ctx) {
76
89
  const product = ctx.productName ?? "nowwork";
@@ -99,7 +112,7 @@ export function buildSystemPrompt(ctx) {
99
112
  // scheduled 换成静默版,不出现任何"先确认/先回复"的措辞。
100
113
  const startupSequence = alwaysReport
101
114
  ? `## 启动序列(每轮汇报定时任务)
102
- 1. 使用本提示词末尾已注入的 MEMORY.md 索引;命中相关条目时,再按索引中的 file 从 $CREW_HOME 读取明细。
115
+ 1. 参考本提示词中的 MEMORY.md 预览;需要历史约束或经验时检索完整索引,再按索引中的 file 从 $CREW_HOME 读取明细。
103
116
  2. 执行唤醒提示词里给出的定时指令。
104
117
  3. Return exactly one self-contained final report as your runtime final response.
105
118
  4. Do not call crew message send; the daemon delivers the final response.
@@ -107,14 +120,14 @@ export function buildSystemPrompt(ctx) {
107
120
  6. 只有存在需要后续跟进的具体事项时,才用 \`crew task create\` 创建任务。`
108
121
  : scheduled
109
122
  ? `## 启动序列(静默定时任务)
110
- 1. 使用本提示词末尾已注入的 MEMORY.md 索引;命中相关条目时,再按索引中的 file 从 $CREW_HOME 读取明细。
123
+ 1. 参考本提示词中的 MEMORY.md 预览;需要历史约束或经验时检索完整索引,再按索引中的 file 从 $CREW_HOME 读取明细。
111
124
  2. 执行唤醒提示词里给出的定时指令。**默认零输出**:不判断"是否需要先确认/声明接手",本轮没有人在等你回复。
112
125
  3. 只有发现异常、需要人处理、或指令明确要求汇报时,才用 \`crew message send --send-draft\` 输出到频道(用法见上面"通信"一节)。
113
126
  4. 只有存在需要后续跟进的具体事项时,才用 \`crew task create\` 创建任务。
114
127
  5. 无异常时直接结束,不需要任何输出,不必读频道历史(除非指令要求)。`
115
128
  : `## 启动序列
116
129
  1. 若本轮来信可以直接回答,不要先发确认消息;处理完后只发一条完整回复。只有需要澄清、调用工具、协调他人或较长时间处理时,才先发有信息量的确认/进度消息。
117
- 2. 使用本提示词末尾已注入的 MEMORY.md 索引;命中相关条目时,再按索引中的 file 从 $CREW_HOME 读取明细。
130
+ 2. 参考本提示词中的 MEMORY.md 预览;需要历史约束或经验时检索完整索引,再按索引中的 file 从 $CREW_HOME 读取明细。
118
131
  3. 若本轮只有"有未读"的 inbox notice、没有正文:notice 表示存在你尚未看到的消息(正文被暂时省略以免刷屏,不是没有内容)。是否读、何时读由你判断,可用 \`crew message check\` / \`crew message read\` 拉取。**绝不能仅凭一条 content-free notice 就断定"没有工作"**;若选择暂不读,要诚实当作 defer。
119
132
  4. 收到消息就处理,并用 \`crew message send\` 回复。
120
133
  5. **做完你负责的所有事再停。** 多步任务(调研/改码/测试)要全部完成、汇报结果后再停。新消息会在你存活期间自动送达,无需轮询等待。`;
@@ -329,13 +342,15 @@ ${interactiveTaskRules}${freshnessRule}${externalReplyRule}${collaborationEtique
329
342
 
330
343
  ## Workspace 与分层记忆(CRITICAL — 索引+按需,配合上面的并行规则)
331
344
  你的持久记忆在 \`$CREW_HOME\`(跨你所有任务共享),按“常驻索引 + 功能明细 + 当前工作”分层:
332
- 1. **MEMORY.md = 常驻索引 + 角色**:系统每次已把它(截断索引版)注入本提示词末尾。索引条目包含 \`file/type/scope/summary/triggers/priority/updated\`,其中 file 是相对于 \`$CREW_HOME\` 的路径(例如 \`notes/testing.md\`),先用这些字段判断当前问题是否相关;通常不必再读整份 MEMORY.md。
345
+ 1. **MEMORY.md = 常驻索引 + 角色**:提示词末尾可能只有它的有界预览,预算不足时也可能省略。预览未命中不等于没有记忆。索引条目包含 \`file/type/scope/summary/triggers/priority/updated\`,其中 file 是相对于 \`$CREW_HOME\` 的路径(例如 \`notes/testing.md\`);需要历史约束、经验或偏好时先检索完整索引,再按需分段读取。
333
346
  2. **notes/<topic>.md = 功能明细**:按用户偏好、项目规则、测试、调试、Git、事故复盘等主题拆分。优先读取与当前任务匹配的文件;\`notes/lessons.md\` 只保留未分类经验和历史兼容内容,不是所有新经验的默认目的地。普通任务默认只读不写,但当前用户明确要求时可以按最小范围更新;任务结束后的专门收尾执行仍按收尾指令复核。
334
347
  - 对旧版 MEMORY.md,如果条目没有完整结构化字段但明确指向 \`notes/<file>.md\`,把它视为 legacy 索引;仍需结合条目标题/链接和当前请求判断相关性,不要因为缺少 summary/triggers 就假定正文已注入。
335
348
  3. **本任务 work-log = \`$CREW_TASK_LOG\`**:每任务一份(别的运行不会碰),记当前阶段/下一步/卡点/关键结论。系统已把它的当前内容注入末尾让你续上;有进展就更新它——这是你**唯一**该在任务中持续写的记忆文件。**work-log 是现状快照,不是流水账**:保持 ≤100 行,更新时重写全文替换过时内容,不要无限追加(过长会被注入截断)。
336
349
 
337
350
  **按需读取规则(提示词引导,不是 Daemon 自动召回保证)**:
338
- - 当前请求命中 MEMORY.md 某条目的 \`summary\` 或 \`triggers\`,或用户明确询问历史经验/偏好时,在最终回答或执行动作前用 \`Read $CREW_HOME/<file>\` 读取对应明细;不要再次拼接 \`notes/\`。
351
+ - 需要历史约束、经验或偏好时,在最终回答或执行动作前先用只读命令 \`crew-memory search --query '关键词' [--after-line N]\` 搜索完整 \`$CREW_HOME/MEMORY.md\`;默认返回 JSON,有后续结果时按返回游标继续,不要把预览中未命中当成全文无结果。
352
+ - 用 \`crew-memory read [--file MEMORY.md|notes/xxx.md] [--offset N] [--limit N]\` 读取命中范围,再按索引中的 file 从 $CREW_HOME 读取明细;默认返回 JSON。以当前有效索引及其指向的正文为依据,不自动读取 pending,也不把未决或已替代片段当成有效记忆。
353
+ - 旧 daemon 没有 \`crew-memory\` 时,回退到 runtime 原生文件搜索和分段 Read:先搜索完整 \`$CREW_HOME/MEMORY.md\`,再用 \`Read $CREW_HOME/<file>\` 读取命中范围;不要再次拼接 \`notes/\`。工具提示截断或返回下一页时继续分页,不要一次读取整份大文件。
339
354
  - 未命中时不要为了“保险”读取全部 notes;只读取能直接影响当前任务的文件。MEMORY.md 注入的是索引,不会自动让 note 正文可用。
340
355
 
341
356
  **沉淀与瘦身由系统触发,不要平时自行扩展范围**:任务被改为 done/closed 时,系统会单独唤醒你收尾——那时按功能分类把可复用经验提炼进合适的 \`notes/<topic>.md\`,更新 MEMORY.md 索引。普通执行已经按用户明确要求写入时,收尾先检查、后修改,只在明确缺漏时做最小必要修正,不得重复追加或只为优化措辞而改写。最终结论必须且只能归类为:无变化、已修正、冲突、失败;无变化或已修正时必须满足对应后置条件并清空 work-log,冲突或失败时保留 work-log,任一记忆写入失败则保留 work-log。不要默认全部写入 \`notes/lessons.md\`。默认不要改 MEMORY.md/notes,但不能覆盖当前用户明确授权的最小范围更新。
package/dist/serve.js CHANGED
@@ -54,7 +54,7 @@ import { buildControlPlaneUrl } from "./control-plane-url.js";
54
54
  import { createServeMigrationController, handleMigrationControlMessage } from "./daemon-migration-wiring.js";
55
55
  import { createCodexHomeModeController } from "./codex-home-mode-controller.js";
56
56
  import { resolveDaemonLocalStateRootFromEnv } from "./daemon-local-home.js";
57
- import { attachStorageMigrationRuntime, createServeStorageStatusDelivery, handleStorageMigrationControl, replayStorageMigrationStatus, storageMigrationCapabilities, } from "./storage-serve-adapter.js";
57
+ import { attachStorageMigrationRuntime, bindStorageMigrationServerIdentity, createServeStorageStatusDelivery, handleStorageMigrationControl, replayStorageMigrationStatus, storageMigrationCapabilities, } from "./storage-serve-adapter.js";
58
58
  export { buildControlPlaneUrl } from "./control-plane-url.js";
59
59
  // normalize.ts 的活动种类 → activity 枚举
60
60
  const ACTIVITY_MAP = {
@@ -316,6 +316,7 @@ export function serve(config, opts = {}) {
316
316
  let connectionEpochToken;
317
317
  ws.on("open", () => {
318
318
  connectionEpochToken = projectSkillsController.beginConnectionEpoch();
319
+ storageMigrationRuntime.beginIdentityBinding();
319
320
  const openedSocket = ws;
320
321
  backoff = 1000;
321
322
  connectedAt = Date.now();
@@ -811,16 +812,21 @@ export function serve(config, opts = {}) {
811
812
  // ready 帧带 server 视角的 machineId/workspaceId → 作为后续所有日志的默认关联键
812
813
  const r = msg;
813
814
  setSlogDefaults({ machine_id: r.machineId, workspace_id: r.workspaceId });
814
- if (opts.storageMigration?.ready === true && typeof r.workspaceId === "string" && typeof r.machineId === "string") {
815
- try {
816
- opts.storageMigration.bindServerIdentity?.({ workspaceId: r.workspaceId, machineId: r.machineId });
817
- machineHelloPublisher.republish();
818
- }
819
- catch (error) {
820
- dslog("daemon.storage_identity_bind_failed", "存储迁移 Workspace 身份绑定失败", {
821
- level: "ERROR", error_message: error.message,
822
- });
823
- }
815
+ if (opts.storageMigration !== undefined && typeof r.workspaceId === "string" && typeof r.machineId === "string") {
816
+ const bindingSocket = ws;
817
+ bindStorageMigrationServerIdentity(opts.storageMigration, { workspaceId: r.workspaceId, machineId: r.machineId }, {
818
+ onBound: () => {
819
+ if (bindingSocket !== ws || bindingSocket?.readyState !== WebSocket.OPEN)
820
+ return;
821
+ storageMigrationRuntime.completeIdentityBinding();
822
+ machineHelloPublisher.republish();
823
+ },
824
+ onError: (error) => {
825
+ dslog("daemon.storage_identity_bind_failed", "存储迁移 Workspace 身份绑定失败", { level: "ERROR", error_message: error.message });
826
+ if (bindingSocket === ws && bindingSocket?.readyState === WebSocket.OPEN)
827
+ bindingSocket.close(1011, "storage identity binding failed");
828
+ },
829
+ });
824
830
  }
825
831
  // 旧 server 无此字段 → 空集合(daemon 保持全部旧行为)。
826
832
  serverCapabilities = new Set(Array.isArray(r.serverCapabilities)
@@ -4,6 +4,9 @@ import { createStorageOwnershipClaim } from "./storage-ownership.js";
4
4
  function fingerprint(namespace, value) {
5
5
  return `sha256:${createHash("sha256").update(`${namespace}\0${value}`).digest("hex")}`;
6
6
  }
7
+ export function storageWorkspaceRootFingerprint(workspaceRoot) {
8
+ return fingerprint("workspace-root", workspaceRoot);
9
+ }
7
10
  export function storageIdFingerprint(storageId) {
8
11
  return fingerprint("storage", storageId);
9
12
  }
@@ -15,7 +18,7 @@ export function storageHelloIdentity(input) {
15
18
  || installation.runtimeRoot !== layout.runtimeRoot) {
16
19
  throw new Error("installation storage identity does not match resolved layout");
17
20
  }
18
- const workspaceRootFingerprint = fingerprint("workspace-root", layout.workspaceRoot);
21
+ const workspaceRootFingerprint = storageWorkspaceRootFingerprint(layout.workspaceRoot);
19
22
  let ownership;
20
23
  if (input.ownership !== undefined) {
21
24
  const { claimFingerprint: reportedFingerprint, ...claimIdentity } = input.ownership;