@vectorize-io/hindsight-coding-agents 0.1.1 → 0.2.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/cline.js CHANGED
@@ -81,6 +81,12 @@ function resolveConfig(raw = {}) {
81
81
  surveyBudgetUsd: raw.surveyBudgetUsd || 2,
82
82
  surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
83
83
  gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
84
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
85
+ // nested object cannot reach the API as a tag and fail the whole retain.
86
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
87
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
88
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
89
+ ) : {},
84
90
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
85
91
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
86
92
  };
@@ -134,7 +140,10 @@ var ENV_KEYS = {
134
140
  surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
135
141
  surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
136
142
  logLevel: "HINDSIGHT_LOG_LEVEL",
137
- gitIngest: "HINDSIGHT_GIT_INGEST"
143
+ gitIngest: "HINDSIGHT_GIT_INGEST",
144
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
145
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
146
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
138
147
  };
139
148
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
140
149
  "dynamicBankId",
@@ -145,6 +154,7 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
145
154
  "autoSeed",
146
155
  "codebaseSurvey"
147
156
  ]);
157
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags"]);
148
158
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
149
159
  "apiPort",
150
160
  "daemonIdleTimeout",
@@ -162,6 +172,9 @@ function readEnvConfig(env = process.env) {
162
172
  if (value === void 0 || value.trim() === "") continue;
163
173
  if (ENV_BOOLEANS.has(key)) {
164
174
  out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
175
+ } else if (ENV_LISTS.has(key)) {
176
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
177
+ if (items.length) out[key] = items;
165
178
  } else if (ENV_NUMBERS.has(key)) {
166
179
  const n = Number(value);
167
180
  if (Number.isFinite(n)) out[key] = n;
@@ -211,9 +224,25 @@ function resolvePartial(cfg, patch) {
211
224
  import { execFileSync } from "child_process";
212
225
  import { homedir as homedir2 } from "os";
213
226
  import { basename, dirname as dirname2, join as join3, normalize, sep } from "path";
227
+
228
+ // src/core/template.ts
229
+ var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
230
+ function applyTemplate(template, resolvers, what) {
231
+ return template.replace(PLACEHOLDER, (_, name) => {
232
+ const resolve2 = resolvers[name];
233
+ if (!resolve2) {
234
+ console.error(
235
+ `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
236
+ );
237
+ return "unknown";
238
+ }
239
+ return resolve2();
240
+ });
241
+ }
242
+
243
+ // src/core/bank.ts
214
244
  var DEFAULT_BANK_NAME = "coding";
215
245
  var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
216
- var PLACEHOLDER = /\{([a-zA-Z]+)\}/g;
217
246
  function getProjectRootFromGit(directory) {
218
247
  if (!directory) return null;
219
248
  try {
@@ -262,16 +291,7 @@ function deriveBankId(config2, directory, harness = "coding") {
262
291
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
263
292
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
264
293
  };
265
- return (config2.bankIdTemplate || DEFAULT_TEMPLATE).replace(PLACEHOLDER, (_, name) => {
266
- const r = resolvers[name];
267
- if (!r) {
268
- console.error(
269
- `hindsight: unknown bankIdTemplate placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
270
- );
271
- return "unknown";
272
- }
273
- return r();
274
- });
294
+ return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
275
295
  }
276
296
 
277
297
  // src/core/missions.ts
@@ -395,11 +415,32 @@ var CODING_BANK_TEMPLATE = {
395
415
  entities_allow_free_form: true
396
416
  }
397
417
  };
418
+ var CODING_BANK_STRUCTURE = {
419
+ version: "1",
420
+ bank: {
421
+ retain_strategies: RETAIN_STRATEGIES,
422
+ entity_labels: [KNOWLEDGE_LABELS]
423
+ }
424
+ };
398
425
 
399
426
  // src/core/util.ts
400
427
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
428
+ function semverGte(version2, min) {
429
+ const parts = (v) => {
430
+ const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
431
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
432
+ };
433
+ const a = version2 ? parts(version2) : void 0;
434
+ const b = parts(min);
435
+ if (!a || !b) return false;
436
+ for (let i = 0; i < 3; i++) {
437
+ if (a[i] !== b[i]) return a[i] > b[i];
438
+ }
439
+ return true;
440
+ }
401
441
 
402
442
  // src/core/hindsight.ts
443
+ var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
403
444
  var KnowledgePagesUnavailableError = class extends Error {
404
445
  code = "knowledge_pages_unavailable";
405
446
  constructor() {
@@ -408,6 +449,7 @@ var KnowledgePagesUnavailableError = class extends Error {
408
449
  }
409
450
  };
410
451
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
452
+ var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
411
453
  var HindsightClient = class {
412
454
  apiUrl;
413
455
  apiToken;
@@ -416,6 +458,8 @@ var HindsightClient = class {
416
458
  // async operation ids collected by retain(), for drain()
417
459
  /** Tri-state capability probe: unknown until the first page request, then cached. */
418
460
  knowledgePagesSupported;
461
+ /** Tri-state capability probe: unknown until the first append-mode retain, then cached. */
462
+ idempotentRetain;
419
463
  log;
420
464
  constructor(o) {
421
465
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
@@ -444,7 +488,8 @@ var HindsightClient = class {
444
488
  throw new Error(`${method} ${url2} -> ${r.status} ${await r.text()}`);
445
489
  return r;
446
490
  }
447
- /** Retain one memory. Async by default: enqueue extraction server-side and collect its op-id for drain(). */
491
+ /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
492
+ * drain(). Nothing in this plugin can afford to block a coding agent's hook on extraction. */
448
493
  async retain(content, context, documentId, tags, strategy, opts = {}) {
449
494
  const item = {
450
495
  content,
@@ -455,14 +500,36 @@ var HindsightClient = class {
455
500
  };
456
501
  if (opts.timestamp) item.timestamp = opts.timestamp;
457
502
  if (opts.metadata) item.metadata = opts.metadata;
458
- const isAsync = opts.async !== false;
459
- const r = await this.req("POST", this.bankUrl("/memories"), { items: [item], async: isAsync });
460
- if (isAsync) {
461
- try {
462
- const j = await r.json();
463
- if (j.operation_id) this.opIds.push(j.operation_id);
464
- } catch {
465
- }
503
+ if (opts.updateMode) item.update_mode = opts.updateMode;
504
+ const body = { items: [item], async: true };
505
+ if (opts.operationId) body.operation_id = opts.operationId;
506
+ const r = await this.req("POST", this.bankUrl("/memories"), body);
507
+ try {
508
+ const j = await r.json();
509
+ if (j.operation_id) this.opIds.push(j.operation_id);
510
+ } catch {
511
+ }
512
+ }
513
+ /**
514
+ * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
515
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via GET /version; anything
516
+ * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
517
+ */
518
+ async supportsIdempotentRetain() {
519
+ if (this.idempotentRetain === void 0) {
520
+ this.idempotentRetain = await this.probeIdempotentRetain();
521
+ this.log(`server retain idempotency: ${this.idempotentRetain ? "supported" : "unavailable"}`);
522
+ }
523
+ return this.idempotentRetain;
524
+ }
525
+ async probeIdempotentRetain() {
526
+ try {
527
+ const r = await this.req("GET", `${this.apiUrl}/version`);
528
+ if (!r.ok) return false;
529
+ const j = await r.json();
530
+ return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
531
+ } catch {
532
+ return false;
466
533
  }
467
534
  }
468
535
  /**
@@ -499,12 +566,39 @@ var HindsightClient = class {
499
566
  await this.req("DELETE", this.bankUrl());
500
567
  this.log(`[bank] reset ${this.bank}`);
501
568
  }
502
- await this.req("POST", this.bankUrl("/import"), CODING_BANK_TEMPLATE);
569
+ const seeded = opts.reset ? false : await this.hasBankMissions();
570
+ await this.req(
571
+ "POST",
572
+ this.bankUrl("/import"),
573
+ seeded ? CODING_BANK_STRUCTURE : CODING_BANK_TEMPLATE
574
+ );
503
575
  this.log(
504
- `[bank] template applied to ${this.bank}: missions, entity_labels {knowledge}, strategies {git, gitlog, conversation, document}`
576
+ seeded ? `[bank] structure applied to ${this.bank}: entity_labels {knowledge}, strategies {git, gitlog, conversation, document} \u2014 missions left as configured` : `[bank] template applied to ${this.bank}: missions, entity_labels {knowledge}, strategies {git, gitlog, conversation, document}`
505
577
  );
506
578
  await this.seedPages();
507
579
  }
580
+ /**
581
+ * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
582
+ * the user's own edit. Either way they are not ours to overwrite.
583
+ *
584
+ * Reads the bank-scoped OVERRIDES, not the resolved config, so inherited global defaults don't
585
+ * read as "already set". A missing bank, or a deployment with the bank-config API switched off,
586
+ * answers false: there is nothing to preserve, and without that API a user cannot set per-bank
587
+ * missions in the first place.
588
+ */
589
+ async hasBankMissions() {
590
+ try {
591
+ const r = await this.req("GET", this.bankUrl("/config"));
592
+ if (!r.ok) return false;
593
+ const j = await r.json();
594
+ return MISSION_FIELDS.some((f) => {
595
+ const v = j.overrides?.[f];
596
+ return typeof v === "string" && v.trim() !== "";
597
+ });
598
+ } catch {
599
+ return false;
600
+ }
601
+ }
508
602
  /** Delete one document (cascades its memory units/links). Used by deepen's self-cleanup. */
509
603
  async deleteDocument(documentId) {
510
604
  await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
@@ -750,8 +844,7 @@ var HindsightClient = class {
750
844
  "initiative marker",
751
845
  markerId,
752
846
  ["knowledge:feature-work", `relatedPageId:${pageId}`],
753
- "document",
754
- { async: true }
847
+ "document"
755
848
  );
756
849
  return { page_id: pageId };
757
850
  }
@@ -15791,7 +15884,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15791
15884
  docId,
15792
15885
  ["source:upload", ...opts.harness ? [`harness:${opts.harness}`] : []],
15793
15886
  "document",
15794
- { async: true, metadata: opts.harness ? { harness: opts.harness } : void 0 }
15887
+ { metadata: opts.harness ? { harness: opts.harness } : void 0 }
15795
15888
  );
15796
15889
  return { ok: true, doc_id: docId };
15797
15890
  })
@@ -15799,6 +15892,51 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15799
15892
  ];
15800
15893
  }
15801
15894
 
15895
+ // src/core/retain-cursor.ts
15896
+ import { createHash } from "crypto";
15897
+ function fingerprintTurns(turns, count) {
15898
+ const h = createHash("sha1").update(String(count));
15899
+ for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
15900
+ return h.digest("hex");
15901
+ }
15902
+ function planRetain(turns, cursor, opts) {
15903
+ if (!turns.length) return { mode: "skip" };
15904
+ if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
15905
+ if (cursor.bank !== opts.bank) return { mode: "replace" };
15906
+ if (cursor.turns > turns.length) return { mode: "replace" };
15907
+ if (fingerprintTurns(turns, cursor.turns) !== cursor.fingerprint) return { mode: "replace" };
15908
+ if (cursor.turns === turns.length) return { mode: "skip" };
15909
+ return { mode: "append", fromTurn: cursor.turns };
15910
+ }
15911
+ function memoryCursorStore() {
15912
+ const cursors = /* @__PURE__ */ new Map();
15913
+ return {
15914
+ read: (sessionId2) => cursors.get(sessionId2),
15915
+ write: (sessionId2, cursor) => void cursors.set(sessionId2, cursor)
15916
+ };
15917
+ }
15918
+
15919
+ // src/core/uuid.ts
15920
+ import { createHash as createHash2 } from "crypto";
15921
+ var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
15922
+ function uuidV5(name, namespace = HINDSIGHT_NAMESPACE) {
15923
+ const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
15924
+ if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
15925
+ const bytes = Buffer.from(
15926
+ createHash2("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
15927
+ );
15928
+ bytes[6] = bytes[6] & 15 | 80;
15929
+ bytes[8] = bytes[8] & 63 | 128;
15930
+ const hex3 = bytes.toString("hex");
15931
+ return [
15932
+ hex3.slice(0, 8),
15933
+ hex3.slice(8, 12),
15934
+ hex3.slice(12, 16),
15935
+ hex3.slice(16, 20),
15936
+ hex3.slice(20)
15937
+ ].join("-");
15938
+ }
15939
+
15802
15940
  // src/core/chat.ts
15803
15941
  function withRefId(refId, turns, baseTs) {
15804
15942
  return [{ role: "system", content: `REF-ID: ${refId}`, timestamp: baseTs }, ...turns];
@@ -15806,18 +15944,73 @@ function withRefId(refId, turns, baseTs) {
15806
15944
  function renderSessionJsonl(refId, turns, baseTs) {
15807
15945
  return withRefId(refId, turns, baseTs).map((t) => JSON.stringify(t)).join("\n");
15808
15946
  }
15809
- async function retainLiveSession(client, sessionId2, turns, startTs, harness) {
15947
+ async function supportsAppend(client) {
15948
+ try {
15949
+ return await client.supportsIdempotentRetain();
15950
+ } catch {
15951
+ return false;
15952
+ }
15953
+ }
15954
+ var writeBacks = /* @__PURE__ */ new WeakMap();
15955
+ function serialize(cursors, sessionId2, write2) {
15956
+ const perSession = writeBacks.get(cursors) ?? /* @__PURE__ */ new Map();
15957
+ writeBacks.set(cursors, perSession);
15958
+ const next = (perSession.get(sessionId2) ?? Promise.resolve()).then(write2, write2);
15959
+ const tail = next.catch(() => {
15960
+ });
15961
+ perSession.set(sessionId2, tail);
15962
+ void tail.then(() => {
15963
+ if (perSession.get(sessionId2) === tail) perSession.delete(sessionId2);
15964
+ });
15965
+ return next;
15966
+ }
15967
+ async function retainLiveSession(client, sessionId2, turns, startTs, harness, opts = {}) {
15968
+ const cursors = opts.cursors;
15969
+ if (!cursors) return writeSession(client, sessionId2, turns, startTs, harness, opts.stamp);
15970
+ return serialize(
15971
+ cursors,
15972
+ sessionId2,
15973
+ () => writeSession(client, sessionId2, turns, startTs, harness, opts.stamp, cursors)
15974
+ );
15975
+ }
15976
+ async function writeSession(client, sessionId2, turns, startTs, harness, stamp, cursors) {
15810
15977
  const refId = `conversation:${sessionId2}`;
15978
+ const appendSupported = Boolean(cursors) && await supportsAppend(client);
15979
+ const plan = planRetain(turns, cursors?.read(sessionId2), { appendSupported, bank: client.bank });
15980
+ if (plan.mode === "skip") return;
15981
+ const content = plan.mode === "append" ? turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n") : renderSessionJsonl(refId, turns, startTs);
15982
+ const next = {
15983
+ turns: turns.length,
15984
+ fingerprint: fingerprintTurns(turns, turns.length),
15985
+ bank: client.bank
15986
+ };
15987
+ cursors?.write(sessionId2, { ...next, dirty: true });
15811
15988
  await client.retain(
15812
- renderSessionJsonl(refId, turns, startTs),
15989
+ content,
15813
15990
  "coding agent session",
15814
15991
  refId,
15815
- ["source:chat", ...harness ? [`harness:${harness}`] : []],
15992
+ // Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
15993
+ // the documents list filters and draws its agent logo from, so a template cannot displace them.
15994
+ [
15995
+ .../* @__PURE__ */ new Set([
15996
+ ...stamp?.tags ?? [],
15997
+ "source:chat",
15998
+ ...harness ? [`harness:${harness}`] : []
15999
+ ])
16000
+ ],
15816
16001
  "conversation",
15817
16002
  {
15818
16003
  timestamp: startTs,
15819
- async: true,
16004
+ updateMode: plan.mode === "append" ? "append" : void 0,
16005
+ // Identity of THIS payload: a resubmission of the same bytes is collapsed server-side into
16006
+ // the original operation instead of extracting (or appending) twice.
16007
+ operationId: uuidV5(`${client.bank}
16008
+ ${refId}
16009
+ ${plan.mode}
16010
+ ${content}`),
15820
16011
  metadata: {
16012
+ ...stamp?.metadata,
16013
+ // configured first: the built-ins below win on any key collision
15821
16014
  source: "chat",
15822
16015
  session_id: sessionId2,
15823
16016
  ref_id: refId,
@@ -15825,6 +16018,54 @@ async function retainLiveSession(client, sessionId2, turns, startTs, harness) {
15825
16018
  }
15826
16019
  }
15827
16020
  );
16021
+ cursors?.write(sessionId2, next);
16022
+ }
16023
+
16024
+ // src/core/retain-stamp.ts
16025
+ import { basename as basename2 } from "path";
16026
+ var RESERVED_TAG_PREFIX = /^(source|harness):/;
16027
+ function resolversFor(ctx) {
16028
+ return {
16029
+ // Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
16030
+ // otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
16031
+ gitProject: () => projectNameOf(ctx.directory),
16032
+ project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
16033
+ harness: () => ctx.harness,
16034
+ bankId: () => ctx.bankId,
16035
+ sessionId: () => ctx.sessionId,
16036
+ timestamp: () => (/* @__PURE__ */ new Date()).toISOString(),
16037
+ channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
16038
+ user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
16039
+ };
16040
+ }
16041
+ function buildRetainStamp(cfg, ctx) {
16042
+ const hasTags = Boolean(cfg.retainTags?.length);
16043
+ const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
16044
+ if (!hasTags && !hasMetadata) return { tags: [], metadata: {} };
16045
+ const base = resolversFor(ctx);
16046
+ const cache = /* @__PURE__ */ new Map();
16047
+ const resolvers = Object.fromEntries(
16048
+ Object.entries(base).map(([name, resolve2]) => [
16049
+ name,
16050
+ () => {
16051
+ const hit = cache.get(name);
16052
+ if (hit !== void 0) return hit;
16053
+ const value = resolve2();
16054
+ cache.set(name, value);
16055
+ return value;
16056
+ }
16057
+ ])
16058
+ );
16059
+ const tags = (cfg.retainTags ?? []).map((t) => applyTemplate(t, resolvers, "retainTags").trim()).filter(Boolean).filter((t) => {
16060
+ if (!RESERVED_TAG_PREFIX.test(t)) return true;
16061
+ log.warn("retain-stamp", "ignoring reserved retainTags entry", { tag: t });
16062
+ return false;
16063
+ });
16064
+ const metadata = {};
16065
+ for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
16066
+ metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
16067
+ }
16068
+ return { tags, metadata };
15828
16069
  }
15829
16070
 
15830
16071
  // src/core/session-start.ts
@@ -15926,8 +16167,7 @@ async function buildSessionStartContext(args) {
15926
16167
  "hindsight codebase-survey baseline",
15927
16168
  `${SURVEY_BASELINE_PREFIX}${sha}`,
15928
16169
  [SURVEY_BASELINE_TAG],
15929
- "survey",
15930
- { async: true }
16170
+ "survey"
15931
16171
  )
15932
16172
  ).catch(() => {
15933
16173
  });
@@ -16136,22 +16376,26 @@ async function buildHookOutput(args) {
16136
16376
  var HARNESS = "opencode";
16137
16377
  var RuntimeCore = class {
16138
16378
  // SessionStart-equivalent knowledge preamble, computed once at seedIfCold
16139
- constructor(client, bankId, cfg, harness = HARNESS) {
16379
+ constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
16140
16380
  this.client = client;
16141
16381
  this.bankId = bankId;
16142
16382
  this.cfg = cfg;
16143
16383
  this.harness = harness;
16384
+ this.projectDir = projectDir;
16144
16385
  setLogLevel(cfg.logLevel);
16145
16386
  }
16146
16387
  client;
16147
16388
  bankId;
16148
16389
  cfg;
16149
16390
  harness;
16391
+ projectDir;
16150
16392
  injection = /* @__PURE__ */ new Map();
16151
16393
  // sessionId -> this turn's injection block
16152
16394
  turnCount = /* @__PURE__ */ new Map();
16153
16395
  // sessionId -> user-turn counter (cadence)
16154
16396
  sessionState = /* @__PURE__ */ new Map();
16397
+ /** Live write-back cursors. In memory, unlike the hook harnesses': this host outlives the session. */
16398
+ cursors = memoryCursorStore();
16155
16399
  /** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
16156
16400
  fetchTranscript;
16157
16401
  lastInjection = "";
@@ -16307,7 +16551,15 @@ var RuntimeCore = class {
16307
16551
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
16308
16552
  retain(sessionId2, turns, startTs, trigger = "turn") {
16309
16553
  const t0 = Date.now();
16310
- void retainLiveSession(this.client, sessionId2, turns, startTs, this.harness).then(
16554
+ void retainLiveSession(this.client, sessionId2, turns, startTs, this.harness, {
16555
+ cursors: this.cursors,
16556
+ stamp: buildRetainStamp(this.cfg, {
16557
+ directory: this.projectDir,
16558
+ harness: this.harness,
16559
+ bankId: this.bankId,
16560
+ sessionId: sessionId2
16561
+ })
16562
+ }).then(
16311
16563
  () => diag(this.harness, "retain_ok", {
16312
16564
  ms: Date.now() - t0,
16313
16565
  turns: turns.length,
@@ -16430,7 +16682,7 @@ function createRuntime(workspaceRoot) {
16430
16682
  apiToken: cfg.apiToken,
16431
16683
  bank: resolved.bankId
16432
16684
  });
16433
- return new RuntimeCore(client, resolved.bankId, cfg, HARNESS2);
16685
+ return new RuntimeCore(client, resolved.bankId, cfg, HARNESS2, workspaceRoot || process.cwd());
16434
16686
  }
16435
16687
  var plugin = {
16436
16688
  name: "hindsight-coding-agents",