@shgroup/dsh-serenity-hooks 1.137.0 → 1.137.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1073 @@
1
+ import { n as __exportAll } from "./rolldown-runtime-B4iAMlE-.js";
2
+ import { n as agentCwdFor, r as cccRootForCwd, u as hostService } from "./ccc-roots-Bg4Eq2X3.js";
3
+ import { F as isoLocal, b as parseTrajectoryCode, f as extractSessionMdPathFromText, m as getActiveSessionInfo, v as namingTitleFor, w as sessionEvents, y as parseSessionContextFromEvents } from "./bind-file-Dy6Qmm7z.js";
4
+ import { c as replacesDefaultIdentity } from "./profile-RuvXAGBX.js";
5
+ import { a as trajectoryConstraintFor } from "./session-BUyOHV12.js";
6
+ import { a as ACC_MESSAGE_KIND, d as readLastBound, n as deliver, r as makeInjection, s as appendBound } from "./injection-BVKPD4Yf.js";
7
+ import { basename, dirname, join, resolve } from "node:path";
8
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
9
+ import { deriveEventMessage } from "@deepseek-ai/dsh-session";
10
+ //#region src/seams/bootstrap.ts
11
+ /** 默认首请求工具集:dsp 平台 Minimal 等价核心(anchored 是 bash+str_replace_editor) */
12
+ const DEFAULT_BOOTSTRAP_TOOLS = [
13
+ "read",
14
+ "write",
15
+ "edit",
16
+ "glob",
17
+ "grep"
18
+ ];
19
+ /** 默认剥离的自动注入源(anchored 默认:可用技能目录提醒 + 工作区指令摘要) */
20
+ const DEFAULT_SUPPRESSED_SOURCES = ["skill-catalog", "agent-instructions"];
21
+ /** 默认 compaction 恢复工作集(anchored 默认 read/write/edit/glob/grep/todo_write/ask_user_question) */
22
+ const DEFAULT_COMPACTION_TOOLS = [
23
+ "read",
24
+ "write",
25
+ "edit",
26
+ "glob",
27
+ "grep",
28
+ "todo_write"
29
+ ];
30
+ /**
31
+ * 协议级「假首轮」话语序列(用户确认固化,2026-08-24 S142):任何 CCC 在抽象层都是
32
+ * 宁静号/ACC——假首轮话语统一,无 CCC 配置面。
33
+ *
34
+ * 🔵 **2026-11-16 合并:两条 → 一条**(owner 令「合并吧」)。
35
+ *
36
+ * 判据(为什么合并安全 · 逐条对读过系统提示词**才**动的手):
37
+ * · 本文件这两条**只出现一次**(`hasUserMessageHistory` 守卫:有真人说话就不再插),
38
+ * 而系统提示词里的 EAP 块**每轮注入** ⇒ 两者不构成第二真相源,但确实**功能重叠**。
39
+ * · 重叠的那一块 = EAP 是什么。系统提示词的 `eapBlock()` 给的是**更详细的操作定义**
40
+ * (E↑/R↓/S↑ 各自查什么)⇒ 这里**不必复述**,压成一句指认即可。
41
+ * · ⛔ **不可省的四处,条条只在 bootstrap 有**:
42
+ * ① `personal pronoun is us/we` —— 系统提示词零处(grep 过)
43
+ * ② `We anchor first, then act` —— 同上
44
+ * ③ 协作五条 —— 系统提示词零处
45
+ * ④ 身份句 `operator agent of Serenity…ACC protocol` —— 开场语境
46
+ * · `Please simply reply "acknowledge"` 原本**两条各写一遍**(重复两次),合并后一处。
47
+ *
48
+ * 🔴 **为什么"合并"而不是"删第一条"**:删掉第一条会连同 ①②③④ 一起消失;
49
+ * 合并只是去掉 EAP 的**展开复述**与重复的 acknowledge 指令,语义面零损失。
50
+ * ⚠️ 轮数因此 2 → 1:`requiredSignals` 与 `pendingFakeTurns.remaining` 都由
51
+ * `DEFAULT_FAKE_INITIAL_MESSAGES.length` 派生,**跟着自动变**,无需另改。
52
+ */
53
+ const DEFAULT_FAKE_INITIAL_MESSAGES = ["You are the operator agent of Serenity — a cognitive container governed by the Abstract Cognitive Container (ACC) protocol.\nWe operate under the Explicit Abstraction Principle (EAP), whose operational self-check (E↑ explicit / R↓ reconstructable / S↑ stable) is given in full in the system prompt — apply it there, do not restate it here.\nThe personal pronoun is us/we.\nWe anchor first, then act: the abstract layer precedes the concrete.\nHow we work:\n1. We read before we write — every decision grounds in what already exists in the container.\n2. Every output records its reasoning (R↓): decisions carry reasons and alternatives.\n3. We never jump levels — abstract layer first, then specifics.\n4. Every artifact we create is a durable cognitive anchor for the work that follows.\n5. We keep the container's state coherent (SESSION.md) as we advance.\nPlease simply reply \"acknowledge\" — no action needed."];
54
+ /**
55
+ * 根会话重入判定(v1.28.1 提取导出以便单测):会话是否已有真实用户消息。
56
+ * resume/续跑的会话已有对话历史 → **不重插假首轮**(只注入一次)。
57
+ *
58
+ * 0.1.2-rc.1 适配教训:裸读 `session.events`(经类型断言)恒 undefined →
59
+ * `!undefined` 恒 true → 有历史也永不跳过 → 任何情况发消息都重插假首轮。
60
+ * 统一经 sessionEvents() 读取(snapshotEvents() 优先,.events 兜底)。
61
+ */
62
+ function hasUserMessageHistory(session) {
63
+ return sessionEvents(session).some((event) => {
64
+ const e = event;
65
+ if (e.type !== "user/message") return false;
66
+ return e.data?.source?.kind === "user";
67
+ });
68
+ }
69
+ /**
70
+ * 假首轮的模型回复文本(= 短路产出的那半)。
71
+ *
72
+ * 只写一个词:假首轮话语明确要求 `reply "acknowledge" — no action needed`。
73
+ * 写长了模型会据历史学样(假首轮话语是它的"先例")。
74
+ */
75
+ const FAKE_TURN_ACK_TEXT = "acknowledge";
76
+ /**
77
+ * 假首轮消息的 `source.summary` —— 同时也**是拦截判据的标记之一**(见 {@link isFakeInitialTurn})。
78
+ * 两处必须同源:注入侧写它,拦截侧认它。
79
+ */
80
+ const FAKE_TURN_SUMMARY = "fake initial turn";
81
+ /** 从消息里取纯文本(content 是块数组;只拼 `text` 块) */
82
+ function textOfMessage(message) {
83
+ const content = message?.content;
84
+ if (!Array.isArray(content)) return void 0;
85
+ const parts = [];
86
+ for (const block of content) {
87
+ const b = block;
88
+ if (b?.type === "text" && typeof b.text === "string") parts.push(b.text);
89
+ }
90
+ return parts.length > 0 ? parts.join("") : void 0;
91
+ }
92
+ /**
93
+ * 判据:**这条模型请求是不是假首轮**(纯函数,可单测;见 `tests/fake-initial-turns.test.ts`)。
94
+ *
95
+ * ## 为什么是**双条件**
96
+ *
97
+ * 误拦的代价不对称:**漏拦** = 老老实实发一次真调用(慢一点,错得无害);
98
+ * **误拦** = 把一条**真实的**用户请求吞掉,模型永远不回答(用户眼里是"卡死")。
99
+ * ⇒ 两个**互相独立**的信号同时成立才拦:
100
+ *
101
+ * 1. **登记在册**:该 session 还有未兑现的假首轮(`pending.remaining > 0`);
102
+ * 2. **文本逐字吻合**:请求里**最近一条"人写的话"**的正文 ∈ 待兑现的文本。
103
+ *
104
+ * ## 第 2 条怎么找"最近一条人写的话"
105
+ *
106
+ * 从尾部往前扫,跳过 `system` / `assistant` / `tool`:
107
+ * - `source.kind` 是**我们的假首轮标记** → 它就是候选,逐字判;
108
+ * - `source.kind === 'user'` 或**没有 source** → 真人说的,逐字判;
109
+ * - 其它注入源(`runtime-context` / `time-context` / `skill-catalog` / `plugin:*`…)
110
+ * → **既不是人也不是假首轮**,跳过继续往前找。
111
+ *
112
+ * ⚠️ **不能改成"请求里任意一条消息等于假首轮文本"**:真轮次的历史里**必然**含着那些消息,
113
+ * 那样判会在第一轮真实对话上就误拦(把真请求吞掉)。
114
+ *
115
+ * @param options 模型请求(`llm/stream` 的第一参)
116
+ * @param pending 该 session 的登记(无登记 ⇒ 一定不是假首轮)
117
+ */
118
+ function isFakeInitialTurn(options, pending) {
119
+ if (pending === void 0 || pending.remaining <= 0) return false;
120
+ const messages = options?.messages;
121
+ if (!Array.isArray(messages) || messages.length === 0) return false;
122
+ for (let i = messages.length - 1; i >= 0; i--) {
123
+ const message = messages[i];
124
+ if (message?.role !== "user") continue;
125
+ const kind = message?.source?.kind;
126
+ if (!(kind === void 0 || kind === "user" || kind === "plugin:dsh-serenity-hooks")) continue;
127
+ const text = textOfMessage(message);
128
+ return text !== void 0 && pending.texts.includes(text);
129
+ }
130
+ return false;
131
+ }
132
+ /**
133
+ * 生成一轮**假首轮确认**的流(`llm/stream` 的短路返回值)。
134
+ *
135
+ * ## 为什么这是"拦截"而不是"伪造日志"
136
+ *
137
+ * 它只替换**模型这一侧的输出**:请求由宿主自己发起、`user/message` 由宿主自己写、
138
+ * `assistant/message` 由宿主**据这条流**自己结算 ⇒ 事件形状、turn/step 坐标、
139
+ * `stream` 数组、`source.provider/model` 全部由宿主填写 ⇒ **不可能再写出非法事件**
140
+ * (v1.69.4 事故的根因是手写 `assistant/message` 缺结算字段)。
141
+ *
142
+ * ## 形状(对着宿主 `StreamChunk` 契约逐字段写)
143
+ *
144
+ * 文本块 = `block-start` → `text-delta` → `block-end`(带**装配好的块**);
145
+ * 结算顺序 = `usage` 先、`finish` 最后(宿主契约:`usage` 在终结之前,终结之后什么都没有)。
146
+ * `usage` 全零 —— 没有真的模型调用,不许让计量器把它算进账。
147
+ */
148
+ async function* fakeTurnAckStream() {
149
+ yield {
150
+ type: "block-start",
151
+ index: 0,
152
+ blockType: "text"
153
+ };
154
+ yield {
155
+ type: "text-delta",
156
+ index: 0,
157
+ text: FAKE_TURN_ACK_TEXT
158
+ };
159
+ yield {
160
+ type: "block-end",
161
+ index: 0,
162
+ block: {
163
+ type: "text",
164
+ text: FAKE_TURN_ACK_TEXT
165
+ }
166
+ };
167
+ yield {
168
+ type: "usage",
169
+ usage: {
170
+ inputTokens: 0,
171
+ outputTokens: 0
172
+ }
173
+ };
174
+ yield {
175
+ type: "finish",
176
+ reason: { kind: "stop" }
177
+ };
178
+ }
179
+ /**
180
+ * 构建一个 epoch 感知晋升跟踪器(纯逻辑,可单测)。
181
+ * requiredSignals:晋升所需信号数(boundary 后累计;默认 1)。
182
+ * 多轮锚定(v4):N 轮递进锚定时 requiredSignals = N——每条锚定回复
183
+ * (assistant/message)计一次,最后一条回复后晋升。
184
+ * 🔵 2026-11-16:`DEFAULT_FAKE_INITIAL_MESSAGES` 由两条合并为一条 ⇒ 缺省 N = **1**
185
+ * (仍由 `.length` 派生,不写死;本函数对 N 的语义未变)。
186
+ *
187
+ * maxRoundsFallback:**轮次兜底**(v1.19.3 修复 responses API 兼容)。
188
+ * 某些模型/协议(如 opencode-go-responses)的会话可能不产生标准
189
+ * `assistant/message` 晋升信号 → 永不晋升 → bootstrap 阶段工具被裁空
190
+ * (zeroTools 首请求 0 工具,ACC 工具不可见)。兜底:无论晋升信号是否
191
+ * 到达,观察到的模型 step 数(`step/start` 事件计数,平台稳定事件,
192
+ * responses/completions 都触发,独立于 promoteEvents)达到 maxRoundsFallback
193
+ * 即强制 promoted(开放完整工具)。正常模型锚定轮数(requiredSignals)
194
+ * 通常 ≤ 2 < 默认兜底 3,不受影响。
195
+ */
196
+ function createEpochPromotion(promoteEvents, requiredSignals = 1, maxRoundsFallback = 3) {
197
+ /** sessionId -> { boundary, signalCount, rounds }(rounds = 兜底用回复轮计数) */
198
+ const state = /* @__PURE__ */ new Map();
199
+ const sessionIdOf = (session) => {
200
+ if (session && typeof session === "object") {
201
+ const id = session.id;
202
+ if (typeof id === "string") return id;
203
+ }
204
+ };
205
+ const promotedBy = (entry) => entry.signalCount >= requiredSignals || entry.rounds >= maxRoundsFallback;
206
+ const scan = (session) => {
207
+ let boundary = -1;
208
+ let signalCount = 0;
209
+ let rounds = 0;
210
+ const events = sessionEvents(session);
211
+ if (events.length > 0) for (const event of events) {
212
+ const e = event;
213
+ const seq = typeof e.seq === "number" ? e.seq : 0;
214
+ if (e.type === "compaction/end") {
215
+ boundary = seq;
216
+ signalCount = 0;
217
+ rounds = 0;
218
+ continue;
219
+ }
220
+ if (promoteEvents.has(e.type) && seq > boundary) signalCount++;
221
+ if (e.type === "step/start" && seq > boundary) rounds++;
222
+ }
223
+ const entry = {
224
+ boundary,
225
+ signalCount,
226
+ rounds
227
+ };
228
+ const sid = sessionIdOf(session);
229
+ if (sid) state.set(sid, entry);
230
+ return {
231
+ boundary,
232
+ promoted: promotedBy(entry)
233
+ };
234
+ };
235
+ return {
236
+ status(agent) {
237
+ if (agent === void 0) return {
238
+ boundary: -1,
239
+ promoted: true
240
+ };
241
+ const session = agent.session;
242
+ if (session === void 0) return {
243
+ boundary: -1,
244
+ promoted: true
245
+ };
246
+ const loopSid = session.id;
247
+ const loopCwd = session.header?.cwd ?? process.cwd();
248
+ const loopRoot = cccRootForCwd(loopCwd);
249
+ if (typeof loopSid === "string" && (loopSid.startsWith("cheap-worker-") || loopRoot !== null && replacesDefaultIdentity(trajectoryConstraintFor(loopRoot, loopSid)))) return {
250
+ boundary: -1,
251
+ promoted: true
252
+ };
253
+ if ((session.header?.delegationDepth ?? 0) > 0) return {
254
+ boundary: -1,
255
+ promoted: true
256
+ };
257
+ const sid = sessionIdOf(session);
258
+ if (sid === void 0) return {
259
+ boundary: -1,
260
+ promoted: true
261
+ };
262
+ const s = state.get(sid);
263
+ if (s) return {
264
+ boundary: s.boundary,
265
+ promoted: promotedBy(s)
266
+ };
267
+ return scan(session);
268
+ },
269
+ observe(session, event) {
270
+ const sid = sessionIdOf(session);
271
+ if (sid === void 0) return;
272
+ const entry = state.get(sid);
273
+ if (entry === void 0) return;
274
+ const e = event;
275
+ const seq = typeof e.seq === "number" ? e.seq : 0;
276
+ if (e.type === "compaction/end") {
277
+ state.set(sid, {
278
+ boundary: seq,
279
+ signalCount: 0,
280
+ rounds: 0
281
+ });
282
+ return;
283
+ }
284
+ if (promoteEvents.has(e.type) && seq > entry.boundary) entry.signalCount++;
285
+ if (e.type === "step/start" && seq > entry.boundary) entry.rounds++;
286
+ state.set(sid, entry);
287
+ }
288
+ };
289
+ }
290
+ const PROMOTE_EVENTS = {
291
+ "tool-call": /* @__PURE__ */ new Set(["tool/call"]),
292
+ "assistant-message": /* @__PURE__ */ new Set(["assistant/message"]),
293
+ either: /* @__PURE__ */ new Set(["tool/call", "assistant/message"])
294
+ };
295
+ /** 协议固有 bootstrap 设置(v1.70 fake-initial-turns)。
296
+ *
297
+ * 🔴 **zeroTools 必须为 false**:假首轮**真跑两轮**,但两轮的模型回复走短路
298
+ * (`llm/stream` 不发真调用)⇒ 首请求时晋升信号尚未满足 ⇒ 若仍 `zeroTools: true`,
299
+ * 首请求会真的退化成「0 工具」,模型看不到任何 ACC 工具。
300
+ *
301
+ * 🔴 **为什么不回到"手写历史"那条路**:宿主把 `assistant/message` 当**结算事件**,
302
+ * 形状由四个校验器分段把关,缺一段**写入时不报错**、**投影/重进会话时炸**
303
+ * (v1.69.4 实测:`Cannot read properties of undefined (reading 'length')`)。
304
+ * ⇒ 事件一律由宿主自己写,我们只截模型那一侧。
305
+ *
306
+ * ⇒ 取舍:**首请求就给完整工具目录**(放弃「首请求窄目录」这个 cache 断点优化),
307
+ * 换来**日志合法**。`bootstrapTools` 因此只是历史字段,`boundary < 0` 分支已让位。 */
308
+ function resolveBootstrapSettings() {
309
+ return {
310
+ bootstrapTools: [...DEFAULT_BOOTSTRAP_TOOLS],
311
+ promoteEvents: PROMOTE_EVENTS["assistant-message"],
312
+ requiredSignals: DEFAULT_FAKE_INITIAL_MESSAGES.length,
313
+ suppressedSources: new Set(DEFAULT_SUPPRESSED_SOURCES),
314
+ compactionTools: [...DEFAULT_COMPACTION_TOOLS],
315
+ fakeInitialMessages: [...DEFAULT_FAKE_INITIAL_MESSAGES],
316
+ zeroTools: false
317
+ };
318
+ }
319
+ /**
320
+ * 注册 Anchored bootstrap 机制(协议固有,零配置面——S142;按 agent cwd 定位 CCC root,
321
+ * 晋升状态按 root 隔离,但设置全局一致):
322
+ * 1. session/event 观察晋升信号(assistant/message + step/start 兜底 + compaction/end)
323
+ * 2. system-prompt/assemble:bootstrap 阶段目录窄化到 bootstrapTools(+compaction 后 compactionTools)
324
+ * 3. agent/pre-step:bootstrap 阶段剥离 suppressedSources 注入消息(降级保留全部)
325
+ * 4. agent/inbox/inserted + llm/stream:fake-initial-turns(注入两轮假首轮 + 短路其模型回复)
326
+ *
327
+ * 摘除 = 删除 index.ts 中本注册行(独立模块)。
328
+ */
329
+ /** 从 agent 解析 CCC 根(宽松;无 agent/无 CCC 返回 null) */
330
+ function agentRoot(agent) {
331
+ const cwd = agent?.session?.header?.cwd;
332
+ if (typeof cwd !== "string") return null;
333
+ return cccRootForCwd(cwd);
334
+ }
335
+ /** 协议固有设置(零配置面):所有 CCC 使用同一固化设置 */
336
+ const SETTINGS = resolveBootstrapSettings();
337
+ function registerBootstrap(ctx) {
338
+ const trackers = /* @__PURE__ */ new Map();
339
+ /** 已注入假首轮的会话(进程内防重:子 agent 每会话只注入一次) */
340
+ const anchoredSessions = /* @__PURE__ */ new Set();
341
+ /** 假首轮待短路登记(注入时写入、拦截到就递减;见 {@link isFakeInitialTurn}) */
342
+ const pendingFakeTurns = /* @__PURE__ */ new Map();
343
+ const trackerFor = (root) => {
344
+ let t = trackers.get(root);
345
+ if (!t) {
346
+ t = createEpochPromotion(SETTINGS.promoteEvents, SETTINGS.requiredSignals);
347
+ trackers.set(root, t);
348
+ }
349
+ return t;
350
+ };
351
+ ctx.on("session/event", (session, event) => {
352
+ try {
353
+ const cwd = session?.header?.cwd;
354
+ if (typeof cwd !== "string") return;
355
+ const root = cccRootForCwd(cwd);
356
+ if (!root) return;
357
+ trackerFor(root).observe(session, event);
358
+ } catch {}
359
+ });
360
+ ctx.on("agent/inbox/inserted", ({ agent, message }) => {
361
+ try {
362
+ const root = agentRoot(agent);
363
+ if (!root) return;
364
+ const session = agent.session;
365
+ const depth = session?.header?.delegationDepth ?? 0;
366
+ const sid = typeof session?.id === "string" ? session.id : void 0;
367
+ if (sid === void 0) return;
368
+ if (sid.startsWith("cheap-worker-") || replacesDefaultIdentity(trajectoryConstraintFor(root, sid))) return;
369
+ if (depth === 0) {
370
+ if (hasUserMessageHistory(session)) return;
371
+ } else if (anchoredSessions.has(sid)) return;
372
+ if (message?.source?.kind === "plugin:dsh-serenity-hooks") return;
373
+ const inbox = agent.inbox;
374
+ if (!inbox?.prepend) return;
375
+ for (let i = SETTINGS.fakeInitialMessages.length - 1; i >= 0; i--) inbox.prepend("next-turn", {
376
+ id: `fake-initial-turn-${Date.now()}-${Math.random().toString(36).slice(2, 8)}-${i}`,
377
+ role: "user",
378
+ content: [{
379
+ type: "text",
380
+ text: SETTINGS.fakeInitialMessages[i]
381
+ }],
382
+ source: {
383
+ kind: ACC_MESSAGE_KIND,
384
+ form: "notice",
385
+ summary: FAKE_TURN_SUMMARY
386
+ }
387
+ });
388
+ anchoredSessions.add(sid);
389
+ pendingFakeTurns.set(sid, {
390
+ remaining: SETTINGS.fakeInitialMessages.length,
391
+ texts: [...SETTINGS.fakeInitialMessages]
392
+ });
393
+ warnOnce(`fake initial turns injected: ${SETTINGS.fakeInitialMessages.length} 条(acknowledge 走短路,不请求模型)`);
394
+ } catch {}
395
+ });
396
+ ctx.on("llm/stream", (options, next) => {
397
+ try {
398
+ const sid = typeof options?.sessionId === "string" ? options.sessionId : void 0;
399
+ if (sid === void 0) return next();
400
+ const pending = pendingFakeTurns.get(sid);
401
+ if (!isFakeInitialTurn(options, pending)) return next();
402
+ const left = pending.remaining - 1;
403
+ if (left <= 0) pendingFakeTurns.delete(sid);
404
+ else pendingFakeTurns.set(sid, {
405
+ ...pending,
406
+ remaining: left
407
+ });
408
+ warnOnce("fake initial turn short-circuited: acknowledge 由短路产出,未请求模型");
409
+ return fakeTurnAckStream();
410
+ } catch {
411
+ return next();
412
+ }
413
+ });
414
+ /**
415
+ * 每种消息**只喊一次**(同一条消息去重;不同消息互不影响)。
416
+ *
417
+ * 🔴 v1.70 修:原实现是**全局一个 `warned` 布尔** ⇒ 进程里只要打过任何一条告警,
418
+ * 后面的告警(包括"假首轮短路了"这条**唯一**能证明拦截生效的痕迹)就再也不打了。
419
+ * 实测代价:bench 里注入行打出来、短路行被吞 ⇒ `verify` 无法判"短路真发生过"。
420
+ * ⚠️ 所以消息里**不要带逐次变化的数字**(`剩 N 轮` 这类),否则去重失效、会刷屏。
421
+ */
422
+ const warnedMessages = /* @__PURE__ */ new Set();
423
+ const warnOnce = (message) => {
424
+ if (warnedMessages.has(message)) return;
425
+ warnedMessages.add(message);
426
+ try {
427
+ console.warn(`[serenity-hooks] bootstrap: ${message}`);
428
+ } catch {}
429
+ };
430
+ ctx.on("system-prompt/assemble", async (_assembly, context, next) => {
431
+ const assembled = await next();
432
+ try {
433
+ const agent = context.agent;
434
+ const root = agentRoot(agent);
435
+ if (!root) return assembled;
436
+ const status = trackerFor(root).status(agent);
437
+ if (status.promoted) return assembled;
438
+ const tools = assembled.tools;
439
+ if (!Array.isArray(tools)) return assembled;
440
+ const available = new Set(tools.map((tool) => tool.name).filter((n) => typeof n === "string"));
441
+ if (SETTINGS.zeroTools) {
442
+ if (status.boundary < 0) return {
443
+ ...assembled,
444
+ tools: []
445
+ };
446
+ const keep = new Set(SETTINGS.compactionTools);
447
+ const missing = [...keep].filter((name) => !available.has(name));
448
+ if (missing.length > 0) {
449
+ warnOnce(`expected compaction tools missing=${JSON.stringify(missing)} — bootstrap disabled, full catalog exposed`);
450
+ return assembled;
451
+ }
452
+ return {
453
+ ...assembled,
454
+ tools: tools.filter((tool) => typeof tool.name === "string" && keep.has(tool.name))
455
+ };
456
+ }
457
+ if (status.boundary < 0) return assembled;
458
+ const keep = new Set(SETTINGS.bootstrapTools);
459
+ for (const toolName of SETTINGS.compactionTools) keep.add(toolName);
460
+ const missing = [...keep].filter((name) => !available.has(name));
461
+ if (missing.length > 0) {
462
+ warnOnce(`expected bootstrap tools missing=${JSON.stringify(missing)} — bootstrap disabled, full catalog exposed`);
463
+ return assembled;
464
+ }
465
+ return {
466
+ ...assembled,
467
+ tools: tools.filter((tool) => typeof tool.name === "string" && keep.has(tool.name))
468
+ };
469
+ } catch (error) {
470
+ warnOnce(`assemble filter failed, exposing the full catalog: ${String(error?.message ?? error)}`);
471
+ return assembled;
472
+ }
473
+ });
474
+ ctx.on("agent/pre-step", async ({ agent }, next) => {
475
+ const decision = await next();
476
+ if (decision.kind === "reject") return decision;
477
+ try {
478
+ const root = agentRoot(agent);
479
+ if (!root) return decision;
480
+ if (trackerFor(root).status(agent).promoted || SETTINGS.suppressedSources.size === 0) return decision;
481
+ const messages = decision.messages;
482
+ if (!Array.isArray(messages)) return decision;
483
+ const kept = messages.filter((message) => {
484
+ const kind = message?.source?.kind;
485
+ return typeof kind !== "string" || !SETTINGS.suppressedSources.has(kind);
486
+ });
487
+ return kept.length === messages.length ? decision : {
488
+ ...decision,
489
+ messages: kept
490
+ };
491
+ } catch (error) {
492
+ warnOnce(`pre-step context filter failed, keeping injected context: ${String(error?.message ?? error)}`);
493
+ return decision;
494
+ }
495
+ }, { prepend: true });
496
+ }
497
+ //#endregion
498
+ //#region src/trajectory/assistant.ts
499
+ /**
500
+ * trajectory/assistant.ts — 关卡化注入的统一命名与风格门面(v0.3,S142)
501
+ *
502
+ * 概念(用户拍板 2026-09-05):dsp 全部"过程中动态提示注入"统一命名为
503
+ * cognitive-trajectory-assistant(轨迹助航员)。关卡设计思想塑造**结构与时机**
504
+ * (何时/何地注入),**不用于提示词用词**(D8 词法原则)——纯游戏黑话
505
+ * (BOSS/XP/level-up)禁止出现在提示词文本;CHECKPOINT/LIMIT/TUTORIAL 等
506
+ * 跨领域自然通用词允许。
507
+ *
508
+ * 本模块 = token 常量 + level-event 词汇表的**单一真相源**(避免前缀散落
509
+ * 各文件字符串字面量)+ 风格门面(plain 默认 / metaphor 星舰变体)。
510
+ * 仅当 style=metaphor 时前缀包装措辞变化;可行动正文不变 → 零行为漂移。
511
+ *
512
+ * 设计简写(L0 环境 / L1 教程 / L2 目标 / L3 检查点 / L4 极限 / L5 守卫 /
513
+ * L6 结算)仅在本模块注释与内部文档出现,永不浮现在提示词文本。
514
+ *
515
+ * 结算(settlement)挂点:D6 用户拍板——若 CCC 有标准 SESSION 复盘仪式,
516
+ * 结算视图归 cognitive-trajectory-assistant。当前 close/archive 无复盘摘要 ⇒ 机制延后。
517
+ * 🔴 2026-09-25(S142 分批清死代码·第 1 批):原先那个 `onSettlement(cb)` **空 seam 已删**
518
+ * (零调用者、无触发器、空实现)——仪式真落地时按当时的信号重新设计,**不再靠空占位**。
519
+ */
520
+ /** 可见提示词前缀用词(跨领域自然词,D8:无游戏黑话) */
521
+ const EVENT_LABEL = {
522
+ /** 计分同步提醒(原 TRAJECTORY-STEWARD) */
523
+ checkpoint: "CHECKPOINT",
524
+ /** 交接提醒(rebuild ≡ reconstruct 共用;2026-11-16 由 `limit`/`limitMandatory` 合并而来) */
525
+ handover: "HANDOVER",
526
+ /** 重建锚点头部(原 TRAJECTORY-REBUILD) */
527
+ rebuild: "REBUILD",
528
+ /** 敏感输出边界守卫(原 SERENITY OUTPUT GUARD) */
529
+ guard: "BOUNDARY GUARD",
530
+ /** SESSION.md 体积超限重写提醒(v1.31.1,S142 用户需求) */
531
+ compaction: "LOGBOOK COMPACTION"
532
+ };
533
+ /** 家族标识(所有动态注入统一前缀) */
534
+ const ASSISTANT_PREFIX = "COGNITIVE-TRAJECTORY-ASSISTANT";
535
+ /** 完整 token:`[COGNITIVE-TRAJECTORY-ASSISTANT · <LABEL>]` */
536
+ function eventToken(event) {
537
+ return `[${ASSISTANT_PREFIX} · ${EVENT_LABEL[event]}]`;
538
+ }
539
+ /** ACK 确认码前缀(recorded/skipped 语义不变,仅家族名更新) */
540
+ const ACK_PREFIX = `${ASSISTANT_PREFIX}-recorded`;
541
+ /**
542
+ * 交接便签的**落点**:`LOG/LOG.md` 里的节名(2026-11-16 owner 裁定)。
543
+ *
544
+ * ## 它取代了什么
545
+ * v1.49.0 曾把交界材料分家到**独立文件** `REBUILD-TODO.md`。v1.136.0 起 LOG 有了
546
+ * **机械轮转**(`carrier-log.ts`),于是那个独立文件成了第三种住处——而它要装的东西
547
+ * ("我卡在哪一步")本质是**过程留痕**,与 LOG 同性质、同寿命、同策展度。
548
+ * ⇒ 2026-11-16 owner 裁定:**整体删掉独立文件**,便签住进 LOG 的一节,
549
+ * 轮转时**整节搬运**进新代出生头(否则旧代冻结、新代空白 ⇒ 交接断开)。
550
+ *
551
+ * ## 🔴 三处引用同一常量(单一真相源)
552
+ * **写侧** = `seams/cognitive-trajectory-lifecycle.ts` 的 `handoverReminderText()`|**读侧** = `trajectory/rebuild.ts` 的重建锚点|
553
+ * **搬运** = `trajectory/carrier-log.ts` 的 `rotateCarrierLog()`。
554
+ * 节名一旦漂移,写侧写的东西读侧就找不到,**且没有任何机械信号会报警**。
555
+ */
556
+ const HANDOVER_NOTE_HEADING = "## Handover note";
557
+ /** 交接便签在 LOG 里的相对路径(给人读的提示用) */
558
+ const LOG_FILE_REL = "LOG/LOG.md";
559
+ /** 当前代的固定文件名。**名字即指针** —— 改成 A/B 双槽会引入"谁是当前"这个外部事实。 */
560
+ const LOG_FILE = "LOG.md";
561
+ /** 冻结日志的命名:`LOG-<YYYY-MM-DDTHHmm>.md`(**本地时区,分钟级**)。 */
562
+ function frozenLogName(now) {
563
+ const p = (n) => String(n).padStart(2, "0");
564
+ return `LOG-${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())}T${p(now.getHours())}${p(now.getMinutes())}.md`;
565
+ }
566
+ /**
567
+ * 判断一份日志内容是否"实质上为空"。
568
+ *
569
+ * 判据:去掉空行与**标题行**(`# …`)与引用块(`> …`)之后,还剩不剩字符。
570
+ * 🔴 为什么剔除标题与引用:出生头本身就是"标题 + 两行引用说明",
571
+ * 若按裸字节判非空,**刚开的新代立刻会被判为"有内容可冻结"** ⇒ 产生一堆只有出生头的垃圾归档。
572
+ */
573
+ function isEffectivelyEmpty(text) {
574
+ for (const line of text.split("\n")) {
575
+ const t = line.trim();
576
+ if (t === "") continue;
577
+ if (t.startsWith("#")) continue;
578
+ if (t.startsWith(">")) continue;
579
+ return false;
580
+ }
581
+ return true;
582
+ }
583
+ /** 列出已冻结的日志文件名(`LOG-*.md`),按名字升序(= 时间升序)。 */
584
+ function listFrozen(dir) {
585
+ if (!existsSync(dir)) return [];
586
+ let names;
587
+ try {
588
+ names = readdirSync(dir);
589
+ } catch {
590
+ return [];
591
+ }
592
+ return names.filter((n) => n.startsWith("LOG-") && n.endsWith(".md")).sort();
593
+ }
594
+ /**
595
+ * 从一份 LOG 正文里抽出 `## Handover note` 整节(含标题,到下一个同级或更高级标题为止)。
596
+ *
597
+ * 🔴 **为什么不抽就轮转 = 交接断开**:轮转把整份 `LOG.md` `mv` 成冻结代,新代是空白的。
598
+ * 若在办状态写在旧代里,新会话读新代 ⇒ **读不到** ⇒ 交接失败,且**没有任何报错**。
599
+ * 这与"便签必须被交接后的会话完整读到"是同一条判据(2026-11-16 owner 裁定)。
600
+ *
601
+ * @returns 该节全文(含标题、去掉尾部空行);没有该节 ⇒ `null`
602
+ */
603
+ function extractHandoverNote(text) {
604
+ const lines = text.split("\n");
605
+ const head = lines.findIndex((l) => l.trim() === HANDOVER_NOTE_HEADING);
606
+ if (head < 0) return null;
607
+ let end = lines.length;
608
+ for (let i = head + 1; i < lines.length; i++) {
609
+ const t = lines[i].trim();
610
+ if (t.startsWith("## ") || t.startsWith("# ")) {
611
+ end = i;
612
+ break;
613
+ }
614
+ }
615
+ const section = lines.slice(head, end);
616
+ while (section.length > 0 && section[section.length - 1].trim() === "") section.pop();
617
+ return section.join("\n");
618
+ }
619
+ /**
620
+ * 生成新一代 `LOG.md` 的出生头。
621
+ *
622
+ * ⚠️ **措辞归 CCC**:这里只给一个**可替换的默认模板**,各轨迹可以在自己的 PROMPT.md 里
623
+ * 声明别的写法(ACC 不解析它,只保证"新代存在且非空")。
624
+ *
625
+ * @param generation 代数(1 起)
626
+ * @param now 出生时刻
627
+ * @param previousFrozen 上一代冻结文件名(无则 null)
628
+ */
629
+ function birthHeader(generation, now, previousFrozen) {
630
+ const p = (n) => String(n).padStart(2, "0");
631
+ return [
632
+ `# LOG — generation ${generation} (born ${`${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())}T${p(now.getHours())}:${p(now.getMinutes())}`})`,
633
+ "",
634
+ previousFrozen === null ? "> First generation for this trajectory." : `> Previous generation frozen as: \`LOG/${previousFrozen}\``,
635
+ "> This file holds fine-grained process (how we tried, what broke, what we read).",
636
+ "> High-level abstraction lives in SESSION.md. The boundary is declared in PROMPT.md.",
637
+ ""
638
+ ].join("\n");
639
+ }
640
+ /**
641
+ * 轮转当前代 → 冻结,并开新代。
642
+ *
643
+ * 🔴 **顺序不可换**(每一步都防一个具体的静默失败):
644
+ * ① 判空:实质为空 ⇒ 不轮转(否则产生垃圾归档,代数不可信)
645
+ * ② 定名:目标已存在 ⇒ 加 `-2`/`-3`…(⛔ 覆盖 = 静默丢一代)
646
+ * ③ rename **之后**回读校验:字节数必须与轮转前相同
647
+ * ④ 开新代:新建空文件 → 写出生头
648
+ *
649
+ * @returns 轮转回执。**调用方必须检查 `verified`** —— rename 成功不等于目标对。
650
+ */
651
+ function rotateCarrierLog(trajectoryDir, now = /* @__PURE__ */ new Date()) {
652
+ const dir = join(trajectoryDir, "LOG");
653
+ const live = join(dir, LOG_FILE);
654
+ const skipped = {
655
+ rotated: false,
656
+ frozenAs: null,
657
+ bytesBefore: 0,
658
+ verified: false,
659
+ renamedFrom: null
660
+ };
661
+ if (!existsSync(live)) {
662
+ mkdirSync(dir, { recursive: true });
663
+ if (!existsSync(live)) writeFileSync(live, birthHeader(1, now, null), "utf-8");
664
+ return skipped;
665
+ }
666
+ const text = readFileSync(live, "utf-8");
667
+ if (isEffectivelyEmpty(text)) return skipped;
668
+ mkdirSync(dir, { recursive: true });
669
+ const bytesBefore = Buffer.byteLength(text, "utf-8");
670
+ const base = frozenLogName(now).replace(/\.md$/, "");
671
+ let target = `${base}.md`;
672
+ let renamedFrom = null;
673
+ if (existsSync(join(dir, target))) {
674
+ renamedFrom = target;
675
+ let n = 2;
676
+ while (existsSync(join(dir, `${base}-${n}.md`))) n++;
677
+ target = `${base}-${n}.md`;
678
+ }
679
+ const dst = join(dir, target);
680
+ if (existsSync(dst)) return skipped;
681
+ renameSync(live, dst);
682
+ const verified = existsSync(dst) && statSync(dst).size === bytesBefore;
683
+ if (!existsSync(live)) {
684
+ let header = birthHeader(listFrozen(dir).length + 1, now, target);
685
+ const note = extractHandoverNote(readFileSync(dst, "utf-8"));
686
+ if (note !== null) header += `${note}\n\n`;
687
+ writeFileSync(live, header, "utf-8");
688
+ }
689
+ return {
690
+ rotated: true,
691
+ frozenAs: target,
692
+ bytesBefore,
693
+ verified,
694
+ renamedFrom
695
+ };
696
+ }
697
+ //#endregion
698
+ //#region src/trajectory/rebuild.ts
699
+ var rebuild_exports = /* @__PURE__ */ __exportAll({
700
+ buildRebuildAnchor: () => buildRebuildAnchor,
701
+ performRebuild: () => performRebuild,
702
+ queueRebuild: () => queueRebuild,
703
+ registerRebuildTurnHook: () => registerRebuildTurnHook,
704
+ resolveSessionMdPath: () => resolveSessionMdPath,
705
+ sanitizeFocusLine: () => sanitizeFocusLine,
706
+ stripAckSuffix: () => stripAckSuffix
707
+ });
708
+ /** acknowledge 尾句(fake-initial-turns 的确认要求——rebuild 重建后不重走确认轮,直接继续) */
709
+ const ACK_SUFFIX_RE = /Please simply reply "acknowledge" — no action needed\.\s*$/;
710
+ /**
711
+ * 剥离假首轮消息的 acknowledge 尾句(rebuild 锚点保留协议正文但不要求确认回复)。
712
+ */
713
+ function stripAckSuffix(text) {
714
+ return text.replace(ACK_SUFFIX_RE, "").trimEnd();
715
+ }
716
+ /**
717
+ * 构建重建锚点消息(v1.22.4 定稿语义 + v1.22.5 保留协议正文):
718
+ * 「[TRAJECTORY-REBUILD] + fake-initial-turns 协议正文(去 acknowledge 尾句)+ 继续 {SESSION 名} 的工作」。
719
+ * v1.29.2(R1):可选 task focus 段——简短任务焦点文字传入重建后会话(不含历史,
720
+ * 历史完整在 SESSION.md;让重建后的自己第一时间理解本轮焦点,降低冷启动认知成本)。
721
+ * @param root - CCC 根
722
+ * @param sessionName - 当前 use 的宁静号 SESSION 名(如 S142);无激活则通用指令
723
+ * @param activeMdPath - 持久轨迹 SESSION.md 绝对路径(保持原位)
724
+ * @param protocolMessages - 协议正文消息序列(缺省 DEFAULT_FAKE_INITIAL_MESSAGES;可注入测试)
725
+ * @param focus - 可选任务焦点(单行化 + ≤200 字消毒;无则不输出 focus 段——向后兼容)
726
+ */
727
+ function buildRebuildAnchor(root, sessionName, activeMdPath, protocolMessages = DEFAULT_FAKE_INITIAL_MESSAGES, focus) {
728
+ const rel = activeMdPath.startsWith(root) ? activeMdPath.slice(root.length + 1) : activeMdPath;
729
+ const logDirAbs = join(dirname(activeMdPath), "LOG");
730
+ const logLiveAbs = join(logDirAbs, "LOG.md");
731
+ const logRel = logLiveAbs.startsWith(root) ? logLiveAbs.slice(root.length + 1) : logLiveAbs;
732
+ const sessionDir = basename(dirname(activeMdPath));
733
+ const sessionLine = sessionDir !== "AGENT_SESSIONS" ? `- Serenity session: ${sessionName !== "" ? `${sessionName} (${sessionDir})` : sessionDir}` : null;
734
+ const focusLine = sanitizeFocusLine(focus);
735
+ return [
736
+ `${eventToken("rebuild")} The conversation has been cleared and rebuilt (Ship of Theseus: the carrier is replaced, the cognitive trajectory continues).`,
737
+ "",
738
+ ...protocolMessages.flatMap((text) => [stripAckSuffix(text), ""]),
739
+ sessionName !== "" ? `Continue the work of ${sessionName}.` : "Continue the current work.",
740
+ ...sessionLine ? [sessionLine] : [],
741
+ `- Persistent cognitive trajectory — SESSION.md path: ${rel}`,
742
+ ` (the cognitive trajectory's persistent body — stays in place through rebuilds)`,
743
+ `- Read that SESSION.md first (goal/decisions/progress/unresolved), then continue from the last checkpoint.`,
744
+ `- Handover note: read ${logRel} first — "${HANDOVER_NOTE_HEADING}" in the current generation, and the previous generation's \`LOG-<stamp>.md\` if this handover froze it. The previous carrier wrote its in-flight step there before it was retired.`,
745
+ ...focusLine ? [`- Task focus: ${focusLine}`] : []
746
+ ].join("\n");
747
+ }
748
+ /**
749
+ * 任务焦点行消毒(纯函数可单测):单行化(换行/回车 → 空格)+ 控制字符清除 +
750
+ * ≤200 字截断。空/纯空白 → null(不输出 focus 段)。防 LLM 传多行注入伪造锚点结构。
751
+ */
752
+ function sanitizeFocusLine(focus) {
753
+ if (!focus) return null;
754
+ const single = focus.replace(/[\r\n\t]+/g, " ").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, "").trim();
755
+ if (single === "") return null;
756
+ return single.length <= FOCUS_MAX_CHARS ? single : single.slice(0, FOCUS_MAX_CHARS);
757
+ }
758
+ /** 任务焦点最大长度(字/码点;200 足够一句话任务焦点——非历史) */
759
+ const FOCUS_MAX_CHARS = 200;
760
+ /** 从会话 surface 首条 user 消息(重建锚点)解析 SESSION.md 路径(events 异常/缺失时的兜底) */
761
+ function parseAnchorMdPath(session) {
762
+ try {
763
+ const nodes = [...session.surface.nodes];
764
+ if (nodes.length === 0) return null;
765
+ const events = sessionEvents(session);
766
+ if (events.length === 0) return null;
767
+ const event = events[nodes[0]];
768
+ if (!event) return null;
769
+ const message = deriveEventMessage(event);
770
+ if (!message) return null;
771
+ const text = message.content?.map((c) => c.type === "text" ? c.text ?? "" : "").join("") ?? "";
772
+ return extractSessionMdPathFromText(text);
773
+ } catch {
774
+ return null;
775
+ }
776
+ }
777
+ /** 从 SESSION.md 绝对路径派生会话名(编码;issue 目录回退完整目录名) */
778
+ function sessionNameFromMdPath(mdPath) {
779
+ const dirName = basename(dirname(mdPath));
780
+ return parseTrajectoryCode(dirName) ?? dirName;
781
+ }
782
+ /**
783
+ * 稳固的 SESSION.md 定位(多层候选 + 存在性校验,**绝不输出虚假路径**):
784
+ * ① 内存活跃会话(本会话显式 use 过)→ ② events 恢复(use 标记 + 重建锚点规范行,进程重启后)
785
+ * → ②b **权威绑定**(`AGENT_SESSIONS/.bindings.json`,本会话持久绑定)→ ③ surface 首条锚点
786
+ * (events 异常时兜底)。
787
+ *
788
+ * v1.30.13(S142 用户"微信桥 + 轨迹约束会话锚定要准确",诊断 D4):**移除**原 ④「全局最新未完成
789
+ * 会话」(`findLatestActiveSessionMd`)。理由(R↓):④ 是**跨轨迹**猜测——候选①②③全空时,
790
+ * 它会把 rebuild 静默接到 AGENT_SESSIONS 里最新的另一个会话(临时 轨迹约束会话 persistent=false、
791
+ * 重启后首条消息前、新会话首条消息都命中该形态),而"接错轨迹"比重建失败危险得多
792
+ * (错误轨迹被继续写入 + 正确轨迹静默丢失)。现在全部候选失败 → 返回 null → 调用方
793
+ * 报错引导用户显式 `cognitive_trajectory use`(响亮失败优于静默接错)。
794
+ * 备选:④ 仅在"同 scope 确无绑定"时兜底——同样会接错轨迹,故不采纳。
795
+ *
796
+ * 每候选 resolve 后 existsSync 校验(相对路径按 root 解析);全部失败返回 null → 调用方报错引导。
797
+ */
798
+ function resolveSessionMdPath(root, scope, session) {
799
+ const candidates = [];
800
+ candidates.push(getActiveSessionInfo(scope)?.mdPath ?? null);
801
+ const events = sessionEvents(session);
802
+ if (events.length > 0) candidates.push(parseSessionContextFromEvents(events)?.mdPath ?? null);
803
+ candidates.push(readLastBound(session)?.mdPath ?? null);
804
+ candidates.push(parseAnchorMdPath(session));
805
+ for (const c of candidates) {
806
+ if (!c) continue;
807
+ const abs = c.startsWith(root) ? c : resolve(root, c);
808
+ if (existsSync(abs)) return abs;
809
+ }
810
+ return null;
811
+ }
812
+ const pendingRebuilds = /* @__PURE__ */ new Map();
813
+ /** 陈旧队列存活时长(毫秒):超过则丢弃(turn 异常结束/agent 崩溃时防残留误清空) */
814
+ const PENDING_TTL_MS = 6e5;
815
+ let diagState = {
816
+ lastTs: "",
817
+ lastSessionId: "",
818
+ lastEvent: "",
819
+ queueCount: 0,
820
+ rebuiltCount: 0,
821
+ droppedCount: 0,
822
+ failedCount: 0
823
+ };
824
+ function writeRebuildDiag(root, entry) {
825
+ try {
826
+ const dir = join(root, "AGENT_SESSIONS");
827
+ mkdirSync(dir, { recursive: true });
828
+ const file = join(dir, ".rebuild-diag.json");
829
+ const s = diagState;
830
+ if (entry.event === "queued") s.queueCount += 1;
831
+ if (entry.event === "rebuilt") s.rebuiltCount += 1;
832
+ if (entry.event === "ttl-dropped") s.droppedCount += 1;
833
+ if (entry.event === "failed") s.failedCount += 1;
834
+ s.lastTs = isoLocal();
835
+ s.lastSessionId = entry.sessionId;
836
+ s.lastEvent = entry.event;
837
+ s.detail = entry.detail;
838
+ writeFileSync(file, JSON.stringify(s, null, 2) + "\n", "utf-8");
839
+ } catch {}
840
+ }
841
+ /**
842
+ * 排队一次重建(v1.22.4 定稿语义第一步):
843
+ * ① 门控校验(rebuild.enabled + 会话定位)
844
+ * ② 构建锚点(激活会话名 + 持久轨迹路径)
845
+ * ③ 写入 pending 队列——**不立即改 surface**(等 turn-stopping 执行)
846
+ * @returns 排队结果;rebuild.enabled=false 或非 CCC 抛错
847
+ */
848
+ async function queueRebuild(ctx, opts) {
849
+ const { root, note, summary, dshSessionId } = opts;
850
+ const session = ctx.sessions?.get?.(dshSessionId);
851
+ if (!session) throw new Error(`Unable to locate dsh session ${dshSessionId} (session may be closed)`);
852
+ const mdPath = resolveSessionMdPath(root, dshSessionId, session);
853
+ if (!mdPath) throw new Error("Unable to determine the active SESSION.md for this session — checked (in order): in-memory activation (cognitive_trajectory use in this process), [SESSION CONTEXT] events in this conversation, AGENT_SESSIONS/.bindings.json (authoritative binding), rebuild anchor in the surface. None matched an existing SESSION.md. Run \"cognitive_trajectory use <S###> --summary <one-line summary, ≤20 chars>\" to bind this conversation to a cognitive trajectory, then retry cognitive_trajectory rebuild. (No global fallback is applied on purpose — guessing could resume a different cognitive trajectory.)");
854
+ const sessionName = getActiveSessionInfo(dshSessionId)?.sessionId ?? sessionNameFromMdPath(mdPath);
855
+ const focus = note && note.trim() !== "" ? note : void 0;
856
+ const anchor = buildRebuildAnchor(root, sessionName, mdPath, DEFAULT_FAKE_INITIAL_MESSAGES, focus);
857
+ const boundRec = {
858
+ dirName: basename(dirname(mdPath)),
859
+ mdPath,
860
+ note: "rebuild queued"
861
+ };
862
+ appendBound(session, "rebuild", boundRec);
863
+ try {
864
+ const rot = rotateCarrierLog(dirname(mdPath));
865
+ if (rot.rotated) {
866
+ if (!rot.verified) console.warn(`[serenity-hooks] ⚠️ LOG 轮转回读校验失败:${rot.frozenAs} 的字节数不等于轮转前的 ${rot.bytesBefore} B。 rebuild 照常进行;请人工核对 LOG/ 目录。`);
867
+ else console.log(`[serenity-hooks] ✓ LOG 轮转:${rot.bytesBefore} B → LOG/${rot.frozenAs}(回读校验通过)` + (rot.renamedFrom !== null ? `;原定名 ${rot.renamedFrom} 已存在 ⇒ 改名避让(⛔ 未覆盖)` : ""));
868
+ }
869
+ } catch (e) {
870
+ console.warn(`[serenity-hooks] ⚠️ LOG 轮转未执行(${e.message})—— rebuild 不受影响`);
871
+ }
872
+ pendingRebuilds.set(dshSessionId, {
873
+ anchor,
874
+ summary,
875
+ mdPath,
876
+ focus,
877
+ queuedAt: Date.now()
878
+ });
879
+ writeRebuildDiag(root, {
880
+ sessionId: dshSessionId,
881
+ event: "queued"
882
+ });
883
+ return {
884
+ queued: true,
885
+ anchor,
886
+ sessionMdPath: mdPath
887
+ };
888
+ }
889
+ /**
890
+ * 执行真正的 surface replace(v1.22.4 定稿语义第二步,turn-stopping 时调用):
891
+ * 当前 turn 已完整结束(所有 tool/result 已 append)→ 全部节点替换为锚点消息。
892
+ * 同一会话 id 原地重建——同工作区天然满足,无新/旧会话之分。
893
+ *
894
+ * **shadow-price 协议(v1.23.5 修复,S142 用户问询)**:DSH token-meter 的
895
+ * `foldSurfaceProjection` 对 surface `replace` 要求**紧邻其前的 metering 事件**
896
+ * (`compaction/summary` 或 `compaction/prune`)声明被替换范围的启发式 token 价,
897
+ * 否则 claim 缺失 → `deltaTokens=0` → `contextBreakdown.messageTokens` 永不扣减
898
+ * → UI「对话消息」虚高累计、往复 rebuild 计量爆炸(用户截图实证:总 15% 但
899
+ * 对话消息 ~1M)。官方先例 = `compaction-tool-result-pruner`(append
900
+ * `compaction/prune` → 紧接 replace)。此处同款:先 append `compaction/prune`
901
+ * (定价全部被替换节点,经 ctx.tokenMeter.estimateMessage 逐节点累加),再
902
+ * append 锚点 replace——meter 不可用时退化(无 claim,仅计量漂移,会话功能不受影响)。
903
+ *
904
+ * @returns 是否执行了 replace(false = 无 pending 或 surface 空)
905
+ */
906
+ function performRebuild(session, pending, meter) {
907
+ const nodes = [...session.surface.nodes];
908
+ if (nodes.length === 0) return false;
909
+ /**
910
+ * v1.31.8 二次修正(0.1.5-rc.1 实证,diag 原文):
911
+ * `surface replace: node 0 holds the system prompt and may be rewritten only by a
912
+ * system/message over exactly that node`(宿主 `dsh-session/lib/types/surface.js`
913
+ * `assertSystemHeadRewrite`)。
914
+ *
915
+ * → **surface node 0 是系统提示节点且被宿主保护**;而重建的语义恰恰是"保留系统提示、
916
+ * 只清对话历史",故替换范围必须从 **node 1** 起。(旧实现整体替换 `nodes[0..last]`,
917
+ * 在 0.1.5 上必被拒——这是 §14 之后的第二条 rebuild 阻断规则。)
918
+ */
919
+ const targets = nodes.slice(1);
920
+ if (targets.length === 0) return false;
921
+ if (meter) {
922
+ let shadowedTokenCount = 0;
923
+ const events = sessionEvents(session);
924
+ for (const seq of targets) {
925
+ const event = events[seq];
926
+ if (!event) continue;
927
+ const message = deriveEventMessage(event);
928
+ if (message) shadowedTokenCount += meter.estimateMessage(message);
929
+ }
930
+ session.append("compaction/prune", {
931
+ shadowedRange: {
932
+ start: targets[0],
933
+ end: targets[targets.length - 1]
934
+ },
935
+ shadowedSeqs: targets,
936
+ shadowedTokenCount
937
+ });
938
+ }
939
+ session.append("user/message", {
940
+ /**
941
+ * v1.31.13 修复(**会话打不开的真因**,S142 §26):
942
+ * `user/message` 的 payload 必须是**完整 UserMessage**——宿主
943
+ * `dsh-session/lib/types/index.js:229-259` `assertMessageEventShape` 对四种消息事件
944
+ * (system/user/assistant/message + tool/result)强制:
945
+ * `data.id` 非空字符串 → 否则 `"<subject> lacks an identified message"`
946
+ * `data.role === 'user'` → 否则 `"<subject> message must have role \"user\""`
947
+ * 而 `user/message` 的 message **就是 data 本身**(`type==='user/message' ? record : record.message`)。
948
+ *
949
+ * 旧实现只写 `{content, source}`(缺 `id` 与 `role`)→ 该事件**当场落盘成功**,
950
+ * 但宿主在**下一次打开该会话**时整份日志校验失败抛 `SessionPersistenceCorruptionError`
951
+ * → **会话永久打不开**(用户报的"会话老是损坏")。实证见 S142 §26.2(真实日志 seq 5066)。
952
+ * 正确形状与 `seams/bootstrap.ts:306-311` 的锚定消息一致。
953
+ *
954
+ * 🔴 **DII M2 · 注入点 #10**(2026-11-04):**这一处是 I1 最需要被看见的一格**。
955
+ * 它是 ACC 产的消息(`origin:'acc'`),但宿主校验**强制**要求 `kind:'user'`
956
+ * (缺了它会话打不开,见上)。⇒ 旧的 `source: { kind: 'user' }` 是**没办法的办法**:
957
+ * 它丢掉了"谁产生的"这一信息。现在 `Injection` 记着 `origin:'acc'`,语料/语录
958
+ * 那一侧(M3)就能按 `origin` 正确排除它 —— **不必再靠正文标记猜**。
959
+ * ⚠️ **宿主 kind 仍是 `'user'`,一字不改**:这一格只把"我是谁"补回来,不改落点。
960
+ */
961
+ id: `rebuild-anchor-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
962
+ role: "user",
963
+ content: [{
964
+ type: "text",
965
+ text: pending.anchor
966
+ }],
967
+ source: REBUILD_ANCHOR_SOURCE
968
+ }, {
969
+ surfaceOp: {
970
+ op: "replace",
971
+ startSeq: targets[0],
972
+ endSeq: targets[targets.length - 1]
973
+ },
974
+ sourceEventSeqs: targets
975
+ });
976
+ return true;
977
+ }
978
+ const REBUILD_ANCHOR_SOURCE = { kind: "user" };
979
+ /**
980
+ * 重建后重命名 dsh 会话标题(需求② S142 用户拍板:rebuild 后标题带新阶段概括)。
981
+ * 标题 = S###-YYYY-MM-DD-<summary>——S### 与日期从持久轨迹目录名派生(不信任 LLM),
982
+ * 概括来自 queueRebuild 的 summary 参数(服务端清洗截断)。
983
+ * 失败仅 warn 不阻断重建主流程(标题美观非关键路径)。
984
+ */
985
+ function renameAfterRebuild(ctx, agent, pending) {
986
+ try {
987
+ const mdPath = pending.mdPath;
988
+ const dirName = basename(dirname(mdPath));
989
+ const info = {
990
+ sessionId: parseTrajectoryCode(dirName) ?? dirName.replace(/^\d{4}-\d{2}-\d{2}--/, ""),
991
+ dirName,
992
+ mdPath
993
+ };
994
+ const title = namingTitleFor(info, pending.summary);
995
+ const titles = hostService(ctx, "sessionTitle");
996
+ if (!titles || typeof titles.rename !== "function") {
997
+ console.warn("[serenity-hooks] rebuild 后重命名跳过: sessionTitle 服务不可用");
998
+ return;
999
+ }
1000
+ titles.rename(agent.session, title);
1001
+ console.log(`[serenity-hooks] rebuild 后会话重命名: ${agent.id} → ${title}`);
1002
+ } catch (error) {
1003
+ console.warn(`[serenity-hooks] rebuild 后重命名失败(不阻断): ${String(error?.message ?? error)}`);
1004
+ }
1005
+ }
1006
+ /**
1007
+ * 注册 turn-stopping 钩子(index.ts apply 调用):
1008
+ * agent 每轮 turn 结束前(serial)检查 pending 队列——有该会话的重建请求 → 执行清空
1009
+ * 并 **steer 自动继续**(v1.22.5:next-step 非空 → turn 不 break → 模型自动读取
1010
+ * SESSION.md 继续,无需用户手工输入;DSH 官方先例 hooks-claude-code Stop hook)。
1011
+ * 陈旧队列(超 TTL)丢弃防误清空;无 pending 零开销。
1012
+ */
1013
+ function registerRebuildTurnHook(ctx) {
1014
+ ctx.on("agent/turn-stopping", (payload) => {
1015
+ const agent = payload?.agent;
1016
+ if (!agent) return;
1017
+ const id = agent.id;
1018
+ const pending = pendingRebuilds.get(id);
1019
+ if (pending === void 0) return;
1020
+ if (Date.now() - pending.queuedAt > PENDING_TTL_MS) {
1021
+ pendingRebuilds.delete(id);
1022
+ writeRebuildDiag(resolveSerenityRootFor(agent), {
1023
+ sessionId: id,
1024
+ event: "ttl-dropped",
1025
+ detail: `queuedAt=${isoLocal(pending.queuedAt)} older than ${PENDING_TTL_MS / 6e4}min TTL — turn did not end in time`
1026
+ });
1027
+ return;
1028
+ }
1029
+ pendingRebuilds.delete(id);
1030
+ try {
1031
+ const tokenMeter = hostService(ctx, "tokenMeter");
1032
+ const meter = tokenMeter && typeof tokenMeter.estimateMessage === "function" ? { estimateMessage: (m) => tokenMeter.estimateMessage(m) } : void 0;
1033
+ if (performRebuild(agent.session, pending, meter)) {
1034
+ renameAfterRebuild(ctx, agent, pending);
1035
+ deliver(makeInjection({
1036
+ origin: "acc",
1037
+ form: "instructions",
1038
+ summary: "rebuild 后自动继续",
1039
+ text: `${eventToken("rebuild")} The conversation has been cleared and rebuilt. Follow the anchor instructions above now: read the persistent cognitive trajectory (SESSION.md) and continue the work automatically from the last checkpoint.`,
1040
+ delivery: "wake-now"
1041
+ }), agent);
1042
+ writeRebuildDiag(resolveSerenityRootFor(agent), {
1043
+ sessionId: id,
1044
+ event: "rebuilt"
1045
+ });
1046
+ console.log(`[serenity-hooks] cognitive_trajectory rebuild executed with auto-continue (turn ${payload.turn ?? "?"} ended): ${id}`);
1047
+ } else writeRebuildDiag(resolveSerenityRootFor(agent), {
1048
+ sessionId: id,
1049
+ event: "empty-surface"
1050
+ });
1051
+ } catch (error) {
1052
+ const msg = String(error?.message ?? error);
1053
+ writeRebuildDiag(resolveSerenityRootFor(agent), {
1054
+ sessionId: id,
1055
+ event: "failed",
1056
+ detail: msg
1057
+ });
1058
+ console.warn(`[serenity-hooks] cognitive_trajectory rebuild failed: ${msg}`);
1059
+ }
1060
+ });
1061
+ }
1062
+ /**
1063
+ * 从 agent 会话 cwd 解析 CCC 根(诊断落盘用);无则回退进程 cwd。
1064
+ *
1065
+ * ⚠️ **语义与 `cccRootForExec` 不同且必须不同**:这里 `?? process.cwd()` 是**返回假根**
1066
+ * (诊断落盘总要有个位置,没有根也要写),而工具/缝入口要的是 `null`(让调用方报错)。
1067
+ * C2 归一后此处仍保留该差异,只把"取 cwd"那半交给 `agentCwdFor`(现状稿 §2.D 第 7 条)。
1068
+ */
1069
+ function resolveSerenityRootFor(agent) {
1070
+ return cccRootForCwd(agentCwdFor(agent)) ?? process.cwd();
1071
+ }
1072
+ //#endregion
1073
+ export { ACK_PREFIX as a, eventToken as c, resolveSessionMdPath as i, DEFAULT_FAKE_INITIAL_MESSAGES as l, rebuild_exports as n, ASSISTANT_PREFIX as o, registerRebuildTurnHook as r, LOG_FILE_REL as s, buildRebuildAnchor as t, registerBootstrap as u };