@jwitmann/vcc-brain-opencode-v2 2.8.1 → 2.9.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.
package/dist/server.js CHANGED
@@ -6995,6 +6995,9 @@ function getErrorMessage(error) {
6995
6995
  function isRecord(value) {
6996
6996
  return typeof value === "object" && value !== null && !Array.isArray(value);
6997
6997
  }
6998
+ function isStringArray(value) {
6999
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
7000
+ }
6998
7001
  function readString(value, key) {
6999
7002
  const field = value[key];
7000
7003
  return typeof field === "string" ? field : null;
@@ -7406,7 +7409,7 @@ import { Plugin } from "@opencode/plugin";
7406
7409
  // package.json
7407
7410
  var package_default = {
7408
7411
  name: "@jwitmann/vcc-brain-opencode-v2",
7409
- version: "2.8.1",
7412
+ version: "2.9.0",
7410
7413
  description: "VCC Brain adapter for OpenCode V2.",
7411
7414
  license: "BSD-3-Clause",
7412
7415
  author: "jwitmann",
@@ -217179,7 +217182,7 @@ async function collectIndexFiles(directory, paths) {
217179
217182
  }
217180
217183
 
217181
217184
  // src/brain-updates.ts
217182
- import { join as join8 } from "node:path";
217185
+ import { join as join9 } from "node:path";
217183
217186
 
217184
217187
  // ../core/src/context/triggers.ts
217185
217188
  var EMPTY_TRIGGER_STATE = { fired: {} };
@@ -217232,8 +217235,88 @@ function recordFired(state, kind, estimatedTokens) {
217232
217235
  return { fired: { ...state.fired, [kind]: estimatedTokens } };
217233
217236
  }
217234
217237
 
217235
- // src/runtime.ts
217238
+ // ../core/src/context/session-slot.ts
217239
+ import { mkdir as mkdir3, readFile as readFile4, rename, rm, writeFile as writeFile2 } from "node:fs/promises";
217236
217240
  import { join as join7 } from "node:path";
217241
+ function slotPath(stateDirectory, slot, sessionID) {
217242
+ return join7(stateDirectory, slot, `${sessionID}.json`);
217243
+ }
217244
+ async function slotSet(stateDirectory, slot, sessionID, value) {
217245
+ if (!isSafePathSegment(sessionID)) {
217246
+ return failure({ kind: "unsafe-session-id", sessionID });
217247
+ }
217248
+ try {
217249
+ await mkdir3(join7(stateDirectory, slot), { recursive: true });
217250
+ const target = slotPath(stateDirectory, slot, sessionID);
217251
+ const staging = `${target}.${process.pid}.tmp`;
217252
+ await writeFile2(staging, JSON.stringify(value), "utf8");
217253
+ await rename(staging, target);
217254
+ return success(null);
217255
+ } catch (error) {
217256
+ return failure({ kind: "write-failed", reason: getErrorMessage(error) });
217257
+ }
217258
+ }
217259
+ async function slotGet(stateDirectory, slot, sessionID, guard) {
217260
+ if (!isSafePathSegment(sessionID)) {
217261
+ return failure({ kind: "unsafe-session-id", sessionID });
217262
+ }
217263
+ let raw;
217264
+ try {
217265
+ raw = await readFile4(slotPath(stateDirectory, slot, sessionID), "utf8");
217266
+ } catch {
217267
+ return success(null);
217268
+ }
217269
+ let parsed;
217270
+ try {
217271
+ parsed = JSON.parse(raw);
217272
+ } catch {
217273
+ return success(null);
217274
+ }
217275
+ if (!guard(parsed)) {
217276
+ return success(null);
217277
+ }
217278
+ return success(parsed);
217279
+ }
217280
+ async function slotClear(stateDirectory, slot, sessionID) {
217281
+ if (!isSafePathSegment(sessionID)) {
217282
+ return failure({ kind: "unsafe-session-id", sessionID });
217283
+ }
217284
+ try {
217285
+ await rm(slotPath(stateDirectory, slot, sessionID), { force: true });
217286
+ return success(null);
217287
+ } catch (error) {
217288
+ return failure({ kind: "clear-failed", reason: getErrorMessage(error) });
217289
+ }
217290
+ }
217291
+
217292
+ // ../core/src/context/failure-backoff.ts
217293
+ var FAILURE_BACKOFF_VERSION = 1;
217294
+ var FAILURE_BACKOFF_SLOT = "context-failure-backoff";
217295
+ function isFailureBackoffRecord(value) {
217296
+ if (!isRecord(value)) {
217297
+ return false;
217298
+ }
217299
+ return value.version === FAILURE_BACKOFF_VERSION && typeof value.session_id === "string" && typeof value.at === "number" && typeof value.estimate === "number";
217300
+ }
217301
+ async function failureBackoffSet(stateDirectory, record) {
217302
+ return slotSet(stateDirectory, FAILURE_BACKOFF_SLOT, record.session_id, record);
217303
+ }
217304
+ async function failureBackoffGet(stateDirectory, sessionID) {
217305
+ const stored = await slotGet(stateDirectory, FAILURE_BACKOFF_SLOT, sessionID, isFailureBackoffRecord);
217306
+ if (!stored.ok) {
217307
+ return stored;
217308
+ }
217309
+ if (stored.value !== null && stored.value.session_id !== sessionID) {
217310
+ return success(null);
217311
+ }
217312
+ return stored;
217313
+ }
217314
+ async function failureBackoffClear(stateDirectory, sessionID) {
217315
+ return slotClear(stateDirectory, FAILURE_BACKOFF_SLOT, sessionID);
217316
+ }
217317
+
217318
+ // src/runtime.ts
217319
+ import { join as join8 } from "node:path";
217237
217320
  var PENDING_CAUSE_TTL_MS = 10 * 60 * 1000;
217238
217321
  var FAILED_COMPACTION_COOLDOWN_MS = 10 * 60 * 1000;
217239
217322
  function shouldSuppressCompactionRequest(session, estimatedTokens, windowTokens, now) {
@@ -217255,7 +217338,8 @@ function createContextRuntime() {
217255
217338
  refusals: new Set,
217256
217339
  reportedReceiptFailures: new Set,
217257
217340
  hydrated: new Set,
217258
- pendingCauses: new Map
217341
+ pendingCauses: new Map,
217342
+ pendingAnchors: new Map
217259
217343
  };
217260
217344
  }
217261
217345
  var SHARED_RUNTIME_KEY = "__vccBrainContextRuntime";
@@ -217335,7 +217419,7 @@ async function ensureSessionHydrated(stateDirectory, runtime, sessionID) {
217335
217419
  if (runtime.hydrated.has(sessionID)) {
217336
217420
  return;
217337
217421
  }
217338
- const receipts = await readReceipts(join7(stateDirectory, "context-log"), sessionID);
217422
+ const receipts = await readReceipts(join8(stateDirectory, "context-log"), sessionID);
217339
217423
  if (!receipts.ok) {
217340
217424
  return;
217341
217425
  }
@@ -217351,6 +217435,12 @@ async function ensureSessionHydrated(stateDirectory, runtime, sessionID) {
217351
217435
  }
217352
217436
  }
217353
217437
  session.triggerState = { fired: { ...fired, ...session.triggerState.fired } };
217438
+ if (session.lastCompactionFailure === null) {
217439
+ const backoff = await failureBackoffGet(stateDirectory, sessionID);
217440
+ if (backoff.ok && backoff.value !== null) {
217441
+ session.lastCompactionFailure = { at: backoff.value.at, estimate: backoff.value.estimate };
217442
+ }
217443
+ }
217354
217444
  runtime.hydrated.add(sessionID);
217355
217445
  }
217356
217446
  async function ensureRefusalReceipt(stateDirectory, runtime, sessionID, deps) {
@@ -217358,7 +217448,7 @@ async function ensureRefusalReceipt(stateDirectory, runtime, sessionID, deps) {
217358
217448
  return;
217359
217449
  }
217360
217450
  runtime.refusals.add(sessionID);
217361
- const written = await appendReceipt(join7(stateDirectory, "context-log"), sessionID, {
217451
+ const written = await appendReceipt(join8(stateDirectory, "context-log"), sessionID, {
217362
217452
  kind: "refusal",
217363
217453
  at: new Date().toISOString(),
217364
217454
  reason: "brain-unavailable"
@@ -217403,7 +217493,7 @@ async function maybeAppendBrainUpdateReminder(deps, runtime, sessionID, messages
217403
217493
  threshold: deps.config.toolCallThreshold,
217404
217494
  completedSinceBaseline: decision.completedSinceBaseline
217405
217495
  };
217406
- await appendReceipt(join8(deps.stateDirectory, "context-log"), sessionID, receipt);
217496
+ await appendReceipt(join9(deps.stateDirectory, "context-log"), sessionID, receipt);
217407
217497
  return `${content}
217408
217498
 
217409
217499
  ${brainUpdateReminder(deps.config.toolCallThreshold)}`;
@@ -217583,6 +217673,11 @@ var DEFAULT_RECOVERY_RULE = `Tool input/output omission notices (content IDs) ar
217583
217673
  function buildCompactionPrompt(input) {
217584
217674
  const paths = input.brainPaths.map((path) => `- ${path}`).join(`
217585
217675
  `);
217676
+ const anchorRule = input.anchorView === null ? "" : `- The session carries a verbatim task-anchor block below. Reproduce
217677
+ it byte-identical at the top of the summary, before any other text.
217678
+ It is machine-written orientation state, not prose to compress:
217679
+ ${input.anchorView}
217680
+ `;
217586
217681
  return `<compaction-instructions>
217587
217682
  You are compacting the conversation history for a VCC Brain session.
217588
217683
  Produce a summary that lets the next session continue the work without the
@@ -217597,7 +217692,7 @@ The summary must preserve, in order of importance:
217597
217692
 
217598
217693
  Rules:
217599
217694
  - ${input.recoveryRule ?? DEFAULT_RECOVERY_RULE}
217600
- - Durable knowledge lives in the Brain partitions. Reference these paths
217695
+ ${anchorRule}- Durable knowledge lives in the Brain partitions. Reference these paths
217601
217696
  instead of inlining their content:
217602
217697
  ${paths}
217603
217698
  - Before summarizing, ensure any spec or decision that exists only in this
@@ -217607,7 +217702,7 @@ ${paths}
217607
217702
  }
217608
217703
 
217609
217704
  // src/compaction.ts
217610
- import { join as join10 } from "node:path";
217705
+ import { join as join11 } from "node:path";
217611
217706
 
217612
217707
  // ../core/src/context/compiler.ts
217613
217708
  var TOKEN_RE = /[a-zA-Z]+|[0-9]+|[^\sa-zA-Z0-9]|\s+/g;
@@ -218606,8 +218701,8 @@ function compileCompaction(messages, config, keepMessages, requestTokens) {
218606
218701
  }
218607
218702
 
218608
218703
  // src/compaction-snapshot.ts
218609
- import { mkdir as mkdir3, readFile as readFile4, rename, writeFile as writeFile2 } from "node:fs/promises";
218610
- import { join as join9 } from "node:path";
218704
+ import { mkdir as mkdir4, readFile as readFile5, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
218705
+ import { join as join10 } from "node:path";
218611
218706
 
218612
218707
  // ../core/src/context/session-compat.ts
218613
218708
  var warnSink = null;
@@ -219142,7 +219237,7 @@ async function rememberSnapshot(root, sessionID, messages, at, prev) {
219142
219237
  }
219143
219238
  }
219144
219239
  function snapshotPath(root, sessionID) {
219145
- return join9(root, `${sessionID}.json`);
219240
+ return join10(root, `${sessionID}.json`);
219146
219241
  }
219147
219242
  async function writeCompactionSnapshot(root, sessionID, messages, at) {
219148
219243
  const path = snapshotPath(root, sessionID);
@@ -219151,11 +219246,11 @@ async function writeCompactionSnapshot(root, sessionID, messages, at) {
219151
219246
  }
219152
219247
  const envelope = { ...buildSnapshot(messages), writtenAt: at };
219153
219248
  try {
219154
- await mkdir3(root, { recursive: true });
219249
+ await mkdir4(root, { recursive: true });
219155
219250
  const tmp = `${path}.tmp`;
219156
- await writeFile2(tmp, `${JSON.stringify(envelope)}
219251
+ await writeFile3(tmp, `${JSON.stringify(envelope)}
219157
219252
  `, "utf8");
219158
- await rename(tmp, path);
219253
+ await rename2(tmp, path);
219159
219254
  } catch (cause) {
219160
219255
  return failure({ path, cause });
219161
219256
  }
@@ -219168,7 +219263,7 @@ async function readCompactionSnapshot(root, sessionID) {
219168
219263
  }
219169
219264
  let raw;
219170
219265
  try {
219171
- raw = await readFile4(path, "utf8");
219266
+ raw = await readFile5(path, "utf8");
219172
219267
  } catch (cause) {
219173
219268
  if (isRecord(cause) && cause.code === "ENOENT")
219174
219269
  return success(null);
@@ -219385,6 +219480,125 @@ function classifySnapshotStore(read) {
219385
219480
  return { status: "ready", messages };
219386
219481
  }
219387
219482
 
219483
+ // ../core/src/context/anchor.ts
219484
+ var ANCHOR_VERSION = 1;
219485
+ var ANCHOR_SLOT = "context-anchor";
219486
+ function isAnchorRecord(value) {
219487
+ if (!isRecord(value)) {
219488
+ return false;
219489
+ }
219490
+ const checklist = value.checklist;
219491
+ const workingTree = value.working_tree;
219492
+ const midThrough = value.mid_through;
219493
+ if (!isRecord(checklist)) {
219494
+ return false;
219495
+ }
219496
+ const done = checklist.done;
219497
+ const next = checklist.next;
219498
+ const current = checklist.current;
219499
+ return value.version === ANCHOR_VERSION && typeof value.session_id === "string" && typeof value.task_id === "string" && typeof value.written_at === "string" && isStringArray(value.plan_paths) && isStringArray(done) && isStringArray(next) && (current === null || typeof current === "string") && (workingTree === null || isStringArray(workingTree)) && (midThrough === null || typeof midThrough === "string");
219500
+ }
219501
+ async function anchorSet(stateDirectory, record) {
219502
+ return slotSet(stateDirectory, ANCHOR_SLOT, record.session_id, record);
219503
+ }
219504
+ async function anchorGet(stateDirectory, sessionID) {
219505
+ const stored = await slotGet(stateDirectory, ANCHOR_SLOT, sessionID, isAnchorRecord);
219506
+ if (!stored.ok) {
219507
+ return stored;
219508
+ }
219509
+ if (stored.value !== null && stored.value.session_id !== sessionID) {
219510
+ return success(null);
219511
+ }
219512
+ return stored;
219513
+ }
219514
+ async function anchorClear(stateDirectory, sessionID) {
219515
+ return slotClear(stateDirectory, ANCHOR_SLOT, sessionID);
219516
+ }
219517
+ function sanitizeAnchorLine(value) {
219518
+ return value.replace(/[\r\n]+/g, " ");
219519
+ }
219520
+ function renderAnchorView(record) {
219521
+ const lines = [
219522
+ "<task-anchor>",
219523
+ `task: ${sanitizeAnchorLine(record.task_id)}`,
219524
+ `written: ${sanitizeAnchorLine(record.written_at)}`
219525
+ ];
219526
+ for (const plan of record.plan_paths) {
219527
+ lines.push(`plan: ${sanitizeAnchorLine(plan)}`);
219528
+ }
219529
+ for (const done of record.checklist.done) {
219530
+ lines.push(`done: ${sanitizeAnchorLine(done)}`);
219531
+ }
219532
+ if (record.checklist.current !== null) {
219533
+ lines.push(`current: ${sanitizeAnchorLine(record.checklist.current)}`);
219534
+ }
219535
+ for (const next of record.checklist.next) {
219536
+ lines.push(`next: ${sanitizeAnchorLine(next)}`);
219537
+ }
219538
+ if (record.working_tree !== null) {
219539
+ for (const entry of record.working_tree) {
219540
+ lines.push(`tree: ${sanitizeAnchorLine(entry)}`);
219541
+ }
219542
+ }
219543
+ if (record.mid_through !== null) {
219544
+ lines.push(`mid-through: ${sanitizeAnchorLine(record.mid_through)}`);
219545
+ }
219546
+ lines.push("</task-anchor>");
219547
+ return lines.join(`
219548
+ `);
219549
+ }
219550
+ function renderAnchorResumeSection(record) {
219551
+ const lines = [
219552
+ "",
219553
+ "## Task Anchor",
219554
+ "",
219555
+ "A compaction cut through live task state. Re-read these plan files before acting:"
219556
+ ];
219557
+ for (const plan of record.plan_paths) {
219558
+ lines.push(`- ${sanitizeAnchorLine(plan)}`);
219559
+ }
219560
+ if (record.checklist.current !== null) {
219561
+ lines.push(`Current: ${sanitizeAnchorLine(record.checklist.current)}.`);
219562
+ }
219563
+ return lines.join(`
219564
+ `);
219565
+ }
219566
+
219567
+ // src/anchor.ts
219568
+ function stageAnchor(runtime, sessionID, fields) {
219569
+ runtime.pendingAnchors.set(sessionID, fields);
219570
+ }
219571
+ async function consumeStagedAnchor(stateDirectory, runtime, sessionID, deps, now) {
219572
+ const staged = runtime.pendingAnchors.get(sessionID);
219573
+ if (staged === undefined) {
219574
+ return null;
219575
+ }
219576
+ const record = {
219577
+ version: ANCHOR_VERSION,
219578
+ session_id: sessionID,
219579
+ task_id: staged.task_id,
219580
+ written_at: now,
219581
+ plan_paths: staged.plan_paths,
219582
+ checklist: staged.checklist,
219583
+ working_tree: staged.working_tree,
219584
+ mid_through: staged.mid_through
219585
+ };
219586
+ const written = await anchorSet(stateDirectory, record);
219587
+ if (!written.ok) {
219588
+ reportReceiptFailureOnce(runtime, deps, sessionID, "compact");
219589
+ return null;
219590
+ }
219591
+ runtime.pendingAnchors.delete(sessionID);
219592
+ return renderAnchorView(record);
219593
+ }
219594
+ async function loadSessionAnchor(stateDirectory, sessionID) {
219595
+ const read = await anchorGet(stateDirectory, sessionID);
219596
+ if (!read.ok) {
219597
+ return null;
219598
+ }
219599
+ return read.value;
219600
+ }
219601
+
219388
219602
  // src/compaction.ts
219389
219603
  function registerCompactionHook(context, deps, runtime) {
219390
219604
  context.session.hook("compaction", async (event) => {
@@ -219402,6 +219616,10 @@ function registerCompactionHook(context, deps, runtime) {
219402
219616
  }
219403
219617
  const session = sessionRuntime(runtime, sessionID);
219404
219618
  session.lastCompactionFailure = null;
219619
+ const backoffCleared = await failureBackoffClear(deps.stateDirectory, sessionID);
219620
+ if (!backoffCleared.ok) {
219621
+ reportReceiptFailureOnce(runtime, deps, sessionID, "compact");
219622
+ }
219405
219623
  if (deps.refreshEnabled) {
219406
219624
  session.preambleRefreshPending = true;
219407
219625
  }
@@ -219409,6 +219627,13 @@ function registerCompactionHook(context, deps, runtime) {
219409
219627
  const pending = runtime.pendingCauses.get(sessionID);
219410
219628
  const cause = pending !== undefined && Date.now() - pending.at <= PENDING_CAUSE_TTL_MS ? pending.cause : "manual";
219411
219629
  runtime.pendingCauses.delete(sessionID);
219630
+ const anchorView = await consumeStagedAnchor(deps.stateDirectory, runtime, sessionID, deps, new Date().toISOString());
219631
+ if (isContextStale(deps)) {
219632
+ return;
219633
+ }
219634
+ if (anchorView !== null && deps.onAnchorWritten !== null) {
219635
+ deps.onAnchorWritten(sessionID);
219636
+ }
219412
219637
  const vcc = compileCompaction(event.messages, resolveVccCompilerConfig(), DEFAULT_VCC_KEEP_MESSAGES, Math.max(0, estimatedTokens));
219413
219638
  const receipt = vcc === undefined ? {
219414
219639
  kind: "compact",
@@ -219430,17 +219655,21 @@ function registerCompactionHook(context, deps, runtime) {
219430
219655
  } else {
219431
219656
  event.system.push({
219432
219657
  type: "text",
219433
- text: buildCompactionPrompt({ brainPaths: deps.brainPaths, recoveryRule: null })
219658
+ text: buildCompactionPrompt({
219659
+ brainPaths: deps.brainPaths,
219660
+ recoveryRule: null,
219661
+ anchorView
219662
+ })
219434
219663
  });
219435
219664
  }
219436
- const written = await appendReceipt(join10(deps.stateDirectory, "context-log"), sessionID, receipt);
219665
+ const written = await appendReceipt(join11(deps.stateDirectory, "context-log"), sessionID, receipt);
219437
219666
  if (!written.ok) {
219438
219667
  reportReceiptFailureOnce(runtime, deps, sessionID, "compact");
219439
219668
  }
219440
219669
  if (isContextStale(deps)) {
219441
219670
  return;
219442
219671
  }
219443
- const remembered = await rememberSnapshot(join10(deps.stateDirectory, "context-snapshot"), sessionID, event.messages, new Date().toISOString(), session.snapshotSeen);
219672
+ const remembered = await rememberSnapshot(join11(deps.stateDirectory, "context-snapshot"), sessionID, event.messages, new Date().toISOString(), session.snapshotSeen);
219444
219673
  if (isContextStale(deps)) {
219445
219674
  return;
219446
219675
  }
@@ -219783,7 +220012,7 @@ function countWords(text, maxWords) {
219783
220012
  }
219784
220013
 
219785
220014
  // src/context.ts
219786
- import { join as join11 } from "node:path";
220015
+ import { join as join12 } from "node:path";
219787
220016
 
219788
220017
  // src/context-config.ts
219789
220018
  function isFullContextMode(config) {
@@ -219874,7 +220103,7 @@ function registerContextHook(context, deps, runtime) {
219874
220103
  if (isContextStale(deps)) {
219875
220104
  return;
219876
220105
  }
219877
- const remembered = await rememberSnapshot(join11(deps.stateDirectory, "context-snapshot"), sessionID, event.messages, new Date().toISOString(), session.snapshotSeen);
220106
+ const remembered = await rememberSnapshot(join12(deps.stateDirectory, "context-snapshot"), sessionID, event.messages, new Date().toISOString(), session.snapshotSeen);
219878
220107
  if (isContextStale(deps)) {
219879
220108
  return;
219880
220109
  }
@@ -219911,7 +220140,7 @@ function registerContextHook(context, deps, runtime) {
219911
220140
  removed: trimResult.removedTokens,
219912
220141
  omissions: trimResult.omissionCount
219913
220142
  };
219914
- const written = await appendReceipt(join11(deps.stateDirectory, "context-log"), sessionID, receipt);
220143
+ const written = await appendReceipt(join12(deps.stateDirectory, "context-log"), sessionID, receipt);
219915
220144
  if (!written.ok) {
219916
220145
  reportReceiptFailureOnce(runtime, deps, sessionID, "trim");
219917
220146
  }
@@ -219930,7 +220159,7 @@ function registerContextHook(context, deps, runtime) {
219930
220159
  }
219931
220160
  async function trimRequest(sessionID, messages, deps) {
219932
220161
  const batch = planTrimBatched(messages, { keepRecentTurns: deps.config.keepRecentTurns });
219933
- const omittedRoot = join11(deps.stateDirectory, "omitted");
220162
+ const omittedRoot = join12(deps.stateDirectory, "omitted");
219934
220163
  const stored = await storeOmissions(omittedRoot, sessionID, batch.requests);
219935
220164
  const ids = stored.ok ? stored.value.ids : new Map;
219936
220165
  const fresh = stored.ok ? stored.value.stored : new Set;
@@ -220018,9 +220247,9 @@ async function dispatchEvent(raw, deps, runtime) {
220018
220247
  } else if (event.type === STEP_ENDED) {
220019
220248
  handleStepEnded(event.sessionID, event.tokens, deps, runtime);
220020
220249
  } else if (event.type === COMPACTION_FAILED) {
220021
- handleCompactionFailed(event.sessionID, runtime);
220250
+ await handleCompactionFailed(event.sessionID, deps, runtime);
220022
220251
  } else if (event.type === COMPACTION_ENDED) {
220023
- handleCompactionEnded(event.sessionID, runtime);
220252
+ await handleCompactionEnded(event.sessionID, deps, runtime);
220024
220253
  }
220025
220254
  }
220026
220255
  async function handleExecutionSucceeded(sessionID, deps, runtime) {
@@ -220057,7 +220286,7 @@ function handleStepEnded(sessionID, tokens, deps, runtime) {
220057
220286
  session.lastStepTokens = tokens;
220058
220287
  session.estimator = anchorEstimator(tokens, session.lastMessageCount);
220059
220288
  }
220060
- function handleCompactionFailed(sessionID, runtime) {
220289
+ async function handleCompactionFailed(sessionID, deps, runtime) {
220061
220290
  if (sessionID === undefined) {
220062
220291
  return;
220063
220292
  }
@@ -220065,13 +220294,34 @@ function handleCompactionFailed(sessionID, runtime) {
220065
220294
  if (session.lastEstimate === null) {
220066
220295
  return;
220067
220296
  }
220068
- session.lastCompactionFailure = { at: Date.now(), estimate: session.lastEstimate };
220297
+ const at = Date.now();
220298
+ const estimate = session.lastEstimate;
220299
+ const written = await failureBackoffSet(deps.stateDirectory, {
220300
+ version: FAILURE_BACKOFF_VERSION,
220301
+ session_id: sessionID,
220302
+ at,
220303
+ estimate
220304
+ });
220305
+ if (isContextStale(deps)) {
220306
+ return;
220307
+ }
220308
+ session.lastCompactionFailure = { at, estimate };
220309
+ if (!written.ok) {
220310
+ reportReceiptFailureOnce(runtime, deps, sessionID, "compact");
220311
+ }
220069
220312
  }
220070
- function handleCompactionEnded(sessionID, runtime) {
220313
+ async function handleCompactionEnded(sessionID, deps, runtime) {
220071
220314
  if (sessionID === undefined) {
220072
220315
  return;
220073
220316
  }
220317
+ const cleared = await failureBackoffClear(deps.stateDirectory, sessionID);
220318
+ if (isContextStale(deps)) {
220319
+ return;
220320
+ }
220074
220321
  sessionRuntime(runtime, sessionID).lastCompactionFailure = null;
220322
+ if (!cleared.ok) {
220323
+ reportReceiptFailureOnce(runtime, deps, sessionID, "compact");
220324
+ }
220075
220325
  }
220076
220326
  function requestSessionCompaction(context, runtime, sessionID, cause) {
220077
220327
  const session = context.session;
@@ -220500,6 +220750,7 @@ var PREAMBLE_TENETS = `<vcc-brain-tenets version="1.1">
220500
220750
  - **Your context is ephemeral.** You WILL forget everything after the user starts a new conversation. Proactively persist durable decisions, specs, guides, and lessons in the right place now if they should survive the next session.
220501
220751
  - **Keep documents lean.** Do not restate the code. Record contracts, invariants, and decisions the code cannot own. Do not create paragraphs for minor tweaks. Keep documents cohesive, but well scoped; when a document becomes unfocused: split.
220502
220752
  - **Proactively update your brain.** When durable truth changes, rewrite its canonical home in the present tense (specs, knowledge, plans → delete/convert when done, product vision). No edit sprawl. Update naturally; state what is true now.
220753
+ - **Resume orientation first.** After a compaction, the session task anchor (plan paths, checklist position) outranks the summary for what to do next: re-read the anchored plan files before acting.
220503
220754
  </important>
220504
220755
 
220505
220756
  **You must remember these tenets and apply them while you work.**
@@ -220651,6 +220902,7 @@ var PREAMBLE_TENETS2 = `<vcc-brain-tenets version="2.0">
220651
220902
  - **Documents are truth and knowledge.** Read matching documents before every task. Update when details changes. Explore progressively. Do not default to reading everything.
220652
220903
  - **Persist durable, reusable knowledge.** Your context is ephemeral. You WILL forget everything after this session ends. Proactively maintain essential context: specs, decisions, guides, rules, findings, etc. in their canonical homes. Do not record task-local guidance or findings with no future usefulness. Permanent rules or definitely useful findings may be recorded in appropriate locations. If uncertain about long-term value, ask user whether to record.
220653
220904
  - **Keep memory current and lean.** Update changed contracts, resolve completed plans, and remove obsolete content without duplicating explanations or restating implementation. Outside of essential context or overviews, do not summarize or restate the code. Do not record paragraphs for minor tweaks. No edit sprawl; one home. Update naturally; state what is true now; no mentioning historical detail unless useful.
220905
+ - **Resume orientation first.** After a compaction, the session task anchor (plan paths, checklist position) outranks the summary for what to do next: re-read the anchored plan files before acting.
220654
220906
  </important>
220655
220907
 
220656
220908
  **You must remember these tenets and apply them while you work.**
@@ -220907,15 +221159,15 @@ async function loadPreamble(options) {
220907
221159
  const cached = options.cache.get(options.sessionID);
220908
221160
  if (cached !== undefined)
220909
221161
  return cached;
220910
- const pending = readPreamble(options.projectDirectory, options.homeDirectory);
221162
+ const pending = readPreamble(options.projectDirectory, options.homeDirectory, options.stateDirectory, options.sessionID);
220911
221163
  options.cache.set(options.sessionID, pending);
220912
221164
  return pending;
220913
221165
  }
220914
- async function readPreamble(projectDirectory, homeDirectory) {
221166
+ async function readPreamble(projectDirectory, homeDirectory, stateDirectory, sessionID) {
220915
221167
  try {
220916
221168
  const snapshotPromise = loadMemorySnapshot(projectDirectory, homeDirectory, true);
220917
221169
  const roots = await resolveBrainRoots(projectDirectory, homeDirectory);
220918
- return success2(renderPreamble(await snapshotPromise, {
221170
+ const rendered = renderPreamble(await snapshotPromise, {
220919
221171
  shared: roots.sharedDisplay,
220920
221172
  private: roots.privateDisplay,
220921
221173
  user: roots.userDisplay,
@@ -220924,14 +221176,23 @@ async function readPreamble(projectDirectory, homeDirectory) {
220924
221176
  shared: roots.sharedLegacyAlsoExists,
220925
221177
  user: roots.userLegacyAlsoExists
220926
221178
  }
220927
- }));
221179
+ });
221180
+ const anchor = await loadSessionAnchor(stateDirectory, sessionID);
221181
+ if (anchor === null || !rendered.loaded) {
221182
+ return success2(rendered);
221183
+ }
221184
+ return success2({
221185
+ ...rendered,
221186
+ content: `${rendered.content}
221187
+ ${renderAnchorResumeSection(anchor)}`
221188
+ });
220928
221189
  } catch (cause) {
220929
221190
  return failure2({ message: "VCC Brain failed to create the session preamble.", cause });
220930
221191
  }
220931
221192
  }
220932
221193
 
220933
221194
  // src/project-config.ts
220934
- import { readFile as readFile5 } from "node:fs/promises";
221195
+ import { readFile as readFile6 } from "node:fs/promises";
220935
221196
 
220936
221197
  // src/refresh-config.ts
220937
221198
  var DEFAULT_PREAMBLE_REFRESH_CONFIG = {
@@ -220959,7 +221220,7 @@ function parsePreambleRefreshBlock(block, base = DEFAULT_PREAMBLE_REFRESH_CONFIG
220959
221220
  async function resolveProjectConfig(projectDirectory, base) {
220960
221221
  for (const candidate of projectConfigPaths(projectDirectory)) {
220961
221222
  try {
220962
- const text = await readFile5(candidate, "utf8");
221223
+ const text = await readFile6(candidate, "utf8");
220963
221224
  let raw;
220964
221225
  try {
220965
221226
  raw = JSON.parse(text);
@@ -221052,7 +221313,7 @@ async function findExternalCompactionProvider(context) {
221052
221313
  }
221053
221314
 
221054
221315
  // src/refresh.ts
221055
- import { join as join12 } from "node:path";
221316
+ import { join as join13 } from "node:path";
221056
221317
  async function maybeRefreshPreamble(deps, runtime, sessionID, projectDirectory, homeDirectory, cache, messages) {
221057
221318
  const idle = { refreshed: false, failed: false };
221058
221319
  if (!deps.config.enabled || isContextStale(deps) || !deps.isBrainAvailable(sessionID)) {
@@ -221083,7 +221344,13 @@ async function maybeRefreshPreamble(deps, runtime, sessionID, projectDirectory,
221083
221344
  }
221084
221345
  }
221085
221346
  cache.delete(sessionID);
221086
- const rendered = await loadPreamble({ sessionID, projectDirectory, homeDirectory, cache });
221347
+ const rendered = await loadPreamble({
221348
+ sessionID,
221349
+ projectDirectory,
221350
+ homeDirectory,
221351
+ stateDirectory: deps.stateDirectory,
221352
+ cache
221353
+ });
221087
221354
  if (!rendered.ok || !rendered.value.loaded) {
221088
221355
  cache.delete(sessionID);
221089
221356
  return { refreshed: false, failed: true };
@@ -221094,7 +221361,7 @@ async function maybeRefreshPreamble(deps, runtime, sessionID, projectDirectory,
221094
221361
  reason: postCompaction ? "post-compaction" : "brain-changed",
221095
221362
  at: new Date().toISOString()
221096
221363
  };
221097
- await appendReceipt(join12(deps.stateDirectory, "context-log"), sessionID, receipt);
221364
+ await appendReceipt(join13(deps.stateDirectory, "context-log"), sessionID, receipt);
221098
221365
  return { refreshed: true, content: rendered.value.content };
221099
221366
  }
221100
221367
  async function refreshPreambleContent(deps, runtime, sessionID, projectDirectory, homeDirectory, cache, messages, cachedContent) {
@@ -221113,13 +221380,14 @@ async function refreshPreambleContent(deps, runtime, sessionID, projectDirectory
221113
221380
 
221114
221381
  // src/tool.ts
221115
221382
  import { execFile } from "node:child_process";
221116
- import { join as join13 } from "node:path";
221383
+ import { join as join14 } from "node:path";
221117
221384
  var OMISSION_ID_PATTERN = /^omitted-\d+$/;
221118
221385
  var CONTEXT_MANAGEMENT_TOOL_NAMES = [
221119
221386
  "vcc-brain-read_omitted",
221120
221387
  "vcc-brain-prune",
221121
221388
  "vcc-brain-recall",
221122
- "vcc-brain-search"
221389
+ "vcc-brain-search",
221390
+ "vcc-brain-anchor"
221123
221391
  ];
221124
221392
  function isOmissionID(contentID) {
221125
221393
  return OMISSION_ID_PATTERN.test(contentID);
@@ -221151,7 +221419,7 @@ async function registerReadOmittedTool(context, deps) {
221151
221419
  if (!isOmissionID(contentID)) {
221152
221420
  return { content: `Invalid content ID: ${contentID}.` };
221153
221421
  }
221154
- const stored = await readOmission(join13(deps.stateDirectory, "omitted"), toolContext.sessionID, contentID);
221422
+ const stored = await readOmission(join14(deps.stateDirectory, "omitted"), toolContext.sessionID, contentID);
221155
221423
  if (!stored.ok) {
221156
221424
  return { content: `Could not read omitted content for Content ID: ${contentID}.` };
221157
221425
  }
@@ -221187,7 +221455,7 @@ async function registerPruneTool(context, deps) {
221187
221455
  },
221188
221456
  execute: async (input, toolContext) => {
221189
221457
  const options = asPruneOptions(input);
221190
- const pruned = await pruneOmissions(join13(deps.stateDirectory, "omitted"), toolContext.sessionID, {
221458
+ const pruned = await pruneOmissions(join14(deps.stateDirectory, "omitted"), toolContext.sessionID, {
221191
221459
  maxAgeMs: options.maxAgeDays * 24 * 60 * 60 * 1000,
221192
221460
  maxPayloads: options.maxPayloads,
221193
221461
  maxBytes: options.maxBytes
@@ -221246,7 +221514,7 @@ async function registerRecallTool(context, deps) {
221246
221514
  if (typeof input.id !== "string" || input.id.trim() === "") {
221247
221515
  return { content: "Missing required input: id." };
221248
221516
  }
221249
- const read = await readCompactionSnapshot(join13(deps.stateDirectory, "context-snapshot"), toolContext.sessionID);
221517
+ const read = await readCompactionSnapshot(join14(deps.stateDirectory, "context-snapshot"), toolContext.sessionID);
221250
221518
  const classified = classifySnapshotStore(read);
221251
221519
  if (classified.status === "failed") {
221252
221520
  return { content: "Could not read compaction snapshot for this session." };
@@ -221296,7 +221564,7 @@ async function registerSearchTool(context, deps) {
221296
221564
  if (!isRecord(input) || typeof input.pattern !== "string" || input.pattern.trim() === "") {
221297
221565
  return { content: "Missing required input: pattern." };
221298
221566
  }
221299
- const read = await readCompactionSnapshot(join13(deps.stateDirectory, "context-snapshot"), toolContext.sessionID);
221567
+ const read = await readCompactionSnapshot(join14(deps.stateDirectory, "context-snapshot"), toolContext.sessionID);
221300
221568
  const classified = classifySnapshotStore(read);
221301
221569
  if (classified.status === "failed") {
221302
221570
  return { content: "Could not read compaction snapshot for this session." };
@@ -221439,6 +221707,105 @@ async function registerRecallSessionTool(context) {
221439
221707
  });
221440
221708
  });
221441
221709
  }
221710
+ async function registerAnchorTool(context, deps) {
221711
+ await context.tool.transform((editor) => {
221712
+ editor.add({
221713
+ name: "vcc-brain-anchor",
221714
+ options: { codemode: false },
221715
+ description: "Stage or clear the session task anchor: orientation state that survives " + "compaction deterministically. Action stage records plan paths and checklist " + "position for the next compaction; action clear removes the record on task completion.",
221716
+ input: {
221717
+ type: "object",
221718
+ properties: {
221719
+ action: {
221720
+ type: "string",
221721
+ description: 'Either "stage" or "clear".'
221722
+ },
221723
+ task_id: {
221724
+ type: "string",
221725
+ description: "Task identifier, e.g. a plan path (stage only)."
221726
+ },
221727
+ plan_paths: {
221728
+ type: "array",
221729
+ items: { type: "string" },
221730
+ description: "Plan files to re-read at resume (stage only)."
221731
+ },
221732
+ done: {
221733
+ type: "array",
221734
+ items: { type: "string" },
221735
+ description: "Completed checklist entries (stage only)."
221736
+ },
221737
+ current: {
221738
+ type: "string",
221739
+ description: "Current checklist entry, or null (stage only)."
221740
+ },
221741
+ next: {
221742
+ type: "array",
221743
+ items: { type: "string" },
221744
+ description: "Upcoming checklist entries (stage only)."
221745
+ },
221746
+ working_tree: {
221747
+ type: "array",
221748
+ items: { type: "string" },
221749
+ description: "Working-tree sketch lines, or null (stage only)."
221750
+ },
221751
+ mid_through: {
221752
+ type: "string",
221753
+ description: "One-line mid-through note, or null (stage only)."
221754
+ }
221755
+ },
221756
+ required: ["action"]
221757
+ },
221758
+ execute: async (input, toolContext) => {
221759
+ if (!isRecord(input) || input.action !== "stage" && input.action !== "clear") {
221760
+ return { content: 'Missing or invalid input: action must be "stage" or "clear".' };
221761
+ }
221762
+ if (input.action === "clear") {
221763
+ const cleared = await anchorClear(deps.stateDirectory, toolContext.sessionID);
221764
+ if (!cleared.ok) {
221765
+ return { content: "Could not clear the task anchor for this session." };
221766
+ }
221767
+ return { content: "Task anchor cleared." };
221768
+ }
221769
+ if (typeof input.task_id !== "string" || input.task_id.trim() === "") {
221770
+ return { content: "Missing required input: task_id." };
221771
+ }
221772
+ if (!isStringArray(input.plan_paths)) {
221773
+ return { content: "Missing required input: plan_paths must be an array of strings." };
221774
+ }
221775
+ const doneRaw = input.done === undefined ? [] : input.done;
221776
+ const nextRaw = input.next === undefined ? [] : input.next;
221777
+ if (!isStringArray(doneRaw) || !isStringArray(nextRaw)) {
221778
+ return { content: "Invalid input: done and next must be arrays of strings." };
221779
+ }
221780
+ const done = doneRaw;
221781
+ const next = nextRaw;
221782
+ const currentRaw = input.current === undefined || input.current === null ? null : input.current;
221783
+ if (currentRaw !== null && typeof currentRaw !== "string") {
221784
+ return { content: "Invalid input: current must be a string or null." };
221785
+ }
221786
+ const current = currentRaw;
221787
+ const workingTreeRaw = input.working_tree === undefined || input.working_tree === null ? null : input.working_tree;
221788
+ if (workingTreeRaw !== null && !isStringArray(workingTreeRaw)) {
221789
+ return { content: "Invalid input: working_tree must be an array of strings or null." };
221790
+ }
221791
+ const workingTree = workingTreeRaw;
221792
+ const midThroughRaw = input.mid_through === undefined || input.mid_through === null ? null : input.mid_through;
221793
+ if (midThroughRaw !== null && typeof midThroughRaw !== "string") {
221794
+ return { content: "Invalid input: mid_through must be a string or null." };
221795
+ }
221796
+ const midThrough = midThroughRaw;
221797
+ stageAnchor(deps.runtime, toolContext.sessionID, {
221798
+ task_id: input.task_id,
221799
+ plan_paths: input.plan_paths,
221800
+ checklist: { done, current, next },
221801
+ working_tree: workingTree,
221802
+ mid_through: midThrough
221803
+ });
221804
+ return { content: "Task anchor staged for the next compaction." };
221805
+ }
221806
+ });
221807
+ });
221808
+ }
221442
221809
 
221443
221810
  // src/index.ts
221444
221811
  var setupGeneration = 0;
@@ -221565,6 +221932,7 @@ var VccBrainPlugin = Plugin.define({
221565
221932
  sessionID: event.sessionID,
221566
221933
  projectDirectory: context.location.directory,
221567
221934
  homeDirectory: homedir(),
221935
+ stateDirectory: resolveStateDirectory(homedir()),
221568
221936
  cache
221569
221937
  });
221570
221938
  brainAvailable.set(event.sessionID, result.ok ? result.value.loaded && result.value.initialized : false);
@@ -221663,7 +222031,10 @@ var VccBrainPlugin = Plugin.define({
221663
222031
  isBrainAvailable,
221664
222032
  reportReceiptFailure,
221665
222033
  refreshEnabled: refreshConfig.enabled,
221666
- isCurrent: isActive
222034
+ isCurrent: isActive,
222035
+ onAnchorWritten: (sessionID) => {
222036
+ cache.delete(sessionID);
222037
+ }
221667
222038
  }, runtime);
221668
222039
  }
221669
222040
  registerCompletionTrigger(context, deps, runtime, { signal: controller.signal });
@@ -221672,6 +222043,7 @@ var VccBrainPlugin = Plugin.define({
221672
222043
  if (fullMode) {
221673
222044
  await registerRecallTool(context, { stateDirectory });
221674
222045
  await registerSearchTool(context, { stateDirectory });
222046
+ await registerAnchorTool(context, { stateDirectory, runtime });
221675
222047
  }
221676
222048
  await registerSearchSessionsTool(context, {
221677
222049
  projectDirectory: context.location.directory
@@ -221714,4 +222086,4 @@ export {
221714
222086
  src_default as default
221715
222087
  };
221716
222088
 
221717
- //# debugId=9718B2ECF0DF997964756E2164756E21
222089
+ //# debugId=42815A449197B2CA64756E2164756E21