@vectorize-io/hindsight-coding-agents 0.3.4 → 0.4.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/deepen.js CHANGED
@@ -44,8 +44,8 @@ function getProjectRootFromGit(directory) {
44
44
  return null;
45
45
  }
46
46
  }
47
- function projectNameOf(directory) {
48
- return gitProjectName(directory, true);
47
+ function projectNameOf(directory, sessionRoot) {
48
+ return gitProjectName(directory, true, sessionRoot);
49
49
  }
50
50
  var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
51
51
  function nearestExistingDir(directory) {
@@ -61,18 +61,24 @@ function nearestExistingDir(directory) {
61
61
  function dirName(directory) {
62
62
  return directory && basename(directory) || "unknown";
63
63
  }
64
- function gitProjectName(directory, resolveWorktrees) {
64
+ function mainWorktreeRoot(directory, sessionRoot = "") {
65
+ const candidates = [
66
+ nearestExistingDir(directory),
67
+ sessionRoot,
68
+ ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
69
+ ];
70
+ for (const candidate of candidates) {
71
+ const root = candidate ? getProjectRootFromGit(candidate) : null;
72
+ if (root) return root;
73
+ }
74
+ return null;
75
+ }
76
+ function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
65
77
  if (resolveWorktrees) {
66
- const candidates = [
67
- nearestExistingDir(directory),
68
- ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
69
- ];
70
- for (const candidate of candidates) {
71
- const root = candidate ? getProjectRootFromGit(candidate) : null;
72
- if (root) return basename(root);
73
- }
78
+ const root = mainWorktreeRoot(directory, sessionRoot);
79
+ if (root) return basename(root);
74
80
  }
75
- return dirName(directory);
81
+ return dirName(sessionRoot || directory);
76
82
  }
77
83
  function configuredDir(dir) {
78
84
  const expanded = dir === "~" || dir.startsWith("~/") ? join(homedir(), dir.slice(1)) : dir;
@@ -92,23 +98,38 @@ function mapLookup(map, directory) {
92
98
  }
93
99
  return best?.bank;
94
100
  }
101
+ function lookupDirectories(config, directory, sessionRoot = "") {
102
+ const directories = [normalize(directory)];
103
+ if (config.resolveWorktrees ?? true) {
104
+ const root = mainWorktreeRoot(directory, sessionRoot);
105
+ const normalizedRoot = root ? normalize(root) : "";
106
+ if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
107
+ }
108
+ return directories;
109
+ }
95
110
  function isOptedIn(config, directory) {
96
111
  if (!config.optInOnly) return true;
97
112
  if (!directory) return false;
98
- const cwd = normalize(directory);
99
- if ((config.optInPaths ?? []).some((dir) => dir && isWithin(cwd, configuredDir(dir))))
113
+ const directories = lookupDirectories(config, directory);
114
+ if (directories.some(
115
+ (candidate) => (config.optInPaths ?? []).some(
116
+ (configured) => configured && isWithin(candidate, configuredDir(configured))
117
+ )
118
+ ))
100
119
  return true;
101
- return Boolean(config.mapPathToBank && mapLookup(config.mapPathToBank, directory));
120
+ const pathMap = config.mapPathToBank;
121
+ return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
102
122
  }
103
- function deriveBankId(config, directory, harness = "coding") {
104
- const mapped = directory && config.mapPathToBank ? mapLookup(config.mapPathToBank, directory) : void 0;
123
+ function deriveBankId(config, directory, harness = "coding", sessionRoot) {
124
+ const pathMap = config.mapPathToBank;
125
+ const mapped = directory && pathMap ? lookupDirectories(config, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0) : void 0;
105
126
  if (mapped) return mapped;
106
127
  const dynamic = config.dynamicBankId ?? !config.bankId;
107
128
  if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
108
129
  const resolvers = {
109
130
  harness: () => harness,
110
131
  project: () => dirName(directory),
111
- gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true),
132
+ gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true, sessionRoot),
112
133
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
113
134
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
114
135
  };
@@ -190,7 +211,10 @@ var KNOWLEDGE_LABELS = {
190
211
  }
191
212
  ]
192
213
  };
193
- var PAGES = [
214
+ function pageScopeRule(project) {
215
+ return ` Scope this page to ${project} ITSELF: the bank also holds facts about external tools, libraries and services that ${project} merely uses, configures, deploys or discusses, and those belong to somebody else's codebase. Include something only when its subject is ${project}'s own code, configuration or process; when it is about a dependency, leave it out however well-evidenced it looks \u2014 including any commit SHA or identifier that belongs to that dependency's repository rather than this one.`;
216
+ }
217
+ var PAGE_TAXONOMY = [
194
218
  {
195
219
  name: "Component map",
196
220
  source_query: "From this project's commit history and past discussions, what are the main components/modules/subsystems, what is each responsible for, and how do they relate to or depend on one another? Describe the structure and responsibilities.",
@@ -213,15 +237,28 @@ var PAGES = [
213
237
  },
214
238
  {
215
239
  name: "Initiatives and enhancements",
216
- source_query: "Based on this repository's commit history, what are the major initiatives, features, and enhancements the project has worked on? Summarize the themes and notable changes over time. When a source memory carries a tag of the form `relatedPageId:<id>`, include a Markdown link `[[page:<id>]]` to that page in the summary, so each initiative links to its detailed page.",
240
+ source_query: "Based on this repository's commit history, what are the major initiatives, features, and enhancements the project has worked on? Summarize the themes and notable changes over time. When a source memory's context carries a `[[page:<id>]]` link, repeat that link in the summary of what it describes, so each initiative links to its detailed page.",
217
241
  tags: ["knowledge:feature-work"]
218
242
  }
219
243
  ];
244
+ function pagesFor(project) {
245
+ const scope = pageScopeRule(project);
246
+ return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
247
+ }
220
248
  var PAGE_MAX_TOKENS = 4096;
221
- var PAGE_TRIGGER = {
222
- fact_types: ["world", "experience", "observation"],
223
- refresh_after_consolidation: true
224
- };
249
+ var PAGE_TAGS_MATCH = "all";
250
+ var PAGE_FACT_TYPES = ["world", "experience", "observation"];
251
+ function buildPageTrigger(cfg2 = {}) {
252
+ const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
253
+ switch (cfg2.pageTriggerType) {
254
+ case "cron":
255
+ return { ...base, refresh_cron: cfg2.pageTriggerCron };
256
+ case "manual":
257
+ return { ...base, refresh_after_consolidation: false };
258
+ default:
259
+ return { ...base, refresh_after_consolidation: true };
260
+ }
261
+ }
225
262
  var CODING_BANK_TEMPLATE = {
226
263
  version: "1",
227
264
  bank: {
@@ -276,6 +313,7 @@ async function pool(items, n, fn, onError, onProgress) {
276
313
  }
277
314
 
278
315
  // src/core/hindsight.ts
316
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
279
317
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
280
318
  var RateLimitedError = class extends Error {
281
319
  constructor(retryAfterMs2) {
@@ -308,8 +346,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
308
346
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
309
347
  var HindsightClient = class {
310
348
  apiUrl;
311
- apiToken;
349
+ /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
350
+ * diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
351
+ token;
352
+ tokenProvider;
312
353
  bank;
354
+ project;
313
355
  opIds = [];
314
356
  // async operation ids collected by retain(), for drain()
315
357
  /** Tri-state capability probe: unknown until the first page request, then cached. */
@@ -318,34 +360,81 @@ var HindsightClient = class {
318
360
  idempotentRetain;
319
361
  log;
320
362
  maxParallelRetains;
363
+ observationScopes;
321
364
  constructor(o) {
322
365
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
323
- this.apiToken = o.apiToken;
366
+ this.token = o.apiToken;
367
+ this.tokenProvider = o.tokenProvider;
324
368
  this.bank = o.bank;
369
+ this.project = o.project;
325
370
  this.log = o.log ?? (() => {
326
371
  });
327
372
  this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
373
+ this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
374
+ }
375
+ /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
376
+ get apiToken() {
377
+ return this.token;
328
378
  }
329
379
  headers() {
330
380
  const h = { "Content-Type": "application/json" };
331
- if (this.apiToken) h["Authorization"] = `Bearer ${this.apiToken}`;
381
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
332
382
  return h;
333
383
  }
384
+ /** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
385
+ * only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
386
+ * doubling every failing request. */
387
+ refreshToken() {
388
+ if (!this.tokenProvider) return false;
389
+ let next;
390
+ try {
391
+ next = this.tokenProvider();
392
+ } catch {
393
+ return false;
394
+ }
395
+ if (next === this.token) return false;
396
+ this.token = next;
397
+ return true;
398
+ }
399
+ /**
400
+ * The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
401
+ * poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
402
+ * failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
403
+ * not.
404
+ *
405
+ * On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
406
+ * string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
407
+ * free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
408
+ * bounds the whole call.
409
+ */
410
+ async fetchWithAuth(url, init) {
411
+ const send = () => fetch(url, { ...init, headers: this.headers() });
412
+ const r = await send();
413
+ if (r.status !== 401 || !this.refreshToken()) return r;
414
+ return send();
415
+ }
416
+ /** A 401 with no `Authorization` header is a different failure from a rejected key, and the
417
+ * server answers identically for both — only the client knows which it sent. */
418
+ authHint(status) {
419
+ if (status !== 401) return "";
420
+ return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
421
+ }
334
422
  bankUrl(suffix = "") {
335
423
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
336
424
  }
337
425
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
338
426
  async req(method, url, body, tolerate = []) {
339
- const r = await fetch(url, {
427
+ const r = await this.fetchWithAuth(url, {
340
428
  method,
341
- headers: this.headers(),
342
429
  body: body ? JSON.stringify(body) : void 0,
343
430
  signal: AbortSignal.timeout(15e3)
344
431
  });
345
432
  if (r.status === 429 && !tolerate.includes(429))
346
433
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
347
434
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
348
- throw new Error(`${method} ${url} -> ${r.status} ${await r.text()}`);
435
+ throw new Error(
436
+ `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
437
+ );
349
438
  return r;
350
439
  }
351
440
  /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
@@ -356,7 +445,11 @@ var HindsightClient = class {
356
445
  context,
357
446
  document_id: documentId,
358
447
  tags,
359
- strategy
448
+ strategy,
449
+ // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
450
+ // observations were built under is a property of the write rather than of whichever server
451
+ // version happened to process it. Servers older than 0.4.15 ignore the field.
452
+ observation_scopes: this.observationScopes
360
453
  };
361
454
  if (opts.timestamp) item.timestamp = opts.timestamp;
362
455
  if (opts.metadata) item.metadata = opts.metadata;
@@ -435,7 +528,7 @@ var HindsightClient = class {
435
528
  this.log(
436
529
  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}`
437
530
  );
438
- await this.seedPages();
531
+ await this.seedPages(opts.pageTrigger);
439
532
  }
440
533
  /**
441
534
  * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
@@ -493,7 +586,7 @@ var HindsightClient = class {
493
586
  let backoffMs = POLL_CYCLE_MS;
494
587
  await pool([...pending], this.maxParallelRetains, async (id) => {
495
588
  try {
496
- const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
589
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
497
590
  if (r.status === 429) {
498
591
  backoffMs = Math.min(
499
592
  RETRY_AFTER_CEILING_MS,
@@ -519,18 +612,23 @@ var HindsightClient = class {
519
612
  `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
520
613
  );
521
614
  }
522
- /** Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a caller. */
523
- async reflect(query, opts = {}) {
615
+ /**
616
+ * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
617
+ * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
618
+ * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
619
+ * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
620
+ * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
621
+ */
622
+ async reflect(query, opts) {
524
623
  const ctrl = new AbortController();
525
- const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 12e4);
624
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
526
625
  try {
527
- const resp = await fetch(this.bankUrl("/reflect"), {
626
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
528
627
  method: "POST",
529
- headers: this.headers(),
530
628
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
531
629
  signal: ctrl.signal
532
630
  });
533
- if (!resp.ok) throw new Error(`reflect ${resp.status}`);
631
+ if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
534
632
  const data = await resp.json();
535
633
  return (data.text || "").trim();
536
634
  } finally {
@@ -614,16 +712,18 @@ var HindsightClient = class {
614
712
  }));
615
713
  }
616
714
  /**
617
- * Seed the fixed `PAGES` taxonomy as knowledge-base pages at the tree root, idempotently.
715
+ * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
618
716
  *
619
717
  * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
620
718
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
621
719
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
622
720
  *
623
721
  * An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
624
- * `source_query` re-syncs onto the live page instead of orphaning its synthesized content.
722
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
723
+ * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
625
724
  */
626
- async seedPages() {
725
+ async seedPages(pageTrigger = buildPageTrigger()) {
726
+ const pages = pagesFor(this.project ?? this.bank);
627
727
  const existing = /* @__PURE__ */ new Map();
628
728
  let roots;
629
729
  try {
@@ -640,14 +740,14 @@ var HindsightClient = class {
640
740
  }
641
741
  let created = 0;
642
742
  let updated = 0;
643
- for (const page of PAGES) {
743
+ for (const page of pages) {
644
744
  const hit = existing.get(page.name.toLowerCase());
645
745
  const body = {
646
746
  name: page.name,
647
747
  source_query: page.source_query,
648
748
  tags: page.tags,
649
749
  max_tokens: PAGE_MAX_TOKENS,
650
- trigger: PAGE_TRIGGER
750
+ trigger: pageTrigger
651
751
  };
652
752
  if (!hit) {
653
753
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
@@ -659,11 +759,18 @@ var HindsightClient = class {
659
759
  return;
660
760
  }
661
761
  if (r.status !== 409) created++;
662
- } else if (hit.description !== page.source_query) {
762
+ } else if (hit.description !== page.source_query || hit.trigger?.tags_match !== pageTrigger.tags_match) {
763
+ const patch = {
764
+ trigger: pageTrigger
765
+ };
766
+ if (hit.description !== page.source_query) {
767
+ patch.source_query = page.source_query;
768
+ patch.tags = page.tags;
769
+ }
663
770
  const r = await this.req(
664
771
  "PATCH",
665
772
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
666
- { source_query: page.source_query, tags: page.tags }
773
+ patch
667
774
  );
668
775
  if ([404, 405, 501].includes(r.status)) {
669
776
  this.knowledgePagesSupported = false;
@@ -676,7 +783,7 @@ var HindsightClient = class {
676
783
  }
677
784
  }
678
785
  this.log(
679
- `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
786
+ `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
680
787
  );
681
788
  }
682
789
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
@@ -684,9 +791,17 @@ var HindsightClient = class {
684
791
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
685
792
  }
686
793
  /**
687
- * Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
688
- * New initiative → creates a page under the Initiatives folder tagged `relatedPageId:<pageId>`.
689
- * Enhancement (relatesToPageId) → no new page; only a marker accruing to the existing page.
794
+ * Active-path capture: register a major feature as a per-initiative page + a marker memory.
795
+ * New initiative → creates a page under the Initiatives folder.
796
+ * Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
797
+ * enhancement or a mid-work plan change lands on the initiative it belongs to.
798
+ *
799
+ * The marker carries its page id in two places, neither of them a tag (#3641):
800
+ * `metadata.relatedPageId` for provenance (visible on the document, and to a reflect loop that
801
+ * expands one), and a `[[page:<id>]]` link in the retain CONTEXT, which is the only one of the
802
+ * three channels a page synthesis actually reads — reflect's search results keep `context` and
803
+ * `tags` but strip `metadata` (`_UNREAD_RESULT_FIELDS`), and the id has no business in a tag
804
+ * vocabulary that exists to be matched with exact set-ops.
690
805
  */
691
806
  async captureInitiative(args) {
692
807
  let pageId = args.relatesToPageId;
@@ -697,10 +812,7 @@ var HindsightClient = class {
697
812
  source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.`,
698
813
  parent_id: folderId,
699
814
  tags: ["knowledge:feature-work"],
700
- trigger: {
701
- fact_types: ["world", "experience", "observation"],
702
- refresh_after_consolidation: true
703
- }
815
+ trigger: args.pageTrigger ?? buildPageTrigger()
704
816
  });
705
817
  try {
706
818
  const j = await r.json();
@@ -709,23 +821,14 @@ var HindsightClient = class {
709
821
  }
710
822
  pageId ||= `initiative-${this.slugify(args.title)}`;
711
823
  }
712
- const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
824
+ const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
713
825
  const content = `${verb}: ${args.title}. ${args.summary}`;
714
826
  const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
715
- const tags = [
716
- .../* @__PURE__ */ new Set([
717
- ...args.stamp?.tags ?? [],
718
- "knowledge:feature-work",
719
- `relatedPageId:${pageId}`
720
- ])
721
- ];
722
- if (Object.keys(args.stamp?.metadata ?? {}).length) {
723
- await this.retain(content, "initiative marker", markerId, tags, "document", {
724
- metadata: args.stamp?.metadata
725
- });
726
- } else {
727
- await this.retain(content, "initiative marker", markerId, tags, "document");
728
- }
827
+ const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
828
+ const context = `initiative marker for [[page:${pageId}]]`;
829
+ await this.retain(content, context, markerId, tags, "document", {
830
+ metadata: { ...args.stamp?.metadata ?? {}, relatedPageId: pageId }
831
+ });
729
832
  return { page_id: pageId };
730
833
  }
731
834
  /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
@@ -813,7 +916,7 @@ async function ingestChats(client, sessions, opts = {}) {
813
916
  // src/core/config.ts
814
917
  import { readFileSync } from "fs";
815
918
  import { homedir as homedir2 } from "os";
816
- import { join as join3 } from "path";
919
+ import { join as join4 } from "path";
817
920
 
818
921
  // src/core/seed.ts
819
922
  import { spawn as realSpawn } from "child_process";
@@ -821,11 +924,89 @@ import { dirname as dirname2, join as join2 } from "path";
821
924
  import { fileURLToPath } from "url";
822
925
  var DEFAULT_SEED_LIMIT = 300;
823
926
 
927
+ // src/core/log.ts
928
+ import { appendFileSync, mkdirSync } from "fs";
929
+ import { tmpdir } from "os";
930
+ import { dirname as dirname3, join as join3 } from "path";
931
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
932
+ var current = ["debug", "info", "warn", "error"].find(
933
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
934
+ ) ?? "info";
935
+ function setLogLevel(level) {
936
+ if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
937
+ }
938
+ function logFilePath() {
939
+ return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
940
+ }
941
+ function write(level, scope, msg, extra) {
942
+ if (WEIGHT[level] < WEIGHT[current]) return;
943
+ try {
944
+ const file = logFilePath();
945
+ mkdirSync(dirname3(file), { recursive: true });
946
+ appendFileSync(
947
+ file,
948
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
949
+ );
950
+ } catch {
951
+ }
952
+ }
953
+ var log = {
954
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
955
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
956
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
957
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
958
+ };
959
+ function describeError(value, maxChars = 200) {
960
+ const parts = [];
961
+ const seen = /* @__PURE__ */ new Set();
962
+ let current2 = value;
963
+ while (current2 && !seen.has(current2)) {
964
+ seen.add(current2);
965
+ const error = current2;
966
+ const text = typeof error.message === "string" ? error.message : String(current2);
967
+ const withCode = error.code ? `${text} (${String(error.code)})` : text;
968
+ if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
969
+ current2 = error.cause;
970
+ }
971
+ return (parts.join(": ") || String(value)).slice(0, maxChars);
972
+ }
973
+
824
974
  // src/core/config.ts
825
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
975
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
826
976
  var DEFAULT_DAEMON_PORT = 9077;
827
- var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
828
977
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
978
+ function resolvePageTriggerType(raw) {
979
+ if (raw.pageTriggerType === "manual") return "manual";
980
+ if (raw.pageTriggerType === "cron") {
981
+ if (raw.pageTriggerCron?.trim()) return "cron";
982
+ log.warn(
983
+ "config",
984
+ 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
985
+ );
986
+ }
987
+ return "auto-refresh";
988
+ }
989
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
990
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
991
+ function resolveReflectBudget(raw) {
992
+ const value = raw.reflectBudget;
993
+ if (value === void 0) return "high";
994
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
995
+ return value;
996
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
997
+ return "high";
998
+ }
999
+ var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
1000
+ function resolveObservationScopes(raw) {
1001
+ const value = raw;
1002
+ if (typeof value === "string")
1003
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
1004
+ if (Array.isArray(value)) {
1005
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
1006
+ if (scopes.length) return scopes;
1007
+ }
1008
+ return DEFAULT_OBSERVATION_SCOPES;
1009
+ }
829
1010
  function resolveConfig(raw = {}) {
830
1011
  const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
831
1012
  const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
@@ -837,7 +1018,7 @@ function resolveConfig(raw = {}) {
837
1018
  apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
838
1019
  apiToken: raw.apiToken || void 0,
839
1020
  apiPort,
840
- daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
1021
+ daemonIdleTimeout: raw.daemonIdleTimeout,
841
1022
  daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
842
1023
  embedVersion: raw.embedVersion || void 0,
843
1024
  embedPackagePath: raw.embedPackagePath || void 0,
@@ -852,11 +1033,18 @@ function resolveConfig(raw = {}) {
852
1033
  harness: raw.harness ?? "opencode",
853
1034
  disabled: raw.disabled ?? false,
854
1035
  retainSessions: raw.retainSessions ?? true,
855
- // opencode: write back by default (parity with hook-harness Stop)
1036
+ // write sessions back by default, every harness
856
1037
  maxParallelRetains: raw.maxParallelRetains || 10,
857
1038
  reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
1039
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
1040
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
1041
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
1042
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1043
+ reflectBudget: resolveReflectBudget(raw),
858
1044
  autoReflect: raw.autoReflect ?? true,
859
1045
  pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
1046
+ pageTriggerType: resolvePageTriggerType(raw),
1047
+ pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
860
1048
  autoSeed: raw.autoSeed ?? true,
861
1049
  seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
862
1050
  codebaseSurvey: raw.codebaseSurvey ?? true,
@@ -870,6 +1058,7 @@ function resolveConfig(raw = {}) {
870
1058
  retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
871
1059
  Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
872
1060
  ) : {},
1061
+ observationScopes: resolveObservationScopes(raw.observationScopes),
873
1062
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
874
1063
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
875
1064
  };
@@ -916,8 +1105,12 @@ var ENV_KEYS = {
916
1105
  retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
917
1106
  maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
918
1107
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1108
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1109
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
919
1110
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
920
1111
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1112
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
1113
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
921
1114
  autoSeed: "HINDSIGHT_AUTO_SEED",
922
1115
  seedLimit: "HINDSIGHT_SEED_LIMIT",
923
1116
  codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
@@ -926,6 +1119,9 @@ var ENV_KEYS = {
926
1119
  surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
927
1120
  logLevel: "HINDSIGHT_LOG_LEVEL",
928
1121
  gitIngest: "HINDSIGHT_GIT_INGEST",
1122
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1123
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
1124
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
929
1125
  // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
930
1126
  // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
931
1127
  retainTags: "HINDSIGHT_RETAIN_TAGS"
@@ -946,6 +1142,7 @@ var ENV_NUMBERS = /* @__PURE__ */ new Set([
946
1142
  "daemonIdleTimeout",
947
1143
  "maxParallelRetains",
948
1144
  "reflectTimeoutMs",
1145
+ "reflectToolTimeoutMs",
949
1146
  "pageRefreshEveryTurns",
950
1147
  "seedLimit",
951
1148
  "surveyBudgetUsd",
@@ -1103,6 +1300,13 @@ function gitLogText(repo, limit) {
1103
1300
  ${msg}`;
1104
1301
  }).join("\n\n---\n\n");
1105
1302
  }
1303
+ function gitLogNewestAuthorDate(repo) {
1304
+ try {
1305
+ return git(repo, "log", "-n", "1", "--no-merges", "--format=%aI").trim() || null;
1306
+ } catch {
1307
+ return null;
1308
+ }
1309
+ }
1106
1310
  async function ingestGitLog(client, repo, opts = { limit: 300 }) {
1107
1311
  const log3 = opts.log ?? (() => {
1108
1312
  });
@@ -1125,24 +1329,22 @@ async function ingestGitLog(client, repo, opts = { limit: 300 }) {
1125
1329
  ...head ? [`gitlog-head:${head}`] : []
1126
1330
  ])
1127
1331
  ];
1128
- if (Object.keys(stamp?.metadata ?? {}).length) {
1129
- await client.retain(
1130
- text,
1131
- `git commit-message history (last ${n}) for ${repoName}`,
1132
- `gitlog:${repoName}`,
1133
- tags,
1134
- "gitlog",
1135
- { metadata: stamp?.metadata }
1136
- );
1137
- } else {
1138
- await client.retain(
1139
- text,
1140
- `git commit-message history (last ${n}) for ${repoName}`,
1141
- `gitlog:${repoName}`,
1142
- tags,
1143
- "gitlog"
1144
- );
1145
- }
1332
+ await client.retain(
1333
+ text,
1334
+ `git commit-message history (last ${n}) for ${repoName}`,
1335
+ `gitlog:${repoName}`,
1336
+ tags,
1337
+ "gitlog",
1338
+ {
1339
+ // Anchor the document in time on the newest commit it contains, so extraction can date the
1340
+ // facts it pulls out of these messages. Previously no timestamp was passed at all: retain
1341
+ // then stamped "now", the extraction prompt got `Event Date: Unknown`, and every fact landed
1342
+ // with a null occurred_start/occurred_end — invisible to temporal search (#3602).
1343
+ timestamp: gitLogNewestAuthorDate(repo) ?? void 0,
1344
+ // `retain` only sets metadata when it is truthy, so an empty stamp sends none.
1345
+ metadata: Object.keys(stamp?.metadata ?? {}).length ? stamp?.metadata : void 0
1346
+ }
1347
+ );
1146
1348
  log3(`[gitlog] done: ${n} commit messages ingested as 1 document under strategy 'gitlog'`);
1147
1349
  return 0;
1148
1350
  } catch (e) {
@@ -1155,7 +1357,7 @@ async function ingestGitLog(client, repo, opts = { limit: 300 }) {
1155
1357
  import { spawn as realSpawn2 } from "child_process";
1156
1358
  import { accessSync, constants, existsSync as existsSync2 } from "fs";
1157
1359
  import { homedir as homedir3 } from "os";
1158
- import { delimiter, dirname as dirname3, join as join4 } from "path";
1360
+ import { delimiter, dirname as dirname4, join as join5 } from "path";
1159
1361
  import { fileURLToPath as fileURLToPath2 } from "url";
1160
1362
  var SURVEY_DOC_IDS = [
1161
1363
  "repository-component-map",
@@ -1241,55 +1443,6 @@ async function getHarness(name) {
1241
1443
 
1242
1444
  // src/core/diag.ts
1243
1445
  import { appendFileSync as appendFileSync2 } from "fs";
1244
-
1245
- // src/core/log.ts
1246
- import { appendFileSync, mkdirSync } from "fs";
1247
- import { tmpdir } from "os";
1248
- import { dirname as dirname4, join as join5 } from "path";
1249
- var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
1250
- var current = ["debug", "info", "warn", "error"].find(
1251
- (l) => l === process.env.HINDSIGHT_LOG_LEVEL
1252
- ) ?? "info";
1253
- function setLogLevel(level) {
1254
- if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
1255
- }
1256
- function logFilePath() {
1257
- return process.env.HINDSIGHT_LOG_FILE || join5(tmpdir(), "hindsight-coding-agent", "plugin.log");
1258
- }
1259
- function write(level, scope, msg, extra) {
1260
- if (WEIGHT[level] < WEIGHT[current]) return;
1261
- try {
1262
- const file = logFilePath();
1263
- mkdirSync(dirname4(file), { recursive: true });
1264
- appendFileSync(
1265
- file,
1266
- `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
1267
- );
1268
- } catch {
1269
- }
1270
- }
1271
- var log = {
1272
- debug: (scope, msg, extra) => write("debug", scope, msg, extra),
1273
- info: (scope, msg, extra) => write("info", scope, msg, extra),
1274
- warn: (scope, msg, extra) => write("warn", scope, msg, extra),
1275
- error: (scope, msg, extra) => write("error", scope, msg, extra)
1276
- };
1277
- function describeError(value, maxChars = 200) {
1278
- const parts = [];
1279
- const seen = /* @__PURE__ */ new Set();
1280
- let current2 = value;
1281
- while (current2 && !seen.has(current2)) {
1282
- seen.add(current2);
1283
- const error = current2;
1284
- const text = typeof error.message === "string" ? error.message : String(current2);
1285
- const withCode = error.code ? `${text} (${String(error.code)})` : text;
1286
- if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
1287
- current2 = error.cause;
1288
- }
1289
- return (parts.join(": ") || String(value)).slice(0, maxChars);
1290
- }
1291
-
1292
- // src/core/diag.ts
1293
1446
  function diagFilePath() {
1294
1447
  return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
1295
1448
  }
@@ -1311,7 +1464,7 @@ function resolversFor(ctx) {
1311
1464
  return {
1312
1465
  // Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
1313
1466
  // otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
1314
- gitProject: () => projectNameOf(ctx.directory),
1467
+ gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
1315
1468
  project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
1316
1469
  harness: () => ctx.harness,
1317
1470
  bankId: () => ctx.bankId,
@@ -1426,7 +1579,12 @@ async function main() {
1426
1579
  apiUrl: API_URL,
1427
1580
  apiToken: API_TOKEN,
1428
1581
  bank: FINAL_BANK,
1582
+ // Names the repository in every seeded page's query, so page synthesis can tell this
1583
+ // project's decisions from those of a dependency it merely discusses (#3476). Same
1584
+ // worktree-aware name the gitlog document id uses, so all worktrees agree on it.
1585
+ project: repoNameOf(REPO),
1429
1586
  maxParallelRetains: cfg.maxParallelRetains,
1587
+ observationScopes: cfg.observationScopes,
1430
1588
  log: log2
1431
1589
  });
1432
1590
  log2(`deepen -> ${client.apiUrl} bank=${FINAL_BANK} harness=${harness.name}`);
@@ -1436,7 +1594,7 @@ async function main() {
1436
1594
  bankId: FINAL_BANK,
1437
1595
  sessionId
1438
1596
  });
1439
- await client.configureBank();
1597
+ await client.configureBank({ pageTrigger: buildPageTrigger(cfg) });
1440
1598
  if (client.knowledgePagesSupported === false) {
1441
1599
  diag(harness.name, "knowledge_pages_unavailable", {
1442
1600
  bank: FINAL_BANK,
@@ -1444,11 +1602,18 @@ async function main() {
1444
1602
  });
1445
1603
  }
1446
1604
  const gitIds = await client.listDocumentIds("source:git");
1447
- const chatIds = await client.listDocumentIds("source:chat").catch(() => /* @__PURE__ */ new Set());
1448
- const all = await harness.chatReader.read({ conversations: CONV, repo: REPO });
1449
- const sessions = all.filter((s, i) => !chatIds.has(`chat:${s.id || `s${i}`}`));
1450
- if (all.length !== sessions.length)
1451
- log2(`[chat] ${all.length - sessions.length} conversations already ingested \u2014 skipping those`);
1605
+ let sessions = [];
1606
+ if (!cfg.retainSessions) {
1607
+ log2("[chat] retainSessions: false \u2014 skipping conversation import");
1608
+ } else {
1609
+ const chatIds = await client.listDocumentIds("source:chat").catch(() => /* @__PURE__ */ new Set());
1610
+ const all = await harness.chatReader.read({ conversations: CONV, repo: REPO });
1611
+ sessions = all.filter((s, i) => !chatIds.has(`chat:${s.id || `s${i}`}`));
1612
+ if (all.length !== sessions.length)
1613
+ log2(
1614
+ `[chat] ${all.length - sessions.length} conversations already ingested \u2014 skipping those`
1615
+ );
1616
+ }
1452
1617
  const chatFails = await ingestChats(client, sessions, {
1453
1618
  concurrency: cfg.maxParallelRetains,
1454
1619
  log: log2,