@octopi-agent/engine 0.97.15 → 0.98.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/dist/config-schema/agent.d.ts +2 -0
  2. package/dist/config-schema/engine.d.ts +4 -0
  3. package/dist/config-schema/governance.d.ts +2 -0
  4. package/dist/config-schema/governance.js +30 -0
  5. package/dist/harness/agent/builder.d.ts +11 -0
  6. package/dist/harness/agent/builder.js +59 -32
  7. package/dist/harness/agent/config-integrity.d.ts +66 -0
  8. package/dist/harness/agent/config-integrity.js +89 -0
  9. package/dist/harness/agent/wire-agent-builder.js +5 -0
  10. package/dist/harness/collaboration/autonomous-subsystem/index.d.ts +2 -2
  11. package/dist/harness/collaboration/autonomous-subsystem/index.js +1 -1
  12. package/dist/harness/collaboration/autonomous-subsystem/loader.js +3 -0
  13. package/dist/harness/collaboration/autonomous-subsystem/sense/engine.js +19 -2
  14. package/dist/harness/collaboration/autonomous-subsystem/think/completion-guard.d.ts +40 -0
  15. package/dist/harness/collaboration/autonomous-subsystem/think/completion-guard.js +59 -0
  16. package/dist/harness/collaboration/autonomous-subsystem/think/index.d.ts +2 -0
  17. package/dist/harness/collaboration/autonomous-subsystem/think/index.js +1 -0
  18. package/dist/harness/collaboration/autonomous-subsystem/think/model-resolver.js +1 -1
  19. package/dist/harness/collaboration/autonomous-subsystem/types.d.ts +9 -0
  20. package/dist/harness/context/capabilities/summary/resolver.d.ts +1 -1
  21. package/dist/harness/context/capabilities/summary/resolver.js +4 -4
  22. package/dist/harness/context/capabilities/summary/types.d.ts +2 -2
  23. package/dist/harness/context/layers.d.ts +2 -4
  24. package/dist/harness/context/layers.js +9 -11
  25. package/dist/harness/context/summarize.d.ts +1 -1
  26. package/dist/harness/context/summarize.js +2 -2
  27. package/dist/harness/context/system-prompt-assembler.d.ts +2 -0
  28. package/dist/harness/context/system-prompt-assembler.js +1 -0
  29. package/dist/harness/extension/execution-environment/effect-policy.d.ts +24 -2
  30. package/dist/harness/extension/execution-environment/effect-policy.js +30 -0
  31. package/dist/harness/extension/execution-environment/ops-audit.d.ts +6 -2
  32. package/dist/harness/extension/execution-environment/ops-audit.js +11 -12
  33. package/dist/harness/extension/execution-environment/undo-log.d.ts +6 -2
  34. package/dist/harness/extension/execution-environment/undo-log.js +31 -10
  35. package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +17 -24
  36. package/dist/harness/extension/plugin-ecosystem/tools/document-tools.js +3 -9
  37. package/dist/harness/extension/plugin-ecosystem/tools/file-edit.js +3 -6
  38. package/dist/harness/extension/plugin-ecosystem/tools/file-ops.js +9 -5
  39. package/dist/harness/extension/plugin-ecosystem/tools/file-search.js +9 -130
  40. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.js +122 -14
  41. package/dist/harness/extension/plugin-ecosystem/tools/package-tools.js +4 -13
  42. package/dist/harness/extension/plugin-ecosystem/tools/platform.d.ts +25 -11
  43. package/dist/harness/extension/plugin-ecosystem/tools/platform.js +168 -62
  44. package/dist/harness/governance/security/default-risk-policy.d.ts +1 -0
  45. package/dist/harness/governance/security/default-risk-policy.js +1 -0
  46. package/dist/harness/governance/security/default-security-guard.js +9 -0
  47. package/dist/harness/governance/security/index.d.ts +1 -0
  48. package/dist/harness/governance/security/index.js +2 -0
  49. package/dist/harness/governance/security/risk-evaluator.js +13 -0
  50. package/dist/harness/governance/security/risk-types.d.ts +12 -0
  51. package/dist/harness/governance/security/shell-parser-fallback.d.ts +29 -0
  52. package/dist/harness/governance/security/shell-parser-fallback.js +410 -0
  53. package/dist/harness/governance/security/shell-parser-shared.d.ts +83 -0
  54. package/dist/harness/governance/security/shell-parser-shared.js +188 -0
  55. package/dist/harness/governance/security/shell-parser-treesitter.d.ts +52 -0
  56. package/dist/harness/governance/security/shell-parser-treesitter.js +370 -0
  57. package/dist/harness/governance/security/shell-parser.d.ts +23 -10
  58. package/dist/harness/governance/security/shell-parser.js +37 -496
  59. package/dist/harness/governance/security/vendor/README.md +24 -0
  60. package/dist/harness/governance/security/vendor/tree-sitter-bash.LICENSE.txt +21 -0
  61. package/dist/harness/governance/security/vendor/tree-sitter-bash.wasm +0 -0
  62. package/dist/harness/memory/index.d.ts +6 -2
  63. package/dist/harness/memory/index.js +4 -1
  64. package/dist/harness/memory/memory-events.d.ts +25 -0
  65. package/dist/harness/memory/memory-events.js +38 -0
  66. package/dist/harness/memory/sqlite/agent-db.js +15 -0
  67. package/dist/harness/memory/sqlite/wisdom-store.d.ts +7 -2
  68. package/dist/harness/memory/sqlite/wisdom-store.js +51 -2
  69. package/dist/harness/memory/steward-policy.d.ts +3 -0
  70. package/dist/harness/memory/steward-policy.js +1 -1
  71. package/dist/harness/memory/types.d.ts +41 -3
  72. package/dist/harness/memory/wisdom-attribution.d.ts +136 -0
  73. package/dist/harness/memory/wisdom-attribution.js +287 -0
  74. package/dist/harness/memory/wisdom-events.d.ts +37 -0
  75. package/dist/harness/memory/wisdom-events.js +61 -0
  76. package/dist/harness/memory/wisdom-formation.d.ts +20 -1
  77. package/dist/harness/memory/wisdom-formation.js +55 -21
  78. package/dist/harness/memory/wisdom.d.ts +7 -2
  79. package/dist/harness/memory/wisdom.js +40 -2
  80. package/dist/harness/run/run-scope.d.ts +4 -0
  81. package/dist/harness/run/runner.d.ts +27 -2
  82. package/dist/harness/run/runner.js +48 -4
  83. package/dist/harness/shared/paths/glob.d.ts +52 -0
  84. package/dist/harness/shared/paths/glob.js +218 -0
  85. package/dist/harness/shared/paths/index.d.ts +84 -0
  86. package/dist/harness/shared/paths/index.js +179 -0
  87. package/dist/subsystems/cognition-steward/conceptualize/config.yaml +4 -2
  88. package/dist/subsystems/cognition-steward/conceptualize/handler.js +12 -20
  89. package/dist/subsystems/memory-steward/backfill/config.yaml +4 -2
  90. package/dist/subsystems/memory-steward/backfill/handler.js +44 -52
  91. package/dist/subsystems/wisdom-steward/attribute/SUBSYSTEM.md +24 -0
  92. package/dist/subsystems/wisdom-steward/attribute/config.yaml +60 -0
  93. package/dist/subsystems/wisdom-steward/attribute/handler.d.ts +23 -0
  94. package/dist/subsystems/wisdom-steward/attribute/handler.js +167 -0
  95. package/dist/subsystems/wisdom-steward/evaluate/handler.js +3 -1
  96. package/dist/subsystems/wisdom-steward/formation/config.yaml +12 -5
  97. package/dist/subsystems/wisdom-steward/formation/handler.js +12 -18
  98. package/dist/subsystems/wisdom-steward/govern/config.yaml +1 -1
  99. package/dist/subsystems/wisdom-steward/govern/handler.js +4 -0
  100. package/package.json +7 -2
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Memory 存量变化信号 — 每条命题落库后 emit `memory.stored`
3
+ *
4
+ * 消费方(sense.filter.events 订阅):wisdom.steward.formation 等增量触发的子系统。
5
+ * 事件类型必须真实存在于 EventBus;发射失败静默(不得阻断 memory 写路径)。
6
+ *
7
+ * @module harness/memory/memory-events
8
+ */
9
+ /** 命题落库信号(每条一发;消费方按 minEvents 累积节流) */
10
+ export const MEMORY_STORED_EVENT = 'memory.stored';
11
+ /**
12
+ * 发射命题落库信号。失败静默(不得阻断 Memory 写入)。
13
+ *
14
+ * @param events - EventBus
15
+ * @param payload - 落库载荷
16
+ */
17
+ export function emitMemoryStored(events, payload) {
18
+ if (!events)
19
+ return;
20
+ try {
21
+ events.emit({
22
+ type: MEMORY_STORED_EVENT,
23
+ timestamp: Date.now(),
24
+ agentId: payload.agentId,
25
+ sessionId: payload.sessionId,
26
+ data: {
27
+ memoryId: payload.memoryId,
28
+ type: payload.type,
29
+ status: payload.status,
30
+ sessionId: payload.sessionId,
31
+ agentId: payload.agentId,
32
+ },
33
+ });
34
+ }
35
+ catch {
36
+ // 总线异常不得拖垮 Memory 写入
37
+ }
38
+ }
@@ -297,6 +297,21 @@ export class AgentDatabase {
297
297
  CREATE INDEX IF NOT EXISTS idx_wisdom_status ON wisdom(status);
298
298
  CREATE INDEX IF NOT EXISTS idx_wisdom_priority ON wisdom(priority);
299
299
 
300
+ -- ── Wisdom 归因窗口(弱归因验证:run 收尾记账,判官批量判决)──
301
+ CREATE TABLE IF NOT EXISTS wisdom_attribution_windows (
302
+ id TEXT PRIMARY KEY,
303
+ session_id TEXT NOT NULL,
304
+ agent_id TEXT,
305
+ query TEXT NOT NULL DEFAULT '',
306
+ outcome TEXT NOT NULL DEFAULT '',
307
+ injected_ids TEXT NOT NULL DEFAULT '[]',
308
+ citations TEXT NOT NULL DEFAULT '[]',
309
+ created_at INTEGER NOT NULL,
310
+ judged_at INTEGER
311
+ );
312
+ CREATE INDEX IF NOT EXISTS idx_wisdom_windows_judged ON wisdom_attribution_windows(judged_at);
313
+ CREATE INDEX IF NOT EXISTS idx_wisdom_windows_created ON wisdom_attribution_windows(created_at);
314
+
300
315
  -- ── Knowledge Sources 注册表 ──
301
316
  CREATE TABLE IF NOT EXISTS knowledge_sources (
302
317
  id TEXT PRIMARY KEY,
@@ -5,7 +5,7 @@
5
5
  *
6
6
  * @module
7
7
  */
8
- import type { AdmitWisdomInput, AdmitWisdomResult, WisdomEntry, WisdomInjectPick, WisdomInjectQuery, WisdomOutcomeEvent, WisdomRetireReason, WisdomStats, WisdomStore } from '../types.js';
8
+ import type { AdmitWisdomInput, AdmitWisdomResult, WisdomAttributionWindow, WisdomAttributionWindowInput, WisdomEntry, WisdomInjectPick, WisdomInjectQuery, WisdomOutcomeEvent, WisdomRetireReason, WisdomStats, WisdomStore } from '../types.js';
9
9
  import { AgentDatabase } from './agent-db.js';
10
10
  export interface SqliteWisdomStoreOptions {
11
11
  /** admit 硬顶(存活面);默认 80 */
@@ -29,8 +29,13 @@ export declare class SqliteWisdomStore implements WisdomStore {
29
29
  by: string;
30
30
  reason: WisdomRetireReason | string;
31
31
  }): Promise<void>;
32
- recordOutcomes(events: WisdomOutcomeEvent[]): Promise<void>;
32
+ recordOutcomes(events: WisdomOutcomeEvent[], config?: import('../wisdom-policy.js').WisdomEvaluationConfig): Promise<void>;
33
33
  touchApplied(ids: string[]): Promise<void>;
34
+ recordAttributionWindow(input: WisdomAttributionWindowInput): Promise<string>;
35
+ listPendingWindows(limit?: number): Promise<WisdomAttributionWindow[]>;
36
+ markWindowsJudged(ids: string[], at?: number): Promise<string[]>;
37
+ pruneWindows(before: number): Promise<void>;
38
+ private rowToWindow;
34
39
  stats(): Promise<WisdomStats>;
35
40
  /** 存活面计数(candidate/trial/active/strengthened/contested) */
36
41
  countLive(): number;
@@ -112,7 +112,7 @@ export class SqliteWisdomStore {
112
112
  exceptions: [...(current.exceptions ?? []), `retired:${meta.reason}:${meta.by}`],
113
113
  });
114
114
  }
115
- async recordOutcomes(events) {
115
+ async recordOutcomes(events, config) {
116
116
  if (events.length === 0)
117
117
  return;
118
118
  const byId = new Map();
@@ -127,7 +127,7 @@ export class SqliteWisdomStore {
127
127
  continue;
128
128
  const folded = foldOutcomeEvents(current, evs);
129
129
  let next = { ...current, ...folded, updatedAt: Date.now() };
130
- const plan = planConfidenceUpdate(next);
130
+ const plan = planConfidenceUpdate(next, config);
131
131
  if (plan) {
132
132
  next = {
133
133
  ...next,
@@ -174,6 +174,55 @@ export class SqliteWisdomStore {
174
174
  .run(JSON.stringify(outcomes), now, id);
175
175
  }
176
176
  }
177
+ async recordAttributionWindow(input) {
178
+ const id = AgentDatabase.generateId('waw');
179
+ this.db.raw
180
+ .prepare(`INSERT INTO wisdom_attribution_windows
181
+ (id, session_id, agent_id, query, outcome, injected_ids, citations, created_at)
182
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
183
+ .run(id, input.sessionId, input.agentId ?? null, input.query, input.outcome, JSON.stringify(input.injectedIds), JSON.stringify(input.citations), Date.now());
184
+ return id;
185
+ }
186
+ async listPendingWindows(limit) {
187
+ const rows = this.db.raw
188
+ .prepare(`SELECT * FROM wisdom_attribution_windows WHERE judged_at IS NULL
189
+ ORDER BY created_at ASC LIMIT ?`)
190
+ .all(limit && limit > 0 ? limit : 500);
191
+ return rows.map((r) => this.rowToWindow(r));
192
+ }
193
+ async markWindowsJudged(ids, at) {
194
+ if (ids.length === 0)
195
+ return [];
196
+ const now = at ?? Date.now();
197
+ const stmt = this.db.raw.prepare(`UPDATE wisdom_attribution_windows SET judged_at = ? WHERE id = ? AND judged_at IS NULL`);
198
+ const newlyJudged = [];
199
+ for (const id of ids) {
200
+ // 只有真正置上的才算本次标记(跨进程幂等:他方先标则不发事件)
201
+ const res = stmt.run(now, id);
202
+ if (Number(res.changes ?? 0) > 0)
203
+ newlyJudged.push(id);
204
+ }
205
+ return newlyJudged;
206
+ }
207
+ async pruneWindows(before) {
208
+ this.db.raw
209
+ .prepare(`DELETE FROM wisdom_attribution_windows WHERE judged_at IS NOT NULL AND judged_at < ?`)
210
+ .run(before);
211
+ }
212
+ rowToWindow(r) {
213
+ return {
214
+ id: String(r.id),
215
+ sessionId: String(r.session_id),
216
+ agentId: r.agent_id == null ? undefined : String(r.agent_id),
217
+ query: String(r.query ?? ''),
218
+ outcome: String(r.outcome ?? ''),
219
+ // 坏行不得毒化整批(手工损坏/半写 JSON 跳过字段而非抛错)
220
+ injectedIds: safeParse(String(r.injected_ids ?? ''), []),
221
+ citations: safeParse(String(r.citations ?? ''), []),
222
+ createdAt: Number(r.created_at),
223
+ judgedAt: r.judged_at == null ? undefined : Number(r.judged_at),
224
+ };
225
+ }
177
226
  async stats() {
178
227
  const rows = this.db.raw.prepare(`SELECT * FROM wisdom`).all();
179
228
  const byStatus = Object.fromEntries(WISDOM_STATUSES.map((s) => [s, 0]));
@@ -76,6 +76,9 @@ export interface AdmitResult {
76
76
  id: string;
77
77
  type: MemoryType;
78
78
  status: string;
79
+ proposition: string;
80
+ channel: string;
81
+ evidence?: string;
79
82
  }>;
80
83
  rejected: Array<{
81
84
  reason: AdmitRejectReason;
@@ -275,7 +275,7 @@ export async function admitCandidates(store, candidates, source) {
275
275
  if (idx >= 0)
276
276
  live.splice(idx, 1);
277
277
  }
278
- accepted.push({ id, type, status });
278
+ accepted.push({ id, type, status, proposition: c.proposition, channel: c.channel ?? 'model_inference', evidence: c.evidence });
279
279
  sourceCount += 1;
280
280
  // 同批后续候选可对刚写入条目判重
281
281
  live.push({
@@ -4,6 +4,7 @@
4
4
  * @layer harness/memory — Context Intelligence 存储协议。
5
5
  * 实现:InMemory* / Sqlite*(AgentDatabase)。非 Kernel。
6
6
  */
7
+ import type { WisdomEvaluationConfig } from './wisdom-policy.js';
7
8
  /**
8
9
  * 记忆类型 — 蒸馏产物三类(见 docs/memory.md)
9
10
  *
@@ -243,7 +244,7 @@ export interface WisdomInjectQuery {
243
244
  coreMaxItems?: number;
244
245
  /** 场景条数硬顶 */
245
246
  scenarioMaxItems?: number;
246
- /** 是否包含 trial(默认 false) */
247
+ /** 是否包含 trial(默认 true——trial 的意义就是被试用;显式 false 只注入已站稳条目) */
247
248
  includeTrial?: boolean;
248
249
  }
249
250
  export interface WisdomInjectPick {
@@ -262,6 +263,30 @@ export interface WisdomOutcomeEvent {
262
263
  note?: string;
263
264
  ref?: string;
264
265
  }
266
+ /** 归因窗口中的一处引用摘录(判官强证据) */
267
+ export interface WisdomAttributionCitation {
268
+ wisdomId: string;
269
+ excerpt: string;
270
+ }
271
+ /** 归因窗口输入(run 收尾记账) */
272
+ export interface WisdomAttributionWindowInput {
273
+ sessionId: string;
274
+ agentId?: string;
275
+ /** 本轮任务/查询文本(判官 digest 证据) */
276
+ query: string;
277
+ /** run 收尾原因(completed/aborted/error…)——仅作判官上下文,不作判决 */
278
+ outcome: string;
279
+ /** 本轮注入的 wisdom id(装配 manifest sources) */
280
+ injectedIds: string[];
281
+ citations: WisdomAttributionCitation[];
282
+ }
283
+ /** 归因窗口:弱归因验证的记账单位(run 收尾 → 判官批量判决) */
284
+ export interface WisdomAttributionWindow extends WisdomAttributionWindowInput {
285
+ id: string;
286
+ createdAt: number;
287
+ /** 缺省 = 未判决 */
288
+ judgedAt?: number;
289
+ }
265
290
  export interface WisdomStats {
266
291
  total: number;
267
292
  byStatus: Record<WisdomStatus, number>;
@@ -292,10 +317,23 @@ export interface WisdomStore {
292
317
  by: string;
293
318
  reason: WisdomRetireReason | string;
294
319
  }): Promise<void>;
295
- /** 弱归因结局入账 */
296
- recordOutcomes(events: WisdomOutcomeEvent[]): Promise<void>;
320
+ /** 弱归因结局入账(含 confidence/状态迁移);config 缺省用默认评估参数 */
321
+ recordOutcomes(events: WisdomOutcomeEvent[], config?: WisdomEvaluationConfig): Promise<void>;
297
322
  /** 注入命中轻量入账(S1 applied);不跑 confidence 规划 */
298
323
  touchApplied(ids: string[]): Promise<void>;
324
+ /** 归因窗口:run 收尾记账;返回窗口 id */
325
+ recordAttributionWindow(input: WisdomAttributionWindowInput): Promise<string>;
326
+ /** 未判决窗口(判官取件;createdAt 升序;缺省上限 500,两实现一致) */
327
+ listPendingWindows(limit?: number): Promise<WisdomAttributionWindow[]>;
328
+ /**
329
+ * 标记窗口已判决(`judged_at IS NULL` 原子标记;先标记后发判决事件:宁丢勿重)。
330
+ *
331
+ * @returns 本次真正被标记的 id(已被他方标记的不在内——调用方只对返回集发
332
+ *判决事件,构成跨进程幂等)
333
+ */
334
+ markWindowsJudged(ids: string[], at?: number): Promise<string[]>;
335
+ /** 清理 judgedAt 早于 before 的旧窗口(保留期外) */
336
+ pruneWindows(before: number): Promise<void>;
299
337
  stats(): Promise<WisdomStats>;
300
338
  }
301
339
  /** 概念种类 — 基本层级偏置 */
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Wisdom 归因窗口 — 弱归因验证的记账、取证与判官准备(arch/wisdom-layer-formation.md §7)
3
+ *
4
+ * 分工纪律:代码只做记账 / 取证 / 候选路由;`assisted` / `contested` 判决只出自
5
+ * LLM 判官(wisdom.steward.attribute,digest 批量判决);evaluate 只做入账与状态迁移。
6
+ * 禁止把「任务成功」当「这条有功」——结局标志位只是判官的上下文,不是判决。
7
+ *
8
+ * @module harness/memory/wisdom-attribution
9
+ */
10
+ import type { Message } from '@octopi-agent/core/types.js';
11
+ import type { WisdomAttributionCitation, WisdomAttributionWindow, WisdomEntry, WisdomOutcomeEvent, WisdomStore } from './types.js';
12
+ /** run 收尾记账输入(Runner 钩子) */
13
+ export interface WisdomRunWindowInfo {
14
+ sessionId: string;
15
+ agentId?: string;
16
+ /** run 收尾原因(completed/aborted/error…)——仅作判官上下文 */
17
+ outcome: string;
18
+ /** 本轮任务/查询文本 */
19
+ query: string;
20
+ /** 本轮注入的 wisdom id(装配 manifest sources) */
21
+ injectedIds: string[];
22
+ /** 本轮产出的 assistant 文本(引用摘录来源) */
23
+ assistantTexts: string[];
24
+ }
25
+ /** 判决候选(窗口 × 条目)及其路由 */
26
+ export interface AttributionCandidate {
27
+ window: WisdomAttributionWindow;
28
+ entry: WisdomEntry;
29
+ /** cited=显式引用;scenario=场景命中;sampled=core 常驻抽样(可选证据) */
30
+ route: 'cited' | 'scenario' | 'sampled';
31
+ }
32
+ /** 判官输出的单条判决(pair 为 digest 中的序号,从 1 起) */
33
+ export interface AttributionVerdict {
34
+ pair: number;
35
+ verdict: 'assisted' | 'contested' | 'unclear';
36
+ reason?: string;
37
+ }
38
+ /** 批次装箱结果(窗口原子:必判对整窗进或整窗退) */
39
+ export interface AttributionBatch {
40
+ /** 进 digest 的候选(必判在前,抽样在后) */
41
+ selected: AttributionCandidate[];
42
+ /** 预算不足被整窗推迟的窗口(保持 pending,下批再判) */
43
+ deferredWindowIds: string[];
44
+ /** 判无可判或抽样未中的窗口(按设计直接关闭,不产生事件) */
45
+ closableWindowIds: string[];
46
+ }
47
+ /**
48
+ * 收集本轮新增 assistant 文本(引用摘录来源)。
49
+ *
50
+ * @param messages - 会话消息(含历史 + 本轮新增)
51
+ * @param base - 本轮新增消息的起始下标(装配时抓取的 messages.length)
52
+ * @returns 本轮 assistant 纯文本(非空)
53
+ */
54
+ export declare function collectRunAssistantTexts(messages: Message[], base: number): string[];
55
+ /**
56
+ * 从 assistant 文本提取范式引用摘录。
57
+ *
58
+ * @param texts - 本轮 assistant 文本
59
+ * @param entries - 本轮注入的条目(id + statement)
60
+ * @returns 每条被引用条目一处摘录(id 字面命中,或 statement 整句/长前缀命中)
61
+ */
62
+ export declare function extractCitations(texts: string[], entries: Array<Pick<WisdomEntry, 'id' | 'statement'>>): WisdomAttributionCitation[];
63
+ /**
64
+ * run 收尾记账:取注入条目 → 提取引用摘录 → 落窗口。
65
+ *
66
+ * @param store - WisdomStore
67
+ * @param info - run 收尾信息
68
+ * @returns 窗口 id;本轮无注入时返回 null(不落窗口)
69
+ */
70
+ export declare function recordWisdomRunWindow(store: WisdomStore, info: WisdomRunWindowInfo): Promise<string | null>;
71
+ /**
72
+ * 候选路由:cited / scenario 命中必判;core 常驻只抽样。
73
+ *
74
+ * 注入时的命中可由 (entry, window.query) 确定性重算(同一 matcher、同一 query),
75
+ * 无需在窗口里冗余记录 bucket。终态条目(retired/superseded/candidate)不进候选。
76
+ *
77
+ * @param windows - 未判决窗口
78
+ * @param entries - 条目全集(含终态,内部过滤)
79
+ * @param options - sampleMax 抽样上限(缺省 2)
80
+ * @returns 判决候选(必判在前,抽样在后)
81
+ */
82
+ export declare function selectAttributionCandidates(windows: WisdomAttributionWindow[], entries: WisdomEntry[], options?: {
83
+ sampleMax?: number;
84
+ }): AttributionCandidate[];
85
+ /**
86
+ * 批次装箱(窗口原子):必判对整窗进或整窗退,被 maxPairs 裁掉的窗口保持 pending;
87
+ * 抽样对是可选证据,预算有余才带,未中即按设计丢弃(不悬挂)。
88
+ *
89
+ * @param windows - 未判决窗口
90
+ * @param entries - 条目全集
91
+ * @param options - sampleMax / maxPairs
92
+ * @returns 装箱结果(selected + deferred + closable)
93
+ */
94
+ export declare function planAttributionBatch(windows: WisdomAttributionWindow[], entries: WisdomEntry[], options?: {
95
+ sampleMax?: number;
96
+ maxPairs?: number;
97
+ }): AttributionBatch;
98
+ /**
99
+ * 构建判官 digest(每候选一小块)与 pair 序号映射。
100
+ *
101
+ * @param candidates - 判决候选
102
+ * @returns digest 文本 + P{n} → (windowId, wisdomId)
103
+ */
104
+ export declare function buildAttributionDigest(candidates: AttributionCandidate[]): {
105
+ text: string;
106
+ pairRefs: Array<{
107
+ windowId: string;
108
+ wisdomId: string;
109
+ }>;
110
+ };
111
+ /**
112
+ * 从 LLM 文本提取判决 JSON `{items: [{pair, verdict, reason}]}`。
113
+ *
114
+ * 覆盖率是硬契约:expectedPairs 中每个 pair **恰好一条**判决(unclear 也算判决,
115
+ * 必须显式给出);缺项、重复、越界、空 items 一律视为解析失败(null)——
116
+ * 半截/退化输出不得当业务结果,宁可整批失败重试也不静默吞窗口。
117
+ *
118
+ * @param text - LLM 输出
119
+ * @param expectedPairs - 期望的 pair 序号(1 起)
120
+ * @returns 解析结果或 null(覆盖率不符)
121
+ */
122
+ export declare function parseAttributionVerdicts(text: string, expectedPairs: number[]): {
123
+ items: AttributionVerdict[];
124
+ } | null;
125
+ /**
126
+ * 判决 → 弱归因结局事件(unclear 不入账——宁可不更新也不污染)。
127
+ *
128
+ * @param items - 判官判决(已过覆盖率校验)
129
+ * @param pairRefs - digest 序号映射
130
+ * @param now - 时间戳
131
+ * @returns assisted/contested 事件(ref=窗口 id)
132
+ */
133
+ export declare function verdictsToOutcomeEvents(items: AttributionVerdict[], pairRefs: Array<{
134
+ windowId: string;
135
+ wisdomId: string;
136
+ }>, now?: number): WisdomOutcomeEvent[];
@@ -0,0 +1,287 @@
1
+ /**
2
+ * Wisdom 归因窗口 — 弱归因验证的记账、取证与判官准备(arch/wisdom-layer-formation.md §7)
3
+ *
4
+ * 分工纪律:代码只做记账 / 取证 / 候选路由;`assisted` / `contested` 判决只出自
5
+ * LLM 判官(wisdom.steward.attribute,digest 批量判决);evaluate 只做入账与状态迁移。
6
+ * 禁止把「任务成功」当「这条有功」——结局标志位只是判官的上下文,不是判决。
7
+ *
8
+ * @module harness/memory/wisdom-attribution
9
+ */
10
+ import { messageText } from '../context/turn-envelope.js';
11
+ import { scenarioMatchDetail } from './wisdom-formation.js';
12
+ /** 引用摘录上下文半宽(命中点前后各取的字符数) */
13
+ const CITATION_EXCERPT_HALF = 160;
14
+ /** statement 命中的最短前缀长度(放宽引用识别:整句或长前缀皆算) */
15
+ const CITATION_STATEMENT_PREFIX_MIN = 12;
16
+ /**
17
+ * 收集本轮新增 assistant 文本(引用摘录来源)。
18
+ *
19
+ * @param messages - 会话消息(含历史 + 本轮新增)
20
+ * @param base - 本轮新增消息的起始下标(装配时抓取的 messages.length)
21
+ * @returns 本轮 assistant 纯文本(非空)
22
+ */
23
+ export function collectRunAssistantTexts(messages, base) {
24
+ return messages
25
+ .slice(Math.max(0, base))
26
+ .filter((m) => m.role === 'assistant')
27
+ .map((m) => messageText(m.content))
28
+ .filter((t) => t.trim().length > 0);
29
+ }
30
+ /**
31
+ * 从 assistant 文本提取范式引用摘录。
32
+ *
33
+ * @param texts - 本轮 assistant 文本
34
+ * @param entries - 本轮注入的条目(id + statement)
35
+ * @returns 每条被引用条目一处摘录(id 字面命中,或 statement 整句/长前缀命中)
36
+ */
37
+ export function extractCitations(texts, entries) {
38
+ const out = [];
39
+ for (const e of entries) {
40
+ for (const t of texts) {
41
+ const idIdx = t.indexOf(e.id);
42
+ // statement 命中放宽到长前缀(整句或 ≥12 字符前缀):允许部分引用
43
+ const stmtNeedle = e.statement.length >= CITATION_STATEMENT_PREFIX_MIN
44
+ ? e.statement
45
+ : e.statement.slice(0, CITATION_STATEMENT_PREFIX_MIN);
46
+ const stmtIdx = t.indexOf(stmtNeedle);
47
+ const idx = idIdx >= 0 ? idIdx : stmtIdx;
48
+ if (idx < 0)
49
+ continue;
50
+ const matchedLen = idIdx >= 0 ? e.id.length : stmtNeedle.length;
51
+ const start = Math.max(0, idx - CITATION_EXCERPT_HALF);
52
+ const end = Math.min(t.length, idx + matchedLen + CITATION_EXCERPT_HALF);
53
+ out.push({ wisdomId: e.id, excerpt: t.slice(start, end) });
54
+ break;
55
+ }
56
+ }
57
+ return out;
58
+ }
59
+ /**
60
+ * run 收尾记账:取注入条目 → 提取引用摘录 → 落窗口。
61
+ *
62
+ * @param store - WisdomStore
63
+ * @param info - run 收尾信息
64
+ * @returns 窗口 id;本轮无注入时返回 null(不落窗口)
65
+ */
66
+ export async function recordWisdomRunWindow(store, info) {
67
+ const ids = [...new Set(info.injectedIds)].filter(Boolean);
68
+ if (ids.length === 0)
69
+ return null;
70
+ const all = await store.listForGovern({ includeRetired: true });
71
+ const byId = new Map(all.map((e) => [e.id, e]));
72
+ const entries = ids
73
+ .map((id) => byId.get(id))
74
+ .filter((e) => e !== undefined);
75
+ if (entries.length === 0)
76
+ return null;
77
+ return store.recordAttributionWindow({
78
+ sessionId: info.sessionId,
79
+ agentId: info.agentId,
80
+ query: info.query,
81
+ outcome: info.outcome,
82
+ injectedIds: entries.map((e) => e.id),
83
+ citations: extractCitations(info.assistantTexts, entries),
84
+ });
85
+ }
86
+ /**
87
+ * 候选路由:cited / scenario 命中必判;core 常驻只抽样。
88
+ *
89
+ * 注入时的命中可由 (entry, window.query) 确定性重算(同一 matcher、同一 query),
90
+ * 无需在窗口里冗余记录 bucket。终态条目(retired/superseded/candidate)不进候选。
91
+ *
92
+ * @param windows - 未判决窗口
93
+ * @param entries - 条目全集(含终态,内部过滤)
94
+ * @param options - sampleMax 抽样上限(缺省 2)
95
+ * @returns 判决候选(必判在前,抽样在后)
96
+ */
97
+ export function selectAttributionCandidates(windows, entries, options) {
98
+ const byId = new Map(entries.map((e) => [e.id, e]));
99
+ const sampleMax = options?.sampleMax ?? 2;
100
+ const mandatory = [];
101
+ const sampled = [];
102
+ for (const w of windows) {
103
+ for (const id of w.injectedIds) {
104
+ const entry = byId.get(id);
105
+ if (!entry)
106
+ continue;
107
+ if (entry.status === 'retired' || entry.status === 'superseded' || entry.status === 'candidate') {
108
+ continue;
109
+ }
110
+ const cited = w.citations.some((c) => c.wisdomId === id);
111
+ const scenarioHit = scenarioMatchDetail(entry, w.query).score > 0;
112
+ if (cited)
113
+ mandatory.push({ window: w, entry, route: 'cited' });
114
+ else if (scenarioHit)
115
+ mandatory.push({ window: w, entry, route: 'scenario' });
116
+ else
117
+ sampled.push({ window: w, entry, route: 'sampled' });
118
+ }
119
+ }
120
+ return [...mandatory, ...sampled.slice(0, sampleMax)];
121
+ }
122
+ /**
123
+ * 批次装箱(窗口原子):必判对整窗进或整窗退,被 maxPairs 裁掉的窗口保持 pending;
124
+ * 抽样对是可选证据,预算有余才带,未中即按设计丢弃(不悬挂)。
125
+ *
126
+ * @param windows - 未判决窗口
127
+ * @param entries - 条目全集
128
+ * @param options - sampleMax / maxPairs
129
+ * @returns 装箱结果(selected + deferred + closable)
130
+ */
131
+ export function planAttributionBatch(windows, entries, options) {
132
+ const cands = selectAttributionCandidates(windows, entries, {
133
+ sampleMax: options?.sampleMax,
134
+ });
135
+ const byWindow = new Map();
136
+ for (const c of cands) {
137
+ const list = byWindow.get(c.window.id) ?? [];
138
+ list.push(c);
139
+ byWindow.set(c.window.id, list);
140
+ }
141
+ const budget = options?.maxPairs ?? 40;
142
+ const selected = [];
143
+ const deferredWindowIds = [];
144
+ const closableWindowIds = [];
145
+ for (const w of windows) {
146
+ const list = byWindow.get(w.id) ?? [];
147
+ const mandatory = list.filter((c) => c.route !== 'sampled');
148
+ const optional = list.filter((c) => c.route === 'sampled');
149
+ if (mandatory.length === 0) {
150
+ // 无必判对:抽样有余量就带上(带了就要判),没抽中按设计关闭
151
+ let took = false;
152
+ for (const o of optional) {
153
+ if (selected.length >= budget)
154
+ break;
155
+ selected.push(o);
156
+ took = true;
157
+ }
158
+ if (!took)
159
+ closableWindowIds.push(w.id);
160
+ continue;
161
+ }
162
+ if (selected.length + mandatory.length > budget) {
163
+ deferredWindowIds.push(w.id);
164
+ continue;
165
+ }
166
+ selected.push(...mandatory);
167
+ for (const o of optional) {
168
+ if (selected.length >= budget)
169
+ break;
170
+ selected.push(o);
171
+ }
172
+ }
173
+ return { selected, deferredWindowIds, closableWindowIds };
174
+ }
175
+ /**
176
+ * 构建判官 digest(每候选一小块)与 pair 序号映射。
177
+ *
178
+ * @param candidates - 判决候选
179
+ * @returns digest 文本 + P{n} → (windowId, wisdomId)
180
+ */
181
+ export function buildAttributionDigest(candidates) {
182
+ const pairRefs = [];
183
+ const blocks = [];
184
+ candidates.forEach((c, i) => {
185
+ pairRefs.push({ windowId: c.window.id, wisdomId: c.entry.id });
186
+ const excerpts = c.window.citations
187
+ .filter((x) => x.wisdomId === c.entry.id)
188
+ .slice(0, 2)
189
+ .map((x) => x.excerpt.slice(0, 400));
190
+ blocks.push([
191
+ `### P${i + 1} [${c.entry.id}]`,
192
+ `范式: ${c.entry.statement.slice(0, 240)}`,
193
+ `场景: ${c.entry.scenario.problemTypes.join('、') || '(无)'}` +
194
+ ` / 信号: ${(c.entry.scenario.signals ?? []).join('、') || '(无)'}`,
195
+ `任务: ${c.window.query.slice(0, 120) || '(无)'} | 结局: ${c.window.outcome} | 路由: ${c.route}`,
196
+ `引用摘录: ${excerpts.length ? excerpts.join('\n---\n') : '(无)'}`,
197
+ ].join('\n'));
198
+ });
199
+ return { text: blocks.join('\n\n'), pairRefs };
200
+ }
201
+ /**
202
+ * 从 LLM 文本提取判决 JSON `{items: [{pair, verdict, reason}]}`。
203
+ *
204
+ * 覆盖率是硬契约:expectedPairs 中每个 pair **恰好一条**判决(unclear 也算判决,
205
+ * 必须显式给出);缺项、重复、越界、空 items 一律视为解析失败(null)——
206
+ * 半截/退化输出不得当业务结果,宁可整批失败重试也不静默吞窗口。
207
+ *
208
+ * @param text - LLM 输出
209
+ * @param expectedPairs - 期望的 pair 序号(1 起)
210
+ * @returns 解析结果或 null(覆盖率不符)
211
+ */
212
+ export function parseAttributionVerdicts(text, expectedPairs) {
213
+ const start = text.indexOf('{');
214
+ if (start === -1)
215
+ return null;
216
+ const end = text.lastIndexOf('}');
217
+ if (end <= start)
218
+ return null;
219
+ let parsed;
220
+ try {
221
+ parsed = JSON.parse(text.slice(start, end + 1));
222
+ }
223
+ catch {
224
+ return null;
225
+ }
226
+ if (!Array.isArray(parsed.items))
227
+ return null;
228
+ const byPair = new Map();
229
+ for (const raw of parsed.items) {
230
+ const item = raw;
231
+ if (typeof item.pair !== 'number' || !Number.isInteger(item.pair) || item.pair < 1)
232
+ return null;
233
+ if (item.verdict !== 'assisted' && item.verdict !== 'contested' && item.verdict !== 'unclear') {
234
+ return null;
235
+ }
236
+ if (byPair.has(item.pair))
237
+ return null; // 重复 pair:冲突判决不可信
238
+ byPair.set(item.pair, {
239
+ pair: item.pair,
240
+ verdict: item.verdict,
241
+ reason: typeof item.reason === 'string' ? item.reason.slice(0, 300) : undefined,
242
+ });
243
+ }
244
+ // 覆盖率:期望 pair 每个恰好一条,不允许缺项/多项
245
+ if (byPair.size !== expectedPairs.length)
246
+ return null;
247
+ const items = [];
248
+ for (const pair of expectedPairs) {
249
+ const v = byPair.get(pair);
250
+ if (!v)
251
+ return null;
252
+ items.push(v);
253
+ }
254
+ return { items };
255
+ }
256
+ /**
257
+ * 判决 → 弱归因结局事件(unclear 不入账——宁可不更新也不污染)。
258
+ *
259
+ * @param items - 判官判决(已过覆盖率校验)
260
+ * @param pairRefs - digest 序号映射
261
+ * @param now - 时间戳
262
+ * @returns assisted/contested 事件(ref=窗口 id)
263
+ */
264
+ export function verdictsToOutcomeEvents(items, pairRefs, now = Date.now()) {
265
+ const seen = new Set();
266
+ const out = [];
267
+ for (const v of items) {
268
+ if (v.verdict === 'unclear')
269
+ continue;
270
+ const ref = pairRefs[v.pair - 1];
271
+ if (!ref)
272
+ continue;
273
+ // (windowId, wisdomId, signal) 幂等:同一次证据绝不重复入账
274
+ const key = `${ref.windowId}|${ref.wisdomId}|${v.verdict}`;
275
+ if (seen.has(key))
276
+ continue;
277
+ seen.add(key);
278
+ out.push({
279
+ wisdomId: ref.wisdomId,
280
+ signal: v.verdict,
281
+ at: now,
282
+ note: v.reason,
283
+ ref: ref.windowId,
284
+ });
285
+ }
286
+ return out;
287
+ }