@vectorize-io/hindsight-coding-agents 0.2.1 → 0.3.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.
@@ -4406,11 +4406,11 @@ var require_core = __commonJS({
4406
4406
  Ajv2.ValidationError = validation_error_1.default;
4407
4407
  Ajv2.MissingRefError = ref_error_1.default;
4408
4408
  exports.default = Ajv2;
4409
- function checkOptions(checkOpts, options, msg, log = "error") {
4409
+ function checkOptions(checkOpts, options, msg, log2 = "error") {
4410
4410
  for (const key in checkOpts) {
4411
4411
  const opt = key;
4412
4412
  if (opt in options)
4413
- this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
4413
+ this.logger[log2](`${msg}: option ${key}. ${checkOpts[opt]}`);
4414
4414
  }
4415
4415
  }
4416
4416
  function getSchEnv(keyRef) {
@@ -30959,8 +30959,8 @@ var StdioServerTransport = class {
30959
30959
 
30960
30960
  // src/core/config.ts
30961
30961
  import { readFileSync } from "fs";
30962
- import { homedir } from "os";
30963
- import { join as join2 } from "path";
30962
+ import { homedir as homedir2 } from "os";
30963
+ import { join as join3 } from "path";
30964
30964
 
30965
30965
  // src/core/seed.ts
30966
30966
  import { spawn as realSpawn } from "child_process";
@@ -30968,8 +30968,117 @@ import { dirname, join } from "path";
30968
30968
  import { fileURLToPath } from "url";
30969
30969
  var DEFAULT_SEED_LIMIT = 300;
30970
30970
 
30971
+ // src/core/bank.ts
30972
+ import { execFileSync } from "child_process";
30973
+ import { existsSync } from "fs";
30974
+ import { homedir } from "os";
30975
+ import { basename, dirname as dirname2, join as join2, normalize, sep } from "path";
30976
+
30977
+ // src/core/template.ts
30978
+ var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
30979
+ function applyTemplate(template, resolvers, what) {
30980
+ return template.replace(PLACEHOLDER, (_, name) => {
30981
+ const resolve2 = resolvers[name];
30982
+ if (!resolve2) {
30983
+ console.error(
30984
+ `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
30985
+ );
30986
+ return "unknown";
30987
+ }
30988
+ return resolve2();
30989
+ });
30990
+ }
30991
+
30992
+ // src/core/bank.ts
30993
+ var DEFAULT_BANK_NAME = "coding";
30994
+ var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
30995
+ function getProjectRootFromGit(directory) {
30996
+ if (!directory) return null;
30997
+ try {
30998
+ const commonDir = execFileSync(
30999
+ "git",
31000
+ ["rev-parse", "--path-format=absolute", "--git-common-dir"],
31001
+ { cwd: directory, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 1e3 }
31002
+ ).trim();
31003
+ if (!commonDir) return null;
31004
+ return basename(commonDir) === ".git" ? dirname2(commonDir) : commonDir;
31005
+ } catch {
31006
+ return null;
31007
+ }
31008
+ }
31009
+ function projectNameOf(directory) {
31010
+ return gitProjectName(directory, true);
31011
+ }
31012
+ var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
31013
+ function nearestExistingDir(directory) {
31014
+ let current2 = directory;
31015
+ while (current2) {
31016
+ if (existsSync(current2)) return current2;
31017
+ const parent = dirname2(current2);
31018
+ if (parent === current2) return "";
31019
+ current2 = parent;
31020
+ }
31021
+ return "";
31022
+ }
31023
+ function dirName(directory) {
31024
+ return directory && basename(directory) || "unknown";
31025
+ }
31026
+ function gitProjectName(directory, resolveWorktrees) {
31027
+ if (resolveWorktrees) {
31028
+ const candidates = [
31029
+ nearestExistingDir(directory),
31030
+ ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
31031
+ ];
31032
+ for (const candidate of candidates) {
31033
+ const root = candidate ? getProjectRootFromGit(candidate) : null;
31034
+ if (root) return basename(root);
31035
+ }
31036
+ }
31037
+ return dirName(directory);
31038
+ }
31039
+ function configuredDir(dir) {
31040
+ const expanded = dir === "~" || dir.startsWith("~/") ? join2(homedir(), dir.slice(1)) : dir;
31041
+ return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
31042
+ }
31043
+ function isWithin(directory, configured) {
31044
+ return directory === configured || directory.startsWith(configured + sep);
31045
+ }
31046
+ function mapLookup(map2, directory) {
31047
+ const cwd = normalize(directory);
31048
+ let best;
31049
+ for (const [dir, bank] of Object.entries(map2)) {
31050
+ const p = configuredDir(dir);
31051
+ if (isWithin(cwd, p)) {
31052
+ if (!best || p.length > best.len) best = { len: p.length, bank };
31053
+ }
31054
+ }
31055
+ return best?.bank;
31056
+ }
31057
+ function isOptedIn(config2, directory) {
31058
+ if (!config2.optInOnly) return true;
31059
+ if (!directory) return false;
31060
+ const cwd = normalize(directory);
31061
+ if ((config2.optInPaths ?? []).some((dir) => dir && isWithin(cwd, configuredDir(dir))))
31062
+ return true;
31063
+ return Boolean(config2.mapPathToBank && mapLookup(config2.mapPathToBank, directory));
31064
+ }
31065
+ function deriveBankId(config2, directory, harness = "coding") {
31066
+ const mapped = directory && config2.mapPathToBank ? mapLookup(config2.mapPathToBank, directory) : void 0;
31067
+ if (mapped) return mapped;
31068
+ const dynamic = config2.dynamicBankId ?? !config2.bankId;
31069
+ if (!dynamic) return config2.bankId || DEFAULT_BANK_NAME;
31070
+ const resolvers = {
31071
+ harness: () => harness,
31072
+ project: () => dirName(directory),
31073
+ gitProject: () => gitProjectName(directory, config2.resolveWorktrees ?? true),
31074
+ channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
31075
+ user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
31076
+ };
31077
+ return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
31078
+ }
31079
+
30971
31080
  // src/core/config.ts
30972
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join2(homedir(), ".hindsight", "coding-agent.json");
31081
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
30973
31082
  var DEFAULT_DAEMON_PORT = 9077;
30974
31083
  var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
30975
31084
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
@@ -30993,11 +31102,14 @@ function resolveConfig(raw = {}) {
30993
31102
  bankIdTemplate: raw.bankIdTemplate,
30994
31103
  mapPathToBank: raw.mapPathToBank,
30995
31104
  resolveWorktrees: raw.resolveWorktrees,
31105
+ optInOnly: raw.optInOnly ?? false,
31106
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
31107
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
30996
31108
  harness: raw.harness ?? "opencode",
30997
31109
  disabled: raw.disabled ?? false,
30998
31110
  retainSessions: raw.retainSessions ?? true,
30999
31111
  // opencode: write back by default (parity with hook-harness Stop)
31000
- retainEveryTurns: raw.retainEveryTurns || 1,
31112
+ maxParallelRetains: raw.maxParallelRetains || 10,
31001
31113
  reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
31002
31114
  autoReflect: raw.autoReflect ?? true,
31003
31115
  pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
@@ -31053,10 +31165,12 @@ var ENV_KEYS = {
31053
31165
  dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
31054
31166
  bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
31055
31167
  resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
31168
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
31169
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
31056
31170
  harness: "HINDSIGHT_HARNESS",
31057
31171
  disabled: "HINDSIGHT_DISABLED",
31058
31172
  retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
31059
- retainEveryTurns: "HINDSIGHT_RETAIN_EVERY_TURNS",
31173
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
31060
31174
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
31061
31175
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
31062
31176
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
@@ -31075,17 +31189,18 @@ var ENV_KEYS = {
31075
31189
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
31076
31190
  "dynamicBankId",
31077
31191
  "resolveWorktrees",
31192
+ "optInOnly",
31078
31193
  "disabled",
31079
31194
  "retainSessions",
31080
31195
  "autoReflect",
31081
31196
  "autoSeed",
31082
31197
  "codebaseSurvey"
31083
31198
  ]);
31084
- var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags"]);
31199
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
31085
31200
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
31086
31201
  "apiPort",
31087
31202
  "daemonIdleTimeout",
31088
- "retainEveryTurns",
31203
+ "maxParallelRetains",
31089
31204
  "reflectTimeoutMs",
31090
31205
  "pageRefreshEveryTurns",
31091
31206
  "seedLimit",
@@ -31125,9 +31240,15 @@ var BANK_OVERRIDE_EXCLUDED = [
31125
31240
  "mapPathToBank",
31126
31241
  "dynamicBankId",
31127
31242
  "resolveWorktrees",
31243
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
31244
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
31245
+ "optInOnly",
31246
+ "optInPaths",
31128
31247
  "harness"
31129
31248
  ];
31130
- function applyBankConfig(cfg, resolvedId) {
31249
+ function applyBankConfig(cfg, resolvedId, directory) {
31250
+ if (directory !== void 0 && !isOptedIn(cfg, directory))
31251
+ return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
31131
31252
  const section = cfg.banks[resolvedId];
31132
31253
  if (!section) return { cfg, bankId: resolvedId };
31133
31254
  const safe = { ...section };
@@ -31147,80 +31268,6 @@ function resolvePartial(cfg, patch) {
31147
31268
  return out;
31148
31269
  }
31149
31270
 
31150
- // src/core/bank.ts
31151
- import { execFileSync } from "child_process";
31152
- import { homedir as homedir2 } from "os";
31153
- import { basename, dirname as dirname2, join as join3, normalize, sep } from "path";
31154
-
31155
- // src/core/template.ts
31156
- var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
31157
- function applyTemplate(template, resolvers, what) {
31158
- return template.replace(PLACEHOLDER, (_, name) => {
31159
- const resolve2 = resolvers[name];
31160
- if (!resolve2) {
31161
- console.error(
31162
- `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
31163
- );
31164
- return "unknown";
31165
- }
31166
- return resolve2();
31167
- });
31168
- }
31169
-
31170
- // src/core/bank.ts
31171
- var DEFAULT_BANK_NAME = "coding";
31172
- var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
31173
- function getProjectRootFromGit(directory) {
31174
- if (!directory) return null;
31175
- try {
31176
- const commonDir = execFileSync(
31177
- "git",
31178
- ["rev-parse", "--path-format=absolute", "--git-common-dir"],
31179
- { cwd: directory, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 1e3 }
31180
- ).trim();
31181
- if (!commonDir) return null;
31182
- return basename(commonDir) === ".git" ? dirname2(commonDir) : commonDir;
31183
- } catch {
31184
- return null;
31185
- }
31186
- }
31187
- function projectNameOf(directory) {
31188
- return gitProjectName(directory, true);
31189
- }
31190
- function gitProjectName(directory, resolveWorktrees) {
31191
- if (resolveWorktrees) {
31192
- const root = getProjectRootFromGit(directory);
31193
- if (root) return basename(root);
31194
- }
31195
- return directory ? basename(directory) : "unknown";
31196
- }
31197
- function mapLookup(map2, directory) {
31198
- const cwd = normalize(directory);
31199
- let best;
31200
- for (const [dir, bank] of Object.entries(map2)) {
31201
- const expanded = dir === "~" || dir.startsWith("~/") ? join3(homedir2(), dir.slice(1)) : dir;
31202
- const p = normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
31203
- if (cwd === p || cwd.startsWith(p + sep)) {
31204
- if (!best || p.length > best.len) best = { len: p.length, bank };
31205
- }
31206
- }
31207
- return best?.bank;
31208
- }
31209
- function deriveBankId(config2, directory, harness = "coding") {
31210
- const mapped = directory && config2.mapPathToBank ? mapLookup(config2.mapPathToBank, directory) : void 0;
31211
- if (mapped) return mapped;
31212
- const dynamic = config2.dynamicBankId ?? !config2.bankId;
31213
- if (!dynamic) return config2.bankId || DEFAULT_BANK_NAME;
31214
- const resolvers = {
31215
- harness: () => harness,
31216
- project: () => directory ? basename(directory) : "unknown",
31217
- gitProject: () => gitProjectName(directory, config2.resolveWorktrees ?? true),
31218
- channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
31219
- user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
31220
- };
31221
- return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
31222
- }
31223
-
31224
31271
  // src/core/missions.ts
31225
31272
  var GIT_MISSION = "You are ingesting a single git commit: its message and its full diff. Extract the concrete technical DECISION and the CAUSE/INVARIANT it encodes, bound to the specific code entities (functions, methods, files) and behaviors it changes. Preserve exact identifiers, paths, and literal values verbatim. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Capture both WHAT changed and WHY. Issue/PR references (#123, GH-123, PROJ-123) are load-bearing: keep them VERBATIM in the fact text and emit each as an ENTITY, so a later question about that issue or PR retrieves this decision.";
31226
31273
  var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, newest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
@@ -31365,9 +31412,40 @@ function semverGte(version2, min) {
31365
31412
  }
31366
31413
  return true;
31367
31414
  }
31415
+ async function pool(items, n, fn, onError, onProgress) {
31416
+ let i = 0, done = 0;
31417
+ async function worker() {
31418
+ while (i < items.length) {
31419
+ const idx = i++;
31420
+ try {
31421
+ await fn(items[idx], idx);
31422
+ } catch (e) {
31423
+ onError?.(idx, e);
31424
+ }
31425
+ onProgress?.(++done, items.length);
31426
+ }
31427
+ }
31428
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
31429
+ }
31368
31430
 
31369
31431
  // src/core/hindsight.ts
31370
31432
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
31433
+ var RateLimitedError = class extends Error {
31434
+ constructor(retryAfterMs2) {
31435
+ super(`rate limited; retry after ${Math.round(retryAfterMs2 / 1e3)}s`);
31436
+ this.retryAfterMs = retryAfterMs2;
31437
+ this.name = "RateLimitedError";
31438
+ }
31439
+ retryAfterMs;
31440
+ code = "rate_limited";
31441
+ };
31442
+ function retryAfterMs(header) {
31443
+ if (!header) return 0;
31444
+ const secs = Number(header.trim());
31445
+ if (Number.isFinite(secs) && secs >= 0) return secs * 1e3;
31446
+ const at = Date.parse(header);
31447
+ return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
31448
+ }
31371
31449
  var KnowledgePagesUnavailableError = class extends Error {
31372
31450
  code = "knowledge_pages_unavailable";
31373
31451
  constructor() {
@@ -31376,6 +31454,10 @@ var KnowledgePagesUnavailableError = class extends Error {
31376
31454
  }
31377
31455
  };
31378
31456
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
31457
+ var DEFAULT_MAX_PARALLEL_RETAINS = 10;
31458
+ var POLL_CYCLE_MS = 5e3;
31459
+ var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
31460
+ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
31379
31461
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
31380
31462
  var HindsightClient = class {
31381
31463
  apiUrl;
@@ -31388,12 +31470,14 @@ var HindsightClient = class {
31388
31470
  /** Tri-state capability probe: unknown until the first append-mode retain, then cached. */
31389
31471
  idempotentRetain;
31390
31472
  log;
31473
+ maxParallelRetains;
31391
31474
  constructor(o) {
31392
31475
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
31393
31476
  this.apiToken = o.apiToken;
31394
31477
  this.bank = o.bank;
31395
31478
  this.log = o.log ?? (() => {
31396
31479
  });
31480
+ this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
31397
31481
  }
31398
31482
  headers() {
31399
31483
  const h = { "Content-Type": "application/json" };
@@ -31411,6 +31495,8 @@ var HindsightClient = class {
31411
31495
  body: body ? JSON.stringify(body) : void 0,
31412
31496
  signal: AbortSignal.timeout(15e3)
31413
31497
  });
31498
+ if (r.status === 429 && !tolerate.includes(429))
31499
+ throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
31414
31500
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
31415
31501
  throw new Error(`${method} ${url2} -> ${r.status} ${await r.text()}`);
31416
31502
  return r;
@@ -31542,7 +31628,14 @@ var HindsightClient = class {
31542
31628
  return 0;
31543
31629
  }
31544
31630
  }
31545
- /** Poll each enqueued operation by id until terminal. LIST only shows active ops, so per-id GET is reliable. */
31631
+ /**
31632
+ * Poll each enqueued operation by id until terminal. LIST only shows active ops, so per-id GET is reliable.
31633
+ *
31634
+ * Concurrency is capped at `maxParallelRetains` (the API rate-limits bursts, not single
31635
+ * requests — a 200 to a lone GET with 429s under `Promise.all` over every pending op). A 429
31636
+ * leaves the op pending and backs the next cycle off by its `Retry-After` (10s floor) instead
31637
+ * of hammering the next cycle 5s later.
31638
+ */
31546
31639
  async drain(ids, label, maxMs = 60 * 60 * 1e3) {
31547
31640
  if (!ids.length) return;
31548
31641
  this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
@@ -31550,23 +31643,29 @@ var HindsightClient = class {
31550
31643
  const pending = new Set(ids);
31551
31644
  let failed = 0;
31552
31645
  while (pending.size && Date.now() - start < maxMs) {
31553
- await Promise.all(
31554
- [...pending].map(async (id) => {
31555
- try {
31556
- const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
31557
- if (!r.ok) return;
31558
- const st = ((await r.json()).status || "").toLowerCase();
31559
- if (TERMINAL.has(st)) {
31560
- pending.delete(id);
31561
- if (st !== "completed") failed++;
31562
- }
31563
- } catch {
31646
+ let backoffMs = POLL_CYCLE_MS;
31647
+ await pool([...pending], this.maxParallelRetains, async (id) => {
31648
+ try {
31649
+ const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
31650
+ if (r.status === 429) {
31651
+ backoffMs = Math.min(
31652
+ RETRY_AFTER_CEILING_MS,
31653
+ Math.max(backoffMs, RETRY_AFTER_FLOOR_MS, retryAfterMs(r.headers.get("retry-after")))
31654
+ );
31655
+ return;
31564
31656
  }
31565
- })
31566
- );
31657
+ if (!r.ok) return;
31658
+ const st = ((await r.json()).status || "").toLowerCase();
31659
+ if (TERMINAL.has(st)) {
31660
+ pending.delete(id);
31661
+ if (st !== "completed") failed++;
31662
+ }
31663
+ } catch {
31664
+ }
31665
+ });
31567
31666
  if (pending.size) {
31568
31667
  this.log(` \u2026 ${pending.size}/${ids.length} ${label} ops pending`);
31569
- await sleep(5e3);
31668
+ await sleep(backoffMs);
31570
31669
  }
31571
31670
  }
31572
31671
  this.log(
@@ -31766,13 +31865,20 @@ var HindsightClient = class {
31766
31865
  const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
31767
31866
  const content = `${verb}: ${args.title}. ${args.summary}`;
31768
31867
  const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
31769
- await this.retain(
31770
- content,
31771
- "initiative marker",
31772
- markerId,
31773
- ["knowledge:feature-work", `relatedPageId:${pageId}`],
31774
- "document"
31775
- );
31868
+ const tags = [
31869
+ .../* @__PURE__ */ new Set([
31870
+ ...args.stamp?.tags ?? [],
31871
+ "knowledge:feature-work",
31872
+ `relatedPageId:${pageId}`
31873
+ ])
31874
+ ];
31875
+ if (Object.keys(args.stamp?.metadata ?? {}).length) {
31876
+ await this.retain(content, "initiative marker", markerId, tags, "document", {
31877
+ metadata: args.stamp?.metadata
31878
+ });
31879
+ } else {
31880
+ await this.retain(content, "initiative marker", markerId, tags, "document");
31881
+ }
31776
31882
  return { page_id: pageId };
31777
31883
  }
31778
31884
  /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
@@ -31795,7 +31901,7 @@ var HindsightClient = class {
31795
31901
  };
31796
31902
 
31797
31903
  // src/core/knowledge-tools.ts
31798
- import { existsSync as existsSync2 } from "fs";
31904
+ import { existsSync as existsSync3 } from "fs";
31799
31905
  import { homedir as homedir4 } from "os";
31800
31906
  import { join as join5 } from "path";
31801
31907
 
@@ -31835,7 +31941,7 @@ function parsePageList(raw) {
31835
31941
 
31836
31942
  // src/core/survey.ts
31837
31943
  import { spawn as realSpawn2 } from "child_process";
31838
- import { accessSync, constants, existsSync } from "fs";
31944
+ import { accessSync, constants, existsSync as existsSync2 } from "fs";
31839
31945
  import { homedir as homedir3 } from "os";
31840
31946
  import { delimiter, dirname as dirname3, join as join4 } from "path";
31841
31947
  import { fileURLToPath as fileURLToPath2 } from "url";
@@ -31950,7 +32056,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
31950
32056
  workspace: opts.repoDir ?? process.cwd(),
31951
32057
  config: {
31952
32058
  path: configPath,
31953
- exists: existsSync2(configPath),
32059
+ exists: existsSync3(configPath),
31954
32060
  api_url: cfg.apiUrl,
31955
32061
  api_token_configured: Boolean(cfg.apiToken),
31956
32062
  disabled: cfg.disabled
@@ -32015,7 +32121,12 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
32015
32121
  relates_to_page_id: external_exports.string().optional()
32016
32122
  },
32017
32123
  handler: guarded(
32018
- async ({ title, summary, relates_to_page_id }) => client.captureInitiative({ title, summary, relatesToPageId: relates_to_page_id })
32124
+ async ({ title, summary, relates_to_page_id }) => client.captureInitiative({
32125
+ title,
32126
+ summary,
32127
+ relatesToPageId: relates_to_page_id,
32128
+ ...opts.stampFor ? { stamp: opts.stampFor() } : {}
32129
+ })
32019
32130
  )
32020
32131
  },
32021
32132
  {
@@ -32024,13 +32135,24 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
32024
32135
  inputSchema: { title: external_exports.string(), content: external_exports.string() },
32025
32136
  handler: guarded(async ({ title, content }) => {
32026
32137
  const docId = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "doc";
32138
+ const stamp = opts.stampFor?.();
32139
+ const metadata = {
32140
+ ...stamp?.metadata,
32141
+ ...opts.harness ? { harness: opts.harness } : {}
32142
+ };
32027
32143
  await client.retain(
32028
32144
  content,
32029
32145
  "ingested document",
32030
32146
  docId,
32031
- ["source:upload", ...opts.harness ? [`harness:${opts.harness}`] : []],
32147
+ [
32148
+ .../* @__PURE__ */ new Set([
32149
+ ...stamp?.tags ?? [],
32150
+ "source:upload",
32151
+ ...opts.harness ? [`harness:${opts.harness}`] : []
32152
+ ])
32153
+ ],
32032
32154
  "document",
32033
- { metadata: opts.harness ? { harness: opts.harness } : void 0 }
32155
+ Object.keys(metadata).length ? { metadata } : {}
32034
32156
  );
32035
32157
  return { ok: true, doc_id: docId };
32036
32158
  })
@@ -32038,18 +32160,106 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
32038
32160
  ];
32039
32161
  }
32040
32162
 
32163
+ // src/core/log.ts
32164
+ import { appendFileSync, mkdirSync } from "fs";
32165
+ import { tmpdir } from "os";
32166
+ import { dirname as dirname4, join as join6 } from "path";
32167
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
32168
+ var current = ["debug", "info", "warn", "error"].find(
32169
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
32170
+ ) ?? "info";
32171
+ function logFilePath() {
32172
+ return process.env.HINDSIGHT_LOG_FILE || join6(tmpdir(), "hindsight-coding-agent", "plugin.log");
32173
+ }
32174
+ function write(level, scope, msg, extra) {
32175
+ if (WEIGHT[level] < WEIGHT[current]) return;
32176
+ try {
32177
+ const file2 = logFilePath();
32178
+ mkdirSync(dirname4(file2), { recursive: true });
32179
+ appendFileSync(
32180
+ file2,
32181
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
32182
+ );
32183
+ } catch {
32184
+ }
32185
+ }
32186
+ var log = {
32187
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
32188
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
32189
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
32190
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
32191
+ };
32192
+
32193
+ // src/core/retain-stamp.ts
32194
+ import { basename as basename2 } from "path";
32195
+ var RESERVED_TAG_PREFIX = /^(source|harness):/;
32196
+ function resolversFor(ctx) {
32197
+ return {
32198
+ // Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
32199
+ // otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
32200
+ gitProject: () => projectNameOf(ctx.directory),
32201
+ project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
32202
+ harness: () => ctx.harness,
32203
+ bankId: () => ctx.bankId,
32204
+ sessionId: () => ctx.sessionId ?? "unknown",
32205
+ timestamp: () => (/* @__PURE__ */ new Date()).toISOString(),
32206
+ channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
32207
+ user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
32208
+ };
32209
+ }
32210
+ function buildRetainStamp(cfg, ctx) {
32211
+ const hasTags = Boolean(cfg.retainTags?.length);
32212
+ const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
32213
+ if (!hasTags && !hasMetadata) return { tags: [], metadata: {} };
32214
+ const base = resolversFor(ctx);
32215
+ const cache = /* @__PURE__ */ new Map();
32216
+ const resolvers = Object.fromEntries(
32217
+ Object.entries(base).map(([name, resolve2]) => [
32218
+ name,
32219
+ () => {
32220
+ const hit = cache.get(name);
32221
+ if (hit !== void 0) return hit;
32222
+ const value = resolve2();
32223
+ cache.set(name, value);
32224
+ return value;
32225
+ }
32226
+ ])
32227
+ );
32228
+ const tags = (cfg.retainTags ?? []).map((t) => applyTemplate(t, resolvers, "retainTags").trim()).filter(Boolean).filter((t) => {
32229
+ if (!RESERVED_TAG_PREFIX.test(t)) return true;
32230
+ log.warn("retain-stamp", "ignoring reserved retainTags entry", { tag: t });
32231
+ return false;
32232
+ });
32233
+ const metadata = {};
32234
+ for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
32235
+ metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
32236
+ }
32237
+ return { tags, metadata };
32238
+ }
32239
+
32041
32240
  // src/mcp-server.ts
32042
- function selectTools(cfg, client, bankId) {
32043
- return cfg.disabled ? [] : buildKnowledgeTools(client, bankId, { repoDir: process.cwd(), harness: cfg.harness });
32241
+ function selectTools(cfg, client, bankId, opts = {}) {
32242
+ const cwd = opts.cwd ?? process.cwd();
32243
+ const harness = opts.harness ?? cfg.harness;
32244
+ return cfg.disabled ? [] : buildKnowledgeTools(client, bankId, {
32245
+ repoDir: cwd,
32246
+ harness,
32247
+ stampFor: () => buildRetainStamp(cfg, { directory: cwd, harness, bankId })
32248
+ });
32044
32249
  }
32045
32250
  async function main() {
32046
32251
  const cwd = process.env.HINDSIGHT_MCP_PROJECT_CWD || process.cwd();
32047
32252
  const harness = process.env.HINDSIGHT_MCP_HARNESS || "claude-code";
32048
32253
  const cfg0 = loadConfig({ harness });
32049
- const { cfg, bankId } = applyBankConfig(cfg0, deriveBankId(cfg0, cwd, harness));
32050
- const client = new HindsightClient({ apiUrl: cfg.apiUrl, apiToken: cfg.apiToken, bank: bankId });
32254
+ const { cfg, bankId } = applyBankConfig(cfg0, deriveBankId(cfg0, cwd, harness), cwd);
32255
+ const client = new HindsightClient({
32256
+ apiUrl: cfg.apiUrl,
32257
+ apiToken: cfg.apiToken,
32258
+ bank: bankId,
32259
+ maxParallelRetains: cfg.maxParallelRetains
32260
+ });
32051
32261
  const server = new McpServer({ name: "hindsight", version: "0.1.0" });
32052
- for (const t of selectTools(cfg, client, bankId)) {
32262
+ for (const t of selectTools(cfg, client, bankId, { cwd, harness })) {
32053
32263
  server.tool(t.name, t.description, t.inputSchema, t.handler);
32054
32264
  }
32055
32265
  await server.connect(new StdioServerTransport());