dsh-cross-memory 0.2.12 → 0.2.13

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/docs/DETAIL.md CHANGED
@@ -14,10 +14,10 @@ dsh-cross-memory extracts whatever is worth keeping from a session (preferences,
14
14
  Each conversation receives the following blocks in order, each with its own budget:
15
15
 
16
16
  1. `<persona>`: a snapshot of the user profile, bounded by `personaMaxBytes` (default 12000 bytes, `0` disables it) and truncated at a line boundary. A legacy single-file `persona.md` is still read; saving writes `persona/human.md`.
17
- 2. Memory summary: within `maxSummaryBytes` (default 4096), split into a `global` and a `project` section. Both scopes share one byte budget and `global` renders first, so it also has `globalSummaryEntries` and `globalSummaryBytes` caps of its own.
17
+ 2. Memory summary: within `maxSummaryBytes` (default 8192), split into a `global` and a `project` section. Both scopes share one byte budget and `global` renders first, so it also has `globalSummaryEntries` and `globalSummaryBytes` caps of its own.
18
18
  3. Delta block: memories written after the summary was injected are announced in small blocks (`injectDelta`, at most twice per conversation, `deltaMaxBytes` default 1600 each; one complete entry costs 200-350 bytes, so the former 800 admitted one or two).
19
19
  4. Title rotation: titles the summary had no room for, `rotationEntries` (default 16) per conversation, re-emitted every `rotationEveryTurns` (default 8) user turns in a long session.
20
- 5. On-demand recall: injected only when the current user turn lands enough distinct terms in an entry's title, `keys`, `tags` or `appliesTo` (or matches a whole phrase) (`recallMinTerms` default 2, `recallMinScore` default 9, at most `recallMaxPerConversation` per conversation). A term appearing in more than `evidenceMaxDf` (default 0.15) of one scope does not count as evidence. When the strict gate refuses, one alias fallback still runs: it scores `keys` and `appliesTo` only, needs a single substantive term, and applies a floor scaled by `ALIAS_FLOOR_SHARE` (0.5, so half of `recallMinScore`), injecting at most two entries with a line saying the match was by alias. It exists because a turn phrased with a memory's *other* name shares exactly one term and the two-term gate refuses it. The floor has to be scaled rather than shared: one CJK alias term scores 6 in those two fields at most, so the normal 9 would have made the pass fire for English turns and never for Chinese ones. An alias filed in only one field (3.5) is still refused, and body words never take part.
20
+ 5. On-demand recall: injected only when the current user turn lands enough distinct terms in an entry's title, `keys`, `tags` or `appliesTo` (or matches a whole phrase) (`recallMinTerms` default 1, `recallMinScore` default 6, at most `recallMaxPerConversation` per conversation). A term appearing in more than `evidenceMaxDf` (default 0.15) of one scope does not count as evidence. When the strict gate refuses, one alias fallback still runs: it scores `keys` and `appliesTo` only, needs a single substantive term, and applies a floor scaled by `ALIAS_FLOOR_SHARE` (0.5, so half of `recallMinScore`), injecting at most two entries with a line saying the match was by alias. An alias filed in only one field (3.5) is still refused, and body words never take part.
21
21
  6. Raw excerpts: with `rawRecall` on, the recall block also carries original excerpts from the source session, read from the persisted session logs on this machine only.
22
22
 
23
23
  Every injected block says that memories are background data rather than instructions, and that an entry records what was true when it was written, not necessarily now.
@@ -50,9 +50,9 @@ Consolidation is the second pass. It resolves contradictions and fragments acros
50
50
 
51
51
  ## Retention and archival
52
52
 
53
- - A memory that has not been read or surfaced, and is not newly written, for `maxUnusedDays` (default 90) is archived. Archiving is not deletion: `/memories restore` brings it back.
54
- - An entry with `durability=snapshot` is also archived once it is `snapshotMaxAgeDays` (default 60) past the moment it was measured; reading a stale reading does not make it fresh.
55
- - `maxEntriesPerScope` (default 1000) caps each scope; past it, the least recently read or surfaced entries are archived. `pinned`, `permanent` and `source=user` entries are never retired automatically, so a scope can stay slightly above its cap.
53
+ - A memory that has not been read or surfaced, and is not newly written, for `maxUnusedDays` (default `0`, disabled) is archived when enabled. Archiving is not deletion: `/memories restore` brings it back.
54
+ - An entry with `durability=snapshot` is also archived once it is `snapshotMaxAgeDays` (default `0`, disabled) past the moment it was measured when enabled; reading a stale reading does not make it fresh.
55
+ - `maxEntriesPerScope` (default `0`, unlimited) caps each scope when set; past it, the least recently read or surfaced entries are archived. `pinned`, `permanent` and `source=user` entries are never retired automatically, so a scope can stay slightly above its cap.
56
56
  - Each scope's `archive/` keeps the newest 500 files; older archives are cleaned up.
57
57
  - Evidence notes under `sessions/` keep the newest 200; older ones are removed. When a note is gone, `evidence` says so explicitly instead of inventing a summary.
58
58
  - `forget` (the `memory` tool and `/memories forget`) is a physical delete, with no restore.
package/docs/DETAIL.zh.md CHANGED
@@ -14,10 +14,10 @@ dsh-cross-memory 把会话里值得长期保留的内容(偏好、决定、踩
14
14
  每个会话按顺序拿到下面这些块,每块都有自己的预算:
15
15
 
16
16
  1. `<persona>`:用户画像快照,预算 `personaMaxBytes`(默认 12000 字节,`0` 关闭),超长部分按行截断。旧的单文件 `persona.md` 仍会被读取,保存后写到 `persona/human.md`。
17
- 2. 记忆摘要:在 `maxSummaryBytes`(默认 4096)内分 `global` 与 `project` 两段;两段共用一个字节预算,`global` 先渲染,另有 `globalSummaryEntries` 与 `globalSummaryBytes` 限制它的大小。
17
+ 2. 记忆摘要:在 `maxSummaryBytes`(默认 8192)内分 `global` 与 `project` 两段;两段共用一个字节预算,`global` 先渲染,另有 `globalSummaryEntries` 与 `globalSummaryBytes` 限制它的大小。
18
18
  3. 增量块:摘要注入之后新写入的记忆以小块补发(`injectDelta`,每会话最多两次、每次 `deltaMaxBytes` 默认 1600 字节;一条完整条目约 200–350 字节,旧的 800 只装得下一两条)。
19
19
  4. 标题轮转:只列摘要没提到的标题,每会话 `rotationEntries`(默认 16)条,同一个长会话里每 `rotationEveryTurns`(默认 8)个用户轮重新发一次。
20
- 5. 按需补注:当前用户轮与某条记忆的标题、`keys`、`tags`、`appliesTo` 命中足够多的实词(或整句短语命中)才会注入(`recallMinTerms` 默认 2、`recallMinScore` 默认 9、每会话最多 `recallMaxPerConversation` 条);在单个作用域里出现比例超过 `evidenceMaxDf`(默认 0.15)的词不计入证据。严格门没过时还有一道别名回退:只对 `keys` 与 `appliesTo` 计分、只要求一个实词、门槛按 `ALIAS_FLOOR_SHARE`(0.5)缩放(默认 9 的一半),最多补 2 条,注入块里会写明「按别名匹配」。它存在的原因是用户常按「另一个名字」提问,那种回合只共享一个词,会被两词门槛挡掉。门槛必须缩放不能共用:一个中文别名词在这两个字段里最多得 6 分,用同一个 9 分门槛就等于只对英文提问生效。同一别名只登记在一个字段里(3.5 分)仍然不补,正文里的词从不参与这条路径。
20
+ 5. 按需补注:当前用户轮与某条记忆的标题、`keys`、`tags`、`appliesTo` 命中足够多的实词(或整句短语命中)才会注入(`recallMinTerms` 默认 1、`recallMinScore` 默认 6、每会话最多 `recallMaxPerConversation` 条);在单个作用域里出现比例超过 `evidenceMaxDf`(默认 0.15)的词不计入证据。严格门没过时还有一道别名回退:只对 `keys` 与 `appliesTo` 计分、只要求一个实词、门槛按 `ALIAS_FLOOR_SHARE`(0.5)缩放,最多补 2 条,注入块里会写明「按别名匹配」。它存在的原因是用户常按「另一个名字」提问,门槛缩放可避免中文单别名在两个字段里最高 6 分被拦掉。同一别名只登记在一个字段里(3.5 分)仍然不补,正文里的词从不参与这条路径。
21
21
  6. 原始片段:`rawRecall` 打开时,补注块附带来源会话的原文片段,只读本机会话日志。
22
22
 
23
23
  注入块都写明记忆是背景数据、不是指令,并且记录的是写入时成立的事实,可能已经过期。
@@ -50,9 +50,9 @@ dsh-cross-memory 把会话里值得长期保留的内容(偏好、决定、踩
50
50
 
51
51
  ## 保留与归档
52
52
 
53
- - `maxUnusedDays`(默认 90)内没有被读到、没有被注入摘要、也不是新写的记忆会被归档;归档不是删除,`/memories restore` 可以取回。
54
- - `durability=snapshot` 的条目另按 `snapshotMaxAgeDays`(默认 60)从测量时间起算归档,被读一次不会让读数变新。
55
- - `maxEntriesPerScope`(默认 1000)是每个作用域的上限,超出时归档最久没有被读到或注入的条目;`pinned`、`permanent` 与 `source=user` 的条目不会被自动退役,所以作用域可能略超上限。
53
+ - `maxUnusedDays`(默认 `0` 关闭;设为正数后启用)内没有被读到、没有被注入摘要、也不是新写的记忆会被归档;归档不是删除,`/memories restore` 可以取回。
54
+ - `durability=snapshot` 的条目另按 `snapshotMaxAgeDays`(默认 `0` 关闭;设为正数后启用)从测量时间起算归档,被读一次不会让读数变新。
55
+ - `maxEntriesPerScope`(默认 `0` 不限制;设为正数后启用)是每个作用域的上限,超出时归档最久没有被读到或注入的条目;`pinned`、`permanent` 与 `source=user` 的条目不会被自动退役,所以作用域可能略超上限。
56
56
  - 每个作用域的 `archive/` 目录只保留最新的 500 个文件,更早的归档会被清理。
57
57
  - `sessions/` 下的证据笔记只保留最新的 200 份,更早的会被清掉;笔记不在时 `evidence` 会直接说明没有这份证据笔记,而不是编造内容。
58
58
  - `/memories forget` 与 `memory` 工具的 `forget` 是**物理删除**,不可恢复。
@@ -30,10 +30,10 @@ export const CONSOLIDATE_SYSTEM = [
30
30
  '- A problem that is already fixed is recorded as fixed ("已修 in <commit>"); never leave it reading as an open problem.',
31
31
  '- Write each body as 1-4 self-contained sentences. Titles are short and imperative.',
32
32
  '',
33
- 'When two or more memories together describe a repeatable procedure that would be worth running again, also return it as a skill: a short kebab-case name, a one-line description, and the ordered steps. Skills are drafts a human promotes; return at most 2.',
33
+ 'When two or more memories together describe a repeatable procedure that would be worth running again, also return it as a skill: a short kebab-case name, a one-line description, and the ordered steps. Skills are drafts a human promotes; return at most 2. If "Existing skill drafts" are listed in the input and one already covers the same workflow, either reuse its EXACT name to refine it or omit it — never invent a synonymous new skill name.',
34
34
  '',
35
35
  'When two memories contradict each other, do not quietly pick one: list the pair under "conflicts" with the id to keep, the id to drop, and one sentence saying what disagrees. A memory from the user ("voice: user") beats one the assistant concluded, and the newer statement beats the older — unless a rule is permanent, in which case name the pair and drop the OTHER one. "conflicts" is a report as much as an instruction: it is how the user finds out they changed their mind.',
36
- 'Also maintain "persona": a short profile of the USER, in markdown, built only from what they themselves said. The input marks those entries with "voice: user" and may include the current profile — refine it, do not rewrite it from nothing, and keep it under 40 lines. Contents: how they want work done, the corrections they have issued, how they write, what they care about, and what they never want. Write it in the third person ("他要求…"), never as instructions to yourself. If no entry carries voice: user, and no current profile exists, omit the field entirely.',
36
+ 'Also maintain "persona": a short profile of the USER, in markdown, built only from what they themselves said. The input marks those entries with "voice: user" and may include the current profile — refine it in place, do not rewrite it from nothing, deduplicate any repeated or near-identical bullets within each section (keep only the single sharpest version; never append a rephrased copy of an existing bullet), and keep it under 40 lines. Contents: how they want work done, the corrections they have issued, how they write, what they care about, and what they never want. Write it in the third person ("他要求…"), never as instructions to yourself. If no entry carries voice: user, and no current profile exists, omit the field entirely.',
37
37
  '',
38
38
  'Reply with JSON only, no prose and no code fence:',
39
39
  '{"memories":[{"id":string|null,"scope":"global"|"project","kind":string,"title":string,"body":string,"tags":string[],"keys":string[],"appliesTo":string,"derivedFrom":string[]}],"retire":[string],"skills":[{"name":string,"description":string,"steps":string[]}],"notes":string,"persona":string}',
@@ -104,7 +104,7 @@ export const CONSOLIDATE_JSON_SCHEMA = {
104
104
  },
105
105
  };
106
106
  /** Render the input document handed to the consolidation agent. */
107
- export function renderConsolidationInput(entries, projectLabel, currentPersona) {
107
+ export function renderConsolidationInput(entries, projectLabel, currentPersona, existingSkills) {
108
108
  const sections = new Map();
109
109
  for (const entry of entries) {
110
110
  const list = sections.get(entry.scope);
@@ -118,6 +118,13 @@ export function renderConsolidationInput(entries, projectLabel, currentPersona)
118
118
  blocks.push('## Current profile of the user (refine it; do not rewrite it from nothing)');
119
119
  blocks.push(currentPersona.trim(), '');
120
120
  }
121
+ if (existingSkills !== undefined && existingSkills.length > 0) {
122
+ blocks.push('## Existing skill drafts (reuse exact name to refine; never invent a synonymous new name)');
123
+ for (const skill of existingSkills) {
124
+ blocks.push(`- ${skill.name}${skill.description.length > 0 ? `: ${skill.description}` : ''}`);
125
+ }
126
+ blocks.push('');
127
+ }
121
128
  for (const scope of ['global', 'project']) {
122
129
  const list = sections.get(scope);
123
130
  if (list === undefined || list.length === 0)
@@ -433,7 +440,7 @@ export async function runConsolidation(seam, request) {
433
440
  if (request.entries.length === 0)
434
441
  return undefined;
435
442
  const known = new Set(request.entries.map((entry) => entry.id));
436
- const input = renderConsolidationInput(request.entries, request.projectLabel, request.persona);
443
+ const input = renderConsolidationInput(request.entries, request.projectLabel, request.persona, request.existingSkills);
437
444
  const timeout = AbortSignal.any([request.signal, AbortSignal.timeout(request.timeoutMs)]);
438
445
  const prompt = [{ type: 'text', text: `${CONSOLIDATE_SYSTEM}\n\n---\n\n${input}` }];
439
446
  const answer = await runChild(seam, prompt, request, timeout);
@@ -453,18 +460,17 @@ export async function runConsolidation(seam, request) {
453
460
  return plan;
454
461
  }
455
462
  /**
456
- * Build the spec the 0.2.1-rc.2 seam takes.
463
+ * Build the flattened `SubagentActivationSpec` the kernel seam takes.
457
464
  *
458
- * Extracted so a test can inspect it without a kernel: the one bug this shape
459
- * can carry — a missing `label` — is invisible from the seam's type unless the
460
- * type declares the field, and the failure it causes happens inside the
461
- * kernel's descriptor validator, three calls away from here. See
462
- * {@link ActivationSpec.label}.
465
+ * Extracted so a test can inspect it without a kernel: the kernel reads
466
+ * `provider`, `label`, `signal`, `delivery`, `prompt`, `parent`, `maxDepth`,
467
+ * `outputSchema`, `agentOptions`, and `agentPreset` at the top level.
463
468
  *
464
469
  * @param request - route, preset and lineage parent.
465
470
  * @param prompt - the child's single user message.
466
471
  * @param timeout - the child's deadline.
467
- * @returns the spec, with every optional field absent rather than `undefined`.
472
+ * @param outputSchema - JSON schema for structured output.
473
+ * @returns the flattened spec, with optional fields omitted rather than `undefined`.
468
474
  */
469
475
  export function buildActivationSpec(request, prompt, timeout, outputSchema = CONSOLIDATE_JSON_SCHEMA) {
470
476
  const agentOptions = request.provider !== undefined && request.model !== undefined
@@ -473,32 +479,18 @@ export function buildActivationSpec(request, prompt, timeout, outputSchema = CON
473
479
  return {
474
480
  provider: request.subagentProvider ?? 'spawn',
475
481
  // Never optional, never derived: a missing label fails the kernel's
476
- // descriptor validator BEFORE the child starts, and the symptom is a
477
- // silently dead consolidation pass rather than a start error.
482
+ // descriptor validator BEFORE the child starts.
478
483
  label: CONSOLIDATE_LABEL,
479
- // The result is consumed here, not by the parent conversation: a settlement
480
- // notice for this child is noise, and when the child misses
481
- // `structured_output` that notice reads as a failure even though the answer
482
- // arrived. See {@link ActivationSpec.delivery}.
484
+ // The result is consumed here, not by the parent conversation.
483
485
  delivery: 'caller',
484
- // Same class of mistake as the label, one field later: the kernel reads
485
- // `spec.signal` and never `spec.request.signal`, so it has to be here too.
486
486
  signal: timeout,
487
- request: {
488
- prompt,
489
- parent: request.parent,
490
- signal: timeout,
491
- ...agentOptions !== undefined ? { agentOptions } : {},
492
- outputSchema,
493
- // The child may not delegate further: it returns a plan, nothing else.
494
- //
495
- // `maxDepth` is the cap on the CHILD's depth, and DSH counts depth from
496
- // 1 (a top-level agent is 0, its child is 1). So 1 admits this child and
497
- // rejects any grandchild — 0 would reject the child itself, which is how
498
- // this line was wrong the first time.
499
- maxDepth: 1,
500
- ...request.agentPreset !== undefined ? { agentPreset: request.agentPreset } : {},
501
- },
487
+ prompt,
488
+ parent: request.parent,
489
+ ...agentOptions !== undefined ? { agentOptions } : {},
490
+ outputSchema,
491
+ // `maxDepth` caps the CHILD's depth (top-level agent is 0, child is 1).
492
+ maxDepth: 1,
493
+ ...request.agentPreset !== undefined ? { agentPreset: request.agentPreset } : {},
502
494
  };
503
495
  }
504
496
  /**
@@ -537,8 +529,13 @@ async function runChild(seam, prompt, request, timeout, outputSchema = CONSOLIDA
537
529
  : undefined;
538
530
  if (typeof seam.startActivation === 'function' && request.agentPreset !== undefined) {
539
531
  const run = await seam.startActivation(buildActivationSpec(request, prompt, timeout, outputSchema));
540
- const result = await run.result;
541
- return { text: textOf(result), ...stopReasonOf(result) };
532
+ try {
533
+ const result = await run.result;
534
+ return { text: textOf(result), ...stopReasonOf(result) };
535
+ }
536
+ finally {
537
+ await run.dispose?.().catch(() => undefined);
538
+ }
542
539
  }
543
540
  if (typeof seam.start === 'function') {
544
541
  const run = await seam.start('spawn', {
@@ -610,7 +607,7 @@ export async function runConsolidationDirect(llm, request) {
610
607
  if (route === undefined)
611
608
  return undefined;
612
609
  const known = new Set(request.entries.map((entry) => entry.id));
613
- const input = renderConsolidationInput(request.entries, request.projectLabel, request.persona);
610
+ const input = renderConsolidationInput(request.entries, request.projectLabel, request.persona, request.existingSkills);
614
611
  const messages = [createUserMessage({
615
612
  content: [{ type: 'text', text: input }],
616
613
  source: { kind: MEMORY_SOURCE_KIND },
@@ -629,17 +626,22 @@ export async function runConsolidationDirect(llm, request) {
629
626
  const assembler = new BlockAssembler();
630
627
  for await (const chunk of llm.stream(options))
631
628
  assembler.push(chunk);
629
+ const finish = assembler.finish;
630
+ if (finish.kind === 'error' || finish.kind === 'aborted') {
631
+ request.onSkip?.(`the model call failed (${finish.kind}: ${finish.failure.message})`);
632
+ return undefined;
633
+ }
632
634
  const text = assembler.blocks()
633
635
  .filter((block) => block.type === 'text')
634
636
  .map((block) => block.text)
635
637
  .join('\n');
636
638
  if (text.trim().length === 0) {
637
- request.onSkip?.('the model returned an empty reply');
639
+ request.onSkip?.(`the model returned an empty reply (finish: ${finish.kind})`);
638
640
  return undefined;
639
641
  }
640
642
  const plan = parsePlan(text, known, request.maxUpserts);
641
643
  if (plan === undefined)
642
- request.onSkip?.(`the model's reply carried no plan (${text.length} chars)`);
644
+ request.onSkip?.(`the model's reply carried no plan (${text.length} chars, finish: ${finish.kind})`);
643
645
  return plan;
644
646
  }
645
647
  /**
package/lib/dense.js CHANGED
@@ -109,9 +109,9 @@ export async function embed(texts, options) {
109
109
  const BATCH = 16;
110
110
  for (let start = 0; start < missing.length; start += BATCH) {
111
111
  const batch = missing.slice(start, start + BATCH);
112
+ const vectors = await callService(options.url, options.model, batch.map((item) => item.text));
112
113
  for (let index = 0; index < batch.length; index += 1) {
113
- const vectors = await callService(options.url, options.model, [batch[index].text]);
114
- cache.vectors[batch[index].key] = encode(vectors[0]);
114
+ cache.vectors[batch[index].key] = encode(vectors[index]);
115
115
  }
116
116
  }
117
117
  if (missing.length > 0) {
package/lib/extract.js CHANGED
@@ -80,6 +80,7 @@ export const EXTRACT_SYSTEM = [
80
80
  'NO POINTER MEMORIES: do not write 「详见 docs/某报告」「见某文档 §5」 and do not store a review report as a pointer to itself. The body must carry the FACT — the mechanism, the number, the decision, the trap — so a later session can act without opening anything. A pointer is only worth writing when the fact is nowhere else and the document is the authority; even then, state the fact first and name the document as a reference.',
81
81
  'ORDER what you keep by value, and keep at most the requested number: 约定/承诺 > 日期/改口/冲突 > 身份/称呼/边界/第三方人物与变化 > 偏好/计划 > 其他明确事实. Greetings, small talk, repeated restatements and ordinary daily log flow are not worth a memory; when nothing qualifies, return nothing rather than padding.',
82
82
  'REPORTS: when the transcript is an implementation/audit/review report (often a subagent\'s), record what the report LEARNED — the mechanism, the interface trap, the root cause, the measured result, the open gap — and skip what it was ASKED to do: the task boundary ("只改这 5 个文件", "不要 git commit"), the verification commands, the review verdict, the commit hash. Those expire with the task; the finding does not.',
83
+ 'NO ROUTINE PATROL LOGS: do NOT record single readings from routine patrols or daily health checks — such as today\'s disk size (".dsh 1.72 GiB"), "0 items cleaned / no changes today", or periodic app-update check counts ("19 项有更新", "某软件仍未升级"). Only record a durable root cause, a new rule, or a structural change discovered during a patrol.',
83
84
  '',
84
85
  'Write every title and body in Simplified Chinese. Keep paths, commands, identifiers, product names and error strings exactly as they are.',
85
86
  'The injected summary shows only the title and roughly the first 100 characters of the body (the budget forces short previews), so lead with the trigger and the decision; put the detail after.',
@@ -122,8 +123,9 @@ export const EXTRACT_SYSTEM = [
122
123
  '- "dueAt" only when a deadline was actually said, as ISO date or date-time. Never invent one: a loop without a deadline is a note, and nagging somebody about a note turns help into supervision.',
123
124
  '- PROGRESS: when the user reports that part of an existing obligation is done ("先还一件,还剩两件"), the loop text MUST be the REMAINING part with the original promise\'s wording kept ("还剩两件夜班见闻(原欠三件)"), because the ledger recognises it as the same promise and replaces the old amount. A loop that still states the full original amount ("三天内讲完欠的三件") is WRONG after a progress report: it leaves the ledger owing what is already done. Skip the obligation entirely only when nothing is left.',
124
125
  '- Skip what the session shows as already done, and skip the assistant\'s own to-dos. An empty array is the normal result.',
126
+ '- CLOSING LOOPS: when "Current open loops" are listed below and the transcript clearly shows one of them has been completed, return its exact id in "closedLoops":[string]. Only close a loop when the transcript proves it is done.',
125
127
  'Prefer few high-value memories over many trivial ones. Return at most the requested number. If the transcript only supports three, return three: padding a short session with one-off detail is how noise gets into the store and pushes real memories out of the summary.',
126
- 'Reply with JSON only, no prose and no code fence: {"memories":[{"scope":"global"|"project","kind":string,"title":string,"body":string,"tags":string[],"keys":string[],"entities":string[],"appliesTo":string,"quote":string,"voice":"user"|"assistant"}],"loops":[{"text":string,"dueAt":string?}],"summary":string}',
128
+ 'Reply with JSON only, no prose and no code fence: {"memories":[{"scope":"global"|"project","kind":string,"title":string,"body":string,"tags":string[],"keys":string[],"entities":string[],"appliesTo":string,"quote":string,"voice":"user"|"assistant"}],"loops":[{"text":string,"dueAt":string?}],"closedLoops":[string],"summary":string}',
127
129
  'Write the "memories" array first and the "summary" paragraph last: the reply is capped, and a summary written first can spend the whole budget before the first memory is complete.',
128
130
  'Write "summary" as one paragraph (2-4 sentences) saying what this session was about — the task, the decisions, and anything that would help someone judge the memories above later. It is stored as the evidence behind them.',
129
131
  'When nothing is worth remembering, reply exactly {"memories":[],"summary":""}.'
@@ -182,6 +184,10 @@ export const EXTRACT_JSON_SCHEMA = {
182
184
  },
183
185
  },
184
186
  },
187
+ closedLoops: {
188
+ type: 'array',
189
+ items: { type: 'string' },
190
+ },
185
191
  summary: { type: 'string' },
186
192
  },
187
193
  };
@@ -239,6 +245,7 @@ const SECRET_PATTERNS = [
239
245
  /\beyJ[\w-]{10,}\.[\w-]{10,}\.[\w-]{10,}\b/gu,
240
246
  /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gu,
241
247
  /\b(?:api[_-]?key|apikey|access[_-]?token|auth[_-]?token|client[_-]?secret|password|passwd|secret|token)\b\s*[:=]\s*["']?[^\s"',;]{8,}["']?/giu,
248
+ /(?:(?:管理|登录|管理员|默认|root|wifi|路由器)?(?:密码|口令))\s*(?:[:=:为是]\s*|\s+)(?![不无别空未缺占位示例])["'「『]?[A-Za-z0-9!@#$%^&*_.-]{4,}["'」』]?/giu,
242
249
  /\bBearer\s+[\w.-]{20,}/gu,
243
250
  ];
244
251
  /**
@@ -388,17 +395,25 @@ export function collectExtractionWindow(session, afterSeq, maxMessages, maxChars
388
395
  * @returns the route, or `undefined` when no route can be resolved.
389
396
  */
390
397
  export function resolveLlmRoute(session, provider, model, fallback) {
391
- if (provider !== undefined && model !== undefined)
392
- return { provider, model };
398
+ const p = provider?.trim() ?? '';
399
+ const m = model?.trim() ?? '';
400
+ if (p.length > 0 && m.length > 0)
401
+ return { provider: p, model: m };
393
402
  const header = session.requestHeader();
394
403
  if (header !== undefined) {
395
404
  const config = header.config;
396
- return config.reasoningEffort === undefined
397
- ? { provider: config.provider, model: config.model }
398
- : { provider: config.provider, model: config.model, reasoningEffort: config.reasoningEffort };
405
+ const hp = typeof config.provider === 'string' ? config.provider.trim() : '';
406
+ const hm = typeof config.model === 'string' ? config.model.trim() : '';
407
+ if (hp.length > 0 && hm.length > 0) {
408
+ return config.reasoningEffort === undefined
409
+ ? { provider: hp, model: hm }
410
+ : { provider: hp, model: hm, reasoningEffort: config.reasoningEffort };
411
+ }
399
412
  }
400
- if (fallback.provider !== undefined && fallback.model !== undefined) {
401
- return { provider: fallback.provider, model: fallback.model };
413
+ const fp = fallback.provider?.trim() ?? '';
414
+ const fm = fallback.model?.trim() ?? '';
415
+ if (fp.length > 0 && fm.length > 0) {
416
+ return { provider: fp, model: fm };
402
417
  }
403
418
  return undefined;
404
419
  }
@@ -418,7 +433,7 @@ export function resolveLlmRoute(session, provider, model, fallback) {
418
433
  * @returns the drafts, the evidence summary, and how many were over the cap.
419
434
  */
420
435
  export function parseExtraction(text, maxMemories, sessionId) {
421
- const result = { drafts: [], loops: [], summary: '', dropped: 0 };
436
+ const result = { drafts: [], loops: [], closedLoops: [], summary: '', dropped: 0 };
422
437
  const trimmed = text.trim().replace(/^```(?:json)?\s*/iu, '').replace(/```$/u, '').trim();
423
438
  const start = trimmed.indexOf('{');
424
439
  const end = trimmed.lastIndexOf('}');
@@ -505,6 +520,9 @@ export function parseExtraction(text, maxMemories, sessionId) {
505
520
  result.drafts = usable.slice(0, Math.max(0, maxMemories));
506
521
  result.dropped = usable.length - result.drafts.length;
507
522
  result.loops = parseLoops(envelope.loops);
523
+ result.closedLoops = Array.isArray(envelope.closedLoops)
524
+ ? [...new Set(envelope.closedLoops.filter((id) => typeof id === 'string' && id.trim().length > 0).map((id) => id.trim()))].slice(0, 20)
525
+ : [];
508
526
  return result;
509
527
  }
510
528
  /**
@@ -650,7 +668,9 @@ const ANNOTATED_DATE = /^(\d{4}-\d{2}-\d{2})/u;
650
668
  * shape as the reference implementation this was adapted from.
651
669
  */
652
670
  const WORK_SALIENCE_STRONG = /今天|明天|昨天|前天|后天|大后天|下周|上周|这周|月底|月初|年初|年底|星期[一二三四五六日天]|周[一二三四五六日天]|\d{1,2}\s*[月日号]|\d{4}\s*[-/年]|\d{1,2}\s*[点时]|答应|约定|承诺|说好|提醒|记得|别忘|改口|说错|更正|其实|矛盾|两版|之前说|截止|到期|欠|借|还|决定|口径|规范|流程|必须|一律|禁止|不得|要求|确认|验收|发布|上线|部署|迁移|升级|回滚|报价|人天|合同|投标|方案|需求|修复|缺陷|根因|新增|改动|实现|评审|审计|测试|用例|报告|接口|字段|脚本|版本|提交|合并|分支|构建/gu;
653
- const WORK_SALIENCE_WEAK = /叫|称呼|名字|负责|接手|登记|换|工作|职业|同事|师傅|老板|客户|供应商|喜欢|讨厌|不吃|不要|不能|不想|边界|打算|计划|准备|要去|想去|巡检|接口|字段|配置|权限|分支|提交|合并|构建|报错|异常|失败|超时|崩溃|日志|数据|数据库|表|文件|目录|路径|仓库|服务|端口|环境|依赖|锁|并发|幂等|回执|部署|切页|归档|回填|识别|查验|投递|生成|打包|镜像|快照/gui;
671
+ const WORK_SALIENCE_WEAK = /叫|称呼|名字|负责|接手|登记|换|工作|职业|同事|师傅|老板|客户|供应商|喜欢|讨厌|不吃|不要|不能|不想|边界|打算|计划|准备|要去|想去|接口|字段|配置|权限|分支|提交|合并|构建|报错|异常|失败|超时|崩溃|日志|数据|数据库|表|文件|目录|路径|仓库|服务|端口|环境|依赖|锁|并发|幂等|回执|部署|切页|归档|回填|识别|查验|投递|生成|打包|镜像|快照/gui;
672
+ /** Routine patrol / daily health-check readings that must not be promoted to must-cover. */
673
+ const PATROL_NOISE_TURN = /(?:今日无变化|0\s*项清理|无待归位会话|版本对比巡检.*\d+\s*项|巡检.*\b\d+(?:\.\d+)?\s*(?:GiB|GB|MB)\b|\b\d+(?:\.\d+)?\s*(?:GiB|GB|MB)\b.*巡检)/u;
654
674
  /** The salience score of one text: strong hits count double. */
655
675
  function workSalience(text) {
656
676
  const strong = (text.match(WORK_SALIENCE_STRONG) ?? []).length;
@@ -671,6 +691,7 @@ function workSalience(text) {
671
691
  */
672
692
  export function mustCoverCandidates(sources, max = 6) {
673
693
  const rows = sources
694
+ .filter((source) => !PATROL_NOISE_TURN.test(source.text))
674
695
  .map((source) => ({
675
696
  seq: source.seq,
676
697
  score: workSalience(source.text),
@@ -769,6 +790,7 @@ export async function runExtraction(llm, request) {
769
790
  return { kind: 'none', reason: 'no-route' };
770
791
  const maxMemories = effectiveMaxMemories(request.maxMemories, request.window.messages);
771
792
  const known = request.knownTitles ?? [];
793
+ const openLoops = request.openLoops ?? [];
772
794
  const framed = [
773
795
  `Workspace scope label: ${request.projectLabel}`,
774
796
  `Today's date is ${localDate()} (the user's local date). Resolve every relative time in the transcript against it.`,
@@ -779,6 +801,11 @@ export async function runExtraction(llm, request) {
779
801
  ...known.map((title) => `- ${title}`),
780
802
  'If the transcript adds to (or corrects) one of those, reuse its EXACT title so that entry is updated instead of duplicated. Only invent a new title for a genuinely new fact.',
781
803
  ],
804
+ ...openLoops.length === 0 ? [] : [
805
+ '',
806
+ 'Current open loops (return an id in "closedLoops" ONLY if the transcript clearly shows it is now DONE):',
807
+ ...openLoops.map((loop) => `- [${loop.id}] ${loop.text}`),
808
+ ],
782
809
  // The must-cover list is built locally from the window, so it costs no model
783
810
  // call: the turns most likely to be skipped (a new person, a changed name, a
784
811
  // one-line agreement, an interface trap) are named up front.
@@ -844,6 +871,7 @@ export async function runExtraction(llm, request) {
844
871
  kind: 'memories',
845
872
  drafts: timed,
846
873
  loops: salvaged.loops,
874
+ ...salvaged.closedLoops.length === 0 ? {} : { closedLoops: salvaged.closedLoops },
847
875
  summary: salvaged.summary,
848
876
  dropped: salvaged.dropped,
849
877
  unsupported: bound.unsupported,
@@ -866,7 +894,7 @@ export async function runExtraction(llm, request) {
866
894
  if (bound.drafts.length === 0) {
867
895
  return { kind: 'none', reason: 'unsupported-evidence', route, ...usage === undefined ? {} : { usage } };
868
896
  }
869
- return { kind: 'memories', drafts: timed, loops: parsed.loops, summary: parsed.summary, dropped: parsed.dropped, unsupported: bound.unsupported, ...bound.dropped.length === 0 ? {} : { droppedEvidence: bound.dropped }, route, ...usage === undefined ? {} : { usage } };
897
+ return { kind: 'memories', drafts: timed, loops: parsed.loops, ...parsed.closedLoops.length === 0 ? {} : { closedLoops: parsed.closedLoops }, summary: parsed.summary, dropped: parsed.dropped, unsupported: bound.unsupported, ...bound.dropped.length === 0 ? {} : { droppedEvidence: bound.dropped }, route, ...usage === undefined ? {} : { usage } };
870
898
  }
871
899
  /**
872
900
  * Close a JSON reply the output cap cut in half.
package/lib/gate.js CHANGED
@@ -43,6 +43,8 @@ export const GATE_JSON_SCHEMA = {
43
43
  reason: { type: 'string' },
44
44
  },
45
45
  };
46
+ /** Output token cap for one gate call (leaves room for reasoning tokens). */
47
+ export const DEFAULT_GATE_MAX_OUTPUT_TOKENS = 2048;
46
48
  /**
47
49
  * Ask whether any of these is worth saying now.
48
50
  *
@@ -67,7 +69,7 @@ export async function gateNotices(request) {
67
69
  ...request.persona === undefined || request.persona.trim().length === 0
68
70
  ? []
69
71
  : ['## Who the user is', request.persona.trim(), ''],
70
- '## Canddies',
72
+ '## Candidates',
71
73
  ...request.candidates.map((candidate) => `- id: ${candidate.id}\n title: ${candidate.title}\n detail: ${candidate.detail}`),
72
74
  ].join('\n');
73
75
  const messages = [createUserMessage({
@@ -79,16 +81,22 @@ export async function gateNotices(request) {
79
81
  model: route.model,
80
82
  messages,
81
83
  system: GATE_SYSTEM,
82
- maxTokens: 400,
84
+ maxTokens: request.maxOutputTokens ?? DEFAULT_GATE_MAX_OUTPUT_TOKENS,
83
85
  purpose: 'compaction',
84
86
  sessionId: request.session.id,
85
87
  signal: AbortSignal.any([request.signal, AbortSignal.timeout(request.timeoutMs)]),
86
88
  };
87
89
  let text = '';
90
+ let finishKind = 'stop';
88
91
  try {
89
92
  const assembler = new BlockAssembler();
90
93
  for await (const chunk of request.llm.stream(options))
91
94
  assembler.push(chunk);
95
+ const finish = assembler.finish;
96
+ finishKind = finish.kind;
97
+ if (finish.kind === 'error' || finish.kind === 'aborted') {
98
+ return { deliver: new Set(), reason: `gate call ${finish.kind}: ${finish.failure.message}`, skipped: 'failed' };
99
+ }
92
100
  text = assembler.blocks()
93
101
  .filter((block) => block.type === 'text')
94
102
  .map((block) => block.text)
@@ -97,6 +105,9 @@ export async function gateNotices(request) {
97
105
  catch (error) {
98
106
  return { deliver: new Set(), reason: `gate call failed: ${error instanceof Error ? error.message : String(error)}`, skipped: 'failed' };
99
107
  }
108
+ if (finishKind === 'max-tokens' && text.trim().length === 0) {
109
+ return { deliver: new Set(), reason: 'gate reply hit maxTokens before emitting text', skipped: 'failed' };
110
+ }
100
111
  const parsed = parseGateReply(text, request.candidates);
101
112
  return parsed.reason.length === 0 && parsed.deliver.size === 0 && parsed.failed
102
113
  ? { deliver: parsed.deliver, reason: 'reply was not usable JSON', skipped: 'failed' }
@@ -115,23 +126,28 @@ export async function gateNotices(request) {
115
126
  export function parseGateReply(text, candidates) {
116
127
  const known = new Set(candidates.map((candidate) => candidate.id));
117
128
  const trimmed = text.trim().replace(/^```(?:json)?\s*/iu, '').replace(/```$/u, '').trim();
118
- const start = trimmed.indexOf('{');
119
- const end = trimmed.lastIndexOf('}');
120
- if (start < 0 || end <= start)
129
+ const first = trimmed.indexOf('{');
130
+ const last = trimmed.lastIndexOf('}');
131
+ if (first < 0 || last <= first)
121
132
  return { deliver: new Set(), reason: '', failed: true };
122
- let parsed;
123
- try {
124
- parsed = JSON.parse(trimmed.slice(start, end + 1));
133
+ for (let start = first; start >= 0 && start < last; start = trimmed.indexOf('{', start + 1)) {
134
+ let parsed;
135
+ try {
136
+ parsed = JSON.parse(trimmed.slice(start, last + 1));
137
+ }
138
+ catch {
139
+ continue;
140
+ }
141
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
142
+ continue;
143
+ const row = parsed;
144
+ if (!Array.isArray(row.deliver) && typeof row.reason !== 'string')
145
+ continue;
146
+ const deliver = new Set(Array.isArray(row.deliver)
147
+ ? row.deliver.filter((id) => typeof id === 'string' && known.has(id))
148
+ : []);
149
+ const reason = typeof row.reason === 'string' ? row.reason.replace(/\s+/gu, ' ').trim().slice(0, 200) : '';
150
+ return { deliver, reason, failed: false };
125
151
  }
126
- catch {
127
- return { deliver: new Set(), reason: '', failed: true };
128
- }
129
- if (typeof parsed !== 'object' || parsed === null)
130
- return { deliver: new Set(), reason: '', failed: true };
131
- const row = parsed;
132
- const deliver = new Set(Array.isArray(row.deliver)
133
- ? row.deliver.filter((id) => typeof id === 'string' && known.has(id))
134
- : []);
135
- const reason = typeof row.reason === 'string' ? row.reason.replace(/\s+/gu, ' ').trim().slice(0, 200) : '';
136
- return { deliver, reason, failed: false };
152
+ return { deliver: new Set(), reason: '', failed: true };
137
153
  }