@dommaker/harness 4.0.1 → 5.0.0

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 (117) hide show
  1. package/README.md +7 -8
  2. package/dist/bootstrap/bootstrap.d.ts +15 -0
  3. package/dist/bootstrap/bootstrap.js +18 -1
  4. package/dist/bootstrap/index.d.ts +2 -2
  5. package/dist/bootstrap/index.js +3 -2
  6. package/dist/cli/commands/acceptance.d.ts +8 -0
  7. package/dist/cli/commands/acceptance.js +45 -24
  8. package/dist/cli/commands/check.d.ts +2 -0
  9. package/dist/cli/commands/check.js +36 -5
  10. package/dist/cli/commands/command.js +1 -1
  11. package/dist/cli/commands/definitions.js +4 -1
  12. package/dist/cli/commands/release.d.ts +11 -3
  13. package/dist/cli/commands/release.js +159 -52
  14. package/dist/cli/commands/report.d.ts +2 -0
  15. package/dist/cli/commands/report.js +54 -6
  16. package/dist/cli/commands/security.d.ts +3 -3
  17. package/dist/cli/commands/security.js +3 -2
  18. package/dist/cli/commands/sync-docs/capabilities-syncer.d.ts +3 -40
  19. package/dist/cli/commands/sync-docs/capabilities-syncer.js +5 -159
  20. package/dist/cli/commands/sync-docs/compact.js +2 -2
  21. package/dist/cli/commands/sync-docs/context-syncer.d.ts +4 -36
  22. package/dist/cli/commands/sync-docs/context-syncer.js +4 -221
  23. package/dist/cli/commands/sync-docs/index.d.ts +8 -8
  24. package/dist/cli/commands/sync-docs/index.js +8 -8
  25. package/dist/cli/commands/sync-docs/main-flow.d.ts +5 -4
  26. package/dist/cli/commands/sync-docs/main-flow.js +6 -5
  27. package/dist/cli/commands/sync-docs/sync-output.d.ts +1 -1
  28. package/dist/cli/commands/sync-docs/sync-output.js +4 -0
  29. package/dist/cli/commands/sync-docs/sync-writes.d.ts +1 -1
  30. package/dist/cli/commands/validate.d.ts +2 -0
  31. package/dist/cli/commands/validate.js +40 -1
  32. package/dist/core/command-execution-policy.d.ts +59 -0
  33. package/dist/core/command-execution-policy.js +167 -0
  34. package/dist/core/config-files.d.ts +8 -0
  35. package/dist/core/config-files.js +62 -0
  36. package/dist/core/constraints/capabilities-parser.d.ts +2 -1
  37. package/dist/core/constraints/capabilities-parser.js +2 -1
  38. package/dist/core/constraints/checker.d.ts +18 -6
  39. package/dist/core/constraints/checker.js +21 -11
  40. package/dist/core/constraints/checkers/no-hardcoded-credentials.js +14 -15
  41. package/dist/core/constraints/checkers/no-test-simplification.js +8 -6
  42. package/dist/core/constraints/checkers/templated/exec.d.ts +4 -0
  43. package/dist/core/constraints/checkers/templated/exec.js +11 -48
  44. package/dist/core/constraints/checkers/templated/file-exists.js +7 -4
  45. package/dist/core/constraints/checkers/templated/regex-scan.js +11 -15
  46. package/dist/core/constraints/checkers/types.d.ts +13 -2
  47. package/dist/core/constraints/checkers/types.js +5 -2
  48. package/dist/core/constraints/construction-sites.d.ts +1 -1
  49. package/dist/core/constraints/construction-sites.js +1 -1
  50. package/dist/core/constraints/definitions.d.ts +2 -2
  51. package/dist/core/constraints/definitions.js +2 -2
  52. package/dist/core/constraints/injection-writer.d.ts +1 -1
  53. package/dist/core/constraints/injection-writer.js +1 -1
  54. package/dist/core/constraints/project-snapshot.d.ts +43 -0
  55. package/dist/core/constraints/project-snapshot.js +103 -0
  56. package/dist/core/constraints/run-env.d.ts +35 -0
  57. package/dist/core/constraints/run-env.js +36 -0
  58. package/dist/{cli/commands/sync-docs → core/docs-sync}/agents-syncer.d.ts +2 -0
  59. package/dist/{cli/commands/sync-docs → core/docs-sync}/agents-syncer.js +5 -3
  60. package/dist/core/docs-sync/capabilities-table.d.ts +46 -0
  61. package/dist/core/docs-sync/capabilities-table.js +200 -0
  62. package/dist/core/docs-sync/context-collector.d.ts +40 -0
  63. package/dist/core/docs-sync/context-collector.js +227 -0
  64. package/dist/{cli/commands/sync-docs → core/docs-sync}/project-reader.d.ts +5 -1
  65. package/dist/{cli/commands/sync-docs → core/docs-sync}/project-reader.js +10 -6
  66. package/dist/{cli/commands/sync-docs → core/docs-sync}/sync-state.d.ts +15 -9
  67. package/dist/{cli/commands/sync-docs → core/docs-sync}/sync-state.js +26 -29
  68. package/dist/core/effective-constraints.d.ts +1 -1
  69. package/dist/core/effective-constraints.js +1 -1
  70. package/dist/core/validators/check-handlers/command.js +22 -0
  71. package/dist/core/validators/check-handlers/output.js +26 -3
  72. package/dist/core/validators/checkpoint.d.ts +4 -0
  73. package/dist/core/validators/checkpoint.js +10 -2
  74. package/dist/gates/acceptance.d.ts +8 -4
  75. package/dist/gates/acceptance.js +76 -14
  76. package/dist/gates/command.d.ts +3 -4
  77. package/dist/gates/command.js +2 -3
  78. package/dist/gates/contract.d.ts +3 -4
  79. package/dist/gates/contract.js +0 -1
  80. package/dist/gates/definitions.d.ts +2 -4
  81. package/dist/gates/definitions.js +2 -8
  82. package/dist/gates/performance.d.ts +10 -4
  83. package/dist/gates/performance.js +49 -5
  84. package/dist/gates/review.d.ts +3 -4
  85. package/dist/gates/review.js +0 -1
  86. package/dist/gates/security.d.ts +3 -4
  87. package/dist/gates/security.js +26 -19
  88. package/dist/gates/types.d.ts +46 -19
  89. package/dist/index.d.ts +5 -4
  90. package/dist/index.js +9 -6
  91. package/dist/knowledge/index.d.ts +1 -1
  92. package/dist/knowledge/index.js +1 -2
  93. package/dist/knowledge/ingest.d.ts +32 -17
  94. package/dist/knowledge/ingest.js +188 -90
  95. package/dist/knowledge/lifecycle.d.ts +15 -0
  96. package/dist/knowledge/lifecycle.js +62 -0
  97. package/dist/knowledge/query.d.ts +11 -1
  98. package/dist/knowledge/query.js +61 -9
  99. package/dist/knowledge/store.d.ts +56 -3
  100. package/dist/knowledge/store.js +108 -30
  101. package/dist/monitoring/index.d.ts +2 -1
  102. package/dist/monitoring/index.js +3 -1
  103. package/dist/monitoring/traces.d.ts +12 -0
  104. package/dist/monitoring/traces.js +26 -4
  105. package/dist/types/checkpoint.d.ts +28 -1
  106. package/dist/types/command-execution-policy.d.ts +73 -0
  107. package/dist/types/command-execution-policy.js +16 -0
  108. package/dist/types/constraint.d.ts +0 -12
  109. package/dist/utils/exec.d.ts +7 -1
  110. package/dist/utils/exec.js +7 -1
  111. package/package.json +1 -1
  112. package/dist/core/constraints/check-cache.d.ts +0 -43
  113. package/dist/core/constraints/check-cache.js +0 -77
  114. package/dist/core/constraints/checkers/templated/glob.d.ts +0 -8
  115. package/dist/core/constraints/checkers/templated/glob.js +0 -14
  116. /package/dist/{cli/commands/sync-docs → core/docs-sync}/preserve-block.d.ts +0 -0
  117. /package/dist/{cli/commands/sync-docs → core/docs-sync}/preserve-block.js +0 -0
@@ -7,43 +7,68 @@
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.KnowledgeIngest = void 0;
10
- exports.sanitizeExternalContent = sanitizeExternalContent;
11
10
  const types_1 = require("./types");
12
11
  const audit_1 = require("./audit");
13
12
  const audit_rules_1 = require("./audit-rules");
14
13
  const frontmatter_1 = require("../utils/frontmatter");
15
- const MAX_EXTERNAL_CONTENT_LENGTH = 5000;
16
- /** Known prompt injection patterns to strip from external content */
17
- const INJECTION_PATTERNS = [
18
- /ignore\s+(all\s+)?previous\s+instructions/gi,
19
- /ignore\s+(all\s+)?prior\s+instructions/gi,
20
- /system:\s*/gi,
21
- /\[INST\]/gi,
22
- /\[\/INST\]/gi,
23
- /<\|im_start\|>/gi,
24
- /<\|im_end\|>/gi,
25
- /you\s+are\s+now\s+/gi,
26
- /forget\s+(everything|all)\s+(you|about)/gi,
27
- /new\s+instructions?:/gi,
28
- /override\s+(your|system)\s+(instructions|prompt)/gi,
29
- ];
14
+ // ── Ingest ─────────────────────────────────────────────────
30
15
  /**
31
- * Sanitize external content for safe ingest.
32
- * - Strips known prompt injection patterns
33
- * - Limits content length
34
- * - Returns sanitized string
16
+ * D7 ingest 批内上下文(包内私有):磁盘去重基线与虚拟序号起点惰性各读一次,
17
+ * 本批已接受条目(新建/merge 的终态)即时进 overlay——
18
+ * 去重视图 = 磁盘基线 + overlay;虚拟 index = 起点 + overlay 终态序号记录
19
+ * (auto-fix 后的 maturity 即时生效,复刻旧逐条路径的序号口径)。
20
+ * reject 不入 overlay。
35
21
  */
36
- function sanitizeExternalContent(content) {
37
- let sanitized = content;
38
- for (const pattern of INJECTION_PATTERNS) {
39
- sanitized = sanitized.replace(pattern, '[FILTERED]');
22
+ class IngestContext {
23
+ store;
24
+ diskCache;
25
+ indexCache;
26
+ overlay = [];
27
+ overlayIndex = [];
28
+ constructor(store) {
29
+ this.store = store;
30
+ }
31
+ /** 共享磁盘去重基线(readEntriesFromDisk 每批至多一次) */
32
+ disk() {
33
+ return (this.diskCache ??= this.store.readEntriesFromDisk());
34
+ }
35
+ /** 虚拟序号/索引状态起点(readIndex 每批至多一次) */
36
+ index() {
37
+ return (this.indexCache ??= this.store.readIndex());
38
+ }
39
+ /** 本批已接受条目的最新状态入列;同 id 替换而非追加(stale 旧态不得残留) */
40
+ accept(entry) {
41
+ const at = this.overlay.findIndex(e => e.id === entry.id);
42
+ if (at >= 0) {
43
+ this.overlay[at] = entry;
44
+ }
45
+ else {
46
+ this.overlay.push(entry);
47
+ }
48
+ const record = { id: entry.id, type: entry.type, maturity: entry.maturity };
49
+ const recAt = this.overlayIndex.findIndex(r => r.id === entry.id);
50
+ if (recAt >= 0) {
51
+ this.overlayIndex[recAt] = record;
52
+ }
53
+ else {
54
+ this.overlayIndex.push(record);
55
+ }
40
56
  }
41
- if (sanitized.length > MAX_EXTERNAL_CONTENT_LENGTH) {
42
- sanitized = sanitized.slice(0, MAX_EXTERNAL_CONTENT_LENGTH) + '...[truncated]';
57
+ /**
58
+ * 去重视图:磁盘基线中被本批更新过的 id 以 overlay 最新状态为准——
59
+ * stale 磁盘条目不得抢在更新态前命中(同批连续 merge 第二次须基于第一次终态);
60
+ * 顺序语义保持盘序在前、本批接受序在后。
61
+ */
62
+ view() {
63
+ const updatedIds = new Set(this.overlay.map(e => e.id));
64
+ return [...this.disk().filter(e => !updatedIds.has(e.id)), ...this.overlay];
65
+ }
66
+ /** 虚拟 index:起点中被本批更新过的 id 按 overlay 终态替换(每 id 至多计一次序号) */
67
+ virtualIndex() {
68
+ const updatedIds = new Set(this.overlayIndex.map(r => r.id));
69
+ return [...this.index().filter(r => !updatedIds.has(r.id)), ...this.overlayIndex];
43
70
  }
44
- return sanitized;
45
71
  }
46
- // ── Ingest ─────────────────────────────────────────────────
47
72
  class KnowledgeIngest {
48
73
  store;
49
74
  constructor(store) {
@@ -55,63 +80,30 @@ class KnowledgeIngest {
55
80
  * Returns a discriminated result: accepted = saved (new or merged), rejected = audit gate refusal.
56
81
  */
57
82
  ingestEntry(partial, options) {
58
- const entry = this.buildEntry(partial, options);
59
- // Quality gate: audit before saving
60
- const audit = new audit_1.KnowledgeAudit(this.store);
61
- let issues = audit.validate(entry);
62
- const critical = issues.filter(i => i.action === 'reject');
63
- if (critical.length > 0) {
64
- // Reject: return without saving; caller branches on status / reasons
65
- return { status: 'rejected', entry, reasons: critical.map(i => i.detail) };
66
- }
67
- // If caller explicitly set maturity, skip demote actions from audit.
68
- // Demote is for auto-inferred maturity that's too high; explicit is a user decision.
69
- if (options.maturity) {
70
- issues = issues.filter(i => i.action !== 'demote');
71
- }
72
- // Dedup check: same title + same type
73
- const existing = this.findDuplicate(entry.title, entry.content, entry.type);
74
- if (existing) {
75
- // Merge: update existing entry with new content and metadata
76
- return { status: 'accepted', entry: this.mergeEntries(existing, entry, options) };
77
- }
78
- this.store.save(entry);
79
- // Post-save: apply auto-fixes (archive/demote/flag)
80
- const fixable = issues.filter(i => i.action !== 'reject');
81
- if (fixable.length > 0) {
82
- for (const issue of fixable) {
83
- if (issue.action === 'archive') {
84
- this.store.update(entry.id, { maturity: 'archived' });
85
- }
86
- else if (issue.action === 'demote') {
87
- this.store.update(entry.id, { maturity: 'draft' });
88
- }
89
- else if (issue.action === 'flag') {
90
- const saved = this.store.get(entry.id);
91
- if (saved && !saved.tags.includes('low_quality')) {
92
- this.store.update(entry.id, { tags: [...saved.tags, 'low_quality'] });
93
- }
94
- }
95
- }
96
- }
97
- return { status: 'accepted', entry };
83
+ return this.ingestOne(partial, options, new IngestContext(this.store));
98
84
  }
99
85
  /**
100
86
  * Ingest multiple entries in batch.
101
87
  * Returns one result per input (accepted/rejected).
88
+ *
89
+ * D7:批内共享一次磁盘去重视图与虚拟 index 起点(IngestContext,惰性各读一次),
90
+ * 本批已接受的新建/merge 即时纳入视图,保留批内重复语义;逐条 ingestEntry 行为不变。
91
+ *
92
+ * 统一落盘:新建与 merge 的完整终态(含 auto-fix 折好)收入写计划,
93
+ * 批尾一次 saveAll——全批只重写一次 index.json,整批预校验
94
+ * (任一脏枚举全批拒写,不制造已落盘假象);批内同 id 按 saveAll 后写覆盖语义。
95
+ * 空批零读写。单条路径(ingestEntry)写时序不变。
102
96
  */
103
97
  ingestBatch(partials, options) {
104
- return partials.map(p => this.ingestEntry(p, options));
105
- }
106
- /**
107
- * Ingest external content with sanitization.
108
- * - Sanitizes content (strips injection patterns, limits length)
109
- * - Forces origin: 'external'
110
- * - Uses consumptionMode from options (default: 'reference')
111
- */
112
- ingestExternal(partial, options) {
113
- const sanitizedContent = sanitizeExternalContent(partial.content || '');
114
- return this.ingestEntry({ ...partial, content: sanitizedContent }, { ...options, origin: 'external' });
98
+ if (partials.length === 0)
99
+ return [];
100
+ const ctx = new IngestContext(this.store);
101
+ const plan = [];
102
+ const results = partials.map(p => this.ingestOne(p, options, ctx, plan));
103
+ if (plan.length > 0) {
104
+ this.store.saveAll(plan);
105
+ }
106
+ return results;
115
107
  }
116
108
  /**
117
109
  * 摄入前单条校验(KnowledgeLinter.validateEntry 的保种落点,ADR-0040 Phase 4;
@@ -207,10 +199,105 @@ class KnowledgeIngest {
207
199
  return issues;
208
200
  }
209
201
  // ── Internal ───────────────────────────────────────────────
210
- buildEntry(partial, options) {
202
+ /**
203
+ * 单条的批内共用执行体(D7):build → audit.validate → reject 或
204
+ * 视图去重 → merge / 新建 + auto-fix。ingestEntry 每调新建上下文(= 原单条行为);
205
+ * ingestBatch 全批共享一个上下文。
206
+ *
207
+ * `plan` 存在 = 批次写计划模式:新建与 merge 的完整终态收进 plan(不逐条落盘,
208
+ * 由批尾一次 saveAll 统一写入);缺省 = 单条即时写路径(save + 逐 fix update),
209
+ * 写时序与旧实现逐字一致。返回值契约两种模式相同(新建返回 pre-fix entry,
210
+ * merge 返回合并终态)。
211
+ */
212
+ ingestOne(partial, options, ctx, plan) {
213
+ const entry = this.buildEntry(partial, options, ctx);
214
+ // Quality gate: audit before saving
215
+ const audit = new audit_1.KnowledgeAudit(this.store);
216
+ let issues = audit.validate(entry);
217
+ const critical = issues.filter(i => i.action === 'reject');
218
+ if (critical.length > 0) {
219
+ // Reject: return without saving; caller branches on status / reasons
220
+ return { status: 'rejected', entry, reasons: critical.map(i => i.detail) };
221
+ }
222
+ // If caller explicitly set maturity, skip demote actions from audit.
223
+ // Demote is for auto-inferred maturity that's too high; explicit is a user decision.
224
+ if (options.maturity) {
225
+ issues = issues.filter(i => i.action !== 'demote');
226
+ }
227
+ // Dedup check: same title + same type(共享视图 = 磁盘基线 + 本批已接受终态)
228
+ const existing = this.findDuplicate(entry.title, entry.content, entry.type, ctx.view());
229
+ if (existing) {
230
+ // Merge: update existing entry with new content and metadata(merge 分支不做新条目 auto-fix)
231
+ if (plan) {
232
+ const merged = this.computeMerge(existing, entry, options);
233
+ plan.push(merged);
234
+ ctx.accept(merged);
235
+ return { status: 'accepted', entry: merged };
236
+ }
237
+ const merged = this.mergeEntries(existing, entry, options);
238
+ ctx.accept(merged);
239
+ return { status: 'accepted', entry: merged };
240
+ }
241
+ if (plan) {
242
+ // 批次模式:auto-fix 折进终态收写计划,批尾一次落盘;返回值仍是 pre-fix entry
243
+ const finalEntry = this.foldAutoFixes(entry, issues);
244
+ plan.push(finalEntry);
245
+ ctx.accept(finalEntry);
246
+ return { status: 'accepted', entry };
247
+ }
248
+ this.store.save(entry);
249
+ // Post-save: apply auto-fixes (archive/demote/flag)
250
+ const finalEntry = this.persistAutoFixes(entry, issues);
251
+ ctx.accept(finalEntry);
252
+ return { status: 'accepted', entry };
253
+ }
254
+ /**
255
+ * auto-fix 折叠(纯,D7 批次模式用):archive/demote/flag 依 issues 顺序折进条目副本,
256
+ * 与单条路径逐步 update 的终态一致。merge 分支不调用(既有语义)。
257
+ */
258
+ foldAutoFixes(entry, issues) {
259
+ let current = entry;
260
+ for (const issue of issues) {
261
+ if (issue.action === 'archive') {
262
+ current = { ...current, maturity: 'archived' };
263
+ }
264
+ else if (issue.action === 'demote') {
265
+ current = { ...current, maturity: 'draft' };
266
+ }
267
+ else if (issue.action === 'flag') {
268
+ if (!current.tags.includes('low_quality')) {
269
+ current = { ...current, tags: [...current.tags, 'low_quality'] };
270
+ }
271
+ }
272
+ }
273
+ return current;
274
+ }
275
+ /** 单条即时写路径的 auto-fix:逐步 store.update(写时序与旧实现一致),返回折好终态供 overlay */
276
+ persistAutoFixes(entry, issues) {
277
+ let current = entry;
278
+ for (const issue of issues) {
279
+ if (issue.action === 'archive') {
280
+ this.store.update(entry.id, { maturity: 'archived' });
281
+ current = { ...current, maturity: 'archived' };
282
+ }
283
+ else if (issue.action === 'demote') {
284
+ this.store.update(entry.id, { maturity: 'draft' });
285
+ current = { ...current, maturity: 'draft' };
286
+ }
287
+ else if (issue.action === 'flag') {
288
+ if (!current.tags.includes('low_quality')) {
289
+ const tags = [...current.tags, 'low_quality'];
290
+ this.store.update(entry.id, { tags });
291
+ current = { ...current, tags };
292
+ }
293
+ }
294
+ }
295
+ return current;
296
+ }
297
+ buildEntry(partial, options, ctx) {
211
298
  const now = new Date().toISOString();
212
299
  const type = partial.type || 'guideline';
213
- const id = partial.id || this.generateId(type);
300
+ const id = partial.id || this.generateId(type, ctx);
214
301
  return {
215
302
  id,
216
303
  type,
@@ -233,18 +320,21 @@ class KnowledgeIngest {
233
320
  skillId: partial.skillId,
234
321
  };
235
322
  }
236
- generateId(type) {
323
+ generateId(type, ctx) {
237
324
  const prefix = type.toUpperCase().slice(0, 3);
238
- // 序号取自索引计数(harness#107):不再走 list() 逐条读条目文件;
239
- // 与 list() 默认过滤口径一致,archived/deprecated 不计入序号
240
- const existing = this.store.readIndex()
325
+ // 序号取自虚拟 index 计数(harness#107 + D7):不再走 list() 逐条读条目文件;
326
+ // 与 list() 默认过滤口径一致,archived/deprecated 不计入序号。
327
+ // 批内起点 = 批首一次 readIndex,叠加本批已接受条目的终态 maturity——
328
+ // 旧逐条路径里前一条 save 后 auto-fix 的 archived 会立即影响下一条序号,此处同口径复刻。
329
+ const existing = ctx.virtualIndex()
241
330
  .filter(e => e.type === type && e.maturity !== 'archived' && e.maturity !== 'deprecated');
242
331
  const seq = String(existing.length + 1).padStart(3, '0');
243
332
  return `${prefix}-${seq}`;
244
333
  }
245
- findDuplicate(title, content, type) {
246
- // A1: Read from disk directly to avoid stale index causing dedup failure
247
- const all = this.store.readEntriesFromDisk().filter(e => e.type === type);
334
+ findDuplicate(title, content, type, candidates) {
335
+ // A1: 共享视图来自盘驱动枚举(readEntriesFromDisk),stale index 不造成去重失效;
336
+ // D7:批内视图含本批已接受终态,重复语义与旧逐条路径一致
337
+ const all = candidates.filter(e => e.type === type);
248
338
  // Exact match (case-insensitive)
249
339
  const exact = all.find(e => (e.title || '').toLowerCase() === title.toLowerCase());
250
340
  if (exact)
@@ -309,8 +399,13 @@ class KnowledgeIngest {
309
399
  const overlap = tokensA.filter(t => setB.has(t)).length;
310
400
  return overlap / Math.max(tokensA.length, tokensB.length);
311
401
  }
312
- mergeEntries(existing, incoming, options) {
313
- const merged = {
402
+ /**
403
+ * 合并终态(纯,D7 两种写模式共用):merge 字段口径与来源上限(MAX_SOURCE_REFS)
404
+ * 只此一份。merge 分支不做新条目 auto-fix(既有语义)。
405
+ */
406
+ computeMerge(existing, incoming, options) {
407
+ return {
408
+ ...existing,
314
409
  content: incoming.content || existing.content,
315
410
  maturity: options.maturity || existing.maturity,
316
411
  lastReferenced: new Date().toISOString(),
@@ -319,6 +414,9 @@ class KnowledgeIngest {
319
414
  tags: [...new Set([...existing.tags, ...incoming.tags])],
320
415
  sourceReferences: [...existing.sourceReferences, ...incoming.sourceReferences].slice(-audit_rules_1.MAX_SOURCE_REFS),
321
416
  };
417
+ }
418
+ mergeEntries(existing, incoming, options) {
419
+ const merged = this.computeMerge(existing, incoming, options);
322
420
  // fail-fast:刚经 readEntriesFromDisk 读到的条目 update 不到 = 并发删除/索引漂移,不静默吞
323
421
  const updated = this.store.update(existing.id, merged);
324
422
  if (!updated) {
@@ -26,6 +26,21 @@ export declare class KnowledgeLifecycle {
26
26
  * Optionally records execution success/failure.
27
27
  */
28
28
  recordReference(entryId: string, contributor?: string, success?: boolean, source?: 'human' | 'auto'): KnowledgeEntry | undefined;
29
+ /**
30
+ * 批量形 recordReference(P1.3):一次 query 的 N 条引用收集进一次 applyAll 落盘,
31
+ * 消除 N 次「全量重写 index.json」。逐项语义与逐条 recordReference 一致:
32
+ * same-day refKey 去重(去重时 success 给定额补记 executionResults)、
33
+ * referencedBy 20 条上限、contributors 去重、未知 id 跳过;
34
+ * 回调保持「不早于持久化成功」语义——批量落盘成功后逐条触发,去重/未知 id 不触发
35
+ * (批量本就改变了落盘粒度,不声称逐条版的部分失败时序原样保留)。
36
+ * 单事件调用方仍用 recordReference()(其「返回更新后条目 + 触发回调」契约不变)。
37
+ *
38
+ * D7 引用复用:可选 `preloaded` 传 query 本次已物化的条目(id → 完整条目)——
39
+ * 条目查线不再 store.get,applyAll 以预载为合并基线(层间零重复读取);
40
+ * 缺省走原取盘路径,原四参公共调用兼容。preloaded 缺项的 id 回退 store.get 取盘,
41
+ * 取不到才按未知 id 跳过。
42
+ */
43
+ recordReferences(entryIds: string[], contributor?: string, success?: boolean, source?: 'human' | 'auto', preloaded?: ReadonlyMap<string, KnowledgeEntry>): void;
29
44
  /**
30
45
  * Check if an entry meets promotion criteria.
31
46
  * Returns the target maturity level if promotion is warranted, otherwise undefined.
@@ -72,6 +72,68 @@ class KnowledgeLifecycle {
72
72
  }
73
73
  return updated;
74
74
  }
75
+ /**
76
+ * 批量形 recordReference(P1.3):一次 query 的 N 条引用收集进一次 applyAll 落盘,
77
+ * 消除 N 次「全量重写 index.json」。逐项语义与逐条 recordReference 一致:
78
+ * same-day refKey 去重(去重时 success 给定额补记 executionResults)、
79
+ * referencedBy 20 条上限、contributors 去重、未知 id 跳过;
80
+ * 回调保持「不早于持久化成功」语义——批量落盘成功后逐条触发,去重/未知 id 不触发
81
+ * (批量本就改变了落盘粒度,不声称逐条版的部分失败时序原样保留)。
82
+ * 单事件调用方仍用 recordReference()(其「返回更新后条目 + 触发回调」契约不变)。
83
+ *
84
+ * D7 引用复用:可选 `preloaded` 传 query 本次已物化的条目(id → 完整条目)——
85
+ * 条目查线不再 store.get,applyAll 以预载为合并基线(层间零重复读取);
86
+ * 缺省走原取盘路径,原四参公共调用兼容。preloaded 缺项的 id 回退 store.get 取盘,
87
+ * 取不到才按未知 id 跳过。
88
+ */
89
+ recordReferences(entryIds, contributor, success, source, preloaded) {
90
+ const now = new Date().toISOString();
91
+ const updates = [];
92
+ const events = [];
93
+ const seen = new Set();
94
+ for (const entryId of entryIds) {
95
+ if (seen.has(entryId))
96
+ continue;
97
+ seen.add(entryId);
98
+ const entry = preloaded?.get(entryId) ?? this.store.get(entryId);
99
+ if (!entry)
100
+ continue;
101
+ const contributors = contributor && !entry.contributors.includes(contributor)
102
+ ? [...entry.contributors, contributor]
103
+ : entry.contributors;
104
+ const refKey = `${contributor || 'unknown'}:${now.slice(0, 10)}`;
105
+ const execSource = source || (contributor?.startsWith('auto-') ? 'auto' : undefined);
106
+ // B4: same-day, same-contributor 去重(与逐条版同口径)
107
+ if (entry.referencedBy.includes(refKey)) {
108
+ // 去重仍补记执行结果(若给了 success),但不触发回调
109
+ if (success !== undefined) {
110
+ const executionResults = [
111
+ ...(entry.executionResults),
112
+ { contributor: contributor || 'unknown', success, timestamp: now, source: execSource },
113
+ ].slice(-MAX_REFERENCED_BY);
114
+ updates.push({ id: entryId, partial: { executionResults } });
115
+ }
116
+ continue;
117
+ }
118
+ const referencedBy = [...entry.referencedBy, refKey].slice(-MAX_REFERENCED_BY);
119
+ const executionResults = success !== undefined
120
+ ? [...(entry.executionResults), { contributor: contributor || 'unknown', success, timestamp: now, source: execSource }].slice(-MAX_REFERENCED_BY)
121
+ : entry.executionResults;
122
+ updates.push({ id: entryId, partial: { lastReferenced: now, contributors, referencedBy, executionResults } });
123
+ events.push({ entryId, contributor: contributor || 'unknown', timestamp: now, success });
124
+ }
125
+ // 一次落盘:applyAll 循环内只更新内存索引、结束一次 writeIndex(空批零读写)。
126
+ // 落盘成功前不触发任何回调;抛错则整批中断上抛,由调用方 fail-open 兜底。
127
+ // preloaded 作为合并基线传入:批内条目零重复 get(D7 引用复用)。
128
+ this.store.applyAll(updates, preloaded);
129
+ // 批量落盘成功后才逐条触发消费回调(去重/未知 id 不在 events 内,天然不触发)
130
+ for (const event of events) {
131
+ for (const cb of this.onReferenceCallbacks) {
132
+ // 显式 fail-open(attempt):消费回调是外挂监听,崩了不拖死引用记账主流程
133
+ (0, attempt_1.attempt)(() => cb(event), () => undefined);
134
+ }
135
+ }
136
+ }
75
137
  /**
76
138
  * Check if an entry meets promotion criteria.
77
139
  * Returns the target maturity level if promotion is warranted, otherwise undefined.
@@ -8,7 +8,7 @@ import type { KnowledgeEntry, ConsumptionMode, QueryBudget, QueryResult, QueryFi
8
8
  import type { KnowledgeStore } from './store';
9
9
  import { KnowledgeLifecycle } from './lifecycle';
10
10
  /**
11
- * 外部来源条目的 prompt 标记(harness#161:三层防御第二层 marking 的唯一正本)。
11
+ * 外部来源条目的 retrieval marking 标准(harness#161:唯一正本)。
12
12
  * `KnowledgeQuery.formatForPrompt()` 与下游编排消费方的注入格式化共用同一常量,
13
13
  * 仓内不允许存在第二份字面量。
14
14
  */
@@ -75,6 +75,16 @@ export declare class KnowledgeQuery {
75
75
  * Adds [External Source] warning prefix for external-origin entries.
76
76
  */
77
77
  static formatForPrompt(entry: KnowledgeEntry): string;
78
+ /**
79
+ * D7 按需物化路径:候选只经 index 元数据过滤/排序/截断——被过滤排除与
80
+ * budget 截断掉的溢出候选全文零读取,最终返回子集才经 materializeByIndex 回读
81
+ * (漂移错误与 list 同一正本)。tokenCount 写入时已按 estimateTokens 两次 ceil
82
+ * 口径算好,tokensUsed 与兼容路径逐字相等。
83
+ *
84
+ * 返回 undefined = 走兼容路径:store 未提供 materializeByIndex(外部自定义 store)
85
+ * 或过滤后候选存在无 tokenCount 的旧格式条目(readIndex 会打一行 rebuildIndex 提示)。
86
+ */
87
+ private queryFromIndex;
78
88
  private sortEntries;
79
89
  private applyBudget;
80
90
  private cacheKey;
@@ -7,13 +7,14 @@
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.KnowledgeQuery = exports.EXTERNAL_SOURCE_MARKER = void 0;
10
+ const store_1 = require("./store");
10
11
  const lifecycle_1 = require("./lifecycle");
11
12
  const token_estimate_1 = require("./token-estimate");
12
13
  const attempt_1 = require("../utils/attempt");
13
14
  // ── Constants ──────────────────────────────────────────────
14
15
  const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
15
16
  /**
16
- * 外部来源条目的 prompt 标记(harness#161:三层防御第二层 marking 的唯一正本)。
17
+ * 外部来源条目的 retrieval marking 标准(harness#161:唯一正本)。
17
18
  * `KnowledgeQuery.formatForPrompt()` 与下游编排消费方的注入格式化共用同一常量,
18
19
  * 仓内不允许存在第二份字面量。
19
20
  */
@@ -55,16 +56,28 @@ class KnowledgeQuery {
55
56
  types: budget.focusTypes.length > 0 ? budget.focusTypes : filter?.types,
56
57
  excludeArchived: filter?.excludeArchived ?? true,
57
58
  };
58
- const candidates = this.store.list(mergedFilter);
59
- const sorted = this.sortEntries(candidates);
60
- const { entries, tokensUsed, truncated } = this.applyBudget(sorted, budget);
59
+ // D7:新索引(候选全带 tokenCount 元数据)先经 index 过滤/排序/截断,
60
+ // 只物化最终返回集;旧索引/外部自定义 store 走 list+applyBudget 兼容路径
61
+ const fromIndex = this.queryFromIndex(mergedFilter, budget);
62
+ let entries;
63
+ let tokensUsed;
64
+ let truncated;
65
+ if (fromIndex) {
66
+ ({ entries, tokensUsed, truncated } = fromIndex);
67
+ }
68
+ else {
69
+ const candidates = this.store.list(mergedFilter);
70
+ const sorted = this.sortEntries(candidates);
71
+ ({ entries, tokensUsed, truncated } = this.applyBudget(sorted, budget));
72
+ }
61
73
  const result = { entries, tokensUsed, truncated, fromCache: false };
62
74
  this.cache.set(cacheKey, { result, timestamp: Date.now() });
63
- // P2a: Record references for all returned entries (drives maturity ladder)
64
- for (const entry of entries) {
65
- // 显式 fail-open(attempt):引用记账是查询的副作用,失败不影响查询结果返回
66
- (0, attempt_1.attempt)(() => this.lifecycle.recordReference(entry.id), () => undefined);
67
- }
75
+ // P1.3: 一次 query 的全部引用经生命周期批量记账、一次 applyAll 落盘
76
+ // (不再逐条 recordReference→update→全量重写 index.json)
77
+ // D7: 本次已物化条目作为预载传入——记账查线与合并基线零重复读取
78
+ // 显式 fail-open(attempt):引用记账是查询的副作用,失败不影响查询结果返回
79
+ const preloaded = new Map(entries.map(e => [e.id, e]));
80
+ (0, attempt_1.attempt)(() => this.lifecycle.recordReferences(entries.map(e => e.id), undefined, undefined, undefined, preloaded), () => undefined);
68
81
  return result;
69
82
  }
70
83
  /**
@@ -150,6 +163,45 @@ class KnowledgeQuery {
150
163
  }
151
164
  // ── Internal ───────────────────────────────────────────────
152
165
  // ── Internal ───────────────────────────────────────────────
166
+ /**
167
+ * D7 按需物化路径:候选只经 index 元数据过滤/排序/截断——被过滤排除与
168
+ * budget 截断掉的溢出候选全文零读取,最终返回子集才经 materializeByIndex 回读
169
+ * (漂移错误与 list 同一正本)。tokenCount 写入时已按 estimateTokens 两次 ceil
170
+ * 口径算好,tokensUsed 与兼容路径逐字相等。
171
+ *
172
+ * 返回 undefined = 走兼容路径:store 未提供 materializeByIndex(外部自定义 store)
173
+ * 或过滤后候选存在无 tokenCount 的旧格式条目(readIndex 会打一行 rebuildIndex 提示)。
174
+ */
175
+ queryFromIndex(filter, budget) {
176
+ const materialize = this.store.materializeByIndex;
177
+ if (typeof materialize !== 'function')
178
+ return undefined;
179
+ const filtered = (0, store_1.filterIndexEntries)(this.store.readIndex(), filter);
180
+ if (!filtered.every(e => (0, store_1.indexEntryTokenCount)(e) !== undefined))
181
+ return undefined;
182
+ // 排序口径与 sortEntries 一致:maturity desc → lastReferenced desc
183
+ const sorted = [...filtered].sort((a, b) => {
184
+ const maturityDiff = MATURITY_RANK[b.maturity] - MATURITY_RANK[a.maturity];
185
+ if (maturityDiff !== 0)
186
+ return maturityDiff;
187
+ return (b.lastReferenced || '').localeCompare(a.lastReferenced || '');
188
+ });
189
+ const picked = [];
190
+ let tokensUsed = 0;
191
+ for (const entry of sorted) {
192
+ if (picked.length >= budget.maxEntries)
193
+ break;
194
+ const entryTokens = (0, store_1.indexEntryTokenCount)(entry);
195
+ if (entryTokens === undefined)
196
+ break; // 候选全带 tokenCount 已由上方 every 闸保证
197
+ if (tokensUsed + entryTokens > budget.maxTokens)
198
+ break;
199
+ picked.push(entry);
200
+ tokensUsed += entryTokens;
201
+ }
202
+ const entries = materialize.call(this.store, picked);
203
+ return { entries, tokensUsed, truncated: picked.length < sorted.length };
204
+ }
153
205
  sortEntries(entries) {
154
206
  return [...entries].sort((a, b) => {
155
207
  // Primary: maturity descending