@vectorize-io/hindsight-coding-agents 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -11,9 +11,25 @@ import { posix, win32 } from "path";
11
11
  import { execFileSync } from "child_process";
12
12
  import { homedir } from "os";
13
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
14
31
  var DEFAULT_BANK_NAME = "coding";
15
32
  var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
16
- var PLACEHOLDER = /\{([a-zA-Z]+)\}/g;
17
33
  function getProjectRootFromGit(directory) {
18
34
  if (!directory) return null;
19
35
  try {
@@ -62,16 +78,7 @@ function deriveBankId(config3, directory, harness = "coding") {
62
78
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
63
79
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
64
80
  };
65
- return (config3.bankIdTemplate || DEFAULT_TEMPLATE).replace(PLACEHOLDER, (_, name) => {
66
- const r = resolvers[name];
67
- if (!r) {
68
- console.error(
69
- `hindsight: unknown bankIdTemplate placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
70
- );
71
- return "unknown";
72
- }
73
- return r();
74
- });
81
+ return applyTemplate(config3.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
75
82
  }
76
83
 
77
84
  // src/core/config.ts
@@ -151,6 +158,12 @@ function resolveConfig(raw = {}) {
151
158
  surveyBudgetUsd: raw.surveyBudgetUsd || 2,
152
159
  surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
153
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
+ ) : {},
154
167
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
155
168
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
156
169
  };
@@ -204,7 +217,10 @@ var ENV_KEYS = {
204
217
  surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
205
218
  surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
206
219
  logLevel: "HINDSIGHT_LOG_LEVEL",
207
- 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"
208
224
  };
209
225
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
210
226
  "dynamicBankId",
@@ -215,6 +231,7 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
215
231
  "autoSeed",
216
232
  "codebaseSurvey"
217
233
  ]);
234
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags"]);
218
235
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
219
236
  "apiPort",
220
237
  "daemonIdleTimeout",
@@ -232,6 +249,9 @@ function readEnvConfig(env = process.env) {
232
249
  if (value === void 0 || value.trim() === "") continue;
233
250
  if (ENV_BOOLEANS.has(key)) {
234
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;
235
255
  } else if (ENV_NUMBERS.has(key)) {
236
256
  const n = Number(value);
237
257
  if (Number.isFinite(n)) out[key] = n;
@@ -431,6 +451,13 @@ var CODING_BANK_TEMPLATE = {
431
451
  entities_allow_free_form: true
432
452
  }
433
453
  };
454
+ var CODING_BANK_STRUCTURE = {
455
+ version: "1",
456
+ bank: {
457
+ retain_strategies: RETAIN_STRATEGIES,
458
+ entity_labels: [KNOWLEDGE_LABELS]
459
+ }
460
+ };
434
461
 
435
462
  // src/core/util.ts
436
463
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -458,6 +485,7 @@ var KnowledgePagesUnavailableError = class extends Error {
458
485
  }
459
486
  };
460
487
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
488
+ var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
461
489
  var HindsightClient = class {
462
490
  apiUrl;
463
491
  apiToken;
@@ -574,12 +602,39 @@ var HindsightClient = class {
574
602
  await this.req("DELETE", this.bankUrl());
575
603
  this.log(`[bank] reset ${this.bank}`);
576
604
  }
577
- 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
+ );
578
611
  this.log(
579
- `[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}`
580
613
  );
581
614
  await this.seedPages();
582
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
+ }
583
638
  /** Delete one document (cascades its memory units/links). Used by deepen's self-cleanup. */
584
639
  async deleteDocument(documentId) {
585
640
  await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
@@ -15912,14 +15967,14 @@ function serialize(cursors, sessionId, write2) {
15912
15967
  }
15913
15968
  async function retainLiveSession(client, sessionId, turns, startTs, harness, opts = {}) {
15914
15969
  const cursors = opts.cursors;
15915
- if (!cursors) return writeSession(client, sessionId, turns, startTs, harness);
15970
+ if (!cursors) return writeSession(client, sessionId, turns, startTs, harness, opts.stamp);
15916
15971
  return serialize(
15917
15972
  cursors,
15918
15973
  sessionId,
15919
- () => writeSession(client, sessionId, turns, startTs, harness, cursors)
15974
+ () => writeSession(client, sessionId, turns, startTs, harness, opts.stamp, cursors)
15920
15975
  );
15921
15976
  }
15922
- async function writeSession(client, sessionId, turns, startTs, harness, cursors) {
15977
+ async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors) {
15923
15978
  const refId = `conversation:${sessionId}`;
15924
15979
  const appendSupported = Boolean(cursors) && await supportsAppend(client);
15925
15980
  const plan = planRetain(turns, cursors?.read(sessionId), { appendSupported, bank: client.bank });
@@ -15935,7 +15990,15 @@ async function writeSession(client, sessionId, turns, startTs, harness, cursors)
15935
15990
  content,
15936
15991
  "coding agent session",
15937
15992
  refId,
15938
- ["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
+ ],
15939
16002
  "conversation",
15940
16003
  {
15941
16004
  timestamp: startTs,
@@ -15947,6 +16010,8 @@ ${refId}
15947
16010
  ${plan.mode}
15948
16011
  ${content}`),
15949
16012
  metadata: {
16013
+ ...stamp?.metadata,
16014
+ // configured first: the built-ins below win on any key collision
15950
16015
  source: "chat",
15951
16016
  session_id: sessionId,
15952
16017
  ref_id: refId,
@@ -15957,6 +16022,53 @@ ${content}`),
15957
16022
  cursors?.write(sessionId, next);
15958
16023
  }
15959
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 };
16070
+ }
16071
+
15960
16072
  // src/core/session-start.ts
15961
16073
  import { readFileSync as readFileSync4 } from "fs";
15962
16074
 
@@ -16265,17 +16377,19 @@ async function buildHookOutput(args) {
16265
16377
  var HARNESS = "opencode";
16266
16378
  var RuntimeCore = class {
16267
16379
  // SessionStart-equivalent knowledge preamble, computed once at seedIfCold
16268
- constructor(client, bankId, cfg, harness = HARNESS) {
16380
+ constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
16269
16381
  this.client = client;
16270
16382
  this.bankId = bankId;
16271
16383
  this.cfg = cfg;
16272
16384
  this.harness = harness;
16385
+ this.projectDir = projectDir;
16273
16386
  setLogLevel(cfg.logLevel);
16274
16387
  }
16275
16388
  client;
16276
16389
  bankId;
16277
16390
  cfg;
16278
16391
  harness;
16392
+ projectDir;
16279
16393
  injection = /* @__PURE__ */ new Map();
16280
16394
  // sessionId -> this turn's injection block
16281
16395
  turnCount = /* @__PURE__ */ new Map();
@@ -16439,7 +16553,13 @@ var RuntimeCore = class {
16439
16553
  retain(sessionId, turns, startTs, trigger = "turn") {
16440
16554
  const t0 = Date.now();
16441
16555
  void retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
16442
- cursors: this.cursors
16556
+ cursors: this.cursors,
16557
+ stamp: buildRetainStamp(this.cfg, {
16558
+ directory: this.projectDir,
16559
+ harness: this.harness,
16560
+ bankId: this.bankId,
16561
+ sessionId
16562
+ })
16443
16563
  }).then(
16444
16564
  () => diag(this.harness, "retain_ok", {
16445
16565
  ms: Date.now() - t0,
@@ -16459,7 +16579,7 @@ var RuntimeCore = class {
16459
16579
  };
16460
16580
 
16461
16581
  // src/core/transcript-util.ts
16462
- 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;
16463
16583
  function stripInjectedMemory(s) {
16464
16584
  return s.replace(MEMORY_TAG_RE, "");
16465
16585
  }
@@ -29042,7 +29162,7 @@ function createPluginEntry(harness) {
29042
29162
  apiToken: cfg.apiToken,
29043
29163
  bank: bankId
29044
29164
  });
29045
- const core = new RuntimeCore(client, bankId, cfg, harness);
29165
+ const core = new RuntimeCore(client, bankId, cfg, harness, projectDir || process.cwd());
29046
29166
  const oc = input?.client;
29047
29167
  log.debug(harness, "toast channel", { wired: Boolean(oc?.tui?.showToast) });
29048
29168
  if (oc?.tui?.showToast) {
package/dist/installer.js CHANGED
@@ -168,6 +168,9 @@ function onPath(bin) {
168
168
  }
169
169
  }
170
170
 
171
+ // src/core/retain-stamp.ts
172
+ import { basename as basename2 } from "path";
173
+
171
174
  // src/core/jsonl.ts
172
175
  import { closeSync, openSync, readSync, statSync } from "fs";
173
176
  import { StringDecoder } from "string_decoder";
@@ -230,7 +233,7 @@ function* streamLines(path, start) {
230
233
  }
231
234
 
232
235
  // src/core/transcript-util.ts
233
- 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;
236
+ 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;
234
237
  function stripInjectedMemory(s) {
235
238
  return s.replace(MEMORY_TAG_RE, "");
236
239
  }
@@ -304,6 +307,7 @@ function readClaudeTranscript(path) {
304
307
  if (line.type !== "user" && line.type !== "assistant") continue;
305
308
  if (line.isMeta === true) continue;
306
309
  if (line.isSidechain === true) continue;
310
+ if (line.isCompactSummary === true) continue;
307
311
  if (typeof line.message !== "object" || line.message === null) continue;
308
312
  for (const rendered of renderLine(line.message.content, line.type)) {
309
313
  const turn = { role: rendered.role, content: rendered.content };
package/dist/kilo.js CHANGED
@@ -11,9 +11,25 @@ import { posix, win32 } from "path";
11
11
  import { execFileSync } from "child_process";
12
12
  import { homedir } from "os";
13
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
14
31
  var DEFAULT_BANK_NAME = "coding";
15
32
  var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
16
- var PLACEHOLDER = /\{([a-zA-Z]+)\}/g;
17
33
  function getProjectRootFromGit(directory) {
18
34
  if (!directory) return null;
19
35
  try {
@@ -62,16 +78,7 @@ function deriveBankId(config3, directory, harness = "coding") {
62
78
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
63
79
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
64
80
  };
65
- return (config3.bankIdTemplate || DEFAULT_TEMPLATE).replace(PLACEHOLDER, (_, name) => {
66
- const r = resolvers[name];
67
- if (!r) {
68
- console.error(
69
- `hindsight: unknown bankIdTemplate placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
70
- );
71
- return "unknown";
72
- }
73
- return r();
74
- });
81
+ return applyTemplate(config3.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
75
82
  }
76
83
 
77
84
  // src/core/config.ts
@@ -151,6 +158,12 @@ function resolveConfig(raw = {}) {
151
158
  surveyBudgetUsd: raw.surveyBudgetUsd || 2,
152
159
  surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
153
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
+ ) : {},
154
167
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
155
168
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
156
169
  };
@@ -204,7 +217,10 @@ var ENV_KEYS = {
204
217
  surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
205
218
  surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
206
219
  logLevel: "HINDSIGHT_LOG_LEVEL",
207
- 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"
208
224
  };
209
225
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
210
226
  "dynamicBankId",
@@ -215,6 +231,7 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
215
231
  "autoSeed",
216
232
  "codebaseSurvey"
217
233
  ]);
234
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags"]);
218
235
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
219
236
  "apiPort",
220
237
  "daemonIdleTimeout",
@@ -232,6 +249,9 @@ function readEnvConfig(env = process.env) {
232
249
  if (value === void 0 || value.trim() === "") continue;
233
250
  if (ENV_BOOLEANS.has(key)) {
234
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;
235
255
  } else if (ENV_NUMBERS.has(key)) {
236
256
  const n = Number(value);
237
257
  if (Number.isFinite(n)) out[key] = n;
@@ -431,6 +451,13 @@ var CODING_BANK_TEMPLATE = {
431
451
  entities_allow_free_form: true
432
452
  }
433
453
  };
454
+ var CODING_BANK_STRUCTURE = {
455
+ version: "1",
456
+ bank: {
457
+ retain_strategies: RETAIN_STRATEGIES,
458
+ entity_labels: [KNOWLEDGE_LABELS]
459
+ }
460
+ };
434
461
 
435
462
  // src/core/util.ts
436
463
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -458,6 +485,7 @@ var KnowledgePagesUnavailableError = class extends Error {
458
485
  }
459
486
  };
460
487
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
488
+ var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
461
489
  var HindsightClient = class {
462
490
  apiUrl;
463
491
  apiToken;
@@ -574,12 +602,39 @@ var HindsightClient = class {
574
602
  await this.req("DELETE", this.bankUrl());
575
603
  this.log(`[bank] reset ${this.bank}`);
576
604
  }
577
- 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
+ );
578
611
  this.log(
579
- `[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}`
580
613
  );
581
614
  await this.seedPages();
582
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
+ }
583
638
  /** Delete one document (cascades its memory units/links). Used by deepen's self-cleanup. */
584
639
  async deleteDocument(documentId) {
585
640
  await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
@@ -15912,14 +15967,14 @@ function serialize(cursors, sessionId, write2) {
15912
15967
  }
15913
15968
  async function retainLiveSession(client, sessionId, turns, startTs, harness, opts = {}) {
15914
15969
  const cursors = opts.cursors;
15915
- if (!cursors) return writeSession(client, sessionId, turns, startTs, harness);
15970
+ if (!cursors) return writeSession(client, sessionId, turns, startTs, harness, opts.stamp);
15916
15971
  return serialize(
15917
15972
  cursors,
15918
15973
  sessionId,
15919
- () => writeSession(client, sessionId, turns, startTs, harness, cursors)
15974
+ () => writeSession(client, sessionId, turns, startTs, harness, opts.stamp, cursors)
15920
15975
  );
15921
15976
  }
15922
- async function writeSession(client, sessionId, turns, startTs, harness, cursors) {
15977
+ async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors) {
15923
15978
  const refId = `conversation:${sessionId}`;
15924
15979
  const appendSupported = Boolean(cursors) && await supportsAppend(client);
15925
15980
  const plan = planRetain(turns, cursors?.read(sessionId), { appendSupported, bank: client.bank });
@@ -15935,7 +15990,15 @@ async function writeSession(client, sessionId, turns, startTs, harness, cursors)
15935
15990
  content,
15936
15991
  "coding agent session",
15937
15992
  refId,
15938
- ["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
+ ],
15939
16002
  "conversation",
15940
16003
  {
15941
16004
  timestamp: startTs,
@@ -15947,6 +16010,8 @@ ${refId}
15947
16010
  ${plan.mode}
15948
16011
  ${content}`),
15949
16012
  metadata: {
16013
+ ...stamp?.metadata,
16014
+ // configured first: the built-ins below win on any key collision
15950
16015
  source: "chat",
15951
16016
  session_id: sessionId,
15952
16017
  ref_id: refId,
@@ -15957,6 +16022,53 @@ ${content}`),
15957
16022
  cursors?.write(sessionId, next);
15958
16023
  }
15959
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 };
16070
+ }
16071
+
15960
16072
  // src/core/session-start.ts
15961
16073
  import { readFileSync as readFileSync4 } from "fs";
15962
16074
 
@@ -16265,17 +16377,19 @@ async function buildHookOutput(args) {
16265
16377
  var HARNESS = "opencode";
16266
16378
  var RuntimeCore = class {
16267
16379
  // SessionStart-equivalent knowledge preamble, computed once at seedIfCold
16268
- constructor(client, bankId, cfg, harness = HARNESS) {
16380
+ constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
16269
16381
  this.client = client;
16270
16382
  this.bankId = bankId;
16271
16383
  this.cfg = cfg;
16272
16384
  this.harness = harness;
16385
+ this.projectDir = projectDir;
16273
16386
  setLogLevel(cfg.logLevel);
16274
16387
  }
16275
16388
  client;
16276
16389
  bankId;
16277
16390
  cfg;
16278
16391
  harness;
16392
+ projectDir;
16279
16393
  injection = /* @__PURE__ */ new Map();
16280
16394
  // sessionId -> this turn's injection block
16281
16395
  turnCount = /* @__PURE__ */ new Map();
@@ -16439,7 +16553,13 @@ var RuntimeCore = class {
16439
16553
  retain(sessionId, turns, startTs, trigger = "turn") {
16440
16554
  const t0 = Date.now();
16441
16555
  void retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
16442
- cursors: this.cursors
16556
+ cursors: this.cursors,
16557
+ stamp: buildRetainStamp(this.cfg, {
16558
+ directory: this.projectDir,
16559
+ harness: this.harness,
16560
+ bankId: this.bankId,
16561
+ sessionId
16562
+ })
16443
16563
  }).then(
16444
16564
  () => diag(this.harness, "retain_ok", {
16445
16565
  ms: Date.now() - t0,
@@ -16459,7 +16579,7 @@ var RuntimeCore = class {
16459
16579
  };
16460
16580
 
16461
16581
  // src/core/transcript-util.ts
16462
- 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;
16463
16583
  function stripInjectedMemory(s) {
16464
16584
  return s.replace(MEMORY_TAG_RE, "");
16465
16585
  }
@@ -29042,7 +29162,7 @@ function createPluginEntry(harness) {
29042
29162
  apiToken: cfg.apiToken,
29043
29163
  bank: bankId
29044
29164
  });
29045
- const core = new RuntimeCore(client, bankId, cfg, harness);
29165
+ const core = new RuntimeCore(client, bankId, cfg, harness, projectDir || process.cwd());
29046
29166
  const oc = input?.client;
29047
29167
  log.debug(harness, "toast channel", { wired: Boolean(oc?.tui?.showToast) });
29048
29168
  if (oc?.tui?.showToast) {