@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,37 @@
1
+ /**
2
+ * Wisdom 判决信号 — 判官产出的弱归因结局事件 → `wisdom.steward.evaluate.request`
3
+ *
4
+ * 消费方(sense.filter.events 订阅):wisdom.steward.evaluate(入账 + 状态迁移)。
5
+ * 事件类型必须真实存在于 EventBus;发射失败静默(不得阻断判官主流程,窗口已标记
6
+ * judged,宁丢勿重)。
7
+ *
8
+ * @module harness/memory/wisdom-events
9
+ */
10
+ import type { EventBus } from '@octopi-agent/core/primitives/event-bus.js';
11
+ import type { WisdomOutcomeEvent } from './types.js';
12
+ /** 弱归因结局入账请求(判官批量判决产物) */
13
+ export declare const WISDOM_EVALUATE_REQUEST_EVENT = "wisdom.steward.evaluate.request";
14
+ /** 治理脉搏(govern 每轮完成;判官等维护动作挂此脉搏) */
15
+ export declare const WISDOM_GOVERNED_EVENT = "wisdom.steward.governed";
16
+ /**
17
+ * 发射治理脉搏信号。失败静默(不得阻断 govern 主流程)。
18
+ *
19
+ * @param events - EventBus
20
+ * @param payload - 载荷(可选 agentId/sessionId)
21
+ */
22
+ export declare function emitWisdomGoverned(events: EventBus | undefined, payload?: {
23
+ agentId?: string;
24
+ sessionId?: string;
25
+ }): void;
26
+ export interface WisdomEvaluateRequestPayload {
27
+ events: WisdomOutcomeEvent[];
28
+ agentId?: string;
29
+ sessionId?: string;
30
+ }
31
+ /**
32
+ * 发射弱归因结局入账请求。失败静默(不得阻断判官;窗口已 judged,宁丢勿重)。
33
+ *
34
+ * @param events - EventBus
35
+ * @param payload - 结局事件集
36
+ */
37
+ export declare function emitWisdomEvaluateRequest(events: EventBus | undefined, payload: WisdomEvaluateRequestPayload): void;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Wisdom 判决信号 — 判官产出的弱归因结局事件 → `wisdom.steward.evaluate.request`
3
+ *
4
+ * 消费方(sense.filter.events 订阅):wisdom.steward.evaluate(入账 + 状态迁移)。
5
+ * 事件类型必须真实存在于 EventBus;发射失败静默(不得阻断判官主流程,窗口已标记
6
+ * judged,宁丢勿重)。
7
+ *
8
+ * @module harness/memory/wisdom-events
9
+ */
10
+ /** 弱归因结局入账请求(判官批量判决产物) */
11
+ export const WISDOM_EVALUATE_REQUEST_EVENT = 'wisdom.steward.evaluate.request';
12
+ /** 治理脉搏(govern 每轮完成;判官等维护动作挂此脉搏) */
13
+ export const WISDOM_GOVERNED_EVENT = 'wisdom.steward.governed';
14
+ /**
15
+ * 发射治理脉搏信号。失败静默(不得阻断 govern 主流程)。
16
+ *
17
+ * @param events - EventBus
18
+ * @param payload - 载荷(可选 agentId/sessionId)
19
+ */
20
+ export function emitWisdomGoverned(events, payload) {
21
+ if (!events)
22
+ return;
23
+ try {
24
+ events.emit({
25
+ type: WISDOM_GOVERNED_EVENT,
26
+ timestamp: Date.now(),
27
+ agentId: payload?.agentId,
28
+ sessionId: payload?.sessionId,
29
+ data: { at: Date.now() },
30
+ });
31
+ }
32
+ catch {
33
+ // 总线异常不得拖垮 govern
34
+ }
35
+ }
36
+ /**
37
+ * 发射弱归因结局入账请求。失败静默(不得阻断判官;窗口已 judged,宁丢勿重)。
38
+ *
39
+ * @param events - EventBus
40
+ * @param payload - 结局事件集
41
+ */
42
+ export function emitWisdomEvaluateRequest(events, payload) {
43
+ if (!events || payload.events.length === 0)
44
+ return;
45
+ try {
46
+ events.emit({
47
+ type: WISDOM_EVALUATE_REQUEST_EVENT,
48
+ timestamp: Date.now(),
49
+ agentId: payload.agentId,
50
+ sessionId: payload.sessionId,
51
+ data: {
52
+ events: payload.events,
53
+ agentId: payload.agentId,
54
+ sessionId: payload.sessionId,
55
+ },
56
+ });
57
+ }
58
+ catch {
59
+ // 总线异常不得拖垮判官;判决可由下轮窗口重新积累
60
+ }
61
+ }
@@ -71,6 +71,17 @@ export declare function formAndAdmit(llmText: string, store: WisdomStore, option
71
71
  results: AdmitWisdomResult[];
72
72
  droppedNotes: string[];
73
73
  }>;
74
+ /**
75
+ * 关键词/字面场景匹配分 + 全字面命中标记。
76
+ *
77
+ * @param entry - 条目
78
+ * @param text - 本轮查询/任务文本
79
+ * @returns score∈[0,1](无命中为 0);fullHit=problemTypes/signals 任一词全字面命中
80
+ */
81
+ export declare function scenarioMatchDetail(entry: WisdomEntry, text: string): {
82
+ score: number;
83
+ fullHit: boolean;
84
+ };
74
85
  /**
75
86
  * 关键词/字面场景匹配分。
76
87
  *
@@ -79,12 +90,20 @@ export declare function formAndAdmit(llmText: string, store: WisdomStore, option
79
90
  * @returns [0,1];无命中为 0
80
91
  */
81
92
  export declare function scenarioMatchScore(entry: WisdomEntry, text: string): number;
93
+ /**
94
+ * core 桶资格:宽覆盖(多 problemTypes 或 strengthened/factory);
95
+ * trial 永不进 core——未验证的假设只走场景匹配命中,不常驻刷屏。
96
+ *
97
+ * @param entry - 条目(状态已过 usable 过滤或可独立断言)
98
+ * @returns 是否可进 core 桶
99
+ */
100
+ export declare function isCoreEligible(entry: Pick<WisdomEntry, 'status' | 'origin' | 'scenario'>): boolean;
82
101
  /**
83
102
  * 选择注入集:小核心 + 场景匹配。
84
103
  *
85
104
  * @param entries - 可注入条目(store 已滤状态)
86
105
  * @param text - 本轮文本
87
- * @param options - 条数硬顶
106
+ * @param options - 条数硬顶;includeTrial 缺省 true(trial 的意义就是被试用)
88
107
  * @returns 排序后的注入选择
89
108
  */
90
109
  export declare function pickForInjection(entries: WisdomEntry[], text: string, options?: {
@@ -181,36 +181,49 @@ export async function formAndAdmit(llmText, store, options) {
181
181
  }
182
182
  // ── 场景匹配(P0 keyword;embedding/llm 留给后续,不假装已实现) ──
183
183
  /**
184
- * 关键词/字面场景匹配分。
184
+ * 关键词/字面场景匹配分 + 全字面命中标记。
185
185
  *
186
186
  * @param entry - 条目
187
187
  * @param text - 本轮查询/任务文本
188
- * @returns [0,1];无命中为 0
188
+ * @returns score∈[0,1](无命中为 0);fullHit=problemTypes/signals 任一词全字面命中
189
189
  */
190
- export function scenarioMatchScore(entry, text) {
190
+ export function scenarioMatchDetail(entry, text) {
191
191
  const q = text.toLowerCase();
192
192
  if (!q.trim())
193
- return 0;
193
+ return { score: 0, fullHit: false };
194
194
  const anti = (entry.scenario.antiScenarios ?? []).map((s) => s.toLowerCase());
195
195
  if (anti.some((a) => a && q.includes(a)))
196
- return 0;
196
+ return { score: 0, fullHit: false };
197
197
  const types = entry.scenario.problemTypes.map((s) => s.toLowerCase());
198
198
  const signals = (entry.scenario.signals ?? []).map((s) => s.toLowerCase());
199
199
  const words = types.concat(signals);
200
200
  if (words.length === 0)
201
- return 0;
201
+ return { score: 0, fullHit: false };
202
202
  let hit = 0;
203
+ let fullHit = false;
203
204
  for (const w of words) {
204
205
  if (!w)
205
206
  continue;
206
- if (q.includes(w))
207
+ if (q.includes(w)) {
207
208
  hit += 2;
209
+ fullHit = true;
210
+ }
208
211
  else if (overlapChars(q, w))
209
212
  hit += 1;
210
213
  }
211
214
  if (hit === 0)
212
- return 0;
213
- return Math.min(1, hit / (words.length * 2));
215
+ return { score: 0, fullHit: false };
216
+ return { score: Math.min(1, hit / (words.length * 2)), fullHit };
217
+ }
218
+ /**
219
+ * 关键词/字面场景匹配分。
220
+ *
221
+ * @param entry - 条目
222
+ * @param text - 本轮查询/任务文本
223
+ * @returns [0,1];无命中为 0
224
+ */
225
+ export function scenarioMatchScore(entry, text) {
226
+ return scenarioMatchDetail(entry, text).score;
214
227
  }
215
228
  function overlapChars(q, w) {
216
229
  // CJK 友好:词全字面出现在 q 已由 includes 覆盖;此处做 2-gram 弱重叠
@@ -223,18 +236,32 @@ function overlapChars(q, w) {
223
236
  }
224
237
  return false;
225
238
  }
239
+ /**
240
+ * core 桶资格:宽覆盖(多 problemTypes 或 strengthened/factory);
241
+ * trial 永不进 core——未验证的假设只走场景匹配命中,不常驻刷屏。
242
+ *
243
+ * @param entry - 条目(状态已过 usable 过滤或可独立断言)
244
+ * @returns 是否可进 core 桶
245
+ */
246
+ export function isCoreEligible(entry) {
247
+ if (entry.status === 'trial')
248
+ return false;
249
+ return (entry.origin === 'factory' ||
250
+ entry.status === 'strengthened' ||
251
+ entry.scenario.problemTypes.length >= 2);
252
+ }
226
253
  /**
227
254
  * 选择注入集:小核心 + 场景匹配。
228
255
  *
229
256
  * @param entries - 可注入条目(store 已滤状态)
230
257
  * @param text - 本轮文本
231
- * @param options - 条数硬顶
258
+ * @param options - 条数硬顶;includeTrial 缺省 true(trial 的意义就是被试用)
232
259
  * @returns 排序后的注入选择
233
260
  */
234
261
  export function pickForInjection(entries, text, options) {
235
262
  const coreMax = options?.coreMaxItems ?? 8;
236
263
  const scenarioMax = options?.scenarioMaxItems ?? 8;
237
- const includeTrial = options?.includeTrial ?? false;
264
+ const includeTrial = options?.includeTrial ?? true;
238
265
  const usable = entries.filter((e) => {
239
266
  if (e.status === 'retired' || e.status === 'superseded' || e.status === 'candidate')
240
267
  return false;
@@ -244,21 +271,27 @@ export function pickForInjection(entries, text, options) {
244
271
  return false;
245
272
  return true;
246
273
  });
247
- const scored = usable.map((e) => ({
248
- entry: e,
249
- match: scenarioMatchScore(e, text),
250
- score: wisdomInjectScore(e, 1),
251
- scenarioScore: wisdomInjectScore(e, scenarioMatchScore(e, text)),
252
- }));
253
- // core:宽覆盖(多 problemTypes 或 strengthened/factory)优先
274
+ const scored = usable.map((e) => {
275
+ const m = scenarioMatchDetail(e, text);
276
+ return {
277
+ entry: e,
278
+ match: m.score,
279
+ fullHit: m.fullHit,
280
+ score: wisdomInjectScore(e, 1),
281
+ scenarioScore: wisdomInjectScore(e, m.score),
282
+ };
283
+ });
254
284
  const coreCandidates = scored
255
- .filter((s) => s.entry.origin === 'factory' || s.entry.status === 'strengthened' || s.entry.scenario.problemTypes.length >= 2)
285
+ .filter((s) => isCoreEligible(s.entry))
256
286
  .sort((a, b) => b.score - a.score)
257
287
  .slice(0, coreMax)
258
288
  .map((s) => ({ entry: s.entry, bucket: 'core', score: 1 }));
259
289
  const coreIds = new Set(coreCandidates.map((c) => c.entry.id));
290
+ // scenario:trial 须全字面命中(bigram 弱重叠不算数——未验证假设不给模糊入场券)
260
291
  const scenario = scored
261
- .filter((s) => s.match > 0 && !coreIds.has(s.entry.id))
292
+ .filter((s) => s.match > 0 &&
293
+ (s.entry.status !== 'trial' || s.fullHit) &&
294
+ !coreIds.has(s.entry.id))
262
295
  .sort((a, b) => b.scenarioScore - a.scenarioScore)
263
296
  .slice(0, scenarioMax)
264
297
  .map((s) => ({ entry: s.entry, bucket: 'scenario', score: s.match }));
@@ -282,6 +315,7 @@ export function formatWisdomBody(picks) {
282
315
  byType.set(key, list);
283
316
  }
284
317
  const blocks = [];
318
+ blocks.push('> 归因:若某条范式实质影响了你的决策,可在回复中引用其 id(如 [wis_xxx])以便事后验证。');
285
319
  for (const [type, list] of byType) {
286
320
  const lines = list.map((e) => formatWisdomBullet(e));
287
321
  blocks.push(`## 面对「${type}」\n\n${lines.join('\n\n')}`);
@@ -289,7 +323,7 @@ export function formatWisdomBody(picks) {
289
323
  return blocks.join('\n\n');
290
324
  }
291
325
  function formatWisdomBullet(e) {
292
- const parts = [`- ${e.statement}`];
326
+ const parts = [`- [${e.id}] ${e.statement}`];
293
327
  const effectBits = [];
294
328
  if (e.effect.posture)
295
329
  effectBits.push(`推理姿态:${e.effect.posture}`);
@@ -3,10 +3,11 @@
3
3
  *
4
4
  * @module harness/memory/wisdom
5
5
  */
6
- import type { AdmitWisdomInput, AdmitWisdomResult, WisdomEntry, WisdomInjectPick, WisdomInjectQuery, WisdomRetireReason, WisdomStats, WisdomStore, WisdomOutcomeEvent } from './types.js';
6
+ import type { AdmitWisdomInput, AdmitWisdomResult, WisdomAttributionWindow, WisdomAttributionWindowInput, WisdomEntry, WisdomInjectPick, WisdomInjectQuery, WisdomRetireReason, WisdomStats, WisdomStore, WisdomOutcomeEvent } from './types.js';
7
7
  export declare class InMemoryWisdomStore implements WisdomStore {
8
8
  readonly name = "in-memory-wisdom";
9
9
  private entries;
10
+ private windows;
10
11
  private seq;
11
12
  admit(input: AdmitWisdomInput, options?: {
12
13
  allowedMemoryIds?: ReadonlySet<string>;
@@ -21,7 +22,11 @@ export declare class InMemoryWisdomStore implements WisdomStore {
21
22
  by: string;
22
23
  reason: WisdomRetireReason | string;
23
24
  }): Promise<void>;
24
- recordOutcomes(events: WisdomOutcomeEvent[]): Promise<void>;
25
+ recordOutcomes(events: WisdomOutcomeEvent[], config?: import('./wisdom-policy.js').WisdomEvaluationConfig): Promise<void>;
25
26
  touchApplied(ids: string[]): Promise<void>;
27
+ recordAttributionWindow(input: WisdomAttributionWindowInput): Promise<string>;
28
+ listPendingWindows(limit?: number): Promise<WisdomAttributionWindow[]>;
29
+ markWindowsJudged(ids: string[], at?: number): Promise<string[]>;
30
+ pruneWindows(before: number): Promise<void>;
26
31
  stats(): Promise<WisdomStats>;
27
32
  }
@@ -10,6 +10,7 @@ import { pickForInjection } from './wisdom-formation.js';
10
10
  export class InMemoryWisdomStore {
11
11
  name = 'in-memory-wisdom';
12
12
  entries = new Map();
13
+ windows = new Map();
13
14
  seq = 0;
14
15
  async admit(input, options) {
15
16
  const existing = [...this.entries.values()]
@@ -97,7 +98,7 @@ export class InMemoryWisdomStore {
97
98
  exceptions: [...(cur.exceptions ?? []), `retired:${meta.reason}:${meta.by}`],
98
99
  });
99
100
  }
100
- async recordOutcomes(events) {
101
+ async recordOutcomes(events, config) {
101
102
  const byId = new Map();
102
103
  for (const e of events) {
103
104
  const list = byId.get(e.wisdomId) ?? [];
@@ -110,7 +111,7 @@ export class InMemoryWisdomStore {
110
111
  continue;
111
112
  const folded = foldOutcomeEvents(cur, evs);
112
113
  let next = { ...cur, ...folded, updatedAt: Date.now() };
113
- const plan = planConfidenceUpdate(next);
114
+ const plan = planConfidenceUpdate(next, config);
114
115
  if (plan) {
115
116
  next = {
116
117
  ...next,
@@ -151,6 +152,43 @@ export class InMemoryWisdomStore {
151
152
  });
152
153
  }
153
154
  }
155
+ async recordAttributionWindow(input) {
156
+ const id = `waw_${++this.seq}`;
157
+ this.windows.set(id, {
158
+ ...input,
159
+ injectedIds: [...input.injectedIds],
160
+ citations: input.citations.map((c) => ({ ...c })),
161
+ id,
162
+ createdAt: Date.now(),
163
+ });
164
+ return id;
165
+ }
166
+ async listPendingWindows(limit) {
167
+ const pending = [...this.windows.values()]
168
+ .filter((w) => w.judgedAt === undefined)
169
+ .sort((a, b) => a.createdAt - b.createdAt);
170
+ // 缺省上限 500(与 Sqlite 对齐,防 pending 无界增长拖垮判官)
171
+ return pending.slice(0, limit && limit > 0 ? limit : 500);
172
+ }
173
+ async markWindowsJudged(ids, at) {
174
+ const now = at ?? Date.now();
175
+ const newlyJudged = [];
176
+ for (const id of ids) {
177
+ const w = this.windows.get(id);
178
+ // 只有真正置上的才算本次标记(跨进程幂等:他方先标则不发事件)
179
+ if (!w || w.judgedAt !== undefined)
180
+ continue;
181
+ w.judgedAt = now;
182
+ newlyJudged.push(id);
183
+ }
184
+ return newlyJudged;
185
+ }
186
+ async pruneWindows(before) {
187
+ for (const [id, w] of this.windows) {
188
+ if (w.judgedAt !== undefined && w.judgedAt < before)
189
+ this.windows.delete(id);
190
+ }
191
+ }
154
192
  async stats() {
155
193
  const list = [...this.entries.values()];
156
194
  const byStatus = Object.fromEntries(WISDOM_STATUSES.map((s) => [s, 0]));
@@ -49,6 +49,10 @@ export interface RunToolRuntime {
49
49
  }) => void;
50
50
  /** L2 级别 */
51
51
  pathContainment?: "strict" | "soft" | "none";
52
+ /** 拒绝最终组件为符号链接的文件读写(来自 effectPolicy.refuseFinalSymlink) */
53
+ refuseFinalSymlink?: boolean;
54
+ /** 拒绝清单(glob);空 = 不拒绝 */
55
+ pathDenylist?: readonly string[];
52
56
  confirmEffect?: import("@octopi-agent/core/types/tools.js").ToolExecutionContext["confirmEffect"];
53
57
  effectChannel?: "engine" | "host-gate";
54
58
  /** 提权策略(ops P3/P4,resolved):priv_exec 匹配面(allowlist 全等 / full 全量) */
@@ -78,13 +78,30 @@ export interface SessionAwareRunnerConfig {
78
78
  killSwitchPath?: string;
79
79
  /**
80
80
  * 安全配置漂移守卫(ops P2 §4.3/§8.4 拍板:漂移拒新 run)。
81
- * 宿主注入(通常 `createFileSecurityIntegrity`);未注入 = 无守卫(库嵌入自担)。
81
+ * 宿主注入(通常 `createSecurityIntegrityGuard`);未注入 = 无守卫(库嵌入自担)。
82
82
  */
83
83
  securityIntegrity?: {
84
- /** 启动期锚定的安全字段指纹(审计记录的「旧摘要」) */
84
+ /** 启动期锚定的安全字段指纹(审计记录的「旧摘要」;reattest 后为最新锚) */
85
85
  fingerprint: string;
86
86
  /** 复核当前安全配置(宿主实现,通常重读配置文件) */
87
87
  recheck: () => import('../agent/config-integrity.js').SecurityConfigDrift | Promise<import('../agent/config-integrity.js').SecurityConfigDrift>;
88
+ /**
89
+ * 受控写署名确认(ops P2 §8.4「WebUI 署名通道」):console 管理面写盘成功后
90
+ * 重新锚定指纹。未提供 = 只有重启能重新锚定。宿主实现(`createSecurityIntegrityGuard`)。
91
+ *
92
+ * 调用方**必须**传 `expectHash`(写后 hash)与 `allowedChanged`(本次写声明的字段范围):
93
+ * guard 据此拒绝 TOCTOU 与白洗(评审 M1)。
94
+ */
95
+ reattest?: (options: {
96
+ /** 写后原文 hash;与盘上现状不符 = 有第三方写入,拒绝重锚 */
97
+ expectHash: string;
98
+ /** 允许变化的顶层安全字段;超出范围 = 既存篡改,拒绝重锚 */
99
+ allowedChanged: string[];
100
+ }) => {
101
+ previousFingerprint: string;
102
+ fingerprint: string;
103
+ changed: string[];
104
+ };
88
105
  };
89
106
  /**
90
107
  * 工具效应隔离策略(宪法 I5)
@@ -231,6 +248,8 @@ export declare function adaptLoopEvent(event: HarnessLoopEvent, meta: {
231
248
  export declare class SessionAwareRunner {
232
249
  /** 本 Runner 生效的 L2 级别(由 effectPolicy 展开) */
233
250
  private effectPathContainment;
251
+ private effectRefuseFinalSymlink;
252
+ private effectPathDenylist;
234
253
  private effectChannel;
235
254
  private effectAllowRoots;
236
255
  /** Effective effectPolicy.mode (for Runtime injection / UI) */
@@ -294,6 +313,8 @@ export declare class SessionAwareRunner {
294
313
  private systemPromptAssembler?;
295
314
  /** Assembler 层缓存清理钩子(可选接线;与 contextDetachIndex 无关) */
296
315
  private systemPromptAssemblerClear?;
316
+ /** Wisdom 归因窗口记账钩子(学习环;不是观测通道,失败不得影响 run 收口) */
317
+ private wisdomAttributionSink?;
297
318
  /** turn 级 Knowledge grounding(可选;arch/knowledge-layer.md §4.4) */
298
319
  private groundingAssembler?;
299
320
  /** 模型快照解析器(Gateway 注入;每 run 只调一次) */
@@ -401,6 +422,10 @@ export declare class SessionAwareRunner {
401
422
  runtimeSnapshot?: string;
402
423
  manifest?: import('../context/layer-types.js').AssembleManifest;
403
424
  }>, clearSession?: (sessionId: string) => void): void;
425
+ /**
426
+ * 注入 Wisdom 归因窗口记账(run 收尾;学习环)
427
+ */
428
+ setWisdomAttributionSink(sink: (info: import('../memory/wisdom-attribution.js').WisdomRunWindowInfo) => void | Promise<void>): void;
404
429
  /**
405
430
  * 注入 turn 级 Knowledge grounding(可选)
406
431
  */
@@ -18,6 +18,7 @@ import { OpsAuditJournal, OpsAuditFileExportSink } from '../extension/execution-
18
18
  import { getOctopiHome } from '../../paths.js';
19
19
  import { extractLayerQuery } from '../context/layer-types.js';
20
20
  import { formatTurnEndContent, formatTurnId, formatTurnStartContent, formatTurnContextXml, isTurnStartContent, joinSlotXml, parseTurnIdFromContent, } from '../context/turn-envelope.js';
21
+ import { collectRunAssistantTexts } from '../memory/wisdom-attribution.js';
21
22
  import { splitRuntimeEnvironmentInjection, withRuntimeEnvironmentInjection } from '../context/runtime-datetime.js';
22
23
  import { loadRootInstructionsInjection } from '../context/root-instructions.js';
23
24
  import { extractTaskQueryHints, renderSessionTasksInjection } from '../session/tasks/render.js';
@@ -265,6 +266,8 @@ export function adaptLoopEvent(event, meta, state) {
265
266
  export class SessionAwareRunner {
266
267
  /** 本 Runner 生效的 L2 级别(由 effectPolicy 展开) */
267
268
  effectPathContainment = "none";
269
+ effectRefuseFinalSymlink = false;
270
+ effectPathDenylist = [];
268
271
  effectChannel = "engine";
269
272
  effectAllowRoots = [];
270
273
  /** Effective effectPolicy.mode (for Runtime injection / UI) */
@@ -328,6 +331,8 @@ export class SessionAwareRunner {
328
331
  systemPromptAssembler;
329
332
  /** Assembler 层缓存清理钩子(可选接线;与 contextDetachIndex 无关) */
330
333
  systemPromptAssemblerClear;
334
+ /** Wisdom 归因窗口记账钩子(学习环;不是观测通道,失败不得影响 run 收口) */
335
+ wisdomAttributionSink;
331
336
  /** turn 级 Knowledge grounding(可选;arch/knowledge-layer.md §4.4) */
332
337
  groundingAssembler;
333
338
  /** 模型快照解析器(Gateway 注入;每 run 只调一次) */
@@ -538,6 +543,12 @@ export class SessionAwareRunner {
538
543
  this.systemPromptAssembler = assembler;
539
544
  this.systemPromptAssemblerClear = clearSession;
540
545
  }
546
+ /**
547
+ * 注入 Wisdom 归因窗口记账(run 收尾;学习环)
548
+ */
549
+ setWisdomAttributionSink(sink) {
550
+ this.wisdomAttributionSink = sink;
551
+ }
541
552
  /**
542
553
  * 注入 turn 级 Knowledge grounding(可选)
543
554
  */
@@ -630,6 +641,10 @@ export class SessionAwareRunner {
630
641
  let observerRunId = '';
631
642
  let observerFinalMessages;
632
643
  let observerEndReason;
644
+ /** Wisdom 归因窗口素材(装配时抓 sources/query,收尾时切本轮 assistant 文本) */
645
+ let wisdomInjectedIds = [];
646
+ let runQueryText = '';
647
+ let runMessagesBase = 0;
633
648
  /**
634
649
  * 桥接状态(assistant 文本 / 停止原因)。
635
650
  *
@@ -833,9 +848,9 @@ export class SessionAwareRunner {
833
848
  sessionId,
834
849
  data: { ...driftData },
835
850
  });
836
- throw new Error(`security_config_drift: security-relevant config changed on disk (changed: ${integrity.changed.join(', ')}); ` +
837
- `restart required to re-attest (restart adopts what is on disk — treat the human restart as the attestation act; ` +
838
- `automated attestation lands with the ConfigService write-back)`);
851
+ throw new Error(`security_config_drift: security-relevant config changed on disk outside the console channel (changed: ${integrity.changed.join(', ')}); ` +
852
+ `restart required to re-attest (restart adopts what is on disk — treat the human restart as the attestation act). ` +
853
+ `Console/WebUI config writes re-attest automatically; this drift means the file was edited directly, bypassing the console`);
839
854
  }
840
855
  // ops P5 kill switch:宿主侧急停哨兵——run 准入即拒(不依赖 LLM 判断/agent 合作)
841
856
  {
@@ -868,6 +883,8 @@ export class SessionAwareRunner {
868
883
  const eff = resolveEffectiveEffectPolicy(this.config.effectPolicy ?? {}, this.config.agentWorkspace ?? effectiveRunConfig.cwd ?? undefined, isolation);
869
884
  const sessionExtraRoots = readSessionEffectOverrides(session.metadata).transactionRoots;
870
885
  this.effectPathContainment = eff.pathContainment;
886
+ this.effectRefuseFinalSymlink = eff.refuseFinalSymlink;
887
+ this.effectPathDenylist = eff.pathDenylist;
871
888
  this.effectChannel = eff.effects;
872
889
  this.effectAllowRoots = mergeTransactionRoots(eff.allowRoots, sessionExtraRoots);
873
890
  this.effectMode = eff.mode;
@@ -1066,6 +1083,12 @@ export class SessionAwareRunner {
1066
1083
  : null;
1067
1084
  if (assembled.manifest) {
1068
1085
  const assembledAt = Date.now();
1086
+ const layerQuery = extractLayerQuery(session.messages, { topicHints });
1087
+ // 归因窗口素材(学习环,非观测):本轮 wisdom sources + query + 消息基线
1088
+ wisdomInjectedIds =
1089
+ assembled.manifest.layers.find((l) => l.id === 'wisdom')?.sources ?? [];
1090
+ runQueryText = layerQuery;
1091
+ runMessagesBase = session.messages.length;
1069
1092
  this.emitObserved({
1070
1093
  type: 'context.layers.assembled',
1071
1094
  timestamp: assembledAt,
@@ -1076,7 +1099,7 @@ export class SessionAwareRunner {
1076
1099
  agentId: _agentId,
1077
1100
  manifest: assembled.manifest,
1078
1101
  enabledLayerIds: assembled.manifest.layers.map((l) => l.id),
1079
- query: extractLayerQuery(session.messages, { topicHints }),
1102
+ query: layerQuery,
1080
1103
  assembledAt,
1081
1104
  },
1082
1105
  });
@@ -1246,6 +1269,8 @@ export class SessionAwareRunner {
1246
1269
  ? [resolvedToolCwd.cwd]
1247
1270
  : undefined,
1248
1271
  pathContainment: this.effectPathContainment,
1272
+ refuseFinalSymlink: this.effectRefuseFinalSymlink,
1273
+ pathDenylist: this.effectPathDenylist,
1249
1274
  confirmEffect: this.config.confirmEffect,
1250
1275
  effectChannel: this.effectChannel,
1251
1276
  escalation: this.effectEscalation,
@@ -1990,6 +2015,25 @@ export class SessionAwareRunner {
1990
2015
  inboxRun?.close();
1991
2016
  release();
1992
2017
  gateRelease?.();
2018
+ // Wisdom 归因窗口记账(学习环):锁释放后再写,DB 慢不得拖住 session 锁;
2019
+ // 本轮注入 + 结局 + 引用摘录 → 判官批量判决。失败只告警(学习环可由下批窗口补),
2020
+ // 不走 eventSink/Observer——学习记账不是观测通道。
2021
+ if (this.wisdomAttributionSink && wisdomInjectedIds.length > 0 && observerFinalMessages) {
2022
+ try {
2023
+ await this.wisdomAttributionSink({
2024
+ sessionId,
2025
+ agentId: _agentId,
2026
+ outcome: runEndReason,
2027
+ query: runQueryText,
2028
+ injectedIds: wisdomInjectedIds,
2029
+ assistantTexts: collectRunAssistantTexts(observerFinalMessages, runMessagesBase),
2030
+ });
2031
+ }
2032
+ catch (err) {
2033
+ // 学习环静默关闭是严重问题:至少告警一次,不得只吞不报
2034
+ console.warn(`[Runner] wisdom attribution sink failed: ${err instanceof Error ? err.message : String(err)}`);
2035
+ }
2036
+ }
1993
2037
  }
1994
2038
  }
1995
2039
  /**
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Path glob compilation — shared by tool glob filters and path denylists.
3
+ *
4
+ * Semantics follow rg/git so that `file_search`'s `glob` argument and
5
+ * `effectPolicy.pathDenylist` cannot drift apart:
6
+ * - `**` crosses directories; `*` and `?` do not cross `/`
7
+ * - a pattern without `/` (for example `*.md`) matches at any depth
8
+ * - `{a,b}` alternatives are supported, including nesting
9
+ */
10
+ /**
11
+ * Compile a path glob into a regular expression over root-relative paths.
12
+ *
13
+ * @param glob - glob pattern
14
+ * @returns anchored, case-insensitive matcher for a root-relative path
15
+ */
16
+ export declare function globToPathRegex(glob: string): RegExp;
17
+ /**
18
+ * Normalize a deny pattern into the path dialect the matcher speaks.
19
+ *
20
+ * Windows deployments write separators the way their shell does, so `\` is
21
+ * always a separator here. That makes an escaped literal (`.git\**` meaning
22
+ * "a file literally named `.git*`") impossible to express — acceptable, since a
23
+ * separator is what every real denylist entry means.
24
+ *
25
+ * @param pattern - raw deny pattern from configuration
26
+ * @returns pattern using `/` separators
27
+ */
28
+ export declare function normalizeDenyPattern(pattern: string): string;
29
+ /**
30
+ * Reject deny patterns that can never match a root-relative path.
31
+ *
32
+ * A pattern that silently matches nothing is worse than a startup error: the
33
+ * deployment keeps believing it is protected. Shapes rejected here are all
34
+ * spellings that look meaningful but cannot match (`/x` anchors outside the
35
+ * root, `x/` never matches a resolved file, `../x` has no candidate).
36
+ *
37
+ * @param pattern - raw deny pattern from configuration
38
+ */
39
+ export declare function validateDenyPattern(pattern: string): void;
40
+ /**
41
+ * Whether a root-relative path matches any denylist pattern.
42
+ *
43
+ * Both the full relative path and the file name are tested, so `.env*` and
44
+ * `.git/**` can coexist without the caller deciding which form a pattern means.
45
+ * Invalid patterns are the caller's mistake and throw: silently ignoring a
46
+ * typo'd security pattern would leave the deployment believing it is protected.
47
+ *
48
+ * @param relativePath - path relative to the containing root, using `/`
49
+ * @param patterns - denylist globs
50
+ * @returns true when any pattern matches
51
+ */
52
+ export declare function matchesDenyPattern(relativePath: string, patterns: readonly string[]): boolean;