@nowcrew/daemon 0.6.88-beta.2 → 0.6.88-beta.20
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/README.md +38 -10
- package/dist/agent-memory/policy.js +3 -1
- package/dist/daemon-update-eligibility.js +1 -1
- package/dist/execution-journal.js +9 -6
- package/dist/execution-protocol.js +2 -1
- package/dist/execution-runner.js +5 -3
- package/dist/list-models.js +2 -0
- package/dist/local-execution-lease.js +22 -0
- package/dist/local-executor.js +57 -37
- package/dist/local-memory/candidate.js +43 -0
- package/dist/local-memory/index-budget.js +8 -0
- package/dist/local-memory/inventory-cli.js +61 -0
- package/dist/local-memory/inventory-preview.js +154 -0
- package/dist/local-memory/inventory-source.js +159 -0
- package/dist/local-memory/pending-match.js +29 -0
- package/dist/local-memory/pending-query.js +100 -0
- package/dist/local-memory/pending-schema.js +29 -0
- package/dist/local-memory/pending-source.js +126 -0
- package/dist/local-memory/pending.js +34 -84
- package/dist/local-memory/prompt.js +14 -11
- package/dist/local-memory/read-cli.js +59 -8
- package/dist/local-memory/runtime.js +24 -17
- package/dist/local-memory/work-log-execution.js +31 -0
- package/dist/local-memory/work-log.js +58 -0
- package/dist/local-memory/write.js +27 -58
- package/dist/machine-info.js +54 -16
- package/dist/main.js +4 -69
- package/dist/native-thread-context.js +59 -0
- package/dist/pre-admission-rejection.js +64 -0
- package/dist/project-skills/execution-adapter.js +3 -2
- package/dist/project-skills/runtime-launch.js +14 -0
- package/dist/prompt.js +15 -15
- package/dist/provider-env.js +3 -4
- package/dist/runner.js +14 -15
- package/dist/runtime-probe.js +34 -5
- package/dist/runtimes/acp-probe-transport.js +69 -0
- package/dist/runtimes/claude-session-start-hook.js +24 -0
- package/dist/runtimes/claude-thread-runner.js +266 -0
- package/dist/runtimes/claude.js +23 -4
- package/dist/runtimes/codex-app-server-runner.js +43 -4
- package/dist/runtimes/deepseek-harness-profile.js +92 -0
- package/dist/runtimes/deepseek-harness-runner.js +224 -0
- package/dist/runtimes/deepseek-harness.js +64 -11
- package/dist/runtimes/harness-probe-retry.js +42 -0
- package/dist/runtimes/kimi-acp-runner.js +63 -10
- package/dist/runtimes/opencode-runner.js +7 -1
- package/dist/serve.js +58 -88
- package/dist/session.js +4 -0
- package/dist/storage-identity.js +0 -3
- package/dist/storage-serve-adapter.js +6 -72
- package/dist/supervised-runtime.js +28 -18
- package/dist/thread-input-delivery.js +217 -0
- package/package.json +2 -2
- package/dist/daemon-migration-controller.js +0 -211
- package/dist/daemon-migration-wiring.js +0 -22
- package/dist/storage-control.js +0 -212
- package/dist/storage-copy.js +0 -628
- package/dist/storage-credential-guard.js +0 -21
- package/dist/storage-doctor.js +0 -228
- package/dist/storage-manifest.js +0 -1027
- package/dist/storage-migration-controller.js +0 -440
- package/dist/storage-migration-manifest.js +0 -105
- package/dist/storage-migration-policy.js +0 -100
- package/dist/storage-runtime-controller.js +0 -381
- package/dist/storage-runtime-readiness.js +0 -240
- package/dist/storage-safe-fs.js +0 -302
- package/dist/storage-status-delivery.js +0 -224
- package/dist/storage-status-replay.js +0 -140
- package/dist/storage-target-confirmation.js +0 -129
- package/dist/storage-worker-command.js +0 -37
- package/dist/storage-worker-executor.js +0 -449
- package/dist/storage-worker-handoff.js +0 -151
- package/dist/storage-worker-operation.js +0 -294
- package/dist/storage-worker-status.js +0 -259
|
@@ -1,34 +1,11 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { lstat, mkdir,
|
|
2
|
+
import { lstat, mkdir, realpath, rename, rm, writeFile } from "node:fs/promises";
|
|
3
3
|
import { basename, dirname, join, relative, resolve, sep } from "node:path";
|
|
4
|
-
import {
|
|
4
|
+
import { isRecallablePending, parsePendingMemoryCandidate } from "./pending-schema.js";
|
|
5
|
+
import { pendingFileNames, pendingReadDirectory, PENDING_FILE_BYTES, readPendingSource } from "./pending-source.js";
|
|
6
|
+
import { pendingRecallScore } from "./pending-match.js";
|
|
5
7
|
export const LOCAL_MEMORY_PENDING_SCAN_FILE_CAP = 128;
|
|
6
8
|
export const LOCAL_MEMORY_PENDING_SCAN_BYTE_CAP = 1_000_000;
|
|
7
|
-
const CandidateSchema = z.object({
|
|
8
|
-
operation: z.enum(["create", "update", "supersede"]),
|
|
9
|
-
memoryId: z.string().nullable(),
|
|
10
|
-
baseRevision: z.number().int().nonnegative().nullable(),
|
|
11
|
-
supersedesMemoryId: z.string().nullable(),
|
|
12
|
-
title: z.string().min(1),
|
|
13
|
-
kind: z.enum(["procedural", "semantic", "episodic", "preference"]),
|
|
14
|
-
summary: z.string().min(1),
|
|
15
|
-
triggers: z.array(z.string()).min(1),
|
|
16
|
-
priority: z.enum(["high", "medium", "low"]),
|
|
17
|
-
detailCategory: z.enum(["preferences", "project-rules", "testing", "debugging", "git", "incidents", "lessons"]),
|
|
18
|
-
detailBody: z.string().min(1),
|
|
19
|
-
reviewAfter: z.string().nullable(),
|
|
20
|
-
}).strict();
|
|
21
|
-
const PendingSchema = z.object({
|
|
22
|
-
schemaVersion: z.literal(1),
|
|
23
|
-
pendingId: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/u),
|
|
24
|
-
createdAt: z.string().min(1),
|
|
25
|
-
reason: z.literal("index_over_budget"),
|
|
26
|
-
source: z.object({
|
|
27
|
-
executionId: z.string().min(1),
|
|
28
|
-
pruneTraceId: z.string().min(1).nullable(),
|
|
29
|
-
}).strict(),
|
|
30
|
-
candidate: CandidateSchema,
|
|
31
|
-
}).strict();
|
|
32
9
|
function within(root, candidate) {
|
|
33
10
|
const path = relative(root, candidate);
|
|
34
11
|
return path === "" || (path !== ".." && !path.startsWith(`..${sep}`));
|
|
@@ -122,13 +99,11 @@ async function atomicWrite(path, content) {
|
|
|
122
99
|
}
|
|
123
100
|
}
|
|
124
101
|
export async function persistPendingMemoryCandidate(input) {
|
|
125
|
-
const parsed =
|
|
126
|
-
if (!parsed.success)
|
|
127
|
-
throw new Error("local_memory_pending_invalid");
|
|
102
|
+
const parsed = parsePendingMemoryCandidate(input.candidate);
|
|
128
103
|
const directory = await pendingDirectory(input.agentDir);
|
|
129
|
-
const target = join(directory, `${parsed.
|
|
104
|
+
const target = join(directory, `${parsed.pendingId}.json`);
|
|
130
105
|
await assertRegularFile(target);
|
|
131
|
-
await atomicWrite(target, `${JSON.stringify(parsed
|
|
106
|
+
await atomicWrite(target, `${JSON.stringify(parsed, null, 2)}\n`);
|
|
132
107
|
return target;
|
|
133
108
|
}
|
|
134
109
|
export async function removePendingMemoryCandidate(input) {
|
|
@@ -140,73 +115,44 @@ export async function removePendingMemoryCandidate(input) {
|
|
|
140
115
|
await rm(target, { force: true });
|
|
141
116
|
}
|
|
142
117
|
export async function readPendingMemoryCandidates(input) {
|
|
143
|
-
const directory = await
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
118
|
+
const { directory } = await pendingReadDirectory(input.agentDir).catch((error) => {
|
|
119
|
+
if (error instanceof Error && error.message === "memory_pending_path_invalid") {
|
|
120
|
+
throw new Error("local_memory_pending_path_invalid");
|
|
121
|
+
}
|
|
122
|
+
throw error;
|
|
123
|
+
});
|
|
124
|
+
const names = await pendingFileNames(directory);
|
|
147
125
|
const maxFiles = Math.max(0, input.maxFiles ?? LOCAL_MEMORY_PENDING_SCAN_FILE_CAP);
|
|
148
126
|
const maxBytes = Math.max(0, input.maxBytes ?? LOCAL_MEMORY_PENDING_SCAN_BYTE_CAP);
|
|
149
127
|
const result = [];
|
|
150
128
|
let scannedBytes = 0;
|
|
151
|
-
for (const name of names) {
|
|
152
|
-
if (
|
|
129
|
+
for (const name of names.slice(0, maxFiles)) {
|
|
130
|
+
if (scannedBytes >= maxBytes)
|
|
153
131
|
break;
|
|
154
|
-
const path = join(directory, name);
|
|
155
132
|
try {
|
|
156
|
-
await
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
throw new Error("local_memory_pending_path_invalid");
|
|
160
|
-
if (scannedBytes + stat.size > maxBytes)
|
|
161
|
-
break;
|
|
162
|
-
const raw = await readFile(path, "utf8");
|
|
163
|
-
const size = Buffer.byteLength(raw, "utf8");
|
|
164
|
-
if (scannedBytes + size > maxBytes)
|
|
165
|
-
break;
|
|
166
|
-
scannedBytes += size;
|
|
167
|
-
const parsed = PendingSchema.safeParse(JSON.parse(raw));
|
|
168
|
-
if (parsed.success && `${parsed.data.pendingId}.json` === name)
|
|
169
|
-
result.push(parsed.data);
|
|
133
|
+
const source = await readPendingSource(input.agentDir, name, maxBytes - scannedBytes);
|
|
134
|
+
scannedBytes += source.bytes;
|
|
135
|
+
result.push(source.candidate);
|
|
170
136
|
}
|
|
171
137
|
catch {
|
|
172
|
-
//
|
|
138
|
+
// 失败读取也消耗预算,显式分页命令负责返回诊断和继续扫描。
|
|
139
|
+
scannedBytes += Math.min(PENDING_FILE_BYTES, maxBytes - scannedBytes);
|
|
173
140
|
}
|
|
174
141
|
}
|
|
175
142
|
return result;
|
|
176
143
|
}
|
|
177
|
-
function normalize(value) {
|
|
178
|
-
return value.normalize("NFKC").toLocaleLowerCase().replace(/\s+/gu, " ").trim();
|
|
179
|
-
}
|
|
180
144
|
function priorityRank(priority) {
|
|
181
145
|
return priority === "high" ? 0 : priority === "medium" ? 1 : 2;
|
|
182
146
|
}
|
|
183
|
-
function candidateText(candidate) {
|
|
184
|
-
return [
|
|
185
|
-
candidate.candidate.title,
|
|
186
|
-
candidate.candidate.summary,
|
|
187
|
-
...candidate.candidate.triggers,
|
|
188
|
-
candidate.candidate.detailCategory,
|
|
189
|
-
candidate.candidate.detailBody,
|
|
190
|
-
].join("\n");
|
|
191
|
-
}
|
|
192
|
-
function recallScore(candidate, query) {
|
|
193
|
-
const normalizedQuery = normalize(query);
|
|
194
|
-
if (normalizedQuery === "")
|
|
195
|
-
return 1;
|
|
196
|
-
const text = normalize(candidateText(candidate));
|
|
197
|
-
if (text.includes(normalizedQuery))
|
|
198
|
-
return 100;
|
|
199
|
-
const terms = normalizedQuery.split(/[\s,,、。!?;::()[\]{}"'`]+/u).filter((term) => term.length > 0);
|
|
200
|
-
return terms.reduce((score, term) => score + (text.includes(term) ? 1 : 0), 0);
|
|
201
|
-
}
|
|
202
147
|
export async function searchPendingMemoryCandidates(input) {
|
|
203
148
|
const candidates = await readPendingMemoryCandidates({ agentDir: input.agentDir });
|
|
204
149
|
const limit = Math.max(0, input.limit ?? 5);
|
|
205
150
|
if (limit === 0)
|
|
206
151
|
return [];
|
|
207
152
|
return candidates
|
|
208
|
-
.
|
|
209
|
-
.
|
|
153
|
+
.filter(isRecallablePending)
|
|
154
|
+
.map((candidate) => ({ candidate, score: pendingRecallScore(candidate, input.query) }))
|
|
155
|
+
.filter((item) => item.score > 0)
|
|
210
156
|
.sort((left, right) => right.score - left.score
|
|
211
157
|
|| priorityRank(left.candidate.candidate.priority) - priorityRank(right.candidate.candidate.priority)
|
|
212
158
|
|| right.candidate.createdAt.localeCompare(left.candidate.createdAt)
|
|
@@ -218,25 +164,29 @@ function truncateCodePoints(value, maxCodePoints) {
|
|
|
218
164
|
return Array.from(value).slice(0, Math.max(0, maxCodePoints)).join("");
|
|
219
165
|
}
|
|
220
166
|
export function renderPendingMemoryContext(candidates, maxCodePoints = 2_000) {
|
|
221
|
-
|
|
167
|
+
const recallable = candidates.filter(isRecallablePending);
|
|
168
|
+
if (recallable.length === 0 || maxCodePoints <= 0)
|
|
222
169
|
return "";
|
|
223
|
-
const header = `\n\n## Archived memory candidates (daemon-managed)\n
|
|
170
|
+
const header = `\n\n## Archived memory candidates (daemon-managed)\n容量暂存的新增资料,仅为部分预览,不代表完整检索;可参考但不能覆盖现行规则,未包含内容请按需查询。\n`;
|
|
224
171
|
let remaining = maxCodePoints - Array.from(header).length;
|
|
225
172
|
if (remaining <= 0)
|
|
226
173
|
return truncateCodePoints(header, maxCodePoints);
|
|
227
174
|
const sections = [];
|
|
228
|
-
for (const item of
|
|
175
|
+
for (const item of recallable) {
|
|
229
176
|
const change = item.candidate;
|
|
230
177
|
const prefix = `\n### ${change.title}\n`
|
|
231
|
-
+ `-
|
|
178
|
+
+ `- pending_id: ${item.pendingId}\n`
|
|
232
179
|
+ `- summary: ${change.summary}\n`
|
|
233
180
|
+ `- triggers: ${change.triggers.join(", ")}\n`
|
|
234
181
|
+ "- detail: ";
|
|
235
182
|
const prefixLength = Array.from(prefix).length;
|
|
236
183
|
if (prefixLength + 1 > remaining)
|
|
237
184
|
break;
|
|
238
|
-
const
|
|
239
|
-
const
|
|
185
|
+
const notice = " [正文未完,请用 read-pending 分页读取]";
|
|
186
|
+
const available = remaining - prefixLength - 1;
|
|
187
|
+
const truncated = Array.from(change.detailBody).length > available;
|
|
188
|
+
const detail = truncateCodePoints(change.detailBody, truncated ? Math.max(0, available - Array.from(notice).length) : available);
|
|
189
|
+
const section = `${prefix}${detail}${truncated ? truncateCodePoints(notice, available - Array.from(detail).length) : ""}\n`;
|
|
240
190
|
const length = Array.from(section).length;
|
|
241
191
|
sections.push(section);
|
|
242
192
|
remaining -= length;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { dslog } from "../slog.js";
|
|
2
2
|
import { renderPendingMemoryContext, searchPendingMemoryCandidates } from "./pending.js";
|
|
3
3
|
import { renderLocalMemoryResultInstructions } from "./runtime.js";
|
|
4
|
+
const PENDING_READ_GUIDANCE = "\n\nV2新增资料预览未命中不代表没有资料;先查有效索引,必要时用 crew-memory search-pending --query '关键词',按 nextCursor 续查;用 read-pending --id ID 分页读正文。容量暂存资料不能覆盖现行规则,未应用修改不作为记忆。用 crew-memory --help 查看参数。\n";
|
|
4
5
|
export async function prepareLocalMemoryPrompt(input) {
|
|
5
6
|
let pending = "";
|
|
6
7
|
if (input.enabled) {
|
|
@@ -21,17 +22,19 @@ export async function prepareLocalMemoryPrompt(input) {
|
|
|
21
22
|
}
|
|
22
23
|
const original = input.renderBase(0);
|
|
23
24
|
const structured = input.resultPath === null ? "" : renderLocalMemoryResultInstructions(input.resultPath);
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
25
|
+
const guidance = input.enabled ? PENDING_READ_GUIDANCE : "";
|
|
26
|
+
// 短命令指引放在当前轮,独立于可舍弃预览;收尾契约仍保持系统与当前轮两份。
|
|
27
|
+
for (const choice of [
|
|
28
|
+
{ suffix: pending + structured, wake: structured + guidance },
|
|
29
|
+
{ suffix: structured, wake: structured + guidance },
|
|
30
|
+
{ suffix: structured, wake: structured },
|
|
31
|
+
]) {
|
|
32
|
+
const reserved = Buffer.byteLength(choice.suffix + choice.wake, "utf8");
|
|
33
|
+
const systemPrompt = (reserved === 0 ? original : input.renderBase(reserved)) + choice.suffix;
|
|
34
|
+
if (input.maxBytes === undefined || Buffer.byteLength(systemPrompt + choice.wake, "utf8") <= input.maxBytes) {
|
|
35
|
+
return { systemPrompt, resultPath: input.resultPath, wakePromptSuffix: choice.wake };
|
|
36
|
+
}
|
|
34
37
|
}
|
|
35
38
|
// 强制基础指令与契约本身仍无法共存时,保留既有非结构化兼容回退,不裁基础指令。
|
|
36
|
-
return { systemPrompt: original, resultPath: null };
|
|
39
|
+
return { systemPrompt: original, resultPath: null, wakePromptSuffix: "" };
|
|
37
40
|
}
|
|
@@ -5,6 +5,7 @@ import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
|
5
5
|
import { pathToFileURL } from "node:url";
|
|
6
6
|
import { parseArgs, TextDecoder } from "node:util";
|
|
7
7
|
import { z } from "zod";
|
|
8
|
+
import { readPendingMemoryBody, searchPendingMemoryPage } from "./pending-query.js";
|
|
8
9
|
const OUTPUT_BYTES = 12 * 1024;
|
|
9
10
|
const FILE_BYTES = 32 * 1024 * 1024;
|
|
10
11
|
const FileSchema = z.string().min(1).refine((file) => {
|
|
@@ -33,14 +34,35 @@ const CommandSchema = z.discriminatedUnion("command", [
|
|
|
33
34
|
offset: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),
|
|
34
35
|
limit: z.coerce.number().int().min(1).max(4000).default(2000),
|
|
35
36
|
}).strict(),
|
|
37
|
+
z.object({
|
|
38
|
+
command: z.literal("search-pending"),
|
|
39
|
+
query: z.string().trim().min(1).max(256),
|
|
40
|
+
cursor: z.string().min(1).max(4096).optional(),
|
|
41
|
+
limit: z.coerce.number().int().min(1).max(40).default(10),
|
|
42
|
+
}).strict(),
|
|
43
|
+
z.object({
|
|
44
|
+
command: z.literal("read-pending"),
|
|
45
|
+
id: z.string().min(1).max(250).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/u),
|
|
46
|
+
ifHash: Common.ifHash,
|
|
47
|
+
offset: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),
|
|
48
|
+
limit: z.coerce.number().int().min(1).max(4000).default(2000),
|
|
49
|
+
}).strict(),
|
|
36
50
|
]);
|
|
37
51
|
const USAGE = `只读记忆工具,默认输出 JSON,不修改任何记忆文件。
|
|
38
52
|
crew-memory search --query <关键词> [--file MEMORY.md|notes/文件.md] [--limit 10] [--after-line 0]
|
|
39
53
|
crew-memory read [--file MEMORY.md|notes/文件.md] [--offset 0] [--limit 2000]
|
|
40
|
-
|
|
54
|
+
crew-memory search-pending --query <关键词> [--cursor <游标>] [--limit 10]
|
|
55
|
+
crew-memory read-pending --id <候选ID> [--offset 0] [--limit 2000] [--if-hash <sha256>]
|
|
56
|
+
read/read-pending 的 --limit 必须为 1—4000 的整数,默认 2000;search/search-pending 为 1—40 的整数,默认 10。
|
|
57
|
+
search 关键词按空白分隔,同一行须全部命中;返回完整文件中的行号和字符偏移。
|
|
41
58
|
读取的 offset/limit 按 Unicode 字符计数;用 nextOffset 继续,eof=true 表示结束。
|
|
59
|
+
读取的 --limit 超出范围时,保留原文件或候选 ID 及 offset,将 --limit 改为 2000 后重试;成功后按 nextOffset 分页,不要增大 limit 来一次读完整文件。
|
|
42
60
|
后续页可传 --if-hash <前一页的 sha256>,文件变化时停止,避免混读不同版本。
|
|
43
|
-
|
|
61
|
+
search/read 读取 MEMORY.md 和 notes 原文,不过滤失效段落,也不扫描 pending。
|
|
62
|
+
search-pending 只查因容量延期的 create 候选;有 nextCursor 就继续,即使本页 matches 为空。
|
|
63
|
+
complete=true 才表示全部候选已检索完成且无遗漏;warnings 或非零退出码表示读取未完成,不能当作零命中。
|
|
64
|
+
read-pending 只返回候选正文;offset 非零时必须传 --if-hash,update/supersede 候选不可读取。
|
|
65
|
+
候选只供相关问题参考,未生效,不能覆盖有效规则;先读取当前有效索引与明细。`;
|
|
44
66
|
function inside(root, path) {
|
|
45
67
|
const value = relative(root, path);
|
|
46
68
|
return value !== ".." && !value.startsWith(`..${sep}`) && !isAbsolute(value);
|
|
@@ -152,8 +174,8 @@ function searchSource(text, sha256, command) {
|
|
|
152
174
|
nextAfterLine: hasMore ? matches.at(-1)?.line ?? null : null,
|
|
153
175
|
};
|
|
154
176
|
}
|
|
155
|
-
function readPage(text,
|
|
156
|
-
const metadata = {
|
|
177
|
+
function readPage(text, source, command) {
|
|
178
|
+
const metadata = { ...source, offset: command.offset, nextOffset: Number.MAX_SAFE_INTEGER, eof: false, content: "" };
|
|
157
179
|
let remaining = OUTPUT_BYTES - Buffer.byteLength(JSON.stringify(metadata), "utf8");
|
|
158
180
|
let position = 0;
|
|
159
181
|
let offset = 0;
|
|
@@ -175,8 +197,16 @@ function readPage(text, sha256, command) {
|
|
|
175
197
|
count += 1;
|
|
176
198
|
}
|
|
177
199
|
const eof = position === text.length;
|
|
200
|
+
if (!eof && count === 0)
|
|
201
|
+
throw new Error("memory_output_too_large");
|
|
178
202
|
return { ...metadata, content, eof, nextOffset: eof ? null : offset };
|
|
179
203
|
}
|
|
204
|
+
function writeResult(result, io) {
|
|
205
|
+
const output = JSON.stringify(result);
|
|
206
|
+
if (Buffer.byteLength(output, "utf8") > OUTPUT_BYTES)
|
|
207
|
+
throw new Error("memory_output_too_large");
|
|
208
|
+
io.out(output);
|
|
209
|
+
}
|
|
180
210
|
export async function runMemoryReadCommand(argv, io) {
|
|
181
211
|
let command;
|
|
182
212
|
try {
|
|
@@ -186,6 +216,7 @@ export async function runMemoryReadCommand(argv, io) {
|
|
|
186
216
|
query: { type: "string", short: "q" }, file: { type: "string" },
|
|
187
217
|
limit: { type: "string" }, offset: { type: "string" },
|
|
188
218
|
"after-line": { type: "string" }, "if-hash": { type: "string" },
|
|
219
|
+
id: { type: "string" }, cursor: { type: "string" },
|
|
189
220
|
json: { type: "boolean" }, help: { type: "boolean", short: "h" },
|
|
190
221
|
},
|
|
191
222
|
});
|
|
@@ -201,24 +232,44 @@ export async function runMemoryReadCommand(argv, io) {
|
|
|
201
232
|
...(afterLine === undefined ? {} : { afterLine }),
|
|
202
233
|
...(ifHash === undefined ? {} : { ifHash }),
|
|
203
234
|
});
|
|
235
|
+
if (command.command === "read-pending" && command.offset > 0 && command.ifHash === undefined) {
|
|
236
|
+
throw new Error("memory_hash_required");
|
|
237
|
+
}
|
|
204
238
|
}
|
|
205
239
|
catch {
|
|
206
|
-
io.err(`memory_arguments_invalid:
|
|
240
|
+
io.err(`memory_arguments_invalid: 参数不合法,记忆读取未完成;请按以下参数范围修正后重试,不要当作没有记忆。\n${USAGE}`);
|
|
207
241
|
return 2;
|
|
208
242
|
}
|
|
209
243
|
try {
|
|
244
|
+
if (!io.env.CREW_HOME)
|
|
245
|
+
throw new Error("memory_home_missing");
|
|
246
|
+
if (command.command === "search-pending") {
|
|
247
|
+
const result = await searchPendingMemoryPage({ agentDir: io.env.CREW_HOME, query: command.query,
|
|
248
|
+
...(command.cursor === undefined ? {} : { cursor: command.cursor }), limit: command.limit });
|
|
249
|
+
writeResult(result, io);
|
|
250
|
+
if (result.warnings.length > 0 || (!result.hasMore && !result.complete)) {
|
|
251
|
+
throw new Error("memory_pending_search_incomplete");
|
|
252
|
+
}
|
|
253
|
+
return 0;
|
|
254
|
+
}
|
|
255
|
+
if (command.command === "read-pending") {
|
|
256
|
+
const { content, ...metadata } = await readPendingMemoryBody({ agentDir: io.env.CREW_HOME,
|
|
257
|
+
pendingId: command.id, ...(command.ifHash === undefined ? {} : { ifHash: command.ifHash }) });
|
|
258
|
+
writeResult(readPage(content, metadata, command), io);
|
|
259
|
+
return 0;
|
|
260
|
+
}
|
|
210
261
|
const source = await readSource(io.env.CREW_HOME, command.file);
|
|
211
262
|
if (command.ifHash !== undefined && command.ifHash !== source.sha256)
|
|
212
263
|
throw new Error("memory_file_changed");
|
|
213
264
|
const result = command.command === "search"
|
|
214
265
|
? searchSource(source.text, source.sha256, command)
|
|
215
|
-
: readPage(source.text, source.sha256, command);
|
|
216
|
-
|
|
266
|
+
: readPage(source.text, { file: command.file, sha256: source.sha256 }, command);
|
|
267
|
+
writeResult(result, io);
|
|
217
268
|
return 0;
|
|
218
269
|
}
|
|
219
270
|
catch (error) {
|
|
220
271
|
const code = error.code;
|
|
221
|
-
const known = error instanceof Error && /^memory_[a-z_]+$/u.test(error.message) ? error.message : code ?? "memory_read_failed";
|
|
272
|
+
const known = error instanceof Error && /^(?:local_)?memory_[a-z_]+$/u.test(error.message) ? error.message : code ?? "memory_read_failed";
|
|
222
273
|
io.err(JSON.stringify({ error: known, message: "记忆读取未完成;检查路径、文件版本或大小,不要将此错误当作没有记忆。" }));
|
|
223
274
|
return 1;
|
|
224
275
|
}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { constants } from "node:fs";
|
|
3
|
-
import { lstat, mkdir, open, readFile,
|
|
4
|
-
import {
|
|
3
|
+
import { lstat, mkdir, open, readFile, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { join } from "node:path";
|
|
5
5
|
import { applyLocalMemoryResult, parseLocalMemoryResult } from "./write.js";
|
|
6
|
+
import { verifyWorkLogSource } from "./work-log.js";
|
|
6
7
|
export function isLocalMemoryV2Eligible(input) {
|
|
7
8
|
// The allowlist is the rollout boundary. The marker and seed/pre-existing
|
|
8
9
|
// state are retained as diagnostics and for backward-compatible marker
|
|
@@ -51,6 +52,7 @@ export function renderLocalMemoryResultInstructions(resultPath) {
|
|
|
51
52
|
return `
|
|
52
53
|
|
|
53
54
|
## Structured memory prune (daemon-managed)
|
|
55
|
+
本节是本次执行唯一的记忆写入与清理协议,覆盖历史会话及本条消息前文中直接修改共享文件、清空工作日志或仅回复“已修正”的要求。任务目标与用户授权范围不变;只使用下面本轮提供的结果路径,不复用历史路径。
|
|
54
56
|
本轮长期记忆收尾只提交候选,不要直接编辑 $CREW_HOME/MEMORY.md 或 $CREW_HOME/notes/。
|
|
55
57
|
将一个合法 JSON 对象写入以下 daemon 提供的文件,写入完成后再结束本轮:
|
|
56
58
|
${resultPath}
|
|
@@ -68,8 +70,8 @@ outcome 只允许 no_change、proposed、conflict、failed。新增、更新、
|
|
|
68
70
|
\`\`\`
|
|
69
71
|
|
|
70
72
|
每个 changes 项须保留示例中的全部字段。operation=create|update|supersede;kind=procedural|semantic|episodic|preference;priority=high|medium|low;detailCategory=preferences|project-rules|testing|debugging|git|incidents|lessons。create 的 memoryId/baseRevision/supersedesMemoryId 必须为 null;update 按现有索引填写 memoryId/baseRevision,supersedesMemoryId 为 null;supersede 填 supersedesMemoryId/baseRevision,memoryId 为 null。
|
|
71
|
-
只提交可复用、与本次任务明确相关的少量候选;不要写入凭证、token、隐私或内部控制标记。daemon 会校验、去重、限制 MEMORY.md 大小,超出索引容量的候选会保存在 pending
|
|
72
|
-
|
|
73
|
+
只提交可复用、与本次任务明确相关的少量候选;不要写入凭证、token、隐私或内部控制标记。daemon 会校验、去重、限制 MEMORY.md 大小,超出索引容量的候选会保存在 pending 归档中。容量暂存的 create 可按需检索参考但不能覆盖现行规则;有空间的后续 proposed 提交可提升。未应用的 update/supersede 不进入普通召回,必须重新核对目标版本后处理。
|
|
74
|
+
写入候选文件只表示提交候选,不能提前宣称已经记住或规则已经更新;daemon 在本轮结束后才处理,候选持久化与进入有效索引也不是同一结果。本结构化轮次覆盖前文提前清理工作日志的要求:保留 $CREW_TASK_LOG,不要清空或删除;daemon 将在处理成功后清理,失败时保留日志和候选用于排查或重试。
|
|
73
75
|
`;
|
|
74
76
|
}
|
|
75
77
|
/** Prevent ordinary V2 turns from racing the daemon-managed memory writer. */
|
|
@@ -79,6 +81,11 @@ export function renderLocalMemoryV2WriteGuard() {
|
|
|
79
81
|
## V2 shared memory write safety
|
|
80
82
|
本节覆盖前文关于普通任务直接更新共享记忆的例外规则。本 Agent 已启用结构化本地记忆 V2。普通任务不得直接编辑共享的 $CREW_HOME/MEMORY.md 或 $CREW_HOME/notes/ 文件;即使用户明确要求记住内容,也只把候选、用户授权和分类理由记录到本任务的 $CREW_TASK_LOG,留给任务结束后的 memory-prune 结构化收尾应用。只有 memory-prune 收尾提示明确要求写入 daemon 提供的 result 文件时,才按该协议提交候选。`;
|
|
81
83
|
}
|
|
84
|
+
function workLogFailure(error) {
|
|
85
|
+
const reason = error instanceof Error ? error.message : "";
|
|
86
|
+
return { status: "failed", error: reason === "local_memory_work_log_source_changed"
|
|
87
|
+
|| reason === "local_memory_work_log_version_missing" ? reason : "local_memory_work_log_cleanup_failed" };
|
|
88
|
+
}
|
|
82
89
|
export async function commitLocalMemoryResultAfterExit(input) {
|
|
83
90
|
if (input.exitCode !== 0)
|
|
84
91
|
return { status: "skipped" };
|
|
@@ -96,6 +103,14 @@ export async function commitLocalMemoryResultAfterExit(input) {
|
|
|
96
103
|
if (result.outcome === "conflict" || result.outcome === "failed") {
|
|
97
104
|
return { status: "failed", error: `local_memory_result_${result.outcome}` };
|
|
98
105
|
}
|
|
106
|
+
if (input.workLogPath !== undefined) {
|
|
107
|
+
try {
|
|
108
|
+
await verifyWorkLogSource(input.agentDir, input.workLogPath, input.expectedWorkLogSha256);
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
return workLogFailure(error);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
99
114
|
await applyLocalMemoryResult({
|
|
100
115
|
agentDir: input.agentDir,
|
|
101
116
|
result,
|
|
@@ -108,20 +123,12 @@ export async function commitLocalMemoryResultAfterExit(input) {
|
|
|
108
123
|
}
|
|
109
124
|
if (input.workLogPath !== undefined) {
|
|
110
125
|
try {
|
|
111
|
-
const
|
|
112
|
-
if (relativeLogPath === "" || relativeLogPath === ".." || relativeLogPath.startsWith(`..${sep}`)
|
|
113
|
-
|| isAbsolute(relativeLogPath))
|
|
114
|
-
throw new Error("local_memory_work_log_path_invalid");
|
|
115
|
-
const expectedLogPath = join(await realpath(input.agentDir), relativeLogPath);
|
|
116
|
-
const before = await lstat(input.workLogPath);
|
|
117
|
-
if (!before.isFile() || before.isSymbolicLink())
|
|
118
|
-
throw new Error("local_memory_work_log_path_invalid");
|
|
119
|
-
if (await realpath(input.workLogPath) !== expectedLogPath)
|
|
120
|
-
throw new Error("local_memory_work_log_path_invalid");
|
|
126
|
+
const before = await verifyWorkLogSource(input.agentDir, input.workLogPath, input.expectedWorkLogSha256);
|
|
121
127
|
const handle = await open(input.workLogPath, constants.O_WRONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
122
128
|
try {
|
|
123
129
|
const opened = await handle.stat();
|
|
124
|
-
if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino
|
|
130
|
+
if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino
|
|
131
|
+
|| opened.size !== before.size || opened.mtimeMs !== before.mtimeMs || opened.ctimeMs !== before.ctimeMs) {
|
|
125
132
|
throw new Error("local_memory_work_log_path_changed");
|
|
126
133
|
}
|
|
127
134
|
await handle.truncate(0);
|
|
@@ -130,8 +137,8 @@ export async function commitLocalMemoryResultAfterExit(input) {
|
|
|
130
137
|
await handle.close();
|
|
131
138
|
}
|
|
132
139
|
}
|
|
133
|
-
catch {
|
|
134
|
-
return
|
|
140
|
+
catch (error) {
|
|
141
|
+
return workLogFailure(error);
|
|
135
142
|
}
|
|
136
143
|
}
|
|
137
144
|
try {
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
import { withKeyedLease } from "../local-execution-lease.js";
|
|
3
|
+
// 只记录尚未结束的本机执行,最后一个执行结束即移除,不落盘。
|
|
4
|
+
const activeExecutions = new Map();
|
|
5
|
+
export function workLogExecutionKey(agentsRoot, handle, taskKey) {
|
|
6
|
+
return `work-log:${JSON.stringify([resolve(agentsRoot, handle), taskKey ?? "default"])}`;
|
|
7
|
+
}
|
|
8
|
+
export async function withWorkLogExecution(key, operation, cancellation) {
|
|
9
|
+
// 只在登记期间持锁;普通任务与收尾的模型调用仍可并行。
|
|
10
|
+
await withKeyedLease(key, async () => {
|
|
11
|
+
activeExecutions.set(key, (activeExecutions.get(key) ?? 0) + 1);
|
|
12
|
+
}, cancellation);
|
|
13
|
+
try {
|
|
14
|
+
return await operation();
|
|
15
|
+
}
|
|
16
|
+
finally {
|
|
17
|
+
const remaining = (activeExecutions.get(key) ?? 1) - 1;
|
|
18
|
+
if (remaining === 0)
|
|
19
|
+
activeExecutions.delete(key);
|
|
20
|
+
else
|
|
21
|
+
activeExecutions.set(key, remaining);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export async function withWorkLogCommit(key, operation, cancellation) {
|
|
25
|
+
return withKeyedLease(key, async () => {
|
|
26
|
+
// 已有同任务执行可能继续写日志,不能提交旧提案;新执行等短提交结束后再登记。
|
|
27
|
+
if (activeExecutions.get(key) !== 1)
|
|
28
|
+
throw new Error("local_memory_work_log_execution_conflict");
|
|
29
|
+
return operation();
|
|
30
|
+
}, cancellation);
|
|
31
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { lstat, readFile, realpath } from "node:fs/promises";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { safeKey } from "../workspace.js";
|
|
5
|
+
/** 收尾会话可以换目录,但仍应消费同一任务已写好的日志;不迁移文件或复用会话。 */
|
|
6
|
+
export async function resolveMemoryPruneWorkLog(workspace, input) {
|
|
7
|
+
// 旧映射有损时无法证明是同一任务,不能用它查找或清理来源。
|
|
8
|
+
if (input.keyMode !== "opaque" || !input.taskKey || safeKey(input.taskKey) !== input.taskKey) {
|
|
9
|
+
return workspace;
|
|
10
|
+
}
|
|
11
|
+
const legacyPath = join(workspace.dir, "tasks", input.taskKey, "work-log.md");
|
|
12
|
+
if (legacyPath === workspace.workLogPath)
|
|
13
|
+
return workspace;
|
|
14
|
+
let legacyStat;
|
|
15
|
+
try {
|
|
16
|
+
legacyStat = await lstat(legacyPath);
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
if (error.code === "ENOENT")
|
|
20
|
+
return workspace;
|
|
21
|
+
throw error;
|
|
22
|
+
}
|
|
23
|
+
if (!legacyStat.isFile() || legacyStat.isSymbolicLink()
|
|
24
|
+
|| await realpath(legacyPath) !== join(await realpath(workspace.dir), "tasks", input.taskKey, "work-log.md")) {
|
|
25
|
+
throw new Error("local_memory_work_log_path_invalid");
|
|
26
|
+
}
|
|
27
|
+
const workLog = await readFile(legacyPath, "utf8");
|
|
28
|
+
if (workLog.length === 0)
|
|
29
|
+
return workspace;
|
|
30
|
+
if ((await readFile(workspace.workLogPath, "utf8")).length > 0) {
|
|
31
|
+
throw new Error("local_memory_work_log_source_conflict");
|
|
32
|
+
}
|
|
33
|
+
return { ...workspace, workLogPath: legacyPath, workLog };
|
|
34
|
+
}
|
|
35
|
+
export function workLogSha256(content) {
|
|
36
|
+
return createHash("sha256").update(content).digest("hex");
|
|
37
|
+
}
|
|
38
|
+
/** 调用方须在同任务的提交互斥边界内校验;指纹对应实际注入模型的那一版内容。 */
|
|
39
|
+
export async function verifyWorkLogSource(agentDir, path, expectedSha256) {
|
|
40
|
+
if (expectedSha256 === undefined)
|
|
41
|
+
throw new Error("local_memory_work_log_version_missing");
|
|
42
|
+
const relativePath = relative(resolve(agentDir), resolve(path));
|
|
43
|
+
if (relativePath === "" || relativePath === ".." || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath)) {
|
|
44
|
+
throw new Error("local_memory_work_log_path_invalid");
|
|
45
|
+
}
|
|
46
|
+
const before = await lstat(path);
|
|
47
|
+
if (!before.isFile() || before.isSymbolicLink()
|
|
48
|
+
|| await realpath(path) !== join(await realpath(agentDir), relativePath)) {
|
|
49
|
+
throw new Error("local_memory_work_log_path_invalid");
|
|
50
|
+
}
|
|
51
|
+
const content = await readFile(path);
|
|
52
|
+
const after = await lstat(path);
|
|
53
|
+
if (workLogSha256(content) !== expectedSha256 || before.dev !== after.dev || before.ino !== after.ino
|
|
54
|
+
|| before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) {
|
|
55
|
+
throw new Error("local_memory_work_log_source_changed");
|
|
56
|
+
}
|
|
57
|
+
return after;
|
|
58
|
+
}
|