@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.
@@ -87,6 +87,12 @@ function resolveConfig(raw = {}) {
87
87
  surveyBudgetUsd: raw.surveyBudgetUsd || 2,
88
88
  surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
89
89
  gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
90
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
91
+ // nested object cannot reach the API as a tag and fail the whole retain.
92
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
93
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
94
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
95
+ ) : {},
90
96
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
91
97
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
92
98
  };
@@ -140,7 +146,10 @@ var ENV_KEYS = {
140
146
  surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
141
147
  surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
142
148
  logLevel: "HINDSIGHT_LOG_LEVEL",
143
- gitIngest: "HINDSIGHT_GIT_INGEST"
149
+ gitIngest: "HINDSIGHT_GIT_INGEST",
150
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
151
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
152
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
144
153
  };
145
154
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
146
155
  "dynamicBankId",
@@ -151,6 +160,7 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
151
160
  "autoSeed",
152
161
  "codebaseSurvey"
153
162
  ]);
163
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags"]);
154
164
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
155
165
  "apiPort",
156
166
  "daemonIdleTimeout",
@@ -168,6 +178,9 @@ function readEnvConfig(env = process.env) {
168
178
  if (value === void 0 || value.trim() === "") continue;
169
179
  if (ENV_BOOLEANS.has(key)) {
170
180
  out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
181
+ } else if (ENV_LISTS.has(key)) {
182
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
183
+ if (items.length) out[key] = items;
171
184
  } else if (ENV_NUMBERS.has(key)) {
172
185
  const n = Number(value);
173
186
  if (Number.isFinite(n)) out[key] = n;
@@ -190,9 +203,25 @@ function loadConfig(opts = {}) {
190
203
  import { execFileSync } from "child_process";
191
204
  import { homedir as homedir2 } from "os";
192
205
  import { basename, dirname as dirname2, join as join3, normalize, sep } from "path";
206
+
207
+ // src/core/template.ts
208
+ var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
209
+ function applyTemplate(template, resolvers, what) {
210
+ return template.replace(PLACEHOLDER, (_, name) => {
211
+ const resolve = resolvers[name];
212
+ if (!resolve) {
213
+ console.error(
214
+ `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
215
+ );
216
+ return "unknown";
217
+ }
218
+ return resolve();
219
+ });
220
+ }
221
+
222
+ // src/core/bank.ts
193
223
  var DEFAULT_BANK_NAME = "coding";
194
224
  var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
195
- var PLACEHOLDER = /\{([a-zA-Z]+)\}/g;
196
225
  function getProjectRootFromGit(directory) {
197
226
  if (!directory) return null;
198
227
  try {
@@ -238,16 +267,7 @@ function deriveBankId(config, directory, harness = "coding") {
238
267
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
239
268
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
240
269
  };
241
- return (config.bankIdTemplate || DEFAULT_TEMPLATE).replace(PLACEHOLDER, (_, name) => {
242
- const r = resolvers[name];
243
- if (!r) {
244
- console.error(
245
- `hindsight: unknown bankIdTemplate placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
246
- );
247
- return "unknown";
248
- }
249
- return r();
250
- });
270
+ return applyTemplate(config.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
251
271
  }
252
272
 
253
273
  // src/hindsight-seed.ts
package/dist/index.js CHANGED
@@ -4,13 +4,32 @@ var __export = (target, all) => {
4
4
  __defProp(target, name, { get: all[name], enumerable: true });
5
5
  };
6
6
 
7
+ // src/harness/plugin-entry.ts
8
+ import { posix, win32 } from "path";
9
+
7
10
  // src/core/bank.ts
8
11
  import { execFileSync } from "child_process";
9
12
  import { homedir } from "os";
10
13
  import { basename, dirname, join, normalize, sep } from "path";
14
+
15
+ // src/core/template.ts
16
+ var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
17
+ function applyTemplate(template, resolvers, what) {
18
+ return template.replace(PLACEHOLDER, (_, name) => {
19
+ const resolve2 = resolvers[name];
20
+ if (!resolve2) {
21
+ console.error(
22
+ `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
23
+ );
24
+ return "unknown";
25
+ }
26
+ return resolve2();
27
+ });
28
+ }
29
+
30
+ // src/core/bank.ts
11
31
  var DEFAULT_BANK_NAME = "coding";
12
32
  var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
13
- var PLACEHOLDER = /\{([a-zA-Z]+)\}/g;
14
33
  function getProjectRootFromGit(directory) {
15
34
  if (!directory) return null;
16
35
  try {
@@ -59,16 +78,7 @@ function deriveBankId(config3, directory, harness = "coding") {
59
78
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
60
79
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
61
80
  };
62
- return (config3.bankIdTemplate || DEFAULT_TEMPLATE).replace(PLACEHOLDER, (_, name) => {
63
- const r = resolvers[name];
64
- if (!r) {
65
- console.error(
66
- `hindsight: unknown bankIdTemplate placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
67
- );
68
- return "unknown";
69
- }
70
- return r();
71
- });
81
+ return applyTemplate(config3.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
72
82
  }
73
83
 
74
84
  // src/core/config.ts
@@ -148,6 +158,12 @@ function resolveConfig(raw = {}) {
148
158
  surveyBudgetUsd: raw.surveyBudgetUsd || 2,
149
159
  surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
150
160
  gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
161
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
162
+ // nested object cannot reach the API as a tag and fail the whole retain.
163
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
164
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
165
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
166
+ ) : {},
151
167
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
152
168
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
153
169
  };
@@ -201,7 +217,10 @@ var ENV_KEYS = {
201
217
  surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
202
218
  surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
203
219
  logLevel: "HINDSIGHT_LOG_LEVEL",
204
- gitIngest: "HINDSIGHT_GIT_INGEST"
220
+ gitIngest: "HINDSIGHT_GIT_INGEST",
221
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
222
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
223
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
205
224
  };
206
225
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
207
226
  "dynamicBankId",
@@ -212,6 +231,7 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
212
231
  "autoSeed",
213
232
  "codebaseSurvey"
214
233
  ]);
234
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags"]);
215
235
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
216
236
  "apiPort",
217
237
  "daemonIdleTimeout",
@@ -229,6 +249,9 @@ function readEnvConfig(env = process.env) {
229
249
  if (value === void 0 || value.trim() === "") continue;
230
250
  if (ENV_BOOLEANS.has(key)) {
231
251
  out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
252
+ } else if (ENV_LISTS.has(key)) {
253
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
254
+ if (items.length) out[key] = items;
232
255
  } else if (ENV_NUMBERS.has(key)) {
233
256
  const n = Number(value);
234
257
  if (Number.isFinite(n)) out[key] = n;
@@ -428,11 +451,32 @@ var CODING_BANK_TEMPLATE = {
428
451
  entities_allow_free_form: true
429
452
  }
430
453
  };
454
+ var CODING_BANK_STRUCTURE = {
455
+ version: "1",
456
+ bank: {
457
+ retain_strategies: RETAIN_STRATEGIES,
458
+ entity_labels: [KNOWLEDGE_LABELS]
459
+ }
460
+ };
431
461
 
432
462
  // src/core/util.ts
433
463
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
464
+ function semverGte(version3, min) {
465
+ const parts = (v) => {
466
+ const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
467
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
468
+ };
469
+ const a = version3 ? parts(version3) : void 0;
470
+ const b = parts(min);
471
+ if (!a || !b) return false;
472
+ for (let i = 0; i < 3; i++) {
473
+ if (a[i] !== b[i]) return a[i] > b[i];
474
+ }
475
+ return true;
476
+ }
434
477
 
435
478
  // src/core/hindsight.ts
479
+ var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
436
480
  var KnowledgePagesUnavailableError = class extends Error {
437
481
  code = "knowledge_pages_unavailable";
438
482
  constructor() {
@@ -441,6 +485,7 @@ var KnowledgePagesUnavailableError = class extends Error {
441
485
  }
442
486
  };
443
487
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
488
+ var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
444
489
  var HindsightClient = class {
445
490
  apiUrl;
446
491
  apiToken;
@@ -449,6 +494,8 @@ var HindsightClient = class {
449
494
  // async operation ids collected by retain(), for drain()
450
495
  /** Tri-state capability probe: unknown until the first page request, then cached. */
451
496
  knowledgePagesSupported;
497
+ /** Tri-state capability probe: unknown until the first append-mode retain, then cached. */
498
+ idempotentRetain;
452
499
  log;
453
500
  constructor(o) {
454
501
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
@@ -477,7 +524,8 @@ var HindsightClient = class {
477
524
  throw new Error(`${method} ${url3} -> ${r.status} ${await r.text()}`);
478
525
  return r;
479
526
  }
480
- /** Retain one memory. Async by default: enqueue extraction server-side and collect its op-id for drain(). */
527
+ /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
528
+ * drain(). Nothing in this plugin can afford to block a coding agent's hook on extraction. */
481
529
  async retain(content, context, documentId, tags, strategy, opts = {}) {
482
530
  const item = {
483
531
  content,
@@ -488,14 +536,36 @@ var HindsightClient = class {
488
536
  };
489
537
  if (opts.timestamp) item.timestamp = opts.timestamp;
490
538
  if (opts.metadata) item.metadata = opts.metadata;
491
- const isAsync = opts.async !== false;
492
- const r = await this.req("POST", this.bankUrl("/memories"), { items: [item], async: isAsync });
493
- if (isAsync) {
494
- try {
495
- const j = await r.json();
496
- if (j.operation_id) this.opIds.push(j.operation_id);
497
- } catch {
498
- }
539
+ if (opts.updateMode) item.update_mode = opts.updateMode;
540
+ const body = { items: [item], async: true };
541
+ if (opts.operationId) body.operation_id = opts.operationId;
542
+ const r = await this.req("POST", this.bankUrl("/memories"), body);
543
+ try {
544
+ const j = await r.json();
545
+ if (j.operation_id) this.opIds.push(j.operation_id);
546
+ } catch {
547
+ }
548
+ }
549
+ /**
550
+ * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
551
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via GET /version; anything
552
+ * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
553
+ */
554
+ async supportsIdempotentRetain() {
555
+ if (this.idempotentRetain === void 0) {
556
+ this.idempotentRetain = await this.probeIdempotentRetain();
557
+ this.log(`server retain idempotency: ${this.idempotentRetain ? "supported" : "unavailable"}`);
558
+ }
559
+ return this.idempotentRetain;
560
+ }
561
+ async probeIdempotentRetain() {
562
+ try {
563
+ const r = await this.req("GET", `${this.apiUrl}/version`);
564
+ if (!r.ok) return false;
565
+ const j = await r.json();
566
+ return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
567
+ } catch {
568
+ return false;
499
569
  }
500
570
  }
501
571
  /**
@@ -532,12 +602,39 @@ var HindsightClient = class {
532
602
  await this.req("DELETE", this.bankUrl());
533
603
  this.log(`[bank] reset ${this.bank}`);
534
604
  }
535
- await this.req("POST", this.bankUrl("/import"), CODING_BANK_TEMPLATE);
605
+ const seeded = opts.reset ? false : await this.hasBankMissions();
606
+ await this.req(
607
+ "POST",
608
+ this.bankUrl("/import"),
609
+ seeded ? CODING_BANK_STRUCTURE : CODING_BANK_TEMPLATE
610
+ );
536
611
  this.log(
537
- `[bank] template applied to ${this.bank}: missions, entity_labels {knowledge}, strategies {git, gitlog, conversation, document}`
612
+ 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}`
538
613
  );
539
614
  await this.seedPages();
540
615
  }
616
+ /**
617
+ * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
618
+ * the user's own edit. Either way they are not ours to overwrite.
619
+ *
620
+ * Reads the bank-scoped OVERRIDES, not the resolved config, so inherited global defaults don't
621
+ * read as "already set". A missing bank, or a deployment with the bank-config API switched off,
622
+ * answers false: there is nothing to preserve, and without that API a user cannot set per-bank
623
+ * missions in the first place.
624
+ */
625
+ async hasBankMissions() {
626
+ try {
627
+ const r = await this.req("GET", this.bankUrl("/config"));
628
+ if (!r.ok) return false;
629
+ const j = await r.json();
630
+ return MISSION_FIELDS.some((f) => {
631
+ const v = j.overrides?.[f];
632
+ return typeof v === "string" && v.trim() !== "";
633
+ });
634
+ } catch {
635
+ return false;
636
+ }
637
+ }
541
638
  /** Delete one document (cascades its memory units/links). Used by deepen's self-cleanup. */
542
639
  async deleteDocument(documentId) {
543
640
  await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
@@ -783,8 +880,7 @@ var HindsightClient = class {
783
880
  "initiative marker",
784
881
  markerId,
785
882
  ["knowledge:feature-work", `relatedPageId:${pageId}`],
786
- "document",
787
- { async: true }
883
+ "document"
788
884
  );
789
885
  return { page_id: pageId };
790
886
  }
@@ -15789,7 +15885,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15789
15885
  docId,
15790
15886
  ["source:upload", ...opts.harness ? [`harness:${opts.harness}`] : []],
15791
15887
  "document",
15792
- { async: true, metadata: opts.harness ? { harness: opts.harness } : void 0 }
15888
+ { metadata: opts.harness ? { harness: opts.harness } : void 0 }
15793
15889
  );
15794
15890
  return { ok: true, doc_id: docId };
15795
15891
  })
@@ -15797,6 +15893,51 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15797
15893
  ];
15798
15894
  }
15799
15895
 
15896
+ // src/core/retain-cursor.ts
15897
+ import { createHash } from "crypto";
15898
+ function fingerprintTurns(turns, count) {
15899
+ const h = createHash("sha1").update(String(count));
15900
+ for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
15901
+ return h.digest("hex");
15902
+ }
15903
+ function planRetain(turns, cursor, opts) {
15904
+ if (!turns.length) return { mode: "skip" };
15905
+ if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
15906
+ if (cursor.bank !== opts.bank) return { mode: "replace" };
15907
+ if (cursor.turns > turns.length) return { mode: "replace" };
15908
+ if (fingerprintTurns(turns, cursor.turns) !== cursor.fingerprint) return { mode: "replace" };
15909
+ if (cursor.turns === turns.length) return { mode: "skip" };
15910
+ return { mode: "append", fromTurn: cursor.turns };
15911
+ }
15912
+ function memoryCursorStore() {
15913
+ const cursors = /* @__PURE__ */ new Map();
15914
+ return {
15915
+ read: (sessionId) => cursors.get(sessionId),
15916
+ write: (sessionId, cursor) => void cursors.set(sessionId, cursor)
15917
+ };
15918
+ }
15919
+
15920
+ // src/core/uuid.ts
15921
+ import { createHash as createHash2 } from "crypto";
15922
+ var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
15923
+ function uuidV5(name, namespace = HINDSIGHT_NAMESPACE) {
15924
+ const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
15925
+ if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
15926
+ const bytes = Buffer.from(
15927
+ createHash2("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
15928
+ );
15929
+ bytes[6] = bytes[6] & 15 | 80;
15930
+ bytes[8] = bytes[8] & 63 | 128;
15931
+ const hex5 = bytes.toString("hex");
15932
+ return [
15933
+ hex5.slice(0, 8),
15934
+ hex5.slice(8, 12),
15935
+ hex5.slice(12, 16),
15936
+ hex5.slice(16, 20),
15937
+ hex5.slice(20)
15938
+ ].join("-");
15939
+ }
15940
+
15800
15941
  // src/core/chat.ts
15801
15942
  function withRefId(refId, turns, baseTs) {
15802
15943
  return [{ role: "system", content: `REF-ID: ${refId}`, timestamp: baseTs }, ...turns];
@@ -15804,18 +15945,73 @@ function withRefId(refId, turns, baseTs) {
15804
15945
  function renderSessionJsonl(refId, turns, baseTs) {
15805
15946
  return withRefId(refId, turns, baseTs).map((t) => JSON.stringify(t)).join("\n");
15806
15947
  }
15807
- async function retainLiveSession(client, sessionId, turns, startTs, harness) {
15948
+ async function supportsAppend(client) {
15949
+ try {
15950
+ return await client.supportsIdempotentRetain();
15951
+ } catch {
15952
+ return false;
15953
+ }
15954
+ }
15955
+ var writeBacks = /* @__PURE__ */ new WeakMap();
15956
+ function serialize(cursors, sessionId, write2) {
15957
+ const perSession = writeBacks.get(cursors) ?? /* @__PURE__ */ new Map();
15958
+ writeBacks.set(cursors, perSession);
15959
+ const next = (perSession.get(sessionId) ?? Promise.resolve()).then(write2, write2);
15960
+ const tail = next.catch(() => {
15961
+ });
15962
+ perSession.set(sessionId, tail);
15963
+ void tail.then(() => {
15964
+ if (perSession.get(sessionId) === tail) perSession.delete(sessionId);
15965
+ });
15966
+ return next;
15967
+ }
15968
+ async function retainLiveSession(client, sessionId, turns, startTs, harness, opts = {}) {
15969
+ const cursors = opts.cursors;
15970
+ if (!cursors) return writeSession(client, sessionId, turns, startTs, harness, opts.stamp);
15971
+ return serialize(
15972
+ cursors,
15973
+ sessionId,
15974
+ () => writeSession(client, sessionId, turns, startTs, harness, opts.stamp, cursors)
15975
+ );
15976
+ }
15977
+ async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors) {
15808
15978
  const refId = `conversation:${sessionId}`;
15979
+ const appendSupported = Boolean(cursors) && await supportsAppend(client);
15980
+ const plan = planRetain(turns, cursors?.read(sessionId), { appendSupported, bank: client.bank });
15981
+ if (plan.mode === "skip") return;
15982
+ const content = plan.mode === "append" ? turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n") : renderSessionJsonl(refId, turns, startTs);
15983
+ const next = {
15984
+ turns: turns.length,
15985
+ fingerprint: fingerprintTurns(turns, turns.length),
15986
+ bank: client.bank
15987
+ };
15988
+ cursors?.write(sessionId, { ...next, dirty: true });
15809
15989
  await client.retain(
15810
- renderSessionJsonl(refId, turns, startTs),
15990
+ content,
15811
15991
  "coding agent session",
15812
15992
  refId,
15813
- ["source:chat", ...harness ? [`harness:${harness}`] : []],
15993
+ // Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
15994
+ // the documents list filters and draws its agent logo from, so a template cannot displace them.
15995
+ [
15996
+ .../* @__PURE__ */ new Set([
15997
+ ...stamp?.tags ?? [],
15998
+ "source:chat",
15999
+ ...harness ? [`harness:${harness}`] : []
16000
+ ])
16001
+ ],
15814
16002
  "conversation",
15815
16003
  {
15816
16004
  timestamp: startTs,
15817
- async: true,
16005
+ updateMode: plan.mode === "append" ? "append" : void 0,
16006
+ // Identity of THIS payload: a resubmission of the same bytes is collapsed server-side into
16007
+ // the original operation instead of extracting (or appending) twice.
16008
+ operationId: uuidV5(`${client.bank}
16009
+ ${refId}
16010
+ ${plan.mode}
16011
+ ${content}`),
15818
16012
  metadata: {
16013
+ ...stamp?.metadata,
16014
+ // configured first: the built-ins below win on any key collision
15819
16015
  source: "chat",
15820
16016
  session_id: sessionId,
15821
16017
  ref_id: refId,
@@ -15823,6 +16019,54 @@ async function retainLiveSession(client, sessionId, turns, startTs, harness) {
15823
16019
  }
15824
16020
  }
15825
16021
  );
16022
+ cursors?.write(sessionId, next);
16023
+ }
16024
+
16025
+ // src/core/retain-stamp.ts
16026
+ import { basename as basename2 } from "path";
16027
+ var RESERVED_TAG_PREFIX = /^(source|harness):/;
16028
+ function resolversFor(ctx) {
16029
+ return {
16030
+ // Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
16031
+ // otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
16032
+ gitProject: () => projectNameOf(ctx.directory),
16033
+ project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
16034
+ harness: () => ctx.harness,
16035
+ bankId: () => ctx.bankId,
16036
+ sessionId: () => ctx.sessionId,
16037
+ timestamp: () => (/* @__PURE__ */ new Date()).toISOString(),
16038
+ channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
16039
+ user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
16040
+ };
16041
+ }
16042
+ function buildRetainStamp(cfg, ctx) {
16043
+ const hasTags = Boolean(cfg.retainTags?.length);
16044
+ const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
16045
+ if (!hasTags && !hasMetadata) return { tags: [], metadata: {} };
16046
+ const base = resolversFor(ctx);
16047
+ const cache = /* @__PURE__ */ new Map();
16048
+ const resolvers = Object.fromEntries(
16049
+ Object.entries(base).map(([name, resolve2]) => [
16050
+ name,
16051
+ () => {
16052
+ const hit = cache.get(name);
16053
+ if (hit !== void 0) return hit;
16054
+ const value = resolve2();
16055
+ cache.set(name, value);
16056
+ return value;
16057
+ }
16058
+ ])
16059
+ );
16060
+ const tags = (cfg.retainTags ?? []).map((t) => applyTemplate(t, resolvers, "retainTags").trim()).filter(Boolean).filter((t) => {
16061
+ if (!RESERVED_TAG_PREFIX.test(t)) return true;
16062
+ log.warn("retain-stamp", "ignoring reserved retainTags entry", { tag: t });
16063
+ return false;
16064
+ });
16065
+ const metadata = {};
16066
+ for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
16067
+ metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
16068
+ }
16069
+ return { tags, metadata };
15826
16070
  }
15827
16071
 
15828
16072
  // src/core/session-start.ts
@@ -15924,8 +16168,7 @@ async function buildSessionStartContext(args) {
15924
16168
  "hindsight codebase-survey baseline",
15925
16169
  `${SURVEY_BASELINE_PREFIX}${sha}`,
15926
16170
  [SURVEY_BASELINE_TAG],
15927
- "survey",
15928
- { async: true }
16171
+ "survey"
15929
16172
  )
15930
16173
  ).catch(() => {
15931
16174
  });
@@ -16134,22 +16377,26 @@ async function buildHookOutput(args) {
16134
16377
  var HARNESS = "opencode";
16135
16378
  var RuntimeCore = class {
16136
16379
  // SessionStart-equivalent knowledge preamble, computed once at seedIfCold
16137
- constructor(client, bankId, cfg, harness = HARNESS) {
16380
+ constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
16138
16381
  this.client = client;
16139
16382
  this.bankId = bankId;
16140
16383
  this.cfg = cfg;
16141
16384
  this.harness = harness;
16385
+ this.projectDir = projectDir;
16142
16386
  setLogLevel(cfg.logLevel);
16143
16387
  }
16144
16388
  client;
16145
16389
  bankId;
16146
16390
  cfg;
16147
16391
  harness;
16392
+ projectDir;
16148
16393
  injection = /* @__PURE__ */ new Map();
16149
16394
  // sessionId -> this turn's injection block
16150
16395
  turnCount = /* @__PURE__ */ new Map();
16151
16396
  // sessionId -> user-turn counter (cadence)
16152
16397
  sessionState = /* @__PURE__ */ new Map();
16398
+ /** Live write-back cursors. In memory, unlike the hook harnesses': this host outlives the session. */
16399
+ cursors = memoryCursorStore();
16153
16400
  /** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
16154
16401
  fetchTranscript;
16155
16402
  lastInjection = "";
@@ -16305,7 +16552,15 @@ var RuntimeCore = class {
16305
16552
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
16306
16553
  retain(sessionId, turns, startTs, trigger = "turn") {
16307
16554
  const t0 = Date.now();
16308
- void retainLiveSession(this.client, sessionId, turns, startTs, this.harness).then(
16555
+ void retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
16556
+ cursors: this.cursors,
16557
+ stamp: buildRetainStamp(this.cfg, {
16558
+ directory: this.projectDir,
16559
+ harness: this.harness,
16560
+ bankId: this.bankId,
16561
+ sessionId
16562
+ })
16563
+ }).then(
16309
16564
  () => diag(this.harness, "retain_ok", {
16310
16565
  ms: Date.now() - t0,
16311
16566
  turns: turns.length,
@@ -16324,7 +16579,7 @@ var RuntimeCore = class {
16324
16579
  };
16325
16580
 
16326
16581
  // src/core/transcript-util.ts
16327
- var MEMORY_TAG_RE = /<(hook_prompt|hindsight_memory|hindsight_memories|hindsight_bank|relevant_memories|user_feedback|hindsight_knowledge|hindsight_knowledge_refresh)\b[\s\S]*?<\/\1>/g;
16582
+ var MEMORY_TAG_RE = /<(hook_prompt|task-notification|system-reminder|hindsight_memory|hindsight_memories|hindsight_bank|relevant_memories|user_feedback|hindsight_knowledge|hindsight_knowledge_refresh)\b[\s\S]*?<\/\1>/g;
16328
16583
  function stripInjectedMemory(s) {
16329
16584
  return s.replace(MEMORY_TAG_RE, "");
16330
16585
  }
@@ -28886,9 +29141,16 @@ var opencodeAdapter = { name: "opencode", chatReader, createRuntime };
28886
29141
 
28887
29142
  // src/harness/plugin-entry.ts
28888
29143
  var TOAST_MOUNT_GRACE_MS = 3e3;
29144
+ function isFilesystemRoot(path) {
29145
+ return posix.parse(path).root === path || win32.parse(path).root === path;
29146
+ }
29147
+ function resolveProjectDirectory(input) {
29148
+ const worktree = input?.worktree;
29149
+ return worktree && !isFilesystemRoot(worktree) ? worktree : input?.directory;
29150
+ }
28889
29151
  function createPluginEntry(harness) {
28890
29152
  return async (input) => {
28891
- const projectDir = input?.worktree || input?.directory;
29153
+ const projectDir = resolveProjectDirectory(input);
28892
29154
  let cfg = loadConfig({ harness });
28893
29155
  if (cfg.disabled) return {};
28894
29156
  const resolved = applyBankConfig(cfg, deriveBankId(cfg, projectDir || process.cwd(), harness));
@@ -28900,7 +29162,7 @@ function createPluginEntry(harness) {
28900
29162
  apiToken: cfg.apiToken,
28901
29163
  bank: bankId
28902
29164
  });
28903
- const core = new RuntimeCore(client, bankId, cfg, harness);
29165
+ const core = new RuntimeCore(client, bankId, cfg, harness, projectDir || process.cwd());
28904
29166
  const oc = input?.client;
28905
29167
  log.debug(harness, "toast channel", { wired: Boolean(oc?.tui?.showToast) });
28906
29168
  if (oc?.tui?.showToast) {