opencode-swarm 7.83.0 → 7.85.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 (67) hide show
  1. package/.opencode/skills/codebase-review-swarm/references/review-protocol-v8.2.md +4 -0
  2. package/.opencode/skills/council/SKILL.md +6 -1
  3. package/.opencode/skills/deep-dive/SKILL.md +2 -0
  4. package/.opencode/skills/deep-research/SKILL.md +6 -0
  5. package/.opencode/skills/swarm-pr-feedback/SKILL.md +6 -0
  6. package/.opencode/skills/swarm-pr-review/SKILL.md +4 -0
  7. package/README.md +3 -1
  8. package/dist/background/lane-output-store.d.ts +72 -0
  9. package/dist/background/pending-delegations.d.ts +6 -0
  10. package/dist/cli/capability-probe-jevmgwmf.js +18 -0
  11. package/dist/cli/config-doctor-zejarrr6.js +35 -0
  12. package/dist/cli/dispatch-k86d928w.js +477 -0
  13. package/dist/cli/evidence-summary-service-g2znnd33.js +320 -0
  14. package/dist/cli/explorer-gz70sm9b.js +16 -0
  15. package/dist/cli/gate-evidence-y8zn7fe2.js +29 -0
  16. package/dist/cli/guardrail-explain-w4txg349.js +30 -0
  17. package/dist/cli/guardrail-log-80116wmz.js +15 -0
  18. package/dist/cli/index-0sxvwjt0.js +1241 -0
  19. package/dist/cli/index-293f68mj.js +13538 -0
  20. package/dist/cli/index-5cb86007.js +110 -0
  21. package/dist/cli/index-a76rekgs.js +67 -0
  22. package/dist/cli/index-b9v501fr.js +371 -0
  23. package/dist/cli/index-bcp79s17.js +1673 -0
  24. package/dist/cli/index-ckntc5gf.js +91 -0
  25. package/dist/cli/index-d9fbxaqd.js +2314 -0
  26. package/dist/cli/index-e7h9bb6v.js +233 -0
  27. package/dist/cli/index-e8pk68cc.js +540 -0
  28. package/dist/cli/index-eb85wtx9.js +242 -0
  29. package/dist/cli/index-f8r50m3h.js +14505 -0
  30. package/dist/cli/index-fjwwrwr5.js +37 -0
  31. package/dist/cli/index-hw9b2xng.js +2046 -0
  32. package/dist/cli/index-hz59hg4h.js +452 -0
  33. package/dist/cli/index-jtqkh8jf.js +119 -0
  34. package/dist/cli/index-p0arc26j.js +28 -0
  35. package/dist/cli/index-p0ye10nd.js +222 -0
  36. package/dist/cli/index-qqabjns2.js +412 -0
  37. package/dist/cli/index-red8fm8p.js +2914 -0
  38. package/dist/cli/index-vq2321gg.js +2391 -0
  39. package/dist/cli/index-x7qck34v.js +583 -0
  40. package/dist/cli/index-yhqt45de.js +29027 -0
  41. package/dist/cli/index-yhsmmv2z.js +339 -0
  42. package/dist/cli/index-yx44zd0p.js +40 -0
  43. package/dist/cli/index-zfsbaaqh.js +29 -0
  44. package/dist/cli/index.js +73 -69708
  45. package/dist/cli/knowledge-store-n4x6zyk7.js +73 -0
  46. package/dist/cli/pending-delegations-rd40tv9s.js +261 -0
  47. package/dist/cli/pr-subscriptions-y1nn36e5.js +33 -0
  48. package/dist/cli/schema-8d32b2v6.js +168 -0
  49. package/dist/cli/skill-generator-a5ehggyg.js +55 -0
  50. package/dist/cli/task-envelope-qn0qtnh0.js +90 -0
  51. package/dist/cli/telemetry-9bbyxrvn.js +20 -0
  52. package/dist/cli/workspace-snapshot-w58jr2ga.js +90 -0
  53. package/dist/commands/guardrail-explain.d.ts +1 -0
  54. package/dist/commands/guardrail-log.d.ts +1 -0
  55. package/dist/commands/index.d.ts +2 -0
  56. package/dist/commands/registry.d.ts +14 -0
  57. package/dist/hooks/guardrails/audit-log.d.ts +114 -0
  58. package/dist/index.js +4005 -2432
  59. package/dist/services/diagnose-service.d.ts +5 -0
  60. package/dist/services/guardrail-explain-service.d.ts +42 -0
  61. package/dist/services/guardrail-log-service.d.ts +10 -0
  62. package/dist/tools/dispatch-lanes.d.ts +14 -3
  63. package/dist/tools/index.d.ts +1 -0
  64. package/dist/tools/manifest.d.ts +1 -0
  65. package/dist/tools/retrieve-lane-output.d.ts +2 -0
  66. package/dist/tools/tool-metadata.d.ts +4 -0
  67. package/package.json +2 -2
@@ -0,0 +1,540 @@
1
+ // @bun
2
+ import {
3
+ atomicWriteFile
4
+ } from "./index-fjwwrwr5.js";
5
+ import {
6
+ readCachedParsedFile
7
+ } from "./index-jtqkh8jf.js";
8
+ import {
9
+ require_proper_lockfile
10
+ } from "./index-bcp79s17.js";
11
+ import {
12
+ __toESM
13
+ } from "./index-a76rekgs.js";
14
+
15
+ // src/hooks/knowledge-store.ts
16
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
17
+ import { existsSync } from "fs";
18
+ import { appendFile, mkdir, readFile } from "fs/promises";
19
+ import * as os from "os";
20
+ import * as path from "path";
21
+ var KNOWLEDGE_JSONL_CACHE_NAMESPACE = "knowledge-jsonl:normalized:v1";
22
+ function getPlatformConfigDir() {
23
+ const platform = process.platform;
24
+ const home = process.env.HOME || os.homedir();
25
+ if (platform === "win32") {
26
+ return path.join(process.env.LOCALAPPDATA || path.join(home, "AppData", "Local"), "opencode-swarm", "config");
27
+ } else if (platform === "darwin") {
28
+ return path.join(home, "Library", "Application Support", "opencode-swarm");
29
+ } else {
30
+ return path.join(process.env.XDG_CONFIG_HOME || path.join(home, ".config"), "opencode-swarm");
31
+ }
32
+ }
33
+ function resolveSwarmKnowledgePath(directory) {
34
+ return path.join(directory, ".swarm", "knowledge.jsonl");
35
+ }
36
+ function resolveSwarmRejectedPath(directory) {
37
+ return path.join(directory, ".swarm", "knowledge-rejected.jsonl");
38
+ }
39
+ function resolveSwarmRetractionsPath(directory) {
40
+ return path.join(directory, ".swarm", "knowledge-retractions.jsonl");
41
+ }
42
+ function resolveHiveKnowledgePath() {
43
+ const platform = process.platform;
44
+ const home = process.env.HOME || os.homedir();
45
+ let dataDir;
46
+ if (platform === "win32") {
47
+ dataDir = path.join(process.env.LOCALAPPDATA || path.join(home, "AppData", "Local"), "opencode-swarm", "Data");
48
+ } else if (platform === "darwin") {
49
+ dataDir = path.join(home, "Library", "Application Support", "opencode-swarm");
50
+ } else {
51
+ dataDir = path.join(process.env.XDG_DATA_HOME || path.join(home, ".local", "share"), "opencode-swarm");
52
+ }
53
+ return path.join(dataDir, "shared-learnings.jsonl");
54
+ }
55
+ function resolveHiveRejectedPath() {
56
+ const hivePath = resolveHiveKnowledgePath();
57
+ return path.join(path.dirname(hivePath), "shared-learnings-rejected.jsonl");
58
+ }
59
+ function resolveHiveEventsPath() {
60
+ const hivePath = resolveHiveKnowledgePath();
61
+ return path.join(path.dirname(hivePath), "shared-knowledge-events.jsonl");
62
+ }
63
+ function parseKnowledgeContent(content, max) {
64
+ const results = [];
65
+ for (const line of content.split(`
66
+ `)) {
67
+ if (Number.isFinite(max) && results.length >= max)
68
+ break;
69
+ const trimmed = line.trim();
70
+ if (!trimmed)
71
+ continue;
72
+ try {
73
+ results.push(normalizeEntry(JSON.parse(trimmed)));
74
+ } catch {
75
+ console.warn(`[knowledge-store] Skipping corrupted JSONL line: ${trimmed.slice(0, 80)}`);
76
+ }
77
+ }
78
+ return results;
79
+ }
80
+ async function readKnowledge(filePath, maxEntries) {
81
+ const resolvedPath = path.resolve(filePath);
82
+ const cap = maxEntries !== undefined && maxEntries > 0 ? maxEntries : undefined;
83
+ if (cap !== undefined) {
84
+ if (!existsSync(resolvedPath))
85
+ return [];
86
+ const content = await readFile(resolvedPath, "utf-8");
87
+ return parseKnowledgeContent(content, cap);
88
+ }
89
+ const entries = await readCachedParsedFile(resolvedPath, KNOWLEDGE_JSONL_CACHE_NAMESPACE, async () => {
90
+ if (!existsSync(resolvedPath))
91
+ return null;
92
+ return await readFile(resolvedPath, "utf-8");
93
+ }, (content) => parseKnowledgeContent(content, Infinity));
94
+ return entries ?? [];
95
+ }
96
+ function normalizeEntry(raw) {
97
+ if (!raw || typeof raw !== "object")
98
+ return raw;
99
+ const obj = raw;
100
+ if (!("retrieval_outcomes" in obj))
101
+ return raw;
102
+ let ro = obj.retrieval_outcomes;
103
+ if (!ro || typeof ro !== "object") {
104
+ ro = {};
105
+ obj.retrieval_outcomes = ro;
106
+ }
107
+ if (typeof ro.shown_count !== "number") {
108
+ ro.shown_count = typeof ro.applied_count === "number" ? ro.applied_count : 0;
109
+ }
110
+ if (typeof ro.acknowledged_count !== "number")
111
+ ro.acknowledged_count = 0;
112
+ if (typeof ro.applied_explicit_count !== "number") {
113
+ ro.applied_explicit_count = 0;
114
+ }
115
+ if (typeof ro.ignored_count !== "number")
116
+ ro.ignored_count = 0;
117
+ if (typeof ro.violated_count !== "number")
118
+ ro.violated_count = 0;
119
+ if (typeof ro.contradicted_count !== "number")
120
+ ro.contradicted_count = 0;
121
+ if (typeof ro.succeeded_after_shown_count !== "number") {
122
+ ro.succeeded_after_shown_count = typeof ro.succeeded_after_count === "number" ? ro.succeeded_after_count : 0;
123
+ }
124
+ if (typeof ro.failed_after_shown_count !== "number") {
125
+ ro.failed_after_shown_count = typeof ro.failed_after_count === "number" ? ro.failed_after_count : 0;
126
+ }
127
+ try {
128
+ if (typeof obj.encounter_score !== "number" || Number.isNaN(obj.encounter_score)) {
129
+ obj.encounter_score = 0;
130
+ }
131
+ } catch {
132
+ try {
133
+ Object.defineProperty(obj, "encounter_score", {
134
+ value: 0,
135
+ writable: true,
136
+ configurable: true,
137
+ enumerable: true
138
+ });
139
+ } catch {}
140
+ }
141
+ const arrayFields = [
142
+ "triggers",
143
+ "required_actions",
144
+ "forbidden_actions",
145
+ "applies_to_agents",
146
+ "applies_to_tools",
147
+ "verification_checks",
148
+ "source_refs",
149
+ "source_knowledge_ids"
150
+ ];
151
+ for (const f of arrayFields) {
152
+ const v = obj[f];
153
+ if (v !== undefined && !Array.isArray(v)) {
154
+ delete obj[f];
155
+ }
156
+ }
157
+ if (!Array.isArray(obj.tags)) {
158
+ obj.tags = [];
159
+ }
160
+ return raw;
161
+ }
162
+ async function readRejectedLessons(directory) {
163
+ return readKnowledge(resolveSwarmRejectedPath(directory));
164
+ }
165
+ async function readRetractionRecords(directory) {
166
+ return readKnowledge(resolveSwarmRetractionsPath(directory));
167
+ }
168
+ async function appendRetractionRecord(directory, record) {
169
+ await appendKnowledge(resolveSwarmRetractionsPath(directory), record);
170
+ }
171
+ async function appendKnowledge(filePath, entry) {
172
+ const dir = path.dirname(filePath);
173
+ await mkdir(dir, { recursive: true });
174
+ let release = null;
175
+ try {
176
+ release = await import_proper_lockfile.default.lock(dir, {
177
+ retries: { retries: 5, minTimeout: 100, maxTimeout: 500 },
178
+ stale: 5000
179
+ });
180
+ await appendFile(filePath, `${JSON.stringify(entry)}
181
+ `, "utf-8");
182
+ } finally {
183
+ if (release) {
184
+ try {
185
+ await release();
186
+ } catch {}
187
+ }
188
+ }
189
+ }
190
+ async function rewriteKnowledge(filePath, entries) {
191
+ const dir = path.dirname(filePath);
192
+ await mkdir(dir, { recursive: true });
193
+ let release = null;
194
+ try {
195
+ release = await import_proper_lockfile.default.lock(dir, {
196
+ retries: { retries: 5, minTimeout: 100, maxTimeout: 500 },
197
+ stale: 5000
198
+ });
199
+ const content = entries.map((e) => JSON.stringify(e)).join(`
200
+ `) + (entries.length > 0 ? `
201
+ ` : "");
202
+ await atomicWriteFile(filePath, content);
203
+ } finally {
204
+ if (release) {
205
+ try {
206
+ await release();
207
+ } catch {}
208
+ }
209
+ }
210
+ }
211
+ async function transactFile(filePath, read, write, mutate) {
212
+ const dir = path.dirname(filePath);
213
+ try {
214
+ await mkdir(dir, { recursive: true });
215
+ } catch {
216
+ return false;
217
+ }
218
+ let release = null;
219
+ try {
220
+ release = await import_proper_lockfile.default.lock(dir, {
221
+ retries: { retries: 5, minTimeout: 100, maxTimeout: 500 },
222
+ stale: 5000
223
+ });
224
+ const data = await read(filePath);
225
+ const result = mutate(data);
226
+ if (result === null)
227
+ return false;
228
+ await write(filePath, result);
229
+ return true;
230
+ } finally {
231
+ if (release) {
232
+ try {
233
+ await release();
234
+ } catch {}
235
+ }
236
+ }
237
+ }
238
+ async function transactKnowledge(filePath, mutate) {
239
+ return transactFile(filePath, readKnowledge, async (fp, entries) => {
240
+ const content = entries.map((e) => JSON.stringify(e)).join(`
241
+ `) + (entries.length > 0 ? `
242
+ ` : "");
243
+ await atomicWriteFile(fp, content);
244
+ }, mutate);
245
+ }
246
+ async function appendKnowledgeWithCapEnforcement(filePath, entry, maxEntries) {
247
+ return transactKnowledge(filePath, (entries) => {
248
+ const updated = [...entries, entry];
249
+ if (updated.length > maxEntries) {
250
+ return selectKnowledgeCapSurvivors(updated, maxEntries);
251
+ }
252
+ return updated;
253
+ });
254
+ }
255
+ async function enforceKnowledgeCap(filePath, maxEntries) {
256
+ await transactKnowledge(filePath, (entries) => {
257
+ if (entries.length <= maxEntries)
258
+ return null;
259
+ return selectKnowledgeCapSurvivors(entries, maxEntries);
260
+ });
261
+ }
262
+ function selectKnowledgeCapSurvivors(entries, maxEntries) {
263
+ if (entries.length <= maxEntries)
264
+ return entries;
265
+ if (maxEntries <= 0)
266
+ return [];
267
+ const candidates = entries.map((entry, index) => {
268
+ const maybeKnowledge = entry;
269
+ return {
270
+ entry,
271
+ index,
272
+ status: maybeKnowledge.status,
273
+ outcomeSignal: computeOutcomeSignal(maybeKnowledge.retrieval_outcomes)
274
+ };
275
+ });
276
+ const allPromoted = candidates.every((c) => c.status === "promoted");
277
+ const evictable = allPromoted ? candidates : candidates.filter((c) => c.status !== "promoted");
278
+ const targetDropCount = entries.length - maxEntries;
279
+ const dropCount = Math.min(targetDropCount, evictable.length);
280
+ if (dropCount <= 0)
281
+ return entries;
282
+ const drop = new Set([...evictable].sort((a, b) => {
283
+ const inactiveDelta = getKnowledgeCapStatusPriority(a.status) - getKnowledgeCapStatusPriority(b.status);
284
+ if (inactiveDelta !== 0)
285
+ return inactiveDelta;
286
+ const signalDelta = a.outcomeSignal - b.outcomeSignal;
287
+ if (signalDelta !== 0)
288
+ return signalDelta;
289
+ return a.index - b.index;
290
+ }).slice(0, dropCount).map((c) => c.index));
291
+ return candidates.filter((c) => !drop.has(c.index)).map((c) => c.entry);
292
+ }
293
+ function getKnowledgeCapStatusPriority(status) {
294
+ if (status === "archived" || status === "quarantined" || status === "quarantined_unactionable") {
295
+ return 0;
296
+ }
297
+ return 1;
298
+ }
299
+ async function sweepAgedEntries(filePath, defaultMaxPhases) {
300
+ const result = {
301
+ scanned: 0,
302
+ aged: 0,
303
+ archived: 0,
304
+ removed: 0,
305
+ skipped_promoted: 0
306
+ };
307
+ await transactKnowledge(filePath, (entries) => {
308
+ result.scanned = entries.length;
309
+ if (entries.length === 0)
310
+ return null;
311
+ const now = new Date().toISOString();
312
+ let mutated = false;
313
+ for (const entry of entries) {
314
+ if (entry.status === "archived")
315
+ continue;
316
+ if (entry.status === "promoted") {
317
+ result.skipped_promoted++;
318
+ continue;
319
+ }
320
+ entry.phases_alive = (entry.phases_alive ?? 0) + 1;
321
+ result.aged++;
322
+ mutated = true;
323
+ const ttl = entry.max_phases ?? defaultMaxPhases;
324
+ if (entry.phases_alive > ttl) {
325
+ entry.status = "archived";
326
+ entry.updated_at = now;
327
+ result.archived++;
328
+ }
329
+ }
330
+ return mutated ? entries : null;
331
+ });
332
+ return result;
333
+ }
334
+ async function sweepStaleTodos(filePath, todoMaxPhases) {
335
+ const result = {
336
+ scanned: 0,
337
+ aged: 0,
338
+ archived: 0,
339
+ removed: 0,
340
+ skipped_promoted: 0
341
+ };
342
+ await transactKnowledge(filePath, (entries) => {
343
+ result.scanned = entries.length;
344
+ if (entries.length === 0)
345
+ return null;
346
+ const kept = entries.filter((e) => {
347
+ if (e.category !== "todo" || e.status === "promoted")
348
+ return true;
349
+ const age = e.phases_alive ?? 0;
350
+ if (age > todoMaxPhases) {
351
+ result.removed++;
352
+ return false;
353
+ }
354
+ return true;
355
+ });
356
+ return result.removed > 0 ? kept : null;
357
+ });
358
+ return result;
359
+ }
360
+ async function appendRejectedLesson(directory, lesson, maxEntries = 20) {
361
+ const filePath = resolveSwarmRejectedPath(directory);
362
+ await transactKnowledge(filePath, (existing) => {
363
+ const updated = [...existing, lesson];
364
+ if (updated.length > maxEntries) {
365
+ return updated.slice(updated.length - maxEntries);
366
+ }
367
+ return updated;
368
+ });
369
+ }
370
+ function normalize(text) {
371
+ const s = typeof text === "string" ? text : String(text ?? "");
372
+ return s.toLowerCase().replace(/[^\w\s]/g, " ").replace(/\s+/g, " ").trim();
373
+ }
374
+ function wordBigrams(text) {
375
+ const words = normalize(text).split(" ").filter(Boolean);
376
+ const bigrams = new Set;
377
+ for (let i = 0;i < words.length - 1; i++) {
378
+ bigrams.add(`${words[i]} ${words[i + 1]}`);
379
+ }
380
+ return bigrams;
381
+ }
382
+ function jaccardBigram(a, b) {
383
+ if (a.size === 0 && b.size === 0)
384
+ return 1;
385
+ const aArr = Array.from(a);
386
+ const intersection = new Set(aArr.filter((x) => b.has(x)));
387
+ const union = new Set([...aArr, ...Array.from(b)]);
388
+ return intersection.size / union.size;
389
+ }
390
+ function findNearDuplicate(candidate, entries, threshold = 0.6) {
391
+ const candidateBigrams = wordBigrams(candidate);
392
+ return entries.find((entry) => {
393
+ const entryBigrams = wordBigrams(entry.lesson);
394
+ return jaccardBigram(candidateBigrams, entryBigrams) >= threshold;
395
+ });
396
+ }
397
+ function computeConfidence(confirmedByCount, autoGenerated) {
398
+ let score = 0.5;
399
+ score += Math.min(confirmedByCount, 3) * 0.1;
400
+ if (!autoGenerated)
401
+ score += 0.1;
402
+ return Math.min(score, 1);
403
+ }
404
+ var OUTCOME_SIGNAL_SMOOTHING = 4;
405
+ function computeOutcomeSignal(outcomes) {
406
+ if (!outcomes)
407
+ return 0;
408
+ const positives = (outcomes.applied_explicit_count ?? 0) + (outcomes.succeeded_after_shown_count ?? 0);
409
+ const negatives = (outcomes.ignored_count ?? 0) + (outcomes.violated_count ?? 0) + (outcomes.contradicted_count ?? 0) + (outcomes.failed_after_shown_count ?? 0);
410
+ const total = positives + negatives;
411
+ if (total === 0)
412
+ return 0;
413
+ return (positives - negatives) / (total + OUTCOME_SIGNAL_SMOOTHING);
414
+ }
415
+ function inferTags(lesson) {
416
+ const lower = lesson.toLowerCase();
417
+ const tags = [];
418
+ if (/(^|\s)(?:todo|remember|don't?(?:\s+)?forget)(?:\s|:|,|$)/i.test(lesson))
419
+ tags.push("todo");
420
+ if (/\b(?:typescript|ts)\b/.test(lower))
421
+ tags.push("typescript");
422
+ if (/\b(?:javascript|js)\b/.test(lower))
423
+ tags.push("javascript");
424
+ if (/\b(?:python)\b/.test(lower))
425
+ tags.push("python");
426
+ if (/\b(?:bun|node|deno)\b/.test(lower))
427
+ tags.push("runtime");
428
+ if (/\b(?:react|vue|svelte|angular)\b/.test(lower))
429
+ tags.push("frontend");
430
+ if (/\b(?:git|github|gitlab)\b/.test(lower))
431
+ tags.push("git");
432
+ if (/\b(?:docker|kubernetes|k8s)\b/.test(lower))
433
+ tags.push("container");
434
+ if (/\b(?:sql|postgres|mysql|sqlite)\b/.test(lower))
435
+ tags.push("database");
436
+ if (/\b(?:test|spec|vitest|jest|mocha)\b/.test(lower))
437
+ tags.push("testing");
438
+ if (/\b(?:ci|cd|pipeline|workflow|action)\b/.test(lower))
439
+ tags.push("ci-cd");
440
+ if (/\b(?:security|auth|token|password|encrypt)\b/.test(lower))
441
+ tags.push("security");
442
+ if (/\b(?:performance|latency|throughput|cache)\b/.test(lower))
443
+ tags.push("performance");
444
+ if (/\b(?:api|rest|graphql|grpc|endpoint)\b/.test(lower))
445
+ tags.push("api");
446
+ if (/\b(?:swarm|architect|agent|hook|plan)\b/.test(lower))
447
+ tags.push("opencode-swarm");
448
+ return Array.from(new Set(tags));
449
+ }
450
+ var CONFIDENCE_FLOOR = 0.1;
451
+ var CONFIDENCE_CEILING = 1;
452
+ async function bumpKnowledgeConfidenceBatch(directory, deltas) {
453
+ if (deltas.length === 0)
454
+ return;
455
+ const swarmPath = resolveSwarmKnowledgePath(directory);
456
+ const hivePath = resolveHiveKnowledgePath();
457
+ try {
458
+ await applyConfidenceDeltas(swarmPath, deltas);
459
+ const swarmEntries = await readKnowledge(swarmPath);
460
+ const swarmIds = new Set(swarmEntries.map((e) => e.id));
461
+ const hiveOnly = deltas.filter((d) => !swarmIds.has(d.id));
462
+ if (hiveOnly.length > 0) {
463
+ await applyConfidenceDeltas(hivePath, hiveOnly);
464
+ }
465
+ } catch (err) {
466
+ console.warn("[knowledge-store] bumpKnowledgeConfidenceBatch failed (fail-open):", err instanceof Error ? err.message : String(err));
467
+ }
468
+ }
469
+ async function applyConfidenceDeltas(filePath, deltas) {
470
+ const idDeltaMap = new Map;
471
+ for (const d of deltas) {
472
+ const existing = idDeltaMap.get(d.id);
473
+ idDeltaMap.set(d.id, existing !== undefined ? existing + d.delta : d.delta);
474
+ }
475
+ let release = null;
476
+ try {
477
+ const dir = path.dirname(filePath);
478
+ await mkdir(dir, { recursive: true });
479
+ release = await import_proper_lockfile.default.lock(dir, {
480
+ retries: { retries: 5, minTimeout: 100, maxTimeout: 500 },
481
+ stale: 5000
482
+ });
483
+ const entries = await readKnowledge(filePath);
484
+ if (entries.length === 0)
485
+ return;
486
+ const now = new Date().toISOString();
487
+ let mutated = false;
488
+ for (const entry of entries) {
489
+ const delta = idDeltaMap.get(entry.id);
490
+ if (delta === undefined)
491
+ continue;
492
+ entry.confidence = Math.max(CONFIDENCE_FLOOR, Math.min(CONFIDENCE_CEILING, entry.confidence + delta));
493
+ entry.updated_at = now;
494
+ mutated = true;
495
+ }
496
+ if (mutated) {
497
+ const content = entries.map((e) => JSON.stringify(e)).join(`
498
+ `) + (entries.length > 0 ? `
499
+ ` : "");
500
+ await atomicWriteFile(filePath, content);
501
+ }
502
+ } catch (err) {
503
+ console.warn(`[knowledge-store] applyConfidenceDeltas failed on ${filePath} (fail-open):`, err instanceof Error ? err.message : String(err));
504
+ } finally {
505
+ if (release) {
506
+ try {
507
+ await release();
508
+ } catch {}
509
+ }
510
+ }
511
+ }
512
+ var _internals = {
513
+ getPlatformConfigDir,
514
+ resolveSwarmKnowledgePath,
515
+ resolveSwarmRejectedPath,
516
+ resolveHiveKnowledgePath,
517
+ resolveHiveRejectedPath,
518
+ resolveHiveEventsPath,
519
+ readKnowledge,
520
+ parseKnowledgeContent,
521
+ readRejectedLessons,
522
+ appendKnowledge,
523
+ rewriteKnowledge,
524
+ transactKnowledge,
525
+ enforceKnowledgeCap,
526
+ sweepAgedEntries,
527
+ sweepStaleTodos,
528
+ appendRejectedLesson,
529
+ normalize,
530
+ wordBigrams,
531
+ jaccardBigram,
532
+ findNearDuplicate,
533
+ computeConfidence,
534
+ computeOutcomeSignal,
535
+ selectKnowledgeCapSurvivors,
536
+ inferTags,
537
+ bumpKnowledgeConfidenceBatch
538
+ };
539
+
540
+ export { getPlatformConfigDir, resolveSwarmKnowledgePath, resolveSwarmRejectedPath, resolveSwarmRetractionsPath, resolveHiveKnowledgePath, resolveHiveRejectedPath, resolveHiveEventsPath, readKnowledge, normalizeEntry, readRejectedLessons, readRetractionRecords, appendRetractionRecord, appendKnowledge, rewriteKnowledge, transactFile, transactKnowledge, appendKnowledgeWithCapEnforcement, enforceKnowledgeCap, sweepAgedEntries, sweepStaleTodos, appendRejectedLesson, normalize, wordBigrams, jaccardBigram, findNearDuplicate, computeConfidence, OUTCOME_SIGNAL_SMOOTHING, computeOutcomeSignal, inferTags, bumpKnowledgeConfidenceBatch, _internals };