@jwitmann/vcc-brain-opencode-v2 2.6.0 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -7403,13 +7403,10 @@ async function loadMemorySnapshot(projectDirectory, homeDirectory, loadFiles) {
7403
7403
 
7404
7404
  // src/index.ts
7405
7405
  import { Plugin } from "@opencode/plugin";
7406
-
7407
- // src/id.ts
7408
- var pluginId = "jwitmann.vcc-brain";
7409
7406
  // package.json
7410
7407
  var package_default = {
7411
7408
  name: "@jwitmann/vcc-brain-opencode-v2",
7412
- version: "2.6.0",
7409
+ version: "2.7.1",
7413
7410
  description: "VCC Brain adapter for OpenCode V2.",
7414
7411
  license: "BSD-3-Clause",
7415
7412
  author: "jwitmann",
@@ -7475,379 +7472,6 @@ var package_default = {
7475
7472
  }
7476
7473
  };
7477
7474
 
7478
- // src/commands.ts
7479
- var VCC_BRAIN_COMMAND_NAMES = [
7480
- "vcc-brain:user-init",
7481
- "vcc-brain:project-init",
7482
- "vcc-brain:index"
7483
- ];
7484
- var commands = {
7485
- "vcc-brain:user-init": {
7486
- description: "Initialize VCC Brain User Instructions",
7487
- operation: "user init",
7488
- guide: "Follow the User Setup guide in its output, including when initialization reports failures."
7489
- },
7490
- "vcc-brain:project-init": {
7491
- description: "Initialize VCC Brain Project",
7492
- operation: "project init",
7493
- guide: "Follow the Project Setup guide in its output, including when initialization reports failures."
7494
- },
7495
- "vcc-brain:index": {
7496
- description: "Build or refresh the VCC Brain Project Index",
7497
- operation: "index init",
7498
- guide: "Follow the Project Index Setup guide in its output, including when inspection reports failures."
7499
- }
7500
- };
7501
- async function registerCommands(context) {
7502
- const existing = new Set((await context.command.list()).data.map((command) => command.name));
7503
- await context.command.transform((draft) => {
7504
- for (const name of VCC_BRAIN_COMMAND_NAMES) {
7505
- if (existing.has(name))
7506
- continue;
7507
- const command = commands[name];
7508
- draft.add({
7509
- name,
7510
- description: command.description,
7511
- execute: async (input) => {
7512
- await context.session.prompt({
7513
- ...input.prompt,
7514
- sessionID: input.sessionID,
7515
- text: `# ${command.description}
7516
-
7517
- 1. Run \`vcc-brain-helper version\`. If an update is available, run \`vcc-brain-helper upgrade\` before continuing.
7518
- 2. Run \`vcc-brain-helper ${command.operation}\`. ${command.guide}
7519
-
7520
- ## Recovery
7521
-
7522
- - If Helper cannot start, install or repair the npm package \`@jwitmann/vcc-brain-helper\` globally and retry the failed command.
7523
- - If the version check or upgrade fails, diagnose the error and retry.
7524
- - If \`vcc-brain-helper ${command.operation}\` reports a failure, use its output to resolve it and rerun it as needed.
7525
- - If you cannot resolve a problem, report the blocker.
7526
-
7527
- Use Helper output as working context. Do not reproduce it wholesale or reimplement Helper logic.`,
7528
- delivery: input.delivery
7529
- });
7530
- }
7531
- });
7532
- }
7533
- });
7534
- }
7535
-
7536
- // ../core/src/context/compaction.ts
7537
- var DEFAULT_RECOVERY_RULE = `Tool input/output omission notices (content IDs) are the only recoverable
7538
- ` + ` handles for trimmed content. Keep every omission notice verbatim in the
7539
- ` + ` summary; the agent recovers payloads through the vcc-brain-read_omitted
7540
- ` + " tool.";
7541
- function buildCompactionPrompt(input) {
7542
- const paths = input.brainPaths.map((path) => `- ${path}`).join(`
7543
- `);
7544
- return `<compaction-instructions>
7545
- You are compacting the conversation history for a VCC Brain session.
7546
- Produce a summary that lets the next session continue the work without the
7547
- full history.
7548
-
7549
- The summary must preserve, in order of importance:
7550
- 1. The current task and what has been completed so far.
7551
- 2. Active files: paths the work depends on, with a one-line note on the role
7552
- of each.
7553
- 3. Blockers and open questions.
7554
- 4. Key decisions already made, with their reasons.
7555
-
7556
- Rules:
7557
- - ${input.recoveryRule ?? DEFAULT_RECOVERY_RULE}
7558
- - Durable knowledge lives in the Brain partitions. Reference these paths
7559
- instead of inlining their content:
7560
- ${paths}
7561
- - Before summarizing, ensure any spec or decision that exists only in this
7562
- conversation is written to the appropriate Brain document.
7563
- - Compaction is lossy; the Brain is not.
7564
- </compaction-instructions>`;
7565
- }
7566
-
7567
- // ../core/src/context/receipts.ts
7568
- import { appendFile as appendFile2, mkdir as mkdir2, readFile as readFile3 } from "node:fs/promises";
7569
- import { join as join5 } from "node:path";
7570
-
7571
- // ../core/src/context/store.ts
7572
- import { appendFile, mkdir, readFile as readFile2, stat as stat3, unlink, writeFile } from "node:fs/promises";
7573
- import { join as join4 } from "node:path";
7574
- var INDEX_FILE = "index.jsonl";
7575
- var ID_PREFIX = "omitted-";
7576
- async function storeOmissions(root, sessionID, items) {
7577
- const sessionRoot = join4(root, sessionID);
7578
- if (!isSafePathSegment(sessionID)) {
7579
- return failure({ path: sessionRoot, cause: new Error("Unsafe path segment") });
7580
- }
7581
- const directoryResult = await mkdirSafe(sessionRoot);
7582
- if (!directoryResult.ok) {
7583
- return directoryResult;
7584
- }
7585
- const entriesResult = await readIndex(sessionRoot);
7586
- if (!entriesResult.ok) {
7587
- return entriesResult;
7588
- }
7589
- const known = new Map;
7590
- for (const entry of entriesResult.value) {
7591
- if (!known.has(entry.key)) {
7592
- known.set(entry.key, entry.id);
7593
- }
7594
- }
7595
- const ids = new Map(known);
7596
- const stored = new Set;
7597
- const failed = new Set;
7598
- const fresh = [];
7599
- let next = nextId(entriesResult.value);
7600
- for (const item of items) {
7601
- if (ids.has(item.key)) {
7602
- continue;
7603
- }
7604
- if (!isSafePathSegment(item.key)) {
7605
- failed.add(item.key);
7606
- continue;
7607
- }
7608
- const id = formatContentID(next);
7609
- next += 1;
7610
- try {
7611
- await writeFile(join4(sessionRoot, id), item.content, "utf8");
7612
- } catch {
7613
- failed.add(item.key);
7614
- continue;
7615
- }
7616
- ids.set(item.key, id);
7617
- stored.add(item.key);
7618
- fresh.push({ key: item.key, id });
7619
- }
7620
- if (fresh.length > 0) {
7621
- const lines = fresh.map((entry) => `${JSON.stringify(entry)}
7622
- `).join("");
7623
- try {
7624
- await appendFile(indexPath(sessionRoot), lines, "utf8");
7625
- } catch (cause) {
7626
- for (const entry of fresh) {
7627
- ids.delete(entry.key);
7628
- stored.delete(entry.key);
7629
- failed.add(entry.key);
7630
- }
7631
- return failure({ path: indexPath(sessionRoot), cause });
7632
- }
7633
- }
7634
- return success({ ids, stored, failed });
7635
- }
7636
- async function readOmission(root, sessionID, contentID) {
7637
- const payloadPath = join4(root, sessionID, contentID);
7638
- if (!isSafePathSegment(sessionID) || !isSafePathSegment(contentID)) {
7639
- return failure({ path: payloadPath, cause: new Error("Unsafe path segment") });
7640
- }
7641
- try {
7642
- return success(await readFile2(payloadPath, "utf8"));
7643
- } catch (cause) {
7644
- return hasNodeErrorCode(cause, "ENOENT") ? success(null) : failure({ path: payloadPath, cause });
7645
- }
7646
- }
7647
- var DEFAULT_RETENTION = {
7648
- maxAgeMs: 30 * 24 * 60 * 60 * 1000,
7649
- maxPayloads: 200,
7650
- maxBytes: 32 * 1024 * 1024
7651
- };
7652
- async function pruneOmissions(root, sessionID, policy, now) {
7653
- const sessionRoot = join4(root, sessionID);
7654
- if (!isSafePathSegment(sessionID)) {
7655
- return failure({ path: sessionRoot, cause: new Error("Unsafe path segment") });
7656
- }
7657
- const entriesResult = await readIndex(sessionRoot);
7658
- if (!entriesResult.ok) {
7659
- return entriesResult;
7660
- }
7661
- if (entriesResult.value.length === 0) {
7662
- return success({ removed: [], freedBytes: 0, remaining: 0 });
7663
- }
7664
- const drop = new Set;
7665
- const stats = new Map;
7666
- const needsStats = policy.maxAgeMs !== null || policy.maxBytes !== null;
7667
- if (needsStats) {
7668
- for (const entry of entriesResult.value) {
7669
- try {
7670
- const info = await stat3(join4(sessionRoot, entry.id));
7671
- stats.set(entry.id, { size: info.size, ageMs: now - info.mtimeMs });
7672
- } catch (cause) {
7673
- if (!hasNodeErrorCode(cause, "ENOENT")) {
7674
- return failure({ path: join4(sessionRoot, entry.id), cause });
7675
- }
7676
- drop.add(entry.id);
7677
- }
7678
- }
7679
- }
7680
- if (policy.maxAgeMs !== null) {
7681
- const maxAgeMs = policy.maxAgeMs;
7682
- for (const entry of entriesResult.value) {
7683
- const info = stats.get(entry.id);
7684
- if (info === undefined || info.ageMs > maxAgeMs) {
7685
- drop.add(entry.id);
7686
- }
7687
- }
7688
- }
7689
- const survivors = () => entriesResult.value.filter((entry) => !drop.has(entry.id));
7690
- if (policy.maxPayloads !== null) {
7691
- const over = survivors();
7692
- for (const entry of over.slice(0, Math.max(0, over.length - policy.maxPayloads))) {
7693
- drop.add(entry.id);
7694
- }
7695
- }
7696
- if (policy.maxBytes !== null) {
7697
- let bytes = 0;
7698
- for (const entry of [...survivors()].reverse()) {
7699
- bytes += stats.get(entry.id)?.size ?? 0;
7700
- }
7701
- for (const entry of survivors()) {
7702
- if (bytes <= policy.maxBytes) {
7703
- break;
7704
- }
7705
- bytes -= stats.get(entry.id)?.size ?? 0;
7706
- drop.add(entry.id);
7707
- }
7708
- }
7709
- let freedBytes = 0;
7710
- for (const entry of entriesResult.value) {
7711
- if (!drop.has(entry.id)) {
7712
- continue;
7713
- }
7714
- freedBytes += stats.get(entry.id)?.size ?? 0;
7715
- try {
7716
- await unlink(join4(sessionRoot, entry.id));
7717
- } catch (cause) {
7718
- if (!hasNodeErrorCode(cause, "ENOENT")) {
7719
- return failure({ path: join4(sessionRoot, entry.id), cause });
7720
- }
7721
- }
7722
- }
7723
- const remaining = entriesResult.value.filter((entry) => !drop.has(entry.id));
7724
- try {
7725
- await writeFile(indexPath(sessionRoot), remaining.map((entry) => `${JSON.stringify(entry)}
7726
- `).join(""), "utf8");
7727
- } catch (cause) {
7728
- return failure({ path: indexPath(sessionRoot), cause });
7729
- }
7730
- return success({
7731
- removed: entriesResult.value.filter((entry) => drop.has(entry.id)).map((entry) => entry.id),
7732
- freedBytes,
7733
- remaining: remaining.length
7734
- });
7735
- }
7736
- async function readIndex(sessionRoot) {
7737
- const path = indexPath(sessionRoot);
7738
- let raw;
7739
- try {
7740
- raw = await readFile2(path, "utf8");
7741
- } catch (cause) {
7742
- return hasNodeErrorCode(cause, "ENOENT") ? success([]) : failure({ path, cause });
7743
- }
7744
- const entries = [];
7745
- for (const line of raw.split(`
7746
- `)) {
7747
- const trimmed = line.trim();
7748
- if (!trimmed) {
7749
- continue;
7750
- }
7751
- try {
7752
- const parsed = JSON.parse(trimmed);
7753
- if (typeof parsed === "object" && parsed !== null && "key" in parsed && "id" in parsed && typeof parsed.key === "string" && typeof parsed.id === "string") {
7754
- entries.push({ key: parsed.key, id: parsed.id });
7755
- }
7756
- } catch {}
7757
- }
7758
- return success(entries);
7759
- }
7760
- async function mkdirSafe(path) {
7761
- try {
7762
- await mkdir(path, { recursive: true });
7763
- return success(undefined);
7764
- } catch (cause) {
7765
- return failure({ path, cause });
7766
- }
7767
- }
7768
- function indexPath(sessionRoot) {
7769
- return join4(sessionRoot, INDEX_FILE);
7770
- }
7771
- function nextId(entries) {
7772
- let max = 0;
7773
- for (const entry of entries) {
7774
- const suffix = entry.id.startsWith(ID_PREFIX) ? entry.id.slice(ID_PREFIX.length) : null;
7775
- const value = suffix === null ? Number.NaN : Number.parseInt(suffix, 10);
7776
- if (!Number.isNaN(value) && value > max) {
7777
- max = value;
7778
- }
7779
- }
7780
- return max + 1;
7781
- }
7782
- function formatContentID(id) {
7783
- return `${ID_PREFIX}${String(id).padStart(3, "0")}`;
7784
- }
7785
- function isSafePathSegment(segment) {
7786
- return segment.length > 0 && !segment.includes("/") && !segment.includes("\\") && segment !== "..";
7787
- }
7788
-
7789
- // ../core/src/context/receipts.ts
7790
- async function appendReceipt(root, sessionID, receipt) {
7791
- const path = join5(root, `${sessionID}.log`);
7792
- if (!isSafePathSegment(sessionID)) {
7793
- return failure({ path, cause: new Error("Unsafe path segment") });
7794
- }
7795
- try {
7796
- await mkdir2(root, { recursive: true });
7797
- await appendFile2(path, `${JSON.stringify(receipt)}
7798
- `, "utf8");
7799
- } catch (cause) {
7800
- return failure({ path, cause });
7801
- }
7802
- return success(undefined);
7803
- }
7804
- async function readReceipts(root, sessionID) {
7805
- const path = join5(root, `${sessionID}.log`);
7806
- if (!isSafePathSegment(sessionID)) {
7807
- return failure({ path, cause: new Error("Unsafe path segment") });
7808
- }
7809
- let raw;
7810
- try {
7811
- raw = await readFile3(path, "utf8");
7812
- } catch (cause) {
7813
- return hasNodeErrorCode(cause, "ENOENT") ? success([]) : failure({ path, cause });
7814
- }
7815
- const receipts = [];
7816
- for (const line of raw.split(`
7817
- `)) {
7818
- const trimmed = line.trim();
7819
- if (!trimmed) {
7820
- continue;
7821
- }
7822
- try {
7823
- const parsed = JSON.parse(trimmed);
7824
- if (isContextReceipt(parsed)) {
7825
- receipts.push(parsed);
7826
- }
7827
- } catch {}
7828
- }
7829
- return success(receipts);
7830
- }
7831
- function isContextReceipt(value) {
7832
- if (typeof value !== "object" || value === null || !("kind" in value)) {
7833
- return false;
7834
- }
7835
- const kind = value.kind;
7836
- if (kind === "trim") {
7837
- return "trigger" in value && "at" in value && "tokens" in value && "removed" in value;
7838
- }
7839
- if (kind === "compact") {
7840
- return "trigger" in value && "at" in value && "summarized" in value;
7841
- }
7842
- if (kind === "refresh") {
7843
- return "reason" in value && "at" in value;
7844
- }
7845
- if (kind === "brain-reminder") {
7846
- return "at" in value && "threshold" in value && "completedSinceBaseline" in value;
7847
- }
7848
- return kind === "refusal" && "at" in value && "reason" in value;
7849
- }
7850
-
7851
7475
  // ../../node_modules/.bun/gpt-tokenizer@4.0.0/node_modules/gpt-tokenizer/esm/constants.js
7852
7476
  var DEFAULT_MERGE_CACHE_SIZE = 1e5;
7853
7477
 
@@ -217122,9 +216746,859 @@ function stringifyToolContent(value) {
217122
216746
  return typeof value === "string" ? value : JSON.stringify(value);
217123
216747
  }
217124
216748
 
217125
- // src/compaction.ts
216749
+ // ../core/src/brain-updates.ts
216750
+ var EMPTY_BRAIN_UPDATE_ACTIVITY_STATE = {
216751
+ fingerprint: null,
216752
+ baselineCompletedCalls: 0,
216753
+ reminded: false
216754
+ };
216755
+ function countCompletedToolCalls(messages) {
216756
+ const completedIDs = new Set;
216757
+ for (const message of messages) {
216758
+ for (const part of message.content) {
216759
+ if (isToolResultPart(part) && !isHelperTool(part)) {
216760
+ completedIDs.add(part.id);
216761
+ }
216762
+ }
216763
+ }
216764
+ const completedCallIDs = new Set;
216765
+ for (const message of messages) {
216766
+ for (const part of message.content) {
216767
+ if (isToolCallPart(part) && !isHelperTool(part) && completedIDs.has(part.id)) {
216768
+ completedCallIDs.add(part.id);
216769
+ }
216770
+ }
216771
+ }
216772
+ return completedCallIDs.size;
216773
+ }
216774
+ function evaluateBrainUpdateActivity(state, fingerprint, completedCalls, threshold) {
216775
+ if (state.fingerprint === null || state.fingerprint !== fingerprint) {
216776
+ const reset = {
216777
+ fingerprint,
216778
+ baselineCompletedCalls: completedCalls,
216779
+ reminded: false
216780
+ };
216781
+ return { state: reset, completedSinceBaseline: 0, crossed: false };
216782
+ }
216783
+ const baseline = completedCalls < state.baselineCompletedCalls ? completedCalls : state.baselineCompletedCalls;
216784
+ const sinceBaseline = completedCalls - baseline;
216785
+ const crossed = sinceBaseline >= threshold && !state.reminded;
216786
+ const next = {
216787
+ fingerprint,
216788
+ baselineCompletedCalls: baseline,
216789
+ reminded: state.reminded || crossed
216790
+ };
216791
+ return { state: next, completedSinceBaseline: sinceBaseline, crossed };
216792
+ }
216793
+ function isHelperTool(part) {
216794
+ return part.namespace === "vcc-brain" || part.namespace === "operator";
216795
+ }
216796
+
216797
+ // ../core/src/context/receipts.ts
216798
+ import { appendFile as appendFile2, mkdir as mkdir2, readFile as readFile3 } from "node:fs/promises";
216799
+ import { join as join5 } from "node:path";
216800
+
216801
+ // ../core/src/context/store.ts
216802
+ import { appendFile, mkdir, readFile as readFile2, stat as stat3, unlink, writeFile } from "node:fs/promises";
216803
+ import { join as join4 } from "node:path";
216804
+ var INDEX_FILE = "index.jsonl";
216805
+ var ID_PREFIX = "omitted-";
216806
+ async function storeOmissions(root, sessionID, items) {
216807
+ const sessionRoot = join4(root, sessionID);
216808
+ if (!isSafePathSegment(sessionID)) {
216809
+ return failure({ path: sessionRoot, cause: new Error("Unsafe path segment") });
216810
+ }
216811
+ const directoryResult = await mkdirSafe(sessionRoot);
216812
+ if (!directoryResult.ok) {
216813
+ return directoryResult;
216814
+ }
216815
+ const entriesResult = await readIndex(sessionRoot);
216816
+ if (!entriesResult.ok) {
216817
+ return entriesResult;
216818
+ }
216819
+ const known = new Map;
216820
+ for (const entry of entriesResult.value) {
216821
+ if (!known.has(entry.key)) {
216822
+ known.set(entry.key, entry.id);
216823
+ }
216824
+ }
216825
+ const ids = new Map(known);
216826
+ const stored = new Set;
216827
+ const failed = new Set;
216828
+ const fresh = [];
216829
+ let next = nextId(entriesResult.value);
216830
+ for (const item of items) {
216831
+ if (ids.has(item.key)) {
216832
+ continue;
216833
+ }
216834
+ if (!isSafePathSegment(item.key)) {
216835
+ failed.add(item.key);
216836
+ continue;
216837
+ }
216838
+ const id = formatContentID(next);
216839
+ next += 1;
216840
+ try {
216841
+ await writeFile(join4(sessionRoot, id), item.content, "utf8");
216842
+ } catch {
216843
+ failed.add(item.key);
216844
+ continue;
216845
+ }
216846
+ ids.set(item.key, id);
216847
+ stored.add(item.key);
216848
+ fresh.push({ key: item.key, id });
216849
+ }
216850
+ if (fresh.length > 0) {
216851
+ const lines = fresh.map((entry) => `${JSON.stringify(entry)}
216852
+ `).join("");
216853
+ try {
216854
+ await appendFile(indexPath(sessionRoot), lines, "utf8");
216855
+ } catch (cause) {
216856
+ for (const entry of fresh) {
216857
+ ids.delete(entry.key);
216858
+ stored.delete(entry.key);
216859
+ failed.add(entry.key);
216860
+ }
216861
+ return failure({ path: indexPath(sessionRoot), cause });
216862
+ }
216863
+ }
216864
+ return success({ ids, stored, failed });
216865
+ }
216866
+ async function readOmission(root, sessionID, contentID) {
216867
+ const payloadPath = join4(root, sessionID, contentID);
216868
+ if (!isSafePathSegment(sessionID) || !isSafePathSegment(contentID)) {
216869
+ return failure({ path: payloadPath, cause: new Error("Unsafe path segment") });
216870
+ }
216871
+ try {
216872
+ return success(await readFile2(payloadPath, "utf8"));
216873
+ } catch (cause) {
216874
+ return hasNodeErrorCode(cause, "ENOENT") ? success(null) : failure({ path: payloadPath, cause });
216875
+ }
216876
+ }
216877
+ var DEFAULT_RETENTION = {
216878
+ maxAgeMs: 30 * 24 * 60 * 60 * 1000,
216879
+ maxPayloads: 200,
216880
+ maxBytes: 32 * 1024 * 1024
216881
+ };
216882
+ async function pruneOmissions(root, sessionID, policy, now) {
216883
+ const sessionRoot = join4(root, sessionID);
216884
+ if (!isSafePathSegment(sessionID)) {
216885
+ return failure({ path: sessionRoot, cause: new Error("Unsafe path segment") });
216886
+ }
216887
+ const entriesResult = await readIndex(sessionRoot);
216888
+ if (!entriesResult.ok) {
216889
+ return entriesResult;
216890
+ }
216891
+ if (entriesResult.value.length === 0) {
216892
+ return success({ removed: [], freedBytes: 0, remaining: 0 });
216893
+ }
216894
+ const drop = new Set;
216895
+ const stats = new Map;
216896
+ const needsStats = policy.maxAgeMs !== null || policy.maxBytes !== null;
216897
+ if (needsStats) {
216898
+ for (const entry of entriesResult.value) {
216899
+ try {
216900
+ const info = await stat3(join4(sessionRoot, entry.id));
216901
+ stats.set(entry.id, { size: info.size, ageMs: now - info.mtimeMs });
216902
+ } catch (cause) {
216903
+ if (!hasNodeErrorCode(cause, "ENOENT")) {
216904
+ return failure({ path: join4(sessionRoot, entry.id), cause });
216905
+ }
216906
+ drop.add(entry.id);
216907
+ }
216908
+ }
216909
+ }
216910
+ if (policy.maxAgeMs !== null) {
216911
+ const maxAgeMs = policy.maxAgeMs;
216912
+ for (const entry of entriesResult.value) {
216913
+ const info = stats.get(entry.id);
216914
+ if (info === undefined || info.ageMs > maxAgeMs) {
216915
+ drop.add(entry.id);
216916
+ }
216917
+ }
216918
+ }
216919
+ const survivors = () => entriesResult.value.filter((entry) => !drop.has(entry.id));
216920
+ if (policy.maxPayloads !== null) {
216921
+ const over = survivors();
216922
+ for (const entry of over.slice(0, Math.max(0, over.length - policy.maxPayloads))) {
216923
+ drop.add(entry.id);
216924
+ }
216925
+ }
216926
+ if (policy.maxBytes !== null) {
216927
+ let bytes = 0;
216928
+ for (const entry of [...survivors()].reverse()) {
216929
+ bytes += stats.get(entry.id)?.size ?? 0;
216930
+ }
216931
+ for (const entry of survivors()) {
216932
+ if (bytes <= policy.maxBytes) {
216933
+ break;
216934
+ }
216935
+ bytes -= stats.get(entry.id)?.size ?? 0;
216936
+ drop.add(entry.id);
216937
+ }
216938
+ }
216939
+ let freedBytes = 0;
216940
+ for (const entry of entriesResult.value) {
216941
+ if (!drop.has(entry.id)) {
216942
+ continue;
216943
+ }
216944
+ freedBytes += stats.get(entry.id)?.size ?? 0;
216945
+ try {
216946
+ await unlink(join4(sessionRoot, entry.id));
216947
+ } catch (cause) {
216948
+ if (!hasNodeErrorCode(cause, "ENOENT")) {
216949
+ return failure({ path: join4(sessionRoot, entry.id), cause });
216950
+ }
216951
+ }
216952
+ }
216953
+ const remaining = entriesResult.value.filter((entry) => !drop.has(entry.id));
216954
+ try {
216955
+ await writeFile(indexPath(sessionRoot), remaining.map((entry) => `${JSON.stringify(entry)}
216956
+ `).join(""), "utf8");
216957
+ } catch (cause) {
216958
+ return failure({ path: indexPath(sessionRoot), cause });
216959
+ }
216960
+ return success({
216961
+ removed: entriesResult.value.filter((entry) => drop.has(entry.id)).map((entry) => entry.id),
216962
+ freedBytes,
216963
+ remaining: remaining.length
216964
+ });
216965
+ }
216966
+ async function readIndex(sessionRoot) {
216967
+ const path = indexPath(sessionRoot);
216968
+ let raw;
216969
+ try {
216970
+ raw = await readFile2(path, "utf8");
216971
+ } catch (cause) {
216972
+ return hasNodeErrorCode(cause, "ENOENT") ? success([]) : failure({ path, cause });
216973
+ }
216974
+ const entries = [];
216975
+ for (const line of raw.split(`
216976
+ `)) {
216977
+ const trimmed = line.trim();
216978
+ if (!trimmed) {
216979
+ continue;
216980
+ }
216981
+ try {
216982
+ const parsed = JSON.parse(trimmed);
216983
+ if (typeof parsed === "object" && parsed !== null && "key" in parsed && "id" in parsed && typeof parsed.key === "string" && typeof parsed.id === "string") {
216984
+ entries.push({ key: parsed.key, id: parsed.id });
216985
+ }
216986
+ } catch {}
216987
+ }
216988
+ return success(entries);
216989
+ }
216990
+ async function mkdirSafe(path) {
216991
+ try {
216992
+ await mkdir(path, { recursive: true });
216993
+ return success(undefined);
216994
+ } catch (cause) {
216995
+ return failure({ path, cause });
216996
+ }
216997
+ }
216998
+ function indexPath(sessionRoot) {
216999
+ return join4(sessionRoot, INDEX_FILE);
217000
+ }
217001
+ function nextId(entries) {
217002
+ let max = 0;
217003
+ for (const entry of entries) {
217004
+ const suffix = entry.id.startsWith(ID_PREFIX) ? entry.id.slice(ID_PREFIX.length) : null;
217005
+ const value = suffix === null ? Number.NaN : Number.parseInt(suffix, 10);
217006
+ if (!Number.isNaN(value) && value > max) {
217007
+ max = value;
217008
+ }
217009
+ }
217010
+ return max + 1;
217011
+ }
217012
+ function formatContentID(id) {
217013
+ return `${ID_PREFIX}${String(id).padStart(3, "0")}`;
217014
+ }
217015
+ function isSafePathSegment(segment) {
217016
+ return segment.length > 0 && !segment.includes("/") && !segment.includes("\\") && segment !== "..";
217017
+ }
217018
+
217019
+ // ../core/src/context/receipts.ts
217020
+ async function appendReceipt(root, sessionID, receipt) {
217021
+ const path = join5(root, `${sessionID}.log`);
217022
+ if (!isSafePathSegment(sessionID)) {
217023
+ return failure({ path, cause: new Error("Unsafe path segment") });
217024
+ }
217025
+ try {
217026
+ await mkdir2(root, { recursive: true });
217027
+ await appendFile2(path, `${JSON.stringify(receipt)}
217028
+ `, "utf8");
217029
+ } catch (cause) {
217030
+ return failure({ path, cause });
217031
+ }
217032
+ return success(undefined);
217033
+ }
217034
+ async function readReceipts(root, sessionID) {
217035
+ const path = join5(root, `${sessionID}.log`);
217036
+ if (!isSafePathSegment(sessionID)) {
217037
+ return failure({ path, cause: new Error("Unsafe path segment") });
217038
+ }
217039
+ let raw;
217040
+ try {
217041
+ raw = await readFile3(path, "utf8");
217042
+ } catch (cause) {
217043
+ return hasNodeErrorCode(cause, "ENOENT") ? success([]) : failure({ path, cause });
217044
+ }
217045
+ const receipts = [];
217046
+ for (const line of raw.split(`
217047
+ `)) {
217048
+ const trimmed = line.trim();
217049
+ if (!trimmed) {
217050
+ continue;
217051
+ }
217052
+ try {
217053
+ const parsed = JSON.parse(trimmed);
217054
+ if (isContextReceipt(parsed)) {
217055
+ receipts.push(parsed);
217056
+ }
217057
+ } catch {}
217058
+ }
217059
+ return success(receipts);
217060
+ }
217061
+ function isContextReceipt(value) {
217062
+ if (typeof value !== "object" || value === null || !("kind" in value)) {
217063
+ return false;
217064
+ }
217065
+ const kind = value.kind;
217066
+ if (kind === "trim") {
217067
+ return "trigger" in value && "at" in value && "tokens" in value && "removed" in value;
217068
+ }
217069
+ if (kind === "compact") {
217070
+ return "trigger" in value && "at" in value && "summarized" in value;
217071
+ }
217072
+ if (kind === "refresh") {
217073
+ return "reason" in value && "at" in value;
217074
+ }
217075
+ if (kind === "brain-reminder") {
217076
+ return "at" in value && "threshold" in value && "completedSinceBaseline" in value;
217077
+ }
217078
+ return kind === "refusal" && "at" in value && "reason" in value;
217079
+ }
217080
+
217081
+ // ../core/src/preamble-refresh.ts
217082
+ import { readdir as readdir2, stat as stat4 } from "node:fs/promises";
217083
+ import { join as join6 } from "node:path";
217084
+ var REFRESH_FLOOR_TOKENS = 4000;
217085
+ async function fingerprintPreamble(projectDirectory, homeDirectory) {
217086
+ const entries = [];
217087
+ const roots = await resolveBrainRoots(projectDirectory, homeDirectory);
217088
+ const sharedRoot = roots.sharedRoot;
217089
+ const privateRoot = roots.privateRoot;
217090
+ const userRoot = roots.userRoot;
217091
+ for (const root of [sharedRoot, privateRoot]) {
217092
+ for (const file of [await resolveInstructionsPath(root), join6(root, "catalog.md")]) {
217093
+ const entry = await fingerprintFile(file);
217094
+ if (!entry.ok) {
217095
+ return entry;
217096
+ }
217097
+ entries.push(entry.value);
217098
+ }
217099
+ }
217100
+ for (const file of [
217101
+ await resolveInstructionsPath(userRoot),
217102
+ join6(userRoot, "catalog.md"),
217103
+ join6(userRoot, "observations.md")
217104
+ ]) {
217105
+ const entry = await fingerprintFile(file);
217106
+ if (!entry.ok) {
217107
+ return entry;
217108
+ }
217109
+ entries.push(entry.value);
217110
+ }
217111
+ for (const root of [sharedRoot, privateRoot]) {
217112
+ const indexEntries = await fingerprintIndex(join6(root, "index"));
217113
+ if (!indexEntries.ok) {
217114
+ return indexEntries;
217115
+ }
217116
+ entries.push(...indexEntries.value);
217117
+ }
217118
+ entries.sort();
217119
+ return success(entries.join(`
217120
+ `));
217121
+ }
217122
+ function isCacheCold(tokens) {
217123
+ return tokens === null || tokens.cacheRead === 0;
217124
+ }
217125
+ async function fingerprintFile(path) {
217126
+ try {
217127
+ const info = await stat4(path);
217128
+ return success(`${path}:${info.mtimeMs}`);
217129
+ } catch (cause) {
217130
+ if (hasNodeErrorCode(cause, "ENOENT")) {
217131
+ return success(`${path}:missing`);
217132
+ }
217133
+ return failure({ path, cause });
217134
+ }
217135
+ }
217136
+ async function fingerprintIndex(indexRoot) {
217137
+ try {
217138
+ await stat4(indexRoot);
217139
+ } catch (cause) {
217140
+ if (hasNodeErrorCode(cause, "ENOENT")) {
217141
+ return success([`${indexRoot}:missing`]);
217142
+ }
217143
+ return failure({ path: indexRoot, cause });
217144
+ }
217145
+ const paths = [];
217146
+ const collected = await collectIndexFiles(indexRoot, paths);
217147
+ if (!collected.ok) {
217148
+ return collected;
217149
+ }
217150
+ const entries = [];
217151
+ for (const path of paths) {
217152
+ const entry = await fingerprintFile(path);
217153
+ if (!entry.ok) {
217154
+ return entry;
217155
+ }
217156
+ entries.push(entry.value);
217157
+ }
217158
+ return success(entries);
217159
+ }
217160
+ async function collectIndexFiles(directory, paths) {
217161
+ let entries;
217162
+ try {
217163
+ entries = await readdir2(directory, { withFileTypes: true });
217164
+ } catch (cause) {
217165
+ return failure({ path: directory, cause });
217166
+ }
217167
+ for (const entry of entries) {
217168
+ const path = join6(directory, entry.name);
217169
+ if (entry.isDirectory()) {
217170
+ const nested = await collectIndexFiles(path, paths);
217171
+ if (!nested.ok) {
217172
+ return nested;
217173
+ }
217174
+ } else if (entry.isFile() && entry.name.endsWith(".md")) {
217175
+ paths.push(path);
217176
+ }
217177
+ }
217178
+ return success(undefined);
217179
+ }
217180
+
217181
+ // src/brain-updates.ts
217126
217182
  import { join as join8 } from "node:path";
217127
217183
 
217184
+ // ../core/src/context/triggers.ts
217185
+ var EMPTY_TRIGGER_STATE = { fired: {} };
217186
+ function dedupDeltaTokens(windowTokens) {
217187
+ if (windowTokens <= 0) {
217188
+ return 25000;
217189
+ }
217190
+ return Math.min(Math.floor(windowTokens * 0.1), 25000);
217191
+ }
217192
+ function exceedsThresholds(estimatedTokens, windowTokens, config) {
217193
+ const overRatio = windowTokens > 0 && estimatedTokens / windowTokens > config.ratio;
217194
+ return overRatio || estimatedTokens > config.hardCapTokens;
217195
+ }
217196
+ function evaluateTrigger(state, event, estimatedTokens, windowTokens, config) {
217197
+ const candidates = event === "request" ? requestCandidates(estimatedTokens, windowTokens, config) : taskCompleteCandidates(estimatedTokens, config);
217198
+ for (const kind of candidates) {
217199
+ if (grewEnough(state, kind, estimatedTokens, windowTokens)) {
217200
+ return { fire: kind, state: recordFired(state, kind, estimatedTokens) };
217201
+ }
217202
+ }
217203
+ return { fire: null, state };
217204
+ }
217205
+ function requestCandidates(estimatedTokens, windowTokens, config) {
217206
+ const candidates = [];
217207
+ if (windowTokens > 0 && estimatedTokens / windowTokens > config.ratio) {
217208
+ candidates.push("ratio");
217209
+ }
217210
+ if (estimatedTokens > config.hardCapTokens) {
217211
+ candidates.push("hard-cap");
217212
+ }
217213
+ return candidates;
217214
+ }
217215
+ function taskCompleteCandidates(estimatedTokens, config) {
217216
+ if (!config.compactOnComplete) {
217217
+ return [];
217218
+ }
217219
+ if (estimatedTokens < config.compactFloorTokens) {
217220
+ return [];
217221
+ }
217222
+ return ["task-complete"];
217223
+ }
217224
+ function grewEnough(state, kind, estimatedTokens, windowTokens) {
217225
+ const firedAt = state.fired[kind];
217226
+ if (firedAt === undefined) {
217227
+ return true;
217228
+ }
217229
+ return estimatedTokens - firedAt >= dedupDeltaTokens(windowTokens);
217230
+ }
217231
+ function recordFired(state, kind, estimatedTokens) {
217232
+ return { fired: { ...state.fired, [kind]: estimatedTokens } };
217233
+ }
217234
+
217235
+ // src/runtime.ts
217236
+ import { join as join7 } from "node:path";
217237
+ var PENDING_CAUSE_TTL_MS = 10 * 60 * 1000;
217238
+ var FAILED_COMPACTION_COOLDOWN_MS = 10 * 60 * 1000;
217239
+ function shouldSuppressCompactionRequest(session, estimatedTokens, windowTokens, now) {
217240
+ const failure = session.lastCompactionFailure;
217241
+ if (failure === null) {
217242
+ return false;
217243
+ }
217244
+ if (now - failure.at <= FAILED_COMPACTION_COOLDOWN_MS) {
217245
+ return true;
217246
+ }
217247
+ return estimatedTokens - failure.estimate < dedupDeltaTokens(windowTokens);
217248
+ }
217249
+ function isContextStale(deps) {
217250
+ return deps.isCurrent !== undefined && !deps.isCurrent();
217251
+ }
217252
+ function createContextRuntime() {
217253
+ return {
217254
+ sessions: new Map,
217255
+ refusals: new Set,
217256
+ reportedReceiptFailures: new Set,
217257
+ hydrated: new Set,
217258
+ pendingCauses: new Map
217259
+ };
217260
+ }
217261
+ var SHARED_RUNTIME_KEY = "__vccBrainContextRuntime";
217262
+ function readSharedRuntime() {
217263
+ const existing = globalThis[SHARED_RUNTIME_KEY];
217264
+ if (typeof existing !== "object" || existing === null || !("sessions" in existing)) {
217265
+ return null;
217266
+ }
217267
+ return existing;
217268
+ }
217269
+ function sharedContextRuntime() {
217270
+ const existing = readSharedRuntime();
217271
+ if (existing !== null) {
217272
+ return existing;
217273
+ }
217274
+ const created = createContextRuntime();
217275
+ globalThis[SHARED_RUNTIME_KEY] = created;
217276
+ return created;
217277
+ }
217278
+ function sessionRuntime(runtime, sessionID) {
217279
+ const existing = runtime.sessions.get(sessionID);
217280
+ if (existing !== undefined) {
217281
+ const legacy = existing;
217282
+ if (legacy.lastCompactionFailure === undefined) {
217283
+ existing.lastCompactionFailure = null;
217284
+ }
217285
+ if (legacy.snapshotSeen === undefined) {
217286
+ existing.snapshotSeen = null;
217287
+ }
217288
+ return existing;
217289
+ }
217290
+ const created = {
217291
+ estimator: EMPTY_ESTIMATOR,
217292
+ triggerState: EMPTY_TRIGGER_STATE,
217293
+ windowTokens: null,
217294
+ windowModel: null,
217295
+ windowFailures: 0,
217296
+ lastEstimate: null,
217297
+ lastMessageCount: 0,
217298
+ lastStepTokens: null,
217299
+ lastCompactionFailure: null,
217300
+ preambleFingerprint: null,
217301
+ preambleRefreshPending: false,
217302
+ brainUpdateActivity: EMPTY_BRAIN_UPDATE_ACTIVITY_STATE,
217303
+ snapshotSeen: null
217304
+ };
217305
+ runtime.sessions.set(sessionID, created);
217306
+ return created;
217307
+ }
217308
+ var MAX_WINDOW_LOOKUP_ATTEMPTS = 3;
217309
+ async function resolveWindowTokens(context, session, model) {
217310
+ if (session.windowModel !== model.id) {
217311
+ session.windowModel = model.id;
217312
+ session.windowTokens = null;
217313
+ session.windowFailures = 0;
217314
+ }
217315
+ if (session.windowTokens !== null || session.windowFailures >= MAX_WINDOW_LOOKUP_ATTEMPTS) {
217316
+ return session.windowTokens;
217317
+ }
217318
+ try {
217319
+ const listed = await context.model.list();
217320
+ const fallback = `${model.providerID}/${model.id.split("/")[1] ?? model.id}`;
217321
+ const info = listed.data.find((entry) => entry.id === model.id || entry.id === fallback);
217322
+ const limit = info?.limit.context ?? 0;
217323
+ if (limit > 0) {
217324
+ session.windowTokens = limit;
217325
+ session.windowFailures = 0;
217326
+ } else {
217327
+ session.windowFailures += 1;
217328
+ }
217329
+ } catch {
217330
+ session.windowFailures += 1;
217331
+ }
217332
+ return session.windowTokens;
217333
+ }
217334
+ async function ensureSessionHydrated(stateDirectory, runtime, sessionID) {
217335
+ if (runtime.hydrated.has(sessionID)) {
217336
+ return;
217337
+ }
217338
+ const receipts = await readReceipts(join7(stateDirectory, "context-log"), sessionID);
217339
+ if (!receipts.ok) {
217340
+ return;
217341
+ }
217342
+ const session = sessionRuntime(runtime, sessionID);
217343
+ const fired = {};
217344
+ for (const receipt of receipts.value) {
217345
+ if (receipt.kind === "refusal") {
217346
+ runtime.refusals.add(sessionID);
217347
+ } else if (receipt.kind === "trim") {
217348
+ fired[receipt.trigger] = receipt.tokens;
217349
+ } else if (receipt.kind === "compact" && receipt.trigger !== "manual") {
217350
+ fired[receipt.trigger] = receipt.summarized;
217351
+ }
217352
+ }
217353
+ session.triggerState = { fired: { ...fired, ...session.triggerState.fired } };
217354
+ runtime.hydrated.add(sessionID);
217355
+ }
217356
+ async function ensureRefusalReceipt(stateDirectory, runtime, sessionID, deps) {
217357
+ if (runtime.refusals.has(sessionID)) {
217358
+ return;
217359
+ }
217360
+ runtime.refusals.add(sessionID);
217361
+ const written = await appendReceipt(join7(stateDirectory, "context-log"), sessionID, {
217362
+ kind: "refusal",
217363
+ at: new Date().toISOString(),
217364
+ reason: "brain-unavailable"
217365
+ });
217366
+ if (!written.ok) {
217367
+ reportReceiptFailureOnce(runtime, deps, sessionID, "refusal");
217368
+ }
217369
+ }
217370
+ function reportReceiptFailureOnce(runtime, deps, sessionID, kind) {
217371
+ if (isContextStale(deps)) {
217372
+ return;
217373
+ }
217374
+ const key = sessionID === null ? `null:${kind}` : sessionID;
217375
+ if (runtime.reportedReceiptFailures.has(key)) {
217376
+ return;
217377
+ }
217378
+ runtime.reportedReceiptFailures.add(key);
217379
+ deps.reportReceiptFailure(sessionID, kind);
217380
+ }
217381
+
217382
+ // src/brain-updates.ts
217383
+ async function maybeAppendBrainUpdateReminder(deps, runtime, sessionID, messages, content) {
217384
+ if (!deps.config.enabled || isContextStale(deps) || !deps.isBrainAvailable(sessionID)) {
217385
+ return content;
217386
+ }
217387
+ const session = sessionRuntime(runtime, sessionID);
217388
+ const fingerprinted = await fingerprintPreamble(deps.projectDirectory, deps.homeDirectory);
217389
+ if (!fingerprinted.ok) {
217390
+ return content;
217391
+ }
217392
+ const decision = evaluateBrainUpdateActivity(session.brainUpdateActivity, fingerprinted.value, countCompletedToolCalls(messages), deps.config.toolCallThreshold);
217393
+ if (isContextStale(deps)) {
217394
+ return content;
217395
+ }
217396
+ session.brainUpdateActivity = decision.state;
217397
+ if (!decision.crossed) {
217398
+ return content;
217399
+ }
217400
+ const receipt = {
217401
+ kind: "brain-reminder",
217402
+ at: new Date().toISOString(),
217403
+ threshold: deps.config.toolCallThreshold,
217404
+ completedSinceBaseline: decision.completedSinceBaseline
217405
+ };
217406
+ await appendReceipt(join8(deps.stateDirectory, "context-log"), sessionID, receipt);
217407
+ return `${content}
217408
+
217409
+ ${brainUpdateReminder(deps.config.toolCallThreshold)}`;
217410
+ }
217411
+ function brainUpdateReminder(toolCallThreshold) {
217412
+ return `<vcc-brain-brain-update-reminder>
217413
+ You have completed ${toolCallThreshold} tool calls without a Brain change.
217414
+ Before continuing, record any durable decisions, contracts, or lessons in the
217415
+ appropriate Brain partition. Do not write transient task progress or restate
217416
+ implementation. If nothing durable has emerged, make no Brain edits.
217417
+ </vcc-brain-brain-update-reminder>`;
217418
+ }
217419
+
217420
+ // src/utils.ts
217421
+ function success2(value) {
217422
+ return { ok: true, value };
217423
+ }
217424
+ function failure2(error) {
217425
+ return { ok: false, error };
217426
+ }
217427
+
217428
+ // src/options.ts
217429
+ function readOptionBlock(options, block) {
217430
+ if (typeof options !== "object" || options === null) {
217431
+ return success2(null);
217432
+ }
217433
+ const primary = "vcc-brain" in options ? options["vcc-brain"] : undefined;
217434
+ const legacy = "operator" in options ? options.operator : undefined;
217435
+ const source = primary ?? legacy ?? null;
217436
+ if (source === null || source === undefined) {
217437
+ return success2(null);
217438
+ }
217439
+ if (typeof source !== "object" || Array.isArray(source)) {
217440
+ return failure2({
217441
+ message: 'The "vcc-brain" (legacy "operator") plugin option must be an object.'
217442
+ });
217443
+ }
217444
+ const section = block in source ? source[block] : null;
217445
+ if (section === null || section === undefined) {
217446
+ return success2(null);
217447
+ }
217448
+ if (typeof section !== "object" || Array.isArray(section)) {
217449
+ return failure2({ message: `The "vcc-brain.${block}" option must be an object.` });
217450
+ }
217451
+ return success2(section);
217452
+ }
217453
+ function readOptionNumber(path, block, key, defaultValue) {
217454
+ const value = block[key];
217455
+ if (value === undefined) {
217456
+ return success2(defaultValue);
217457
+ }
217458
+ if (typeof value !== "number" || !Number.isFinite(value)) {
217459
+ return failure2({ message: `The "${path}.${key}" option must be a number.` });
217460
+ }
217461
+ return success2(value);
217462
+ }
217463
+ function readOptionBoolean(path, block, key, defaultValue) {
217464
+ const value = block[key];
217465
+ if (value === undefined) {
217466
+ return success2(defaultValue);
217467
+ }
217468
+ if (typeof value !== "boolean") {
217469
+ return failure2({ message: `The "${path}.${key}" option must be a boolean.` });
217470
+ }
217471
+ return success2(value);
217472
+ }
217473
+
217474
+ // src/brain-updates-config.ts
217475
+ var DEFAULT_BRAIN_UPDATES_CONFIG = {
217476
+ enabled: false,
217477
+ toolCallThreshold: 25
217478
+ };
217479
+ var BRAIN_UPDATES_PATH = "operator.brainUpdates";
217480
+ function parseBrainUpdatesConfig(options, base = DEFAULT_BRAIN_UPDATES_CONFIG) {
217481
+ const block = readOptionBlock(options, "brainUpdates");
217482
+ if (!block.ok) {
217483
+ return block;
217484
+ }
217485
+ return parseBrainUpdatesBlock(block.value, base);
217486
+ }
217487
+ function parseBrainUpdatesBlock(block, base = DEFAULT_BRAIN_UPDATES_CONFIG) {
217488
+ if (block === null) {
217489
+ return success2(base);
217490
+ }
217491
+ const enabled = readOptionBoolean(BRAIN_UPDATES_PATH, block, "enabled", base.enabled);
217492
+ if (!enabled.ok) {
217493
+ return enabled;
217494
+ }
217495
+ const toolCallThreshold = readOptionNumber(BRAIN_UPDATES_PATH, block, "toolCallThreshold", base.toolCallThreshold);
217496
+ if (!toolCallThreshold.ok) {
217497
+ return toolCallThreshold;
217498
+ }
217499
+ if (!Number.isInteger(toolCallThreshold.value) || toolCallThreshold.value <= 0) {
217500
+ return {
217501
+ ok: false,
217502
+ error: {
217503
+ message: `The "${BRAIN_UPDATES_PATH}.toolCallThreshold" option must be a positive integer.`
217504
+ }
217505
+ };
217506
+ }
217507
+ return success2({ enabled: enabled.value, toolCallThreshold: toolCallThreshold.value });
217508
+ }
217509
+
217510
+ // src/commands.ts
217511
+ var VCC_BRAIN_COMMAND_NAMES = [
217512
+ "vcc-brain:user-init",
217513
+ "vcc-brain:project-init",
217514
+ "vcc-brain:index"
217515
+ ];
217516
+ var commands = {
217517
+ "vcc-brain:user-init": {
217518
+ description: "Initialize VCC Brain User Instructions",
217519
+ operation: "user init",
217520
+ guide: "Follow the User Setup guide in its output, including when initialization reports failures."
217521
+ },
217522
+ "vcc-brain:project-init": {
217523
+ description: "Initialize VCC Brain Project",
217524
+ operation: "project init",
217525
+ guide: "Follow the Project Setup guide in its output, including when initialization reports failures."
217526
+ },
217527
+ "vcc-brain:index": {
217528
+ description: "Build or refresh the VCC Brain Project Index",
217529
+ operation: "index init",
217530
+ guide: "Follow the Project Index Setup guide in its output, including when inspection reports failures."
217531
+ }
217532
+ };
217533
+ async function registerCommands(context) {
217534
+ const existing = new Set((await context.command.list()).data.map((command) => command.name));
217535
+ await context.command.transform((draft) => {
217536
+ for (const name of VCC_BRAIN_COMMAND_NAMES) {
217537
+ if (existing.has(name))
217538
+ continue;
217539
+ const command = commands[name];
217540
+ draft.add({
217541
+ name,
217542
+ description: command.description,
217543
+ execute: async (input) => {
217544
+ await context.session.prompt({
217545
+ ...input.prompt,
217546
+ sessionID: input.sessionID,
217547
+ text: `# ${command.description}
217548
+
217549
+ 1. Run \`vcc-brain-helper version\`. If an update is available, run \`vcc-brain-helper upgrade\` before continuing.
217550
+ 2. Run \`vcc-brain-helper ${command.operation}\`. ${command.guide}
217551
+
217552
+ ## Recovery
217553
+
217554
+ - If Helper cannot start, install or repair the npm package \`@jwitmann/vcc-brain-helper\` globally and retry the failed command.
217555
+ - If the version check or upgrade fails, diagnose the error and retry.
217556
+ - If \`vcc-brain-helper ${command.operation}\` reports a failure, use its output to resolve it and rerun it as needed.
217557
+ - If you cannot resolve a problem, report the blocker.
217558
+
217559
+ Use Helper output as working context. Do not reproduce it wholesale or reimplement Helper logic.`,
217560
+ delivery: input.delivery
217561
+ });
217562
+ }
217563
+ });
217564
+ }
217565
+ });
217566
+ }
217567
+
217568
+ // ../core/src/context/compaction.ts
217569
+ var DEFAULT_RECOVERY_RULE = `Tool input/output omission notices (content IDs) are the only recoverable
217570
+ ` + ` handles for trimmed content. Keep every omission notice verbatim in the
217571
+ ` + ` summary; the agent recovers payloads through the vcc-brain-read_omitted
217572
+ ` + " tool.";
217573
+ function buildCompactionPrompt(input) {
217574
+ const paths = input.brainPaths.map((path) => `- ${path}`).join(`
217575
+ `);
217576
+ return `<compaction-instructions>
217577
+ You are compacting the conversation history for a VCC Brain session.
217578
+ Produce a summary that lets the next session continue the work without the
217579
+ full history.
217580
+
217581
+ The summary must preserve, in order of importance:
217582
+ 1. The current task and what has been completed so far.
217583
+ 2. Active files: paths the work depends on, with a one-line note on the role
217584
+ of each.
217585
+ 3. Blockers and open questions.
217586
+ 4. Key decisions already made, with their reasons.
217587
+
217588
+ Rules:
217589
+ - ${input.recoveryRule ?? DEFAULT_RECOVERY_RULE}
217590
+ - Durable knowledge lives in the Brain partitions. Reference these paths
217591
+ instead of inlining their content:
217592
+ ${paths}
217593
+ - Before summarizing, ensure any spec or decision that exists only in this
217594
+ conversation is written to the appropriate Brain document.
217595
+ - Compaction is lossy; the Brain is not.
217596
+ </compaction-instructions>`;
217597
+ }
217598
+
217599
+ // src/compaction.ts
217600
+ import { join as join10 } from "node:path";
217601
+
217128
217602
  // ../core/src/context/compiler.ts
217129
217603
  var TOKEN_RE = /[a-zA-Z]+|[0-9]+|[^\sa-zA-Z0-9]|\s+/g;
217130
217604
  var ANSI_RE = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;
@@ -218109,7 +218583,7 @@ function compileCompaction(messages, config, keepMessages, requestTokens) {
218109
218583
 
218110
218584
  // src/compaction-snapshot.ts
218111
218585
  import { mkdir as mkdir3, readFile as readFile4, rename, writeFile as writeFile2 } from "node:fs/promises";
218112
- import { join as join6 } from "node:path";
218586
+ import { join as join9 } from "node:path";
218113
218587
 
218114
218588
  // ../core/src/context/session-compat.ts
218115
218589
  var warnSink = null;
@@ -218644,7 +219118,7 @@ async function rememberSnapshot(root, sessionID, messages, at, prev) {
218644
219118
  }
218645
219119
  }
218646
219120
  function snapshotPath(root, sessionID) {
218647
- return join6(root, `${sessionID}.json`);
219121
+ return join9(root, `${sessionID}.json`);
218648
219122
  }
218649
219123
  async function writeCompactionSnapshot(root, sessionID, messages, at) {
218650
219124
  const path = snapshotPath(root, sessionID);
@@ -218863,252 +219337,6 @@ function classifySnapshotStore(read) {
218863
219337
  return { status: "ready", messages };
218864
219338
  }
218865
219339
 
218866
- // ../core/src/context/triggers.ts
218867
- var EMPTY_TRIGGER_STATE = { fired: {} };
218868
- function dedupDeltaTokens(windowTokens) {
218869
- if (windowTokens <= 0) {
218870
- return 25000;
218871
- }
218872
- return Math.min(Math.floor(windowTokens * 0.1), 25000);
218873
- }
218874
- function exceedsThresholds(estimatedTokens, windowTokens, config) {
218875
- const overRatio = windowTokens > 0 && estimatedTokens / windowTokens > config.ratio;
218876
- return overRatio || estimatedTokens > config.hardCapTokens;
218877
- }
218878
- function evaluateTrigger(state, event, estimatedTokens, windowTokens, config) {
218879
- const candidates = event === "request" ? requestCandidates(estimatedTokens, windowTokens, config) : taskCompleteCandidates(estimatedTokens, config);
218880
- for (const kind of candidates) {
218881
- if (grewEnough(state, kind, estimatedTokens, windowTokens)) {
218882
- return { fire: kind, state: recordFired(state, kind, estimatedTokens) };
218883
- }
218884
- }
218885
- return { fire: null, state };
218886
- }
218887
- function requestCandidates(estimatedTokens, windowTokens, config) {
218888
- const candidates = [];
218889
- if (windowTokens > 0 && estimatedTokens / windowTokens > config.ratio) {
218890
- candidates.push("ratio");
218891
- }
218892
- if (estimatedTokens > config.hardCapTokens) {
218893
- candidates.push("hard-cap");
218894
- }
218895
- return candidates;
218896
- }
218897
- function taskCompleteCandidates(estimatedTokens, config) {
218898
- if (!config.compactOnComplete) {
218899
- return [];
218900
- }
218901
- if (estimatedTokens < config.compactFloorTokens) {
218902
- return [];
218903
- }
218904
- return ["task-complete"];
218905
- }
218906
- function grewEnough(state, kind, estimatedTokens, windowTokens) {
218907
- const firedAt = state.fired[kind];
218908
- if (firedAt === undefined) {
218909
- return true;
218910
- }
218911
- return estimatedTokens - firedAt >= dedupDeltaTokens(windowTokens);
218912
- }
218913
- function recordFired(state, kind, estimatedTokens) {
218914
- return { fired: { ...state.fired, [kind]: estimatedTokens } };
218915
- }
218916
-
218917
- // ../core/src/brain-updates.ts
218918
- var EMPTY_BRAIN_UPDATE_ACTIVITY_STATE = {
218919
- fingerprint: null,
218920
- baselineCompletedCalls: 0,
218921
- reminded: false
218922
- };
218923
- function countCompletedToolCalls(messages) {
218924
- const completedIDs = new Set;
218925
- for (const message of messages) {
218926
- for (const part of message.content) {
218927
- if (isToolResultPart(part) && !isHelperTool(part)) {
218928
- completedIDs.add(part.id);
218929
- }
218930
- }
218931
- }
218932
- const completedCallIDs = new Set;
218933
- for (const message of messages) {
218934
- for (const part of message.content) {
218935
- if (isToolCallPart(part) && !isHelperTool(part) && completedIDs.has(part.id)) {
218936
- completedCallIDs.add(part.id);
218937
- }
218938
- }
218939
- }
218940
- return completedCallIDs.size;
218941
- }
218942
- function evaluateBrainUpdateActivity(state, fingerprint, completedCalls, threshold) {
218943
- if (state.fingerprint === null || state.fingerprint !== fingerprint) {
218944
- const reset = {
218945
- fingerprint,
218946
- baselineCompletedCalls: completedCalls,
218947
- reminded: false
218948
- };
218949
- return { state: reset, completedSinceBaseline: 0, crossed: false };
218950
- }
218951
- const baseline = completedCalls < state.baselineCompletedCalls ? completedCalls : state.baselineCompletedCalls;
218952
- const sinceBaseline = completedCalls - baseline;
218953
- const crossed = sinceBaseline >= threshold && !state.reminded;
218954
- const next = {
218955
- fingerprint,
218956
- baselineCompletedCalls: baseline,
218957
- reminded: state.reminded || crossed
218958
- };
218959
- return { state: next, completedSinceBaseline: sinceBaseline, crossed };
218960
- }
218961
- function isHelperTool(part) {
218962
- return part.namespace === "vcc-brain" || part.namespace === "operator";
218963
- }
218964
-
218965
- // src/runtime.ts
218966
- import { join as join7 } from "node:path";
218967
- var PENDING_CAUSE_TTL_MS = 10 * 60 * 1000;
218968
- var FAILED_COMPACTION_COOLDOWN_MS = 10 * 60 * 1000;
218969
- function shouldSuppressCompactionRequest(session, estimatedTokens, windowTokens, now) {
218970
- const failure = session.lastCompactionFailure;
218971
- if (failure === null) {
218972
- return false;
218973
- }
218974
- if (now - failure.at <= FAILED_COMPACTION_COOLDOWN_MS) {
218975
- return true;
218976
- }
218977
- return estimatedTokens - failure.estimate < dedupDeltaTokens(windowTokens);
218978
- }
218979
- function isContextStale(deps) {
218980
- return deps.isCurrent !== undefined && !deps.isCurrent();
218981
- }
218982
- function createContextRuntime() {
218983
- return {
218984
- sessions: new Map,
218985
- refusals: new Set,
218986
- reportedReceiptFailures: new Set,
218987
- hydrated: new Set,
218988
- pendingCauses: new Map
218989
- };
218990
- }
218991
- var SHARED_RUNTIME_KEY = "__vccBrainContextRuntime";
218992
- function readSharedRuntime() {
218993
- const existing = globalThis[SHARED_RUNTIME_KEY];
218994
- if (typeof existing !== "object" || existing === null || !("sessions" in existing)) {
218995
- return null;
218996
- }
218997
- return existing;
218998
- }
218999
- function sharedContextRuntime() {
219000
- const existing = readSharedRuntime();
219001
- if (existing !== null) {
219002
- return existing;
219003
- }
219004
- const created = createContextRuntime();
219005
- globalThis[SHARED_RUNTIME_KEY] = created;
219006
- return created;
219007
- }
219008
- function sessionRuntime(runtime, sessionID) {
219009
- const existing = runtime.sessions.get(sessionID);
219010
- if (existing !== undefined) {
219011
- const legacy = existing;
219012
- if (legacy.lastCompactionFailure === undefined) {
219013
- existing.lastCompactionFailure = null;
219014
- }
219015
- if (legacy.snapshotSeen === undefined) {
219016
- existing.snapshotSeen = null;
219017
- }
219018
- return existing;
219019
- }
219020
- const created = {
219021
- estimator: EMPTY_ESTIMATOR,
219022
- triggerState: EMPTY_TRIGGER_STATE,
219023
- windowTokens: null,
219024
- windowModel: null,
219025
- windowFailures: 0,
219026
- lastEstimate: null,
219027
- lastMessageCount: 0,
219028
- lastStepTokens: null,
219029
- lastCompactionFailure: null,
219030
- preambleFingerprint: null,
219031
- preambleRefreshPending: false,
219032
- brainUpdateActivity: EMPTY_BRAIN_UPDATE_ACTIVITY_STATE,
219033
- snapshotSeen: null
219034
- };
219035
- runtime.sessions.set(sessionID, created);
219036
- return created;
219037
- }
219038
- var MAX_WINDOW_LOOKUP_ATTEMPTS = 3;
219039
- async function resolveWindowTokens(context, session, model) {
219040
- if (session.windowModel !== model.id) {
219041
- session.windowModel = model.id;
219042
- session.windowTokens = null;
219043
- session.windowFailures = 0;
219044
- }
219045
- if (session.windowTokens !== null || session.windowFailures >= MAX_WINDOW_LOOKUP_ATTEMPTS) {
219046
- return session.windowTokens;
219047
- }
219048
- try {
219049
- const listed = await context.model.list();
219050
- const fallback = `${model.providerID}/${model.id.split("/")[1] ?? model.id}`;
219051
- const info = listed.data.find((entry) => entry.id === model.id || entry.id === fallback);
219052
- const limit = info?.limit.context ?? 0;
219053
- if (limit > 0) {
219054
- session.windowTokens = limit;
219055
- session.windowFailures = 0;
219056
- } else {
219057
- session.windowFailures += 1;
219058
- }
219059
- } catch {
219060
- session.windowFailures += 1;
219061
- }
219062
- return session.windowTokens;
219063
- }
219064
- async function ensureSessionHydrated(stateDirectory, runtime, sessionID) {
219065
- if (runtime.hydrated.has(sessionID)) {
219066
- return;
219067
- }
219068
- const receipts = await readReceipts(join7(stateDirectory, "context-log"), sessionID);
219069
- if (!receipts.ok) {
219070
- return;
219071
- }
219072
- const session = sessionRuntime(runtime, sessionID);
219073
- const fired = {};
219074
- for (const receipt of receipts.value) {
219075
- if (receipt.kind === "refusal") {
219076
- runtime.refusals.add(sessionID);
219077
- } else if (receipt.kind === "trim") {
219078
- fired[receipt.trigger] = receipt.tokens;
219079
- } else if (receipt.kind === "compact" && receipt.trigger !== "manual") {
219080
- fired[receipt.trigger] = receipt.summarized;
219081
- }
219082
- }
219083
- session.triggerState = { fired: { ...fired, ...session.triggerState.fired } };
219084
- runtime.hydrated.add(sessionID);
219085
- }
219086
- async function ensureRefusalReceipt(stateDirectory, runtime, sessionID, deps) {
219087
- if (runtime.refusals.has(sessionID)) {
219088
- return;
219089
- }
219090
- runtime.refusals.add(sessionID);
219091
- const written = await appendReceipt(join7(stateDirectory, "context-log"), sessionID, {
219092
- kind: "refusal",
219093
- at: new Date().toISOString(),
219094
- reason: "brain-unavailable"
219095
- });
219096
- if (!written.ok) {
219097
- reportReceiptFailureOnce(runtime, deps, sessionID, "refusal");
219098
- }
219099
- }
219100
- function reportReceiptFailureOnce(runtime, deps, sessionID, kind) {
219101
- if (isContextStale(deps)) {
219102
- return;
219103
- }
219104
- const key = sessionID === null ? `null:${kind}` : sessionID;
219105
- if (runtime.reportedReceiptFailures.has(key)) {
219106
- return;
219107
- }
219108
- runtime.reportedReceiptFailures.add(key);
219109
- deps.reportReceiptFailure(sessionID, kind);
219110
- }
219111
-
219112
219340
  // src/compaction.ts
219113
219341
  function registerCompactionHook(context, deps, runtime) {
219114
219342
  context.session.hook("compaction", async (event) => {
@@ -219157,14 +219385,14 @@ function registerCompactionHook(context, deps, runtime) {
219157
219385
  text: buildCompactionPrompt({ brainPaths: deps.brainPaths, recoveryRule: null })
219158
219386
  });
219159
219387
  }
219160
- const written = await appendReceipt(join8(deps.stateDirectory, "context-log"), sessionID, receipt);
219388
+ const written = await appendReceipt(join10(deps.stateDirectory, "context-log"), sessionID, receipt);
219161
219389
  if (!written.ok) {
219162
219390
  reportReceiptFailureOnce(runtime, deps, sessionID, "compact");
219163
219391
  }
219164
219392
  if (isContextStale(deps)) {
219165
219393
  return;
219166
219394
  }
219167
- const remembered = await rememberSnapshot(join8(deps.stateDirectory, "context-snapshot"), sessionID, event.messages, new Date().toISOString(), session.snapshotSeen);
219395
+ const remembered = await rememberSnapshot(join10(deps.stateDirectory, "context-snapshot"), sessionID, event.messages, new Date().toISOString(), session.snapshotSeen);
219168
219396
  if (isContextStale(deps)) {
219169
219397
  return;
219170
219398
  }
@@ -219507,61 +219735,7 @@ function countWords(text, maxWords) {
219507
219735
  }
219508
219736
 
219509
219737
  // src/context.ts
219510
- import { join as join9 } from "node:path";
219511
-
219512
- // src/utils.ts
219513
- function success2(value) {
219514
- return { ok: true, value };
219515
- }
219516
- function failure2(error) {
219517
- return { ok: false, error };
219518
- }
219519
-
219520
- // src/options.ts
219521
- function readOptionBlock(options, block) {
219522
- if (typeof options !== "object" || options === null) {
219523
- return success2(null);
219524
- }
219525
- const primary = "vcc-brain" in options ? options["vcc-brain"] : undefined;
219526
- const legacy = "operator" in options ? options.operator : undefined;
219527
- const source = primary ?? legacy ?? null;
219528
- if (source === null || source === undefined) {
219529
- return success2(null);
219530
- }
219531
- if (typeof source !== "object" || Array.isArray(source)) {
219532
- return failure2({
219533
- message: 'The "vcc-brain" (legacy "operator") plugin option must be an object.'
219534
- });
219535
- }
219536
- const section = block in source ? source[block] : null;
219537
- if (section === null || section === undefined) {
219538
- return success2(null);
219539
- }
219540
- if (typeof section !== "object" || Array.isArray(section)) {
219541
- return failure2({ message: `The "vcc-brain.${block}" option must be an object.` });
219542
- }
219543
- return success2(section);
219544
- }
219545
- function readOptionNumber(path, block, key, defaultValue) {
219546
- const value = block[key];
219547
- if (value === undefined) {
219548
- return success2(defaultValue);
219549
- }
219550
- if (typeof value !== "number" || !Number.isFinite(value)) {
219551
- return failure2({ message: `The "${path}.${key}" option must be a number.` });
219552
- }
219553
- return success2(value);
219554
- }
219555
- function readOptionBoolean(path, block, key, defaultValue) {
219556
- const value = block[key];
219557
- if (value === undefined) {
219558
- return success2(defaultValue);
219559
- }
219560
- if (typeof value !== "boolean") {
219561
- return failure2({ message: `The "${path}.${key}" option must be a boolean.` });
219562
- }
219563
- return success2(value);
219564
- }
219738
+ import { join as join11 } from "node:path";
219565
219739
 
219566
219740
  // src/context-config.ts
219567
219741
  var DEFAULT_CONTEXT_MANAGEMENT_CONFIG = {
@@ -219637,7 +219811,7 @@ function registerContextHook(context, deps, runtime) {
219637
219811
  if (isContextStale(deps)) {
219638
219812
  return;
219639
219813
  }
219640
- const remembered = await rememberSnapshot(join9(deps.stateDirectory, "context-snapshot"), sessionID, event.messages, new Date().toISOString(), session.snapshotSeen);
219814
+ const remembered = await rememberSnapshot(join11(deps.stateDirectory, "context-snapshot"), sessionID, event.messages, new Date().toISOString(), session.snapshotSeen);
219641
219815
  if (isContextStale(deps)) {
219642
219816
  return;
219643
219817
  }
@@ -219673,7 +219847,7 @@ function registerContextHook(context, deps, runtime) {
219673
219847
  removed: trimResult.removedTokens,
219674
219848
  omissions: trimResult.omissionCount
219675
219849
  };
219676
- const written = await appendReceipt(join9(deps.stateDirectory, "context-log"), sessionID, receipt);
219850
+ const written = await appendReceipt(join11(deps.stateDirectory, "context-log"), sessionID, receipt);
219677
219851
  if (!written.ok) {
219678
219852
  reportReceiptFailureOnce(runtime, deps, sessionID, "trim");
219679
219853
  }
@@ -219689,7 +219863,7 @@ function registerContextHook(context, deps, runtime) {
219689
219863
  }
219690
219864
  async function trimRequest(sessionID, messages, deps) {
219691
219865
  const batch = planTrimBatched(messages, { keepRecentTurns: deps.config.keepRecentTurns });
219692
- const omittedRoot = join9(deps.stateDirectory, "omitted");
219866
+ const omittedRoot = join11(deps.stateDirectory, "omitted");
219693
219867
  const stored = await storeOmissions(omittedRoot, sessionID, batch.requests);
219694
219868
  const ids = stored.ok ? stored.value.ids : new Map;
219695
219869
  const fresh = stored.ok ? stored.value.stored : new Set;
@@ -219885,6 +220059,47 @@ function readCount(record, key) {
219885
220059
  return typeof value === "number" && Number.isFinite(value) ? value : null;
219886
220060
  }
219887
220061
 
220062
+ // src/id.ts
220063
+ var pluginId = "jwitmann.vcc-brain";
220064
+
220065
+ // src/notifications.ts
220066
+ import { Rpc } from "@opencode/plugin/rpc";
220067
+ var VccBrainNotifications = Rpc.define({
220068
+ id: pluginId,
220069
+ methods: {
220070
+ status: {
220071
+ input: {
220072
+ type: "object",
220073
+ properties: { refresh: { type: "boolean" } },
220074
+ required: ["refresh"]
220075
+ },
220076
+ output: {
220077
+ type: "object",
220078
+ properties: {
220079
+ detail: { type: "string" },
220080
+ user: { enum: ["loaded", "uninitialized", "error"] },
220081
+ private: { enum: ["loaded", "uninitialized", "error"] },
220082
+ shared: { enum: ["loaded", "uninitialized", "error"] }
220083
+ },
220084
+ required: ["detail", "user", "private", "shared"]
220085
+ }
220086
+ }
220087
+ },
220088
+ events: {
220089
+ toast: {
220090
+ schema: {
220091
+ type: "object",
220092
+ properties: {
220093
+ title: { type: "string" },
220094
+ message: { type: "string" },
220095
+ variant: { enum: ["info", "success", "warning", "error"] }
220096
+ },
220097
+ required: ["title", "message", "variant"]
220098
+ }
220099
+ }
220100
+ }
220101
+ });
220102
+
219888
220103
  // ../core/src/preamble-rollout.ts
219889
220104
  import { execFileSync } from "node:child_process";
219890
220105
  import { createHash } from "node:crypto";
@@ -220651,42 +220866,6 @@ async function readPreamble(projectDirectory, homeDirectory) {
220651
220866
  // src/project-config.ts
220652
220867
  import { readFile as readFile5 } from "node:fs/promises";
220653
220868
 
220654
- // src/brain-updates-config.ts
220655
- var DEFAULT_BRAIN_UPDATES_CONFIG = {
220656
- enabled: false,
220657
- toolCallThreshold: 25
220658
- };
220659
- var BRAIN_UPDATES_PATH = "operator.brainUpdates";
220660
- function parseBrainUpdatesConfig(options, base = DEFAULT_BRAIN_UPDATES_CONFIG) {
220661
- const block = readOptionBlock(options, "brainUpdates");
220662
- if (!block.ok) {
220663
- return block;
220664
- }
220665
- return parseBrainUpdatesBlock(block.value, base);
220666
- }
220667
- function parseBrainUpdatesBlock(block, base = DEFAULT_BRAIN_UPDATES_CONFIG) {
220668
- if (block === null) {
220669
- return success2(base);
220670
- }
220671
- const enabled = readOptionBoolean(BRAIN_UPDATES_PATH, block, "enabled", base.enabled);
220672
- if (!enabled.ok) {
220673
- return enabled;
220674
- }
220675
- const toolCallThreshold = readOptionNumber(BRAIN_UPDATES_PATH, block, "toolCallThreshold", base.toolCallThreshold);
220676
- if (!toolCallThreshold.ok) {
220677
- return toolCallThreshold;
220678
- }
220679
- if (!Number.isInteger(toolCallThreshold.value) || toolCallThreshold.value <= 0) {
220680
- return {
220681
- ok: false,
220682
- error: {
220683
- message: `The "${BRAIN_UPDATES_PATH}.toolCallThreshold" option must be a positive integer.`
220684
- }
220685
- };
220686
- }
220687
- return success2({ enabled: enabled.value, toolCallThreshold: toolCallThreshold.value });
220688
- }
220689
-
220690
220869
  // src/refresh-config.ts
220691
220870
  var DEFAULT_PREAMBLE_REFRESH_CONFIG = {
220692
220871
  enabled: false
@@ -220769,108 +220948,8 @@ function readProjectBlock(input, key) {
220769
220948
  return success2(section);
220770
220949
  }
220771
220950
 
220772
- // ../core/src/preamble-refresh.ts
220773
- import { readdir as readdir2, stat as stat4 } from "node:fs/promises";
220774
- import { join as join10 } from "node:path";
220775
- var REFRESH_FLOOR_TOKENS = 4000;
220776
- async function fingerprintPreamble(projectDirectory, homeDirectory) {
220777
- const entries = [];
220778
- const roots = await resolveBrainRoots(projectDirectory, homeDirectory);
220779
- const sharedRoot = roots.sharedRoot;
220780
- const privateRoot = roots.privateRoot;
220781
- const userRoot = roots.userRoot;
220782
- for (const root of [sharedRoot, privateRoot]) {
220783
- for (const file of [await resolveInstructionsPath(root), join10(root, "catalog.md")]) {
220784
- const entry = await fingerprintFile(file);
220785
- if (!entry.ok) {
220786
- return entry;
220787
- }
220788
- entries.push(entry.value);
220789
- }
220790
- }
220791
- for (const file of [
220792
- await resolveInstructionsPath(userRoot),
220793
- join10(userRoot, "catalog.md"),
220794
- join10(userRoot, "observations.md")
220795
- ]) {
220796
- const entry = await fingerprintFile(file);
220797
- if (!entry.ok) {
220798
- return entry;
220799
- }
220800
- entries.push(entry.value);
220801
- }
220802
- for (const root of [sharedRoot, privateRoot]) {
220803
- const indexEntries = await fingerprintIndex(join10(root, "index"));
220804
- if (!indexEntries.ok) {
220805
- return indexEntries;
220806
- }
220807
- entries.push(...indexEntries.value);
220808
- }
220809
- entries.sort();
220810
- return success(entries.join(`
220811
- `));
220812
- }
220813
- function isCacheCold(tokens) {
220814
- return tokens === null || tokens.cacheRead === 0;
220815
- }
220816
- async function fingerprintFile(path) {
220817
- try {
220818
- const info = await stat4(path);
220819
- return success(`${path}:${info.mtimeMs}`);
220820
- } catch (cause) {
220821
- if (hasNodeErrorCode(cause, "ENOENT")) {
220822
- return success(`${path}:missing`);
220823
- }
220824
- return failure({ path, cause });
220825
- }
220826
- }
220827
- async function fingerprintIndex(indexRoot) {
220828
- try {
220829
- await stat4(indexRoot);
220830
- } catch (cause) {
220831
- if (hasNodeErrorCode(cause, "ENOENT")) {
220832
- return success([`${indexRoot}:missing`]);
220833
- }
220834
- return failure({ path: indexRoot, cause });
220835
- }
220836
- const paths = [];
220837
- const collected = await collectIndexFiles(indexRoot, paths);
220838
- if (!collected.ok) {
220839
- return collected;
220840
- }
220841
- const entries = [];
220842
- for (const path of paths) {
220843
- const entry = await fingerprintFile(path);
220844
- if (!entry.ok) {
220845
- return entry;
220846
- }
220847
- entries.push(entry.value);
220848
- }
220849
- return success(entries);
220850
- }
220851
- async function collectIndexFiles(directory, paths) {
220852
- let entries;
220853
- try {
220854
- entries = await readdir2(directory, { withFileTypes: true });
220855
- } catch (cause) {
220856
- return failure({ path: directory, cause });
220857
- }
220858
- for (const entry of entries) {
220859
- const path = join10(directory, entry.name);
220860
- if (entry.isDirectory()) {
220861
- const nested = await collectIndexFiles(path, paths);
220862
- if (!nested.ok) {
220863
- return nested;
220864
- }
220865
- } else if (entry.isFile() && entry.name.endsWith(".md")) {
220866
- paths.push(path);
220867
- }
220868
- }
220869
- return success(undefined);
220870
- }
220871
-
220872
220951
  // src/refresh.ts
220873
- import { join as join11 } from "node:path";
220952
+ import { join as join12 } from "node:path";
220874
220953
  async function maybeRefreshPreamble(deps, runtime, sessionID, projectDirectory, homeDirectory, cache, messages) {
220875
220954
  const idle = { refreshed: false, failed: false };
220876
220955
  if (!deps.config.enabled || isContextStale(deps) || !deps.isBrainAvailable(sessionID)) {
@@ -220912,7 +220991,7 @@ async function maybeRefreshPreamble(deps, runtime, sessionID, projectDirectory,
220912
220991
  reason: postCompaction ? "post-compaction" : "brain-changed",
220913
220992
  at: new Date().toISOString()
220914
220993
  };
220915
- await appendReceipt(join11(deps.stateDirectory, "context-log"), sessionID, receipt);
220994
+ await appendReceipt(join12(deps.stateDirectory, "context-log"), sessionID, receipt);
220916
220995
  return { refreshed: true, content: rendered.value.content };
220917
220996
  }
220918
220997
  async function refreshPreambleContent(deps, runtime, sessionID, projectDirectory, homeDirectory, cache, messages, cachedContent) {
@@ -220929,46 +221008,8 @@ async function refreshPreambleContent(deps, runtime, sessionID, projectDirectory
220929
221008
  return outcome.content;
220930
221009
  }
220931
221010
 
220932
- // src/brain-updates.ts
220933
- import { join as join12 } from "node:path";
220934
- async function maybeAppendBrainUpdateReminder(deps, runtime, sessionID, messages, content) {
220935
- if (!deps.config.enabled || isContextStale(deps) || !deps.isBrainAvailable(sessionID)) {
220936
- return content;
220937
- }
220938
- const session = sessionRuntime(runtime, sessionID);
220939
- const fingerprinted = await fingerprintPreamble(deps.projectDirectory, deps.homeDirectory);
220940
- if (!fingerprinted.ok) {
220941
- return content;
220942
- }
220943
- const decision = evaluateBrainUpdateActivity(session.brainUpdateActivity, fingerprinted.value, countCompletedToolCalls(messages), deps.config.toolCallThreshold);
220944
- if (isContextStale(deps)) {
220945
- return content;
220946
- }
220947
- session.brainUpdateActivity = decision.state;
220948
- if (!decision.crossed) {
220949
- return content;
220950
- }
220951
- const receipt = {
220952
- kind: "brain-reminder",
220953
- at: new Date().toISOString(),
220954
- threshold: deps.config.toolCallThreshold,
220955
- completedSinceBaseline: decision.completedSinceBaseline
220956
- };
220957
- await appendReceipt(join12(deps.stateDirectory, "context-log"), sessionID, receipt);
220958
- return `${content}
220959
-
220960
- ${brainUpdateReminder(deps.config.toolCallThreshold)}`;
220961
- }
220962
- function brainUpdateReminder(toolCallThreshold) {
220963
- return `<vcc-brain-brain-update-reminder>
220964
- You have completed ${toolCallThreshold} tool calls without a Brain change.
220965
- Before continuing, record any durable decisions, contracts, or lessons in the
220966
- appropriate Brain partition. Do not write transient task progress or restate
220967
- implementation. If nothing durable has emerged, make no Brain edits.
220968
- </vcc-brain-brain-update-reminder>`;
220969
- }
220970
-
220971
221011
  // src/tool.ts
221012
+ import { execFile } from "node:child_process";
220972
221013
  import { join as join13 } from "node:path";
220973
221014
  var OMISSION_ID_PATTERN = /^omitted-\d+$/;
220974
221015
  function isOmissionID(contentID) {
@@ -221161,44 +221202,126 @@ async function registerSearchTool(context, deps) {
221161
221202
  });
221162
221203
  });
221163
221204
  }
221164
-
221165
- // src/notifications.ts
221166
- import { Rpc } from "@opencode/plugin/rpc";
221167
- var VccBrainNotifications = Rpc.define({
221168
- id: pluginId,
221169
- methods: {
221170
- status: {
221205
+ var HELPER_BIN = "vcc-brain-helper";
221206
+ var HELPER_TIMEOUT_MS = 60000;
221207
+ function runHelperBinary(argument_) {
221208
+ return new Promise((resolve) => {
221209
+ execFile(HELPER_BIN, [...argument_], { timeout: HELPER_TIMEOUT_MS }, (error, stdout, stderr) => {
221210
+ if (error === null) {
221211
+ resolve({ exitCode: 0, output: stdout });
221212
+ return;
221213
+ }
221214
+ const exitCode = typeof error.code === "number" ? error.code : 2;
221215
+ if (exitCode !== 0 && stderr !== "") {
221216
+ resolve({ exitCode, output: stderr });
221217
+ return;
221218
+ }
221219
+ resolve({ exitCode, output: stdout !== "" ? stdout : error.message });
221220
+ });
221221
+ });
221222
+ }
221223
+ async function registerSearchSessionsTool(context, deps) {
221224
+ await context.tool.transform((editor) => {
221225
+ editor.add({
221226
+ name: "vcc-brain-search-sessions",
221227
+ options: { codemode: false },
221228
+ description: "Search OTHER sessions (cross-session recall) for keywords, scoped to this project plus mutual peers. " + "Returns matching turns with stored session ids (like opencode:ses_... or dsh:<uuid>); " + "call vcc-brain-recall-session to restore a session's full turns. " + "Use vcc-brain-search (not this tool) for the current conversation. " + "OpenCode results require one `vcc-brain-helper recall-cross index` run on this machine first.",
221171
221229
  input: {
221172
- type: "object",
221173
- properties: { refresh: { type: "boolean" } },
221174
- required: ["refresh"]
221175
- },
221176
- output: {
221177
221230
  type: "object",
221178
221231
  properties: {
221179
- detail: { type: "string" },
221180
- user: { enum: ["loaded", "uninitialized", "error"] },
221181
- private: { enum: ["loaded", "uninitialized", "error"] },
221182
- shared: { enum: ["loaded", "uninitialized", "error"] }
221232
+ keywords: {
221233
+ type: "string",
221234
+ description: "Space-separated keywords to search past sessions for."
221235
+ },
221236
+ harness: {
221237
+ type: "string",
221238
+ description: "Limit results to one harness.",
221239
+ enum: ["dsh", "opencode", "all"]
221240
+ }
221183
221241
  },
221184
- required: ["detail", "user", "private", "shared"]
221242
+ required: ["keywords"]
221243
+ },
221244
+ execute: async (input) => {
221245
+ if (!isRecord(input) || typeof input.keywords !== "string" || input.keywords.trim() === "") {
221246
+ return { content: "Missing required input: keywords." };
221247
+ }
221248
+ const words = input.keywords.trim().split(/\s+/);
221249
+ if (words.some((word) => word.startsWith("-"))) {
221250
+ return { content: "Invalid input: keywords must not start with '-'." };
221251
+ }
221252
+ const invocation = [
221253
+ "recall-cross",
221254
+ "query",
221255
+ "--project",
221256
+ deps.projectDirectory,
221257
+ "--project-dir",
221258
+ deps.projectDirectory
221259
+ ];
221260
+ if (input.harness !== undefined && input.harness !== "") {
221261
+ if (input.harness !== "dsh" && input.harness !== "opencode" && input.harness !== "all") {
221262
+ return { content: "Invalid input: harness must be one of dsh, opencode, all." };
221263
+ }
221264
+ invocation.push("--harness", input.harness);
221265
+ }
221266
+ invocation.push(...words);
221267
+ try {
221268
+ const result = await runHelperBinary(invocation);
221269
+ return { content: result.output };
221270
+ } catch {
221271
+ return { content: "Could not run the recall index. Is vcc-brain-helper installed?" };
221272
+ }
221185
221273
  }
221186
- }
221187
- },
221188
- events: {
221189
- toast: {
221190
- schema: {
221274
+ });
221275
+ });
221276
+ }
221277
+ async function registerRecallSessionTool(context) {
221278
+ await context.tool.transform((editor) => {
221279
+ editor.add({
221280
+ name: "vcc-brain-recall-session",
221281
+ options: { codemode: false },
221282
+ description: "Restore the full turns of one indexed past session by its stored session id " + "(like opencode:ses_... or dsh:<uuid>), optionally a single turn by sequence number. " + "Use vcc-brain-recall (not this tool) for the current conversation.",
221283
+ input: {
221191
221284
  type: "object",
221192
221285
  properties: {
221193
- title: { type: "string" },
221194
- message: { type: "string" },
221195
- variant: { enum: ["info", "success", "warning", "error"] }
221286
+ sessionId: {
221287
+ type: "string",
221288
+ description: "Stored session id, like opencode:ses_... or dsh:<uuid>."
221289
+ },
221290
+ seq: {
221291
+ type: "string",
221292
+ description: "Optional single turn sequence number to restore."
221293
+ }
221196
221294
  },
221197
- required: ["title", "message", "variant"]
221295
+ required: ["sessionId"]
221296
+ },
221297
+ execute: async (input) => {
221298
+ if (!isRecord(input) || typeof input.sessionId !== "string" || input.sessionId.trim() === "") {
221299
+ return { content: "Missing required input: sessionId." };
221300
+ }
221301
+ if (input.sessionId.trim().startsWith("-")) {
221302
+ return { content: "Invalid input: sessionId must not start with '-'." };
221303
+ }
221304
+ let sequence = null;
221305
+ if (input.seq !== undefined && input.seq !== null && String(input.seq) !== "") {
221306
+ if (!/^\d+$/.test(String(input.seq).trim())) {
221307
+ return { content: "Invalid input: seq must be a non-negative integer." };
221308
+ }
221309
+ sequence = String(input.seq).trim();
221310
+ }
221311
+ const invocation = ["recall-cross", "recall", input.sessionId.trim()];
221312
+ if (sequence !== null) {
221313
+ invocation.push("--seq", sequence);
221314
+ }
221315
+ try {
221316
+ const result = await runHelperBinary(invocation);
221317
+ return { content: result.output };
221318
+ } catch {
221319
+ return { content: "Could not run the recall index. Is vcc-brain-helper installed?" };
221320
+ }
221198
221321
  }
221199
- }
221200
- }
221201
- });
221322
+ });
221323
+ });
221324
+ }
221202
221325
 
221203
221326
  // src/index.ts
221204
221327
  var setupGeneration = 0;
@@ -221385,6 +221508,10 @@ var VccBrainPlugin = Plugin.define({
221385
221508
  await registerPruneTool(context, { stateDirectory });
221386
221509
  await registerRecallTool(context, { stateDirectory });
221387
221510
  await registerSearchTool(context, { stateDirectory });
221511
+ await registerSearchSessionsTool(context, {
221512
+ projectDirectory: context.location.directory
221513
+ });
221514
+ await registerRecallSessionTool(context);
221388
221515
  } else {
221389
221516
  registerStepTracking(context, { isBrainAvailable, isCurrent, reportReceiptFailure }, runtime, {
221390
221517
  signal: controller.signal
@@ -221422,4 +221549,4 @@ export {
221422
221549
  src_default as default
221423
221550
  };
221424
221551
 
221425
- //# debugId=9754EF4475AA485C64756E2164756E21
221552
+ //# debugId=065AF789C3C9FBE764756E2164756E21