@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.
@@ -3,7 +3,7 @@
3
3
  // src/core/config.ts
4
4
  import { readFileSync } from "fs";
5
5
  import { homedir as homedir2 } from "os";
6
- import { join as join3 } from "path";
6
+ import { join as join4 } from "path";
7
7
 
8
8
  // src/core/seed.ts
9
9
  import { spawn as realSpawn } from "child_process";
@@ -51,30 +51,36 @@ function getProjectRootFromGit(directory) {
51
51
  }
52
52
  var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
53
53
  function nearestExistingDir(directory) {
54
- let current = directory;
55
- while (current) {
56
- if (existsSync(current)) return current;
57
- const parent = dirname2(current);
58
- if (parent === current) return "";
59
- current = parent;
54
+ let current2 = directory;
55
+ while (current2) {
56
+ if (existsSync(current2)) return current2;
57
+ const parent = dirname2(current2);
58
+ if (parent === current2) return "";
59
+ current2 = parent;
60
60
  }
61
61
  return "";
62
62
  }
63
63
  function dirName(directory) {
64
64
  return directory && basename(directory) || "unknown";
65
65
  }
66
- function gitProjectName(directory, resolveWorktrees) {
66
+ function mainWorktreeRoot(directory, sessionRoot = "") {
67
+ const candidates = [
68
+ nearestExistingDir(directory),
69
+ sessionRoot,
70
+ ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
71
+ ];
72
+ for (const candidate of candidates) {
73
+ const root = candidate ? getProjectRootFromGit(candidate) : null;
74
+ if (root) return root;
75
+ }
76
+ return null;
77
+ }
78
+ function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
67
79
  if (resolveWorktrees) {
68
- const candidates = [
69
- nearestExistingDir(directory),
70
- ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
71
- ];
72
- for (const candidate of candidates) {
73
- const root = candidate ? getProjectRootFromGit(candidate) : null;
74
- if (root) return basename(root);
75
- }
80
+ const root = mainWorktreeRoot(directory, sessionRoot);
81
+ if (root) return basename(root);
76
82
  }
77
- return dirName(directory);
83
+ return dirName(sessionRoot || directory);
78
84
  }
79
85
  function configuredDir(dir) {
80
86
  const expanded = dir === "~" || dir.startsWith("~/") ? join2(homedir(), dir.slice(1)) : dir;
@@ -94,34 +100,115 @@ function mapLookup(map, directory) {
94
100
  }
95
101
  return best?.bank;
96
102
  }
103
+ function lookupDirectories(config, directory, sessionRoot = "") {
104
+ const directories = [normalize(directory)];
105
+ if (config.resolveWorktrees ?? true) {
106
+ const root = mainWorktreeRoot(directory, sessionRoot);
107
+ const normalizedRoot = root ? normalize(root) : "";
108
+ if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
109
+ }
110
+ return directories;
111
+ }
97
112
  function isOptedIn(config, directory) {
98
113
  if (!config.optInOnly) return true;
99
114
  if (!directory) return false;
100
- const cwd = normalize(directory);
101
- if ((config.optInPaths ?? []).some((dir) => dir && isWithin(cwd, configuredDir(dir))))
115
+ const directories = lookupDirectories(config, directory);
116
+ if (directories.some(
117
+ (candidate) => (config.optInPaths ?? []).some(
118
+ (configured) => configured && isWithin(candidate, configuredDir(configured))
119
+ )
120
+ ))
102
121
  return true;
103
- return Boolean(config.mapPathToBank && mapLookup(config.mapPathToBank, directory));
122
+ const pathMap = config.mapPathToBank;
123
+ return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
104
124
  }
105
- function deriveBankId(config, directory, harness = "coding") {
106
- const mapped = directory && config.mapPathToBank ? mapLookup(config.mapPathToBank, directory) : void 0;
125
+ function deriveBankId(config, directory, harness = "coding", sessionRoot) {
126
+ const pathMap = config.mapPathToBank;
127
+ const mapped = directory && pathMap ? lookupDirectories(config, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0) : void 0;
107
128
  if (mapped) return mapped;
108
129
  const dynamic = config.dynamicBankId ?? !config.bankId;
109
130
  if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
110
131
  const resolvers = {
111
132
  harness: () => harness,
112
133
  project: () => dirName(directory),
113
- gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true),
134
+ gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true, sessionRoot),
114
135
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
115
136
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
116
137
  };
117
138
  return applyTemplate(config.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
118
139
  }
119
140
 
141
+ // src/core/log.ts
142
+ import { appendFileSync, mkdirSync } from "fs";
143
+ import { tmpdir } from "os";
144
+ import { dirname as dirname3, join as join3 } from "path";
145
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
146
+ var current = ["debug", "info", "warn", "error"].find(
147
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
148
+ ) ?? "info";
149
+ function logFilePath() {
150
+ return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
151
+ }
152
+ function write(level, scope, msg, extra) {
153
+ if (WEIGHT[level] < WEIGHT[current]) return;
154
+ try {
155
+ const file = logFilePath();
156
+ mkdirSync(dirname3(file), { recursive: true });
157
+ appendFileSync(
158
+ file,
159
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
160
+ );
161
+ } catch {
162
+ }
163
+ }
164
+ var log = {
165
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
166
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
167
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
168
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
169
+ };
170
+
171
+ // src/core/hindsight.ts
172
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
173
+ var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
174
+ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
175
+
120
176
  // src/core/config.ts
121
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
177
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
122
178
  var DEFAULT_DAEMON_PORT = 9077;
123
- var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
124
179
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
180
+ function resolvePageTriggerType(raw) {
181
+ if (raw.pageTriggerType === "manual") return "manual";
182
+ if (raw.pageTriggerType === "cron") {
183
+ if (raw.pageTriggerCron?.trim()) return "cron";
184
+ log.warn(
185
+ "config",
186
+ 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
187
+ );
188
+ }
189
+ return "auto-refresh";
190
+ }
191
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
192
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
193
+ function resolveReflectBudget(raw) {
194
+ const value = raw.reflectBudget;
195
+ if (value === void 0) return "high";
196
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
197
+ return value;
198
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
199
+ return "high";
200
+ }
201
+ var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
202
+ function resolveObservationScopes(raw) {
203
+ const value = raw;
204
+ if (typeof value === "string")
205
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
206
+ if (Array.isArray(value)) {
207
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
208
+ if (scopes.length) return scopes;
209
+ }
210
+ return DEFAULT_OBSERVATION_SCOPES;
211
+ }
125
212
  function resolveConfig(raw = {}) {
126
213
  const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
127
214
  const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
@@ -133,7 +220,7 @@ function resolveConfig(raw = {}) {
133
220
  apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
134
221
  apiToken: raw.apiToken || void 0,
135
222
  apiPort,
136
- daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
223
+ daemonIdleTimeout: raw.daemonIdleTimeout,
137
224
  daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
138
225
  embedVersion: raw.embedVersion || void 0,
139
226
  embedPackagePath: raw.embedPackagePath || void 0,
@@ -148,11 +235,18 @@ function resolveConfig(raw = {}) {
148
235
  harness: raw.harness ?? "opencode",
149
236
  disabled: raw.disabled ?? false,
150
237
  retainSessions: raw.retainSessions ?? true,
151
- // opencode: write back by default (parity with hook-harness Stop)
238
+ // write sessions back by default, every harness
152
239
  maxParallelRetains: raw.maxParallelRetains || 10,
153
240
  reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
241
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
242
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
243
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
244
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
245
+ reflectBudget: resolveReflectBudget(raw),
154
246
  autoReflect: raw.autoReflect ?? true,
155
247
  pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
248
+ pageTriggerType: resolvePageTriggerType(raw),
249
+ pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
156
250
  autoSeed: raw.autoSeed ?? true,
157
251
  seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
158
252
  codebaseSurvey: raw.codebaseSurvey ?? true,
@@ -166,6 +260,7 @@ function resolveConfig(raw = {}) {
166
260
  retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
167
261
  Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
168
262
  ) : {},
263
+ observationScopes: resolveObservationScopes(raw.observationScopes),
169
264
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
170
265
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
171
266
  };
@@ -212,8 +307,12 @@ var ENV_KEYS = {
212
307
  retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
213
308
  maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
214
309
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
310
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
311
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
215
312
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
216
313
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
314
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
315
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
217
316
  autoSeed: "HINDSIGHT_AUTO_SEED",
218
317
  seedLimit: "HINDSIGHT_SEED_LIMIT",
219
318
  codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
@@ -222,6 +321,9 @@ var ENV_KEYS = {
222
321
  surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
223
322
  logLevel: "HINDSIGHT_LOG_LEVEL",
224
323
  gitIngest: "HINDSIGHT_GIT_INGEST",
324
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
325
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
326
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
225
327
  // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
226
328
  // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
227
329
  retainTags: "HINDSIGHT_RETAIN_TAGS"
@@ -242,6 +344,7 @@ var ENV_NUMBERS = /* @__PURE__ */ new Set([
242
344
  "daemonIdleTimeout",
243
345
  "maxParallelRetains",
244
346
  "reflectTimeoutMs",
347
+ "reflectToolTimeoutMs",
245
348
  "pageRefreshEveryTurns",
246
349
  "seedLimit",
247
350
  "surveyBudgetUsd",