@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/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,6 +415,13 @@ 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));
@@ -422,6 +449,7 @@ var KnowledgePagesUnavailableError = class extends Error {
422
449
  }
423
450
  };
424
451
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
452
+ var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
425
453
  var HindsightClient = class {
426
454
  apiUrl;
427
455
  apiToken;
@@ -538,12 +566,39 @@ var HindsightClient = class {
538
566
  await this.req("DELETE", this.bankUrl());
539
567
  this.log(`[bank] reset ${this.bank}`);
540
568
  }
541
- 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
+ );
542
575
  this.log(
543
- `[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}`
544
577
  );
545
578
  await this.seedPages();
546
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
+ }
547
602
  /** Delete one document (cascades its memory units/links). Used by deepen's self-cleanup. */
548
603
  async deleteDocument(documentId) {
549
604
  await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
@@ -15911,14 +15966,14 @@ function serialize(cursors, sessionId2, write2) {
15911
15966
  }
15912
15967
  async function retainLiveSession(client, sessionId2, turns, startTs, harness, opts = {}) {
15913
15968
  const cursors = opts.cursors;
15914
- if (!cursors) return writeSession(client, sessionId2, turns, startTs, harness);
15969
+ if (!cursors) return writeSession(client, sessionId2, turns, startTs, harness, opts.stamp);
15915
15970
  return serialize(
15916
15971
  cursors,
15917
15972
  sessionId2,
15918
- () => writeSession(client, sessionId2, turns, startTs, harness, cursors)
15973
+ () => writeSession(client, sessionId2, turns, startTs, harness, opts.stamp, cursors)
15919
15974
  );
15920
15975
  }
15921
- async function writeSession(client, sessionId2, turns, startTs, harness, cursors) {
15976
+ async function writeSession(client, sessionId2, turns, startTs, harness, stamp, cursors) {
15922
15977
  const refId = `conversation:${sessionId2}`;
15923
15978
  const appendSupported = Boolean(cursors) && await supportsAppend(client);
15924
15979
  const plan = planRetain(turns, cursors?.read(sessionId2), { appendSupported, bank: client.bank });
@@ -15934,7 +15989,15 @@ async function writeSession(client, sessionId2, turns, startTs, harness, cursors
15934
15989
  content,
15935
15990
  "coding agent session",
15936
15991
  refId,
15937
- ["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
+ ],
15938
16001
  "conversation",
15939
16002
  {
15940
16003
  timestamp: startTs,
@@ -15946,6 +16009,8 @@ ${refId}
15946
16009
  ${plan.mode}
15947
16010
  ${content}`),
15948
16011
  metadata: {
16012
+ ...stamp?.metadata,
16013
+ // configured first: the built-ins below win on any key collision
15949
16014
  source: "chat",
15950
16015
  session_id: sessionId2,
15951
16016
  ref_id: refId,
@@ -15956,6 +16021,53 @@ ${content}`),
15956
16021
  cursors?.write(sessionId2, next);
15957
16022
  }
15958
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 };
16069
+ }
16070
+
15959
16071
  // src/core/session-start.ts
15960
16072
  import { readFileSync as readFileSync4 } from "fs";
15961
16073
 
@@ -16264,17 +16376,19 @@ async function buildHookOutput(args) {
16264
16376
  var HARNESS = "opencode";
16265
16377
  var RuntimeCore = class {
16266
16378
  // SessionStart-equivalent knowledge preamble, computed once at seedIfCold
16267
- constructor(client, bankId, cfg, harness = HARNESS) {
16379
+ constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
16268
16380
  this.client = client;
16269
16381
  this.bankId = bankId;
16270
16382
  this.cfg = cfg;
16271
16383
  this.harness = harness;
16384
+ this.projectDir = projectDir;
16272
16385
  setLogLevel(cfg.logLevel);
16273
16386
  }
16274
16387
  client;
16275
16388
  bankId;
16276
16389
  cfg;
16277
16390
  harness;
16391
+ projectDir;
16278
16392
  injection = /* @__PURE__ */ new Map();
16279
16393
  // sessionId -> this turn's injection block
16280
16394
  turnCount = /* @__PURE__ */ new Map();
@@ -16438,7 +16552,13 @@ var RuntimeCore = class {
16438
16552
  retain(sessionId2, turns, startTs, trigger = "turn") {
16439
16553
  const t0 = Date.now();
16440
16554
  void retainLiveSession(this.client, sessionId2, turns, startTs, this.harness, {
16441
- cursors: this.cursors
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
+ })
16442
16562
  }).then(
16443
16563
  () => diag(this.harness, "retain_ok", {
16444
16564
  ms: Date.now() - t0,
@@ -16562,7 +16682,7 @@ function createRuntime(workspaceRoot) {
16562
16682
  apiToken: cfg.apiToken,
16563
16683
  bank: resolved.bankId
16564
16684
  });
16565
- return new RuntimeCore(client, resolved.bankId, cfg, HARNESS2);
16685
+ return new RuntimeCore(client, resolved.bankId, cfg, HARNESS2, workspaceRoot || process.cwd());
16566
16686
  }
16567
16687
  var plugin = {
16568
16688
  name: "hindsight-coding-agents",
@@ -7,9 +7,25 @@ import { existsSync, readFileSync as readFileSync3 } from "fs";
7
7
  import { execFileSync } from "child_process";
8
8
  import { homedir } from "os";
9
9
  import { basename, dirname, join, normalize, sep } from "path";
10
+
11
+ // src/core/template.ts
12
+ var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
13
+ function applyTemplate(template, resolvers, what) {
14
+ return template.replace(PLACEHOLDER, (_, name) => {
15
+ const resolve2 = resolvers[name];
16
+ if (!resolve2) {
17
+ console.error(
18
+ `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
19
+ );
20
+ return "unknown";
21
+ }
22
+ return resolve2();
23
+ });
24
+ }
25
+
26
+ // src/core/bank.ts
10
27
  var DEFAULT_BANK_NAME = "coding";
11
28
  var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
12
- var PLACEHOLDER = /\{([a-zA-Z]+)\}/g;
13
29
  function getProjectRootFromGit(directory) {
14
30
  if (!directory) return null;
15
31
  try {
@@ -55,16 +71,7 @@ function deriveBankId(config, directory, harness = "coding") {
55
71
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
56
72
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
57
73
  };
58
- return (config.bankIdTemplate || DEFAULT_TEMPLATE).replace(PLACEHOLDER, (_, name) => {
59
- const r = resolvers[name];
60
- if (!r) {
61
- console.error(
62
- `hindsight: unknown bankIdTemplate placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
63
- );
64
- return "unknown";
65
- }
66
- return r();
67
- });
74
+ return applyTemplate(config.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
68
75
  }
69
76
 
70
77
  // src/core/config.ts
@@ -144,6 +151,12 @@ function resolveConfig(raw = {}) {
144
151
  surveyBudgetUsd: raw.surveyBudgetUsd || 2,
145
152
  surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
146
153
  gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
154
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
155
+ // nested object cannot reach the API as a tag and fail the whole retain.
156
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
157
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
158
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
159
+ ) : {},
147
160
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
148
161
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
149
162
  };
@@ -197,7 +210,10 @@ var ENV_KEYS = {
197
210
  surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
198
211
  surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
199
212
  logLevel: "HINDSIGHT_LOG_LEVEL",
200
- gitIngest: "HINDSIGHT_GIT_INGEST"
213
+ gitIngest: "HINDSIGHT_GIT_INGEST",
214
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
215
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
216
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
201
217
  };
202
218
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
203
219
  "dynamicBankId",
@@ -208,6 +224,7 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
208
224
  "autoSeed",
209
225
  "codebaseSurvey"
210
226
  ]);
227
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags"]);
211
228
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
212
229
  "apiPort",
213
230
  "daemonIdleTimeout",
@@ -225,6 +242,9 @@ function readEnvConfig(env = process.env) {
225
242
  if (value === void 0 || value.trim() === "") continue;
226
243
  if (ENV_BOOLEANS.has(key)) {
227
244
  out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
245
+ } else if (ENV_LISTS.has(key)) {
246
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
247
+ if (items.length) out[key] = items;
228
248
  } else if (ENV_NUMBERS.has(key)) {
229
249
  const n = Number(value);
230
250
  if (Number.isFinite(n)) out[key] = n;
@@ -439,6 +459,13 @@ var CODING_BANK_TEMPLATE = {
439
459
  entities_allow_free_form: true
440
460
  }
441
461
  };
462
+ var CODING_BANK_STRUCTURE = {
463
+ version: "1",
464
+ bank: {
465
+ retain_strategies: RETAIN_STRATEGIES,
466
+ entity_labels: [KNOWLEDGE_LABELS]
467
+ }
468
+ };
442
469
 
443
470
  // src/core/util.ts
444
471
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -466,6 +493,7 @@ var KnowledgePagesUnavailableError = class extends Error {
466
493
  }
467
494
  };
468
495
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
496
+ var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
469
497
  var HindsightClient = class {
470
498
  apiUrl;
471
499
  apiToken;
@@ -582,12 +610,39 @@ var HindsightClient = class {
582
610
  await this.req("DELETE", this.bankUrl());
583
611
  this.log(`[bank] reset ${this.bank}`);
584
612
  }
585
- await this.req("POST", this.bankUrl("/import"), CODING_BANK_TEMPLATE);
613
+ const seeded = opts.reset ? false : await this.hasBankMissions();
614
+ await this.req(
615
+ "POST",
616
+ this.bankUrl("/import"),
617
+ seeded ? CODING_BANK_STRUCTURE : CODING_BANK_TEMPLATE
618
+ );
586
619
  this.log(
587
- `[bank] template applied to ${this.bank}: missions, entity_labels {knowledge}, strategies {git, gitlog, conversation, document}`
620
+ 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}`
588
621
  );
589
622
  await this.seedPages();
590
623
  }
624
+ /**
625
+ * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
626
+ * the user's own edit. Either way they are not ours to overwrite.
627
+ *
628
+ * Reads the bank-scoped OVERRIDES, not the resolved config, so inherited global defaults don't
629
+ * read as "already set". A missing bank, or a deployment with the bank-config API switched off,
630
+ * answers false: there is nothing to preserve, and without that API a user cannot set per-bank
631
+ * missions in the first place.
632
+ */
633
+ async hasBankMissions() {
634
+ try {
635
+ const r = await this.req("GET", this.bankUrl("/config"));
636
+ if (!r.ok) return false;
637
+ const j = await r.json();
638
+ return MISSION_FIELDS.some((f) => {
639
+ const v = j.overrides?.[f];
640
+ return typeof v === "string" && v.trim() !== "";
641
+ });
642
+ } catch {
643
+ return false;
644
+ }
645
+ }
591
646
  /** Delete one document (cascades its memory units/links). Used by deepen's self-cleanup. */
592
647
  async deleteDocument(documentId) {
593
648
  await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
@@ -1086,6 +1141,9 @@ import { execFileSync as execFileSync2, spawn as realSpawn2 } from "child_proces
1086
1141
  import { dirname as dirname5, join as join6 } from "path";
1087
1142
  import { fileURLToPath as fileURLToPath2 } from "url";
1088
1143
 
1144
+ // src/core/retain-stamp.ts
1145
+ import { basename as basename2 } from "path";
1146
+
1089
1147
  // src/core/jsonl.ts
1090
1148
  import { closeSync, openSync, readSync, statSync } from "fs";
1091
1149
  import { StringDecoder } from "string_decoder";
@@ -1148,7 +1206,7 @@ function* streamLines(path, start) {
1148
1206
  }
1149
1207
 
1150
1208
  // src/core/transcript-util.ts
1151
- 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;
1209
+ 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;
1152
1210
  function stripInjectedMemory(s) {
1153
1211
  return s.replace(MEMORY_TAG_RE, "");
1154
1212
  }
@@ -7,9 +7,25 @@ import { existsSync, readFileSync as readFileSync3 } from "fs";
7
7
  import { execFileSync } from "child_process";
8
8
  import { homedir } from "os";
9
9
  import { basename, dirname, join, normalize, sep } from "path";
10
+
11
+ // src/core/template.ts
12
+ var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
13
+ function applyTemplate(template, resolvers, what) {
14
+ return template.replace(PLACEHOLDER, (_, name) => {
15
+ const resolve2 = resolvers[name];
16
+ if (!resolve2) {
17
+ console.error(
18
+ `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
19
+ );
20
+ return "unknown";
21
+ }
22
+ return resolve2();
23
+ });
24
+ }
25
+
26
+ // src/core/bank.ts
10
27
  var DEFAULT_BANK_NAME = "coding";
11
28
  var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
12
- var PLACEHOLDER = /\{([a-zA-Z]+)\}/g;
13
29
  function getProjectRootFromGit(directory) {
14
30
  if (!directory) return null;
15
31
  try {
@@ -55,16 +71,7 @@ function deriveBankId(config, directory, harness = "coding") {
55
71
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
56
72
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
57
73
  };
58
- return (config.bankIdTemplate || DEFAULT_TEMPLATE).replace(PLACEHOLDER, (_, name) => {
59
- const r = resolvers[name];
60
- if (!r) {
61
- console.error(
62
- `hindsight: unknown bankIdTemplate placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
63
- );
64
- return "unknown";
65
- }
66
- return r();
67
- });
74
+ return applyTemplate(config.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
68
75
  }
69
76
 
70
77
  // src/core/config.ts
@@ -144,6 +151,12 @@ function resolveConfig(raw = {}) {
144
151
  surveyBudgetUsd: raw.surveyBudgetUsd || 2,
145
152
  surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
146
153
  gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
154
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
155
+ // nested object cannot reach the API as a tag and fail the whole retain.
156
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
157
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
158
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
159
+ ) : {},
147
160
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
148
161
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
149
162
  };
@@ -197,7 +210,10 @@ var ENV_KEYS = {
197
210
  surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
198
211
  surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
199
212
  logLevel: "HINDSIGHT_LOG_LEVEL",
200
- gitIngest: "HINDSIGHT_GIT_INGEST"
213
+ gitIngest: "HINDSIGHT_GIT_INGEST",
214
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
215
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
216
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
201
217
  };
202
218
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
203
219
  "dynamicBankId",
@@ -208,6 +224,7 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
208
224
  "autoSeed",
209
225
  "codebaseSurvey"
210
226
  ]);
227
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags"]);
211
228
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
212
229
  "apiPort",
213
230
  "daemonIdleTimeout",
@@ -225,6 +242,9 @@ function readEnvConfig(env = process.env) {
225
242
  if (value === void 0 || value.trim() === "") continue;
226
243
  if (ENV_BOOLEANS.has(key)) {
227
244
  out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
245
+ } else if (ENV_LISTS.has(key)) {
246
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
247
+ if (items.length) out[key] = items;
228
248
  } else if (ENV_NUMBERS.has(key)) {
229
249
  const n = Number(value);
230
250
  if (Number.isFinite(n)) out[key] = n;
@@ -439,6 +459,13 @@ var CODING_BANK_TEMPLATE = {
439
459
  entities_allow_free_form: true
440
460
  }
441
461
  };
462
+ var CODING_BANK_STRUCTURE = {
463
+ version: "1",
464
+ bank: {
465
+ retain_strategies: RETAIN_STRATEGIES,
466
+ entity_labels: [KNOWLEDGE_LABELS]
467
+ }
468
+ };
442
469
 
443
470
  // src/core/util.ts
444
471
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -466,6 +493,7 @@ var KnowledgePagesUnavailableError = class extends Error {
466
493
  }
467
494
  };
468
495
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
496
+ var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
469
497
  var HindsightClient = class {
470
498
  apiUrl;
471
499
  apiToken;
@@ -582,12 +610,39 @@ var HindsightClient = class {
582
610
  await this.req("DELETE", this.bankUrl());
583
611
  this.log(`[bank] reset ${this.bank}`);
584
612
  }
585
- await this.req("POST", this.bankUrl("/import"), CODING_BANK_TEMPLATE);
613
+ const seeded = opts.reset ? false : await this.hasBankMissions();
614
+ await this.req(
615
+ "POST",
616
+ this.bankUrl("/import"),
617
+ seeded ? CODING_BANK_STRUCTURE : CODING_BANK_TEMPLATE
618
+ );
586
619
  this.log(
587
- `[bank] template applied to ${this.bank}: missions, entity_labels {knowledge}, strategies {git, gitlog, conversation, document}`
620
+ 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}`
588
621
  );
589
622
  await this.seedPages();
590
623
  }
624
+ /**
625
+ * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
626
+ * the user's own edit. Either way they are not ours to overwrite.
627
+ *
628
+ * Reads the bank-scoped OVERRIDES, not the resolved config, so inherited global defaults don't
629
+ * read as "already set". A missing bank, or a deployment with the bank-config API switched off,
630
+ * answers false: there is nothing to preserve, and without that API a user cannot set per-bank
631
+ * missions in the first place.
632
+ */
633
+ async hasBankMissions() {
634
+ try {
635
+ const r = await this.req("GET", this.bankUrl("/config"));
636
+ if (!r.ok) return false;
637
+ const j = await r.json();
638
+ return MISSION_FIELDS.some((f) => {
639
+ const v = j.overrides?.[f];
640
+ return typeof v === "string" && v.trim() !== "";
641
+ });
642
+ } catch {
643
+ return false;
644
+ }
645
+ }
591
646
  /** Delete one document (cascades its memory units/links). Used by deepen's self-cleanup. */
592
647
  async deleteDocument(documentId) {
593
648
  await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
@@ -1046,6 +1101,9 @@ function preflightDaemon(cfg, harness) {
1046
1101
  return true;
1047
1102
  }
1048
1103
 
1104
+ // src/core/retain-stamp.ts
1105
+ import { basename as basename2 } from "path";
1106
+
1049
1107
  // src/core/jsonl.ts
1050
1108
  import { closeSync, openSync, readSync, statSync } from "fs";
1051
1109
  import { StringDecoder } from "string_decoder";
@@ -1108,7 +1166,7 @@ function* streamLines(path, start) {
1108
1166
  }
1109
1167
 
1110
1168
  // src/core/transcript-util.ts
1111
- 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;
1169
+ 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;
1112
1170
  function stripInjectedMemory(s) {
1113
1171
  return s.replace(MEMORY_TAG_RE, "");
1114
1172
  }