@vectorize-io/hindsight-coding-agents 0.3.3 → 0.4.0
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/README.md +124 -37
- package/cordis.patch.yml +18 -0
- package/dist/antigravity-hook.js +440 -265
- package/dist/antigravity-statusline.js +130 -27
- package/dist/antigravity-stop-hook.js +446 -266
- package/dist/claude-hook.js +440 -265
- package/dist/claude-sessionstart-hook.js +436 -269
- package/dist/claude-stop-hook.js +446 -266
- package/dist/cline.js +652 -340
- package/dist/codex-hook.js +440 -265
- package/dist/codex-sessionstart-hook.js +436 -269
- package/dist/codex-stop-hook.js +446 -266
- package/dist/copilot-hook.js +440 -265
- package/dist/copilot-sessionstart-hook.js +436 -269
- package/dist/copilot-stop-hook.js +446 -266
- package/dist/cursor-hook.js +440 -265
- package/dist/cursor-sessionstart-hook.js +436 -269
- package/dist/cursor-stop-hook.js +446 -266
- package/dist/daemon-start.js +101 -45
- package/dist/deepen.js +302 -119
- package/dist/devin-hook.js +440 -265
- package/dist/devin-sessionstart-hook.js +436 -269
- package/dist/devin-stop-hook.js +446 -266
- package/dist/dsh.js +17339 -0
- package/dist/grok-hook.js +440 -265
- package/dist/grok-sessionstart-hook.js +436 -269
- package/dist/grok-stop-hook.js +446 -266
- package/dist/hindsight-seed.js +122 -24
- package/dist/index.js +685 -372
- package/dist/installer.js +229 -49
- package/dist/kilo.js +685 -372
- package/dist/mcp-server.js +529 -289
- package/dist/prime-agent.js +1055 -741
- package/dist/status.js +419 -244
- package/package.json +27 -3
- package/skill/SKILL.md +20 -4
package/dist/codex-stop-hook.js
CHANGED
|
@@ -41,8 +41,8 @@ function getProjectRootFromGit(directory) {
|
|
|
41
41
|
return null;
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
|
-
function projectNameOf(directory) {
|
|
45
|
-
return gitProjectName(directory, true);
|
|
44
|
+
function projectNameOf(directory, sessionRoot) {
|
|
45
|
+
return gitProjectName(directory, true, sessionRoot);
|
|
46
46
|
}
|
|
47
47
|
var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
|
|
48
48
|
function nearestExistingDir(directory) {
|
|
@@ -58,18 +58,24 @@ function nearestExistingDir(directory) {
|
|
|
58
58
|
function dirName(directory) {
|
|
59
59
|
return directory && basename(directory) || "unknown";
|
|
60
60
|
}
|
|
61
|
-
function
|
|
61
|
+
function mainWorktreeRoot(directory, sessionRoot = "") {
|
|
62
|
+
const candidates = [
|
|
63
|
+
nearestExistingDir(directory),
|
|
64
|
+
sessionRoot,
|
|
65
|
+
...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
|
|
66
|
+
];
|
|
67
|
+
for (const candidate of candidates) {
|
|
68
|
+
const root = candidate ? getProjectRootFromGit(candidate) : null;
|
|
69
|
+
if (root) return root;
|
|
70
|
+
}
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
|
|
62
74
|
if (resolveWorktrees) {
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
-
...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
|
|
66
|
-
];
|
|
67
|
-
for (const candidate of candidates) {
|
|
68
|
-
const root = candidate ? getProjectRootFromGit(candidate) : null;
|
|
69
|
-
if (root) return basename(root);
|
|
70
|
-
}
|
|
75
|
+
const root = mainWorktreeRoot(directory, sessionRoot);
|
|
76
|
+
if (root) return basename(root);
|
|
71
77
|
}
|
|
72
|
-
return dirName(directory);
|
|
78
|
+
return dirName(sessionRoot || directory);
|
|
73
79
|
}
|
|
74
80
|
function configuredDir(dir) {
|
|
75
81
|
const expanded = dir === "~" || dir.startsWith("~/") ? join(homedir(), dir.slice(1)) : dir;
|
|
@@ -89,23 +95,38 @@ function mapLookup(map, directory) {
|
|
|
89
95
|
}
|
|
90
96
|
return best?.bank;
|
|
91
97
|
}
|
|
98
|
+
function lookupDirectories(config, directory, sessionRoot = "") {
|
|
99
|
+
const directories = [normalize(directory)];
|
|
100
|
+
if (config.resolveWorktrees ?? true) {
|
|
101
|
+
const root = mainWorktreeRoot(directory, sessionRoot);
|
|
102
|
+
const normalizedRoot = root ? normalize(root) : "";
|
|
103
|
+
if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
|
|
104
|
+
}
|
|
105
|
+
return directories;
|
|
106
|
+
}
|
|
92
107
|
function isOptedIn(config, directory) {
|
|
93
108
|
if (!config.optInOnly) return true;
|
|
94
109
|
if (!directory) return false;
|
|
95
|
-
const
|
|
96
|
-
if (
|
|
110
|
+
const directories = lookupDirectories(config, directory);
|
|
111
|
+
if (directories.some(
|
|
112
|
+
(candidate) => (config.optInPaths ?? []).some(
|
|
113
|
+
(configured) => configured && isWithin(candidate, configuredDir(configured))
|
|
114
|
+
)
|
|
115
|
+
))
|
|
97
116
|
return true;
|
|
98
|
-
|
|
117
|
+
const pathMap = config.mapPathToBank;
|
|
118
|
+
return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
|
|
99
119
|
}
|
|
100
|
-
function deriveBankId(config, directory, harness = "coding") {
|
|
101
|
-
const
|
|
120
|
+
function deriveBankId(config, directory, harness = "coding", sessionRoot) {
|
|
121
|
+
const pathMap = config.mapPathToBank;
|
|
122
|
+
const mapped = directory && pathMap ? lookupDirectories(config, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0) : void 0;
|
|
102
123
|
if (mapped) return mapped;
|
|
103
124
|
const dynamic = config.dynamicBankId ?? !config.bankId;
|
|
104
125
|
if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
|
|
105
126
|
const resolvers = {
|
|
106
127
|
harness: () => harness,
|
|
107
128
|
project: () => dirName(directory),
|
|
108
|
-
gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true),
|
|
129
|
+
gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true, sessionRoot),
|
|
109
130
|
channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
|
|
110
131
|
user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
|
|
111
132
|
};
|
|
@@ -115,7 +136,7 @@ function deriveBankId(config, directory, harness = "coding") {
|
|
|
115
136
|
// src/core/config.ts
|
|
116
137
|
import { readFileSync } from "fs";
|
|
117
138
|
import { homedir as homedir2 } from "os";
|
|
118
|
-
import { join as
|
|
139
|
+
import { join as join4 } from "path";
|
|
119
140
|
|
|
120
141
|
// src/core/seed.ts
|
|
121
142
|
import { spawn as realSpawn } from "child_process";
|
|
@@ -123,204 +144,10 @@ import { dirname as dirname2, join as join2 } from "path";
|
|
|
123
144
|
import { fileURLToPath } from "url";
|
|
124
145
|
var DEFAULT_SEED_LIMIT = 300;
|
|
125
146
|
|
|
126
|
-
// src/core/config.ts
|
|
127
|
-
var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
|
|
128
|
-
var DEFAULT_DAEMON_PORT = 9077;
|
|
129
|
-
var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
|
|
130
|
-
var DEFAULT_DAEMON_PROFILE = "coding-agent";
|
|
131
|
-
function resolveConfig(raw = {}) {
|
|
132
|
-
const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
|
|
133
|
-
const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
|
|
134
|
-
return {
|
|
135
|
-
serverMode,
|
|
136
|
-
// Daemon mode resolves the URL HERE rather than at each call site: every entry point already
|
|
137
|
-
// builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
|
|
138
|
-
// daemon needs no plumbing through eight separate constructors.
|
|
139
|
-
apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
|
|
140
|
-
apiToken: raw.apiToken || void 0,
|
|
141
|
-
apiPort,
|
|
142
|
-
daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
|
|
143
|
-
daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
|
|
144
|
-
embedVersion: raw.embedVersion || void 0,
|
|
145
|
-
embedPackagePath: raw.embedPackagePath || void 0,
|
|
146
|
-
bankId: raw.bankId,
|
|
147
|
-
dynamicBankId: raw.dynamicBankId,
|
|
148
|
-
bankIdTemplate: raw.bankIdTemplate,
|
|
149
|
-
mapPathToBank: raw.mapPathToBank,
|
|
150
|
-
resolveWorktrees: raw.resolveWorktrees,
|
|
151
|
-
optInOnly: raw.optInOnly ?? false,
|
|
152
|
-
// Same shape as retainTags: a config typo must not become a path that silently approves nothing.
|
|
153
|
-
optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
|
|
154
|
-
harness: raw.harness ?? "opencode",
|
|
155
|
-
disabled: raw.disabled ?? false,
|
|
156
|
-
retainSessions: raw.retainSessions ?? true,
|
|
157
|
-
// opencode: write back by default (parity with hook-harness Stop)
|
|
158
|
-
maxParallelRetains: raw.maxParallelRetains || 10,
|
|
159
|
-
reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
|
|
160
|
-
autoReflect: raw.autoReflect ?? true,
|
|
161
|
-
pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
|
|
162
|
-
autoSeed: raw.autoSeed ?? true,
|
|
163
|
-
seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
|
|
164
|
-
codebaseSurvey: raw.codebaseSurvey ?? true,
|
|
165
|
-
surveyModel: raw.surveyModel || "haiku",
|
|
166
|
-
surveyBudgetUsd: raw.surveyBudgetUsd || 2,
|
|
167
|
-
surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
|
|
168
|
-
gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
|
|
169
|
-
// Hostile input is a config typo, not an attack: keep only string entries so a stray number or
|
|
170
|
-
// nested object cannot reach the API as a tag and fail the whole retain.
|
|
171
|
-
retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
|
|
172
|
-
retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
|
|
173
|
-
Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
|
|
174
|
-
) : {},
|
|
175
|
-
banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
|
|
176
|
-
logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
function readRaw(path) {
|
|
180
|
-
try {
|
|
181
|
-
return JSON.parse(readFileSync(path, "utf8"));
|
|
182
|
-
} catch (e) {
|
|
183
|
-
if (e?.code !== "ENOENT") {
|
|
184
|
-
console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
|
|
185
|
-
}
|
|
186
|
-
return {};
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
function mergeRaw(a, b) {
|
|
190
|
-
const { harnesses: _drop, ...flat } = b;
|
|
191
|
-
return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
|
|
192
|
-
}
|
|
193
|
-
function applyLayer(raw, layer, harness) {
|
|
194
|
-
let out = mergeRaw(raw, layer);
|
|
195
|
-
const perHarness = harness ? layer.harnesses?.[harness] : void 0;
|
|
196
|
-
if (perHarness) out = mergeRaw(out, perHarness);
|
|
197
|
-
return out;
|
|
198
|
-
}
|
|
199
|
-
var ENV_KEYS = {
|
|
200
|
-
serverMode: "HINDSIGHT_SERVER_MODE",
|
|
201
|
-
apiUrl: "HINDSIGHT_API_URL",
|
|
202
|
-
apiToken: "HINDSIGHT_API_TOKEN",
|
|
203
|
-
// These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
|
|
204
|
-
// it can carry their existing environment over unchanged.
|
|
205
|
-
apiPort: "HINDSIGHT_API_PORT",
|
|
206
|
-
daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
|
|
207
|
-
embedVersion: "HINDSIGHT_EMBED_VERSION",
|
|
208
|
-
embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
|
|
209
|
-
daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
|
|
210
|
-
bankId: "HINDSIGHT_BANK_ID",
|
|
211
|
-
dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
|
|
212
|
-
bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
|
|
213
|
-
resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
|
|
214
|
-
optInOnly: "HINDSIGHT_OPT_IN_ONLY",
|
|
215
|
-
optInPaths: "HINDSIGHT_OPT_IN_PATHS",
|
|
216
|
-
harness: "HINDSIGHT_HARNESS",
|
|
217
|
-
disabled: "HINDSIGHT_DISABLED",
|
|
218
|
-
retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
|
|
219
|
-
maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
|
|
220
|
-
reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
|
|
221
|
-
autoReflect: "HINDSIGHT_AUTO_REFLECT",
|
|
222
|
-
pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
|
|
223
|
-
autoSeed: "HINDSIGHT_AUTO_SEED",
|
|
224
|
-
seedLimit: "HINDSIGHT_SEED_LIMIT",
|
|
225
|
-
codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
|
|
226
|
-
surveyModel: "HINDSIGHT_SURVEY_MODEL",
|
|
227
|
-
surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
|
|
228
|
-
surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
|
|
229
|
-
logLevel: "HINDSIGHT_LOG_LEVEL",
|
|
230
|
-
gitIngest: "HINDSIGHT_GIT_INGEST",
|
|
231
|
-
// Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
|
|
232
|
-
// a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
|
|
233
|
-
retainTags: "HINDSIGHT_RETAIN_TAGS"
|
|
234
|
-
};
|
|
235
|
-
var ENV_BOOLEANS = /* @__PURE__ */ new Set([
|
|
236
|
-
"dynamicBankId",
|
|
237
|
-
"resolveWorktrees",
|
|
238
|
-
"optInOnly",
|
|
239
|
-
"disabled",
|
|
240
|
-
"retainSessions",
|
|
241
|
-
"autoReflect",
|
|
242
|
-
"autoSeed",
|
|
243
|
-
"codebaseSurvey"
|
|
244
|
-
]);
|
|
245
|
-
var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
|
|
246
|
-
var ENV_NUMBERS = /* @__PURE__ */ new Set([
|
|
247
|
-
"apiPort",
|
|
248
|
-
"daemonIdleTimeout",
|
|
249
|
-
"maxParallelRetains",
|
|
250
|
-
"reflectTimeoutMs",
|
|
251
|
-
"pageRefreshEveryTurns",
|
|
252
|
-
"seedLimit",
|
|
253
|
-
"surveyBudgetUsd",
|
|
254
|
-
"surveyRefreshCommits"
|
|
255
|
-
]);
|
|
256
|
-
function readEnvConfig(env = process.env) {
|
|
257
|
-
const out = {};
|
|
258
|
-
for (const [key, name] of Object.entries(ENV_KEYS)) {
|
|
259
|
-
const value = env[name];
|
|
260
|
-
if (value === void 0 || value.trim() === "") continue;
|
|
261
|
-
if (ENV_BOOLEANS.has(key)) {
|
|
262
|
-
out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
|
|
263
|
-
} else if (ENV_LISTS.has(key)) {
|
|
264
|
-
const items = value.split(",").map((v) => v.trim()).filter(Boolean);
|
|
265
|
-
if (items.length) out[key] = items;
|
|
266
|
-
} else if (ENV_NUMBERS.has(key)) {
|
|
267
|
-
const n = Number(value);
|
|
268
|
-
if (Number.isFinite(n)) out[key] = n;
|
|
269
|
-
else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
|
|
270
|
-
} else {
|
|
271
|
-
out[key] = value;
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
return out;
|
|
275
|
-
}
|
|
276
|
-
function loadConfig(opts = {}) {
|
|
277
|
-
const o = typeof opts === "string" ? { path: opts } : opts;
|
|
278
|
-
const withEnv = applyLayer({}, readEnvConfig(), o.harness);
|
|
279
|
-
const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
|
|
280
|
-
if (!raw.harness && o.harness) raw.harness = o.harness;
|
|
281
|
-
return resolveConfig(raw);
|
|
282
|
-
}
|
|
283
|
-
var BANK_OVERRIDE_EXCLUDED = [
|
|
284
|
-
"bankId",
|
|
285
|
-
"bankIdTemplate",
|
|
286
|
-
"mapPathToBank",
|
|
287
|
-
"dynamicBankId",
|
|
288
|
-
"resolveWorktrees",
|
|
289
|
-
// Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
|
|
290
|
-
// only ever arrive too late to matter — strip them rather than let them read as effective.
|
|
291
|
-
"optInOnly",
|
|
292
|
-
"optInPaths",
|
|
293
|
-
"harness"
|
|
294
|
-
];
|
|
295
|
-
function applyBankConfig(cfg, resolvedId, directory) {
|
|
296
|
-
if (directory !== void 0 && !isOptedIn(cfg, directory))
|
|
297
|
-
return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
|
|
298
|
-
const section = cfg.banks[resolvedId];
|
|
299
|
-
if (!section) return { cfg, bankId: resolvedId };
|
|
300
|
-
const safe = { ...section };
|
|
301
|
-
for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
|
|
302
|
-
delete safe.banks;
|
|
303
|
-
const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
|
|
304
|
-
delete safe.bank;
|
|
305
|
-
return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
|
|
306
|
-
}
|
|
307
|
-
function resolvePartial(cfg, patch) {
|
|
308
|
-
const full = resolveConfig(patch);
|
|
309
|
-
const out = {};
|
|
310
|
-
for (const key of Object.keys(patch)) {
|
|
311
|
-
if (key in full)
|
|
312
|
-
out[key] = full[key];
|
|
313
|
-
}
|
|
314
|
-
return out;
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
// src/core/diag.ts
|
|
318
|
-
import { appendFileSync as appendFileSync2 } from "fs";
|
|
319
|
-
|
|
320
147
|
// src/core/log.ts
|
|
321
148
|
import { appendFileSync, mkdirSync } from "fs";
|
|
322
149
|
import { tmpdir } from "os";
|
|
323
|
-
import { dirname as dirname3, join as
|
|
150
|
+
import { dirname as dirname3, join as join3 } from "path";
|
|
324
151
|
var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
|
|
325
152
|
var current = ["debug", "info", "warn", "error"].find(
|
|
326
153
|
(l) => l === process.env.HINDSIGHT_LOG_LEVEL
|
|
@@ -329,7 +156,7 @@ function setLogLevel(level) {
|
|
|
329
156
|
if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
|
|
330
157
|
}
|
|
331
158
|
function logFilePath() {
|
|
332
|
-
return process.env.HINDSIGHT_LOG_FILE ||
|
|
159
|
+
return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
|
|
333
160
|
}
|
|
334
161
|
function write(level, scope, msg, extra) {
|
|
335
162
|
if (WEIGHT[level] < WEIGHT[current]) return;
|
|
@@ -349,20 +176,19 @@ var log = {
|
|
|
349
176
|
warn: (scope, msg, extra) => write("warn", scope, msg, extra),
|
|
350
177
|
error: (scope, msg, extra) => write("error", scope, msg, extra)
|
|
351
178
|
};
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
}
|
|
179
|
+
function describeError(value, maxChars = 200) {
|
|
180
|
+
const parts = [];
|
|
181
|
+
const seen = /* @__PURE__ */ new Set();
|
|
182
|
+
let current2 = value;
|
|
183
|
+
while (current2 && !seen.has(current2)) {
|
|
184
|
+
seen.add(current2);
|
|
185
|
+
const error = current2;
|
|
186
|
+
const text = typeof error.message === "string" ? error.message : String(current2);
|
|
187
|
+
const withCode = error.code ? `${text} (${String(error.code)})` : text;
|
|
188
|
+
if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
|
|
189
|
+
current2 = error.cause;
|
|
190
|
+
}
|
|
191
|
+
return (parts.join(": ") || String(value)).slice(0, maxChars);
|
|
366
192
|
}
|
|
367
193
|
|
|
368
194
|
// src/core/missions.ts
|
|
@@ -440,7 +266,10 @@ var KNOWLEDGE_LABELS = {
|
|
|
440
266
|
}
|
|
441
267
|
]
|
|
442
268
|
};
|
|
443
|
-
|
|
269
|
+
function pageScopeRule(project) {
|
|
270
|
+
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.`;
|
|
271
|
+
}
|
|
272
|
+
var PAGE_TAXONOMY = [
|
|
444
273
|
{
|
|
445
274
|
name: "Component map",
|
|
446
275
|
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.",
|
|
@@ -467,11 +296,23 @@ var PAGES = [
|
|
|
467
296
|
tags: ["knowledge:feature-work"]
|
|
468
297
|
}
|
|
469
298
|
];
|
|
299
|
+
function pagesFor(project) {
|
|
300
|
+
const scope = pageScopeRule(project);
|
|
301
|
+
return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
|
|
302
|
+
}
|
|
470
303
|
var PAGE_MAX_TOKENS = 4096;
|
|
471
|
-
var
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
304
|
+
var PAGE_FACT_TYPES = ["world", "experience", "observation"];
|
|
305
|
+
function buildPageTrigger(cfg = {}) {
|
|
306
|
+
const base = { fact_types: PAGE_FACT_TYPES };
|
|
307
|
+
switch (cfg.pageTriggerType) {
|
|
308
|
+
case "cron":
|
|
309
|
+
return { ...base, refresh_cron: cfg.pageTriggerCron };
|
|
310
|
+
case "manual":
|
|
311
|
+
return { ...base, refresh_after_consolidation: false };
|
|
312
|
+
default:
|
|
313
|
+
return { ...base, refresh_after_consolidation: true };
|
|
314
|
+
}
|
|
315
|
+
}
|
|
475
316
|
var CODING_BANK_TEMPLATE = {
|
|
476
317
|
version: "1",
|
|
477
318
|
bank: {
|
|
@@ -526,6 +367,7 @@ async function pool(items, n, fn, onError, onProgress) {
|
|
|
526
367
|
}
|
|
527
368
|
|
|
528
369
|
// src/core/hindsight.ts
|
|
370
|
+
var DEFAULT_OBSERVATION_SCOPES = "shared";
|
|
529
371
|
var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
|
|
530
372
|
var RateLimitedError = class extends Error {
|
|
531
373
|
constructor(retryAfterMs2) {
|
|
@@ -558,8 +400,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
|
|
|
558
400
|
var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
|
|
559
401
|
var HindsightClient = class {
|
|
560
402
|
apiUrl;
|
|
561
|
-
|
|
403
|
+
/** The credential the NEXT request will sign with — NOT the one the config file holds. The two
|
|
404
|
+
* diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
|
|
405
|
+
token;
|
|
406
|
+
tokenProvider;
|
|
562
407
|
bank;
|
|
408
|
+
project;
|
|
563
409
|
opIds = [];
|
|
564
410
|
// async operation ids collected by retain(), for drain()
|
|
565
411
|
/** Tri-state capability probe: unknown until the first page request, then cached. */
|
|
@@ -568,34 +414,81 @@ var HindsightClient = class {
|
|
|
568
414
|
idempotentRetain;
|
|
569
415
|
log;
|
|
570
416
|
maxParallelRetains;
|
|
417
|
+
observationScopes;
|
|
571
418
|
constructor(o) {
|
|
572
419
|
this.apiUrl = o.apiUrl.replace(/\/$/, "");
|
|
573
|
-
this.
|
|
420
|
+
this.token = o.apiToken;
|
|
421
|
+
this.tokenProvider = o.tokenProvider;
|
|
574
422
|
this.bank = o.bank;
|
|
423
|
+
this.project = o.project;
|
|
575
424
|
this.log = o.log ?? (() => {
|
|
576
425
|
});
|
|
577
426
|
this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
|
|
427
|
+
this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
|
|
428
|
+
}
|
|
429
|
+
/** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
|
|
430
|
+
get apiToken() {
|
|
431
|
+
return this.token;
|
|
578
432
|
}
|
|
579
433
|
headers() {
|
|
580
434
|
const h = { "Content-Type": "application/json" };
|
|
581
|
-
if (this.
|
|
435
|
+
if (this.token) h["Authorization"] = `Bearer ${this.token}`;
|
|
582
436
|
return h;
|
|
583
437
|
}
|
|
438
|
+
/** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
|
|
439
|
+
* only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
|
|
440
|
+
* doubling every failing request. */
|
|
441
|
+
refreshToken() {
|
|
442
|
+
if (!this.tokenProvider) return false;
|
|
443
|
+
let next;
|
|
444
|
+
try {
|
|
445
|
+
next = this.tokenProvider();
|
|
446
|
+
} catch {
|
|
447
|
+
return false;
|
|
448
|
+
}
|
|
449
|
+
if (next === this.token) return false;
|
|
450
|
+
this.token = next;
|
|
451
|
+
return true;
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
|
|
455
|
+
* poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
|
|
456
|
+
* failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
|
|
457
|
+
* not.
|
|
458
|
+
*
|
|
459
|
+
* On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
|
|
460
|
+
* string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
|
|
461
|
+
* free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
|
|
462
|
+
* bounds the whole call.
|
|
463
|
+
*/
|
|
464
|
+
async fetchWithAuth(url, init) {
|
|
465
|
+
const send = () => fetch(url, { ...init, headers: this.headers() });
|
|
466
|
+
const r = await send();
|
|
467
|
+
if (r.status !== 401 || !this.refreshToken()) return r;
|
|
468
|
+
return send();
|
|
469
|
+
}
|
|
470
|
+
/** A 401 with no `Authorization` header is a different failure from a rejected key, and the
|
|
471
|
+
* server answers identically for both — only the client knows which it sent. */
|
|
472
|
+
authHint(status) {
|
|
473
|
+
if (status !== 401) return "";
|
|
474
|
+
return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
|
|
475
|
+
}
|
|
584
476
|
bankUrl(suffix = "") {
|
|
585
477
|
return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
|
|
586
478
|
}
|
|
587
479
|
/** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
|
|
588
480
|
async req(method, url, body, tolerate = []) {
|
|
589
|
-
const r = await
|
|
481
|
+
const r = await this.fetchWithAuth(url, {
|
|
590
482
|
method,
|
|
591
|
-
headers: this.headers(),
|
|
592
483
|
body: body ? JSON.stringify(body) : void 0,
|
|
593
484
|
signal: AbortSignal.timeout(15e3)
|
|
594
485
|
});
|
|
595
486
|
if (r.status === 429 && !tolerate.includes(429))
|
|
596
487
|
throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
|
|
597
488
|
if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
|
|
598
|
-
throw new Error(
|
|
489
|
+
throw new Error(
|
|
490
|
+
`${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
|
|
491
|
+
);
|
|
599
492
|
return r;
|
|
600
493
|
}
|
|
601
494
|
/** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
|
|
@@ -606,7 +499,11 @@ var HindsightClient = class {
|
|
|
606
499
|
context,
|
|
607
500
|
document_id: documentId,
|
|
608
501
|
tags,
|
|
609
|
-
strategy
|
|
502
|
+
strategy,
|
|
503
|
+
// Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
|
|
504
|
+
// observations were built under is a property of the write rather than of whichever server
|
|
505
|
+
// version happened to process it. Servers older than 0.4.15 ignore the field.
|
|
506
|
+
observation_scopes: this.observationScopes
|
|
610
507
|
};
|
|
611
508
|
if (opts.timestamp) item.timestamp = opts.timestamp;
|
|
612
509
|
if (opts.metadata) item.metadata = opts.metadata;
|
|
@@ -685,7 +582,7 @@ var HindsightClient = class {
|
|
|
685
582
|
this.log(
|
|
686
583
|
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}`
|
|
687
584
|
);
|
|
688
|
-
await this.seedPages();
|
|
585
|
+
await this.seedPages(opts.pageTrigger);
|
|
689
586
|
}
|
|
690
587
|
/**
|
|
691
588
|
* Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
|
|
@@ -743,7 +640,7 @@ var HindsightClient = class {
|
|
|
743
640
|
let backoffMs = POLL_CYCLE_MS;
|
|
744
641
|
await pool([...pending], this.maxParallelRetains, async (id) => {
|
|
745
642
|
try {
|
|
746
|
-
const r = await
|
|
643
|
+
const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
|
|
747
644
|
if (r.status === 429) {
|
|
748
645
|
backoffMs = Math.min(
|
|
749
646
|
RETRY_AFTER_CEILING_MS,
|
|
@@ -769,18 +666,23 @@ var HindsightClient = class {
|
|
|
769
666
|
`[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
|
|
770
667
|
);
|
|
771
668
|
}
|
|
772
|
-
/**
|
|
773
|
-
|
|
669
|
+
/**
|
|
670
|
+
* Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
|
|
671
|
+
* caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
|
|
672
|
+
* magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
|
|
673
|
+
* tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
|
|
674
|
+
* tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
|
|
675
|
+
*/
|
|
676
|
+
async reflect(query, opts) {
|
|
774
677
|
const ctrl = new AbortController();
|
|
775
|
-
const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs
|
|
678
|
+
const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
|
|
776
679
|
try {
|
|
777
|
-
const resp = await
|
|
680
|
+
const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
|
|
778
681
|
method: "POST",
|
|
779
|
-
headers: this.headers(),
|
|
780
682
|
body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
|
|
781
683
|
signal: ctrl.signal
|
|
782
684
|
});
|
|
783
|
-
if (!resp.ok) throw new Error(`reflect ${resp.status}`);
|
|
685
|
+
if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
|
|
784
686
|
const data = await resp.json();
|
|
785
687
|
return (data.text || "").trim();
|
|
786
688
|
} finally {
|
|
@@ -864,16 +766,18 @@ var HindsightClient = class {
|
|
|
864
766
|
}));
|
|
865
767
|
}
|
|
866
768
|
/**
|
|
867
|
-
* Seed the fixed
|
|
769
|
+
* Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
|
|
868
770
|
*
|
|
869
771
|
* Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
|
|
870
772
|
* client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
|
|
871
773
|
* off a slug). Names are unique per folder server-side, which makes them a sound key.
|
|
872
774
|
*
|
|
873
775
|
* An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
|
|
874
|
-
* `source_query` re-syncs onto the live page instead of orphaning its synthesized content
|
|
776
|
+
* `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
|
|
777
|
+
* which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
|
|
875
778
|
*/
|
|
876
|
-
async seedPages() {
|
|
779
|
+
async seedPages(pageTrigger = buildPageTrigger()) {
|
|
780
|
+
const pages = pagesFor(this.project ?? this.bank);
|
|
877
781
|
const existing = /* @__PURE__ */ new Map();
|
|
878
782
|
let roots;
|
|
879
783
|
try {
|
|
@@ -890,14 +794,14 @@ var HindsightClient = class {
|
|
|
890
794
|
}
|
|
891
795
|
let created = 0;
|
|
892
796
|
let updated = 0;
|
|
893
|
-
for (const page of
|
|
797
|
+
for (const page of pages) {
|
|
894
798
|
const hit = existing.get(page.name.toLowerCase());
|
|
895
799
|
const body = {
|
|
896
800
|
name: page.name,
|
|
897
801
|
source_query: page.source_query,
|
|
898
802
|
tags: page.tags,
|
|
899
803
|
max_tokens: PAGE_MAX_TOKENS,
|
|
900
|
-
trigger:
|
|
804
|
+
trigger: pageTrigger
|
|
901
805
|
};
|
|
902
806
|
if (!hit) {
|
|
903
807
|
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
|
|
@@ -926,7 +830,7 @@ var HindsightClient = class {
|
|
|
926
830
|
}
|
|
927
831
|
}
|
|
928
832
|
this.log(
|
|
929
|
-
`[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${
|
|
833
|
+
`[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
|
|
930
834
|
);
|
|
931
835
|
}
|
|
932
836
|
/** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
|
|
@@ -936,7 +840,8 @@ var HindsightClient = class {
|
|
|
936
840
|
/**
|
|
937
841
|
* Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
|
|
938
842
|
* New initiative → creates a page under the Initiatives folder tagged `relatedPageId:<pageId>`.
|
|
939
|
-
*
|
|
843
|
+
* Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
|
|
844
|
+
* enhancement or a mid-work plan change lands on the initiative it belongs to.
|
|
940
845
|
*/
|
|
941
846
|
async captureInitiative(args) {
|
|
942
847
|
let pageId = args.relatesToPageId;
|
|
@@ -947,10 +852,7 @@ var HindsightClient = class {
|
|
|
947
852
|
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.`,
|
|
948
853
|
parent_id: folderId,
|
|
949
854
|
tags: ["knowledge:feature-work"],
|
|
950
|
-
trigger:
|
|
951
|
-
fact_types: ["world", "experience", "observation"],
|
|
952
|
-
refresh_after_consolidation: true
|
|
953
|
-
}
|
|
855
|
+
trigger: args.pageTrigger ?? buildPageTrigger()
|
|
954
856
|
});
|
|
955
857
|
try {
|
|
956
858
|
const j = await r.json();
|
|
@@ -959,7 +861,7 @@ var HindsightClient = class {
|
|
|
959
861
|
}
|
|
960
862
|
pageId ||= `initiative-${this.slugify(args.title)}`;
|
|
961
863
|
}
|
|
962
|
-
const verb = args.relatesToPageId ? "
|
|
864
|
+
const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
|
|
963
865
|
const content = `${verb}: ${args.title}. ${args.summary}`;
|
|
964
866
|
const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
|
|
965
867
|
const tags = [
|
|
@@ -997,6 +899,260 @@ var HindsightClient = class {
|
|
|
997
899
|
}
|
|
998
900
|
};
|
|
999
901
|
|
|
902
|
+
// src/core/config.ts
|
|
903
|
+
var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
|
|
904
|
+
var DEFAULT_DAEMON_PORT = 9077;
|
|
905
|
+
var DEFAULT_DAEMON_PROFILE = "coding-agent";
|
|
906
|
+
function resolvePageTriggerType(raw) {
|
|
907
|
+
if (raw.pageTriggerType === "manual") return "manual";
|
|
908
|
+
if (raw.pageTriggerType === "cron") {
|
|
909
|
+
if (raw.pageTriggerCron?.trim()) return "cron";
|
|
910
|
+
log.warn(
|
|
911
|
+
"config",
|
|
912
|
+
'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
|
|
913
|
+
);
|
|
914
|
+
}
|
|
915
|
+
return "auto-refresh";
|
|
916
|
+
}
|
|
917
|
+
var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
|
|
918
|
+
var REFLECT_BUDGETS = ["low", "mid", "high"];
|
|
919
|
+
function resolveReflectBudget(raw) {
|
|
920
|
+
const value = raw.reflectBudget;
|
|
921
|
+
if (value === void 0) return "high";
|
|
922
|
+
if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
|
|
923
|
+
return value;
|
|
924
|
+
log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
|
|
925
|
+
return "high";
|
|
926
|
+
}
|
|
927
|
+
var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
|
|
928
|
+
function resolveObservationScopes(raw) {
|
|
929
|
+
const value = raw;
|
|
930
|
+
if (typeof value === "string")
|
|
931
|
+
return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
|
|
932
|
+
if (Array.isArray(value)) {
|
|
933
|
+
const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
|
|
934
|
+
if (scopes.length) return scopes;
|
|
935
|
+
}
|
|
936
|
+
return DEFAULT_OBSERVATION_SCOPES;
|
|
937
|
+
}
|
|
938
|
+
function resolveConfig(raw = {}) {
|
|
939
|
+
const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
|
|
940
|
+
const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
|
|
941
|
+
return {
|
|
942
|
+
serverMode,
|
|
943
|
+
// Daemon mode resolves the URL HERE rather than at each call site: every entry point already
|
|
944
|
+
// builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
|
|
945
|
+
// daemon needs no plumbing through eight separate constructors.
|
|
946
|
+
apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
|
|
947
|
+
apiToken: raw.apiToken || void 0,
|
|
948
|
+
apiPort,
|
|
949
|
+
daemonIdleTimeout: raw.daemonIdleTimeout,
|
|
950
|
+
daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
|
|
951
|
+
embedVersion: raw.embedVersion || void 0,
|
|
952
|
+
embedPackagePath: raw.embedPackagePath || void 0,
|
|
953
|
+
bankId: raw.bankId,
|
|
954
|
+
dynamicBankId: raw.dynamicBankId,
|
|
955
|
+
bankIdTemplate: raw.bankIdTemplate,
|
|
956
|
+
mapPathToBank: raw.mapPathToBank,
|
|
957
|
+
resolveWorktrees: raw.resolveWorktrees,
|
|
958
|
+
optInOnly: raw.optInOnly ?? false,
|
|
959
|
+
// Same shape as retainTags: a config typo must not become a path that silently approves nothing.
|
|
960
|
+
optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
|
|
961
|
+
harness: raw.harness ?? "opencode",
|
|
962
|
+
disabled: raw.disabled ?? false,
|
|
963
|
+
retainSessions: raw.retainSessions ?? true,
|
|
964
|
+
// write sessions back by default, every harness
|
|
965
|
+
maxParallelRetains: raw.maxParallelRetains || 10,
|
|
966
|
+
reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
|
|
967
|
+
// Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
|
|
968
|
+
// reflect already set), but never let it LOWER the tool below the default — a short window is
|
|
969
|
+
// set to bound the automatic hook, not to cut off a call the agent is waiting on.
|
|
970
|
+
reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
|
|
971
|
+
reflectBudget: resolveReflectBudget(raw),
|
|
972
|
+
autoReflect: raw.autoReflect ?? true,
|
|
973
|
+
pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
|
|
974
|
+
pageTriggerType: resolvePageTriggerType(raw),
|
|
975
|
+
pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
|
|
976
|
+
autoSeed: raw.autoSeed ?? true,
|
|
977
|
+
seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
|
|
978
|
+
codebaseSurvey: raw.codebaseSurvey ?? true,
|
|
979
|
+
surveyModel: raw.surveyModel || "haiku",
|
|
980
|
+
surveyBudgetUsd: raw.surveyBudgetUsd || 2,
|
|
981
|
+
surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
|
|
982
|
+
gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
|
|
983
|
+
// Hostile input is a config typo, not an attack: keep only string entries so a stray number or
|
|
984
|
+
// nested object cannot reach the API as a tag and fail the whole retain.
|
|
985
|
+
retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
|
|
986
|
+
retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
|
|
987
|
+
Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
|
|
988
|
+
) : {},
|
|
989
|
+
observationScopes: resolveObservationScopes(raw.observationScopes),
|
|
990
|
+
banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
|
|
991
|
+
logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
|
|
992
|
+
};
|
|
993
|
+
}
|
|
994
|
+
function readRaw(path) {
|
|
995
|
+
try {
|
|
996
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
997
|
+
} catch (e) {
|
|
998
|
+
if (e?.code !== "ENOENT") {
|
|
999
|
+
console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
|
|
1000
|
+
}
|
|
1001
|
+
return {};
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
function mergeRaw(a, b) {
|
|
1005
|
+
const { harnesses: _drop, ...flat } = b;
|
|
1006
|
+
return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
|
|
1007
|
+
}
|
|
1008
|
+
function applyLayer(raw, layer, harness) {
|
|
1009
|
+
let out = mergeRaw(raw, layer);
|
|
1010
|
+
const perHarness = harness ? layer.harnesses?.[harness] : void 0;
|
|
1011
|
+
if (perHarness) out = mergeRaw(out, perHarness);
|
|
1012
|
+
return out;
|
|
1013
|
+
}
|
|
1014
|
+
var ENV_KEYS = {
|
|
1015
|
+
serverMode: "HINDSIGHT_SERVER_MODE",
|
|
1016
|
+
apiUrl: "HINDSIGHT_API_URL",
|
|
1017
|
+
apiToken: "HINDSIGHT_API_TOKEN",
|
|
1018
|
+
// These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
|
|
1019
|
+
// it can carry their existing environment over unchanged.
|
|
1020
|
+
apiPort: "HINDSIGHT_API_PORT",
|
|
1021
|
+
daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
|
|
1022
|
+
embedVersion: "HINDSIGHT_EMBED_VERSION",
|
|
1023
|
+
embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
|
|
1024
|
+
daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
|
|
1025
|
+
bankId: "HINDSIGHT_BANK_ID",
|
|
1026
|
+
dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
|
|
1027
|
+
bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
|
|
1028
|
+
resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
|
|
1029
|
+
optInOnly: "HINDSIGHT_OPT_IN_ONLY",
|
|
1030
|
+
optInPaths: "HINDSIGHT_OPT_IN_PATHS",
|
|
1031
|
+
harness: "HINDSIGHT_HARNESS",
|
|
1032
|
+
disabled: "HINDSIGHT_DISABLED",
|
|
1033
|
+
retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
|
|
1034
|
+
maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
|
|
1035
|
+
reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
|
|
1036
|
+
reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
|
|
1037
|
+
reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
|
|
1038
|
+
autoReflect: "HINDSIGHT_AUTO_REFLECT",
|
|
1039
|
+
pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
|
|
1040
|
+
pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
|
|
1041
|
+
pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
|
|
1042
|
+
autoSeed: "HINDSIGHT_AUTO_SEED",
|
|
1043
|
+
seedLimit: "HINDSIGHT_SEED_LIMIT",
|
|
1044
|
+
codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
|
|
1045
|
+
surveyModel: "HINDSIGHT_SURVEY_MODEL",
|
|
1046
|
+
surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
|
|
1047
|
+
surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
|
|
1048
|
+
logLevel: "HINDSIGHT_LOG_LEVEL",
|
|
1049
|
+
gitIngest: "HINDSIGHT_GIT_INGEST",
|
|
1050
|
+
// Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
|
|
1051
|
+
// list is a list OF lists, which does not survive flattening into one variable — file-only.
|
|
1052
|
+
observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
|
|
1053
|
+
// Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
|
|
1054
|
+
// a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
|
|
1055
|
+
retainTags: "HINDSIGHT_RETAIN_TAGS"
|
|
1056
|
+
};
|
|
1057
|
+
var ENV_BOOLEANS = /* @__PURE__ */ new Set([
|
|
1058
|
+
"dynamicBankId",
|
|
1059
|
+
"resolveWorktrees",
|
|
1060
|
+
"optInOnly",
|
|
1061
|
+
"disabled",
|
|
1062
|
+
"retainSessions",
|
|
1063
|
+
"autoReflect",
|
|
1064
|
+
"autoSeed",
|
|
1065
|
+
"codebaseSurvey"
|
|
1066
|
+
]);
|
|
1067
|
+
var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
|
|
1068
|
+
var ENV_NUMBERS = /* @__PURE__ */ new Set([
|
|
1069
|
+
"apiPort",
|
|
1070
|
+
"daemonIdleTimeout",
|
|
1071
|
+
"maxParallelRetains",
|
|
1072
|
+
"reflectTimeoutMs",
|
|
1073
|
+
"reflectToolTimeoutMs",
|
|
1074
|
+
"pageRefreshEveryTurns",
|
|
1075
|
+
"seedLimit",
|
|
1076
|
+
"surveyBudgetUsd",
|
|
1077
|
+
"surveyRefreshCommits"
|
|
1078
|
+
]);
|
|
1079
|
+
function readEnvConfig(env = process.env) {
|
|
1080
|
+
const out = {};
|
|
1081
|
+
for (const [key, name] of Object.entries(ENV_KEYS)) {
|
|
1082
|
+
const value = env[name];
|
|
1083
|
+
if (value === void 0 || value.trim() === "") continue;
|
|
1084
|
+
if (ENV_BOOLEANS.has(key)) {
|
|
1085
|
+
out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
|
|
1086
|
+
} else if (ENV_LISTS.has(key)) {
|
|
1087
|
+
const items = value.split(",").map((v) => v.trim()).filter(Boolean);
|
|
1088
|
+
if (items.length) out[key] = items;
|
|
1089
|
+
} else if (ENV_NUMBERS.has(key)) {
|
|
1090
|
+
const n = Number(value);
|
|
1091
|
+
if (Number.isFinite(n)) out[key] = n;
|
|
1092
|
+
else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
|
|
1093
|
+
} else {
|
|
1094
|
+
out[key] = value;
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
return out;
|
|
1098
|
+
}
|
|
1099
|
+
function loadConfig(opts = {}) {
|
|
1100
|
+
const o = typeof opts === "string" ? { path: opts } : opts;
|
|
1101
|
+
const withEnv = applyLayer({}, readEnvConfig(), o.harness);
|
|
1102
|
+
const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
|
|
1103
|
+
if (!raw.harness && o.harness) raw.harness = o.harness;
|
|
1104
|
+
return resolveConfig(raw);
|
|
1105
|
+
}
|
|
1106
|
+
var BANK_OVERRIDE_EXCLUDED = [
|
|
1107
|
+
"bankId",
|
|
1108
|
+
"bankIdTemplate",
|
|
1109
|
+
"mapPathToBank",
|
|
1110
|
+
"dynamicBankId",
|
|
1111
|
+
"resolveWorktrees",
|
|
1112
|
+
// Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
|
|
1113
|
+
// only ever arrive too late to matter — strip them rather than let them read as effective.
|
|
1114
|
+
"optInOnly",
|
|
1115
|
+
"optInPaths",
|
|
1116
|
+
"harness"
|
|
1117
|
+
];
|
|
1118
|
+
function applyBankConfig(cfg, resolvedId, directory) {
|
|
1119
|
+
if (directory !== void 0 && !isOptedIn(cfg, directory))
|
|
1120
|
+
return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
|
|
1121
|
+
const section = cfg.banks[resolvedId];
|
|
1122
|
+
if (!section) return { cfg, bankId: resolvedId };
|
|
1123
|
+
const safe = { ...section };
|
|
1124
|
+
for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
|
|
1125
|
+
delete safe.banks;
|
|
1126
|
+
const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
|
|
1127
|
+
delete safe.bank;
|
|
1128
|
+
return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
|
|
1129
|
+
}
|
|
1130
|
+
function resolvePartial(cfg, patch) {
|
|
1131
|
+
const full = resolveConfig(patch);
|
|
1132
|
+
const out = {};
|
|
1133
|
+
for (const key of Object.keys(patch)) {
|
|
1134
|
+
if (key in full)
|
|
1135
|
+
out[key] = full[key];
|
|
1136
|
+
}
|
|
1137
|
+
return out;
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
// src/core/diag.ts
|
|
1141
|
+
import { appendFileSync as appendFileSync2 } from "fs";
|
|
1142
|
+
function diagFilePath() {
|
|
1143
|
+
return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
|
|
1144
|
+
}
|
|
1145
|
+
function diag(harness, event, extra = {}) {
|
|
1146
|
+
log.debug(harness, `diag:${event}`, extra);
|
|
1147
|
+
try {
|
|
1148
|
+
appendFileSync2(
|
|
1149
|
+
diagFilePath(),
|
|
1150
|
+
JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
|
|
1151
|
+
);
|
|
1152
|
+
} catch {
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1000
1156
|
// src/core/session-cache.ts
|
|
1001
1157
|
import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "fs";
|
|
1002
1158
|
import { tmpdir as tmpdir2 } from "os";
|
|
@@ -1015,6 +1171,23 @@ function writeFileAtomic(path, body) {
|
|
|
1015
1171
|
throw e;
|
|
1016
1172
|
}
|
|
1017
1173
|
}
|
|
1174
|
+
function sessionRootFile(harness, sessionId) {
|
|
1175
|
+
return join5(tmpdir2(), `hindsight-${harness}`, `${sessionId}.root`);
|
|
1176
|
+
}
|
|
1177
|
+
function sessionRootDir(harness, sessionId, cwd) {
|
|
1178
|
+
if (!sessionId || !cwd) return cwd;
|
|
1179
|
+
const file = sessionRootFile(harness, sessionId);
|
|
1180
|
+
try {
|
|
1181
|
+
const recorded = readFileSync2(file, "utf8").trim();
|
|
1182
|
+
if (recorded) return recorded;
|
|
1183
|
+
} catch {
|
|
1184
|
+
}
|
|
1185
|
+
try {
|
|
1186
|
+
writeFileAtomic(file, cwd);
|
|
1187
|
+
} catch {
|
|
1188
|
+
}
|
|
1189
|
+
return cwd;
|
|
1190
|
+
}
|
|
1018
1191
|
function cursorFile(harness, sessionId) {
|
|
1019
1192
|
return join5(tmpdir2(), `hindsight-${harness}`, `${sessionId}.retain.json`);
|
|
1020
1193
|
}
|
|
@@ -1320,7 +1493,7 @@ function resolversFor(ctx) {
|
|
|
1320
1493
|
return {
|
|
1321
1494
|
// Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
|
|
1322
1495
|
// otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
|
|
1323
|
-
gitProject: () => projectNameOf(ctx.directory),
|
|
1496
|
+
gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
|
|
1324
1497
|
project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
|
|
1325
1498
|
harness: () => ctx.harness,
|
|
1326
1499
|
bankId: () => ctx.bankId,
|
|
@@ -1525,11 +1698,11 @@ async function buildRetain(args) {
|
|
|
1525
1698
|
diag(harness, "retain_ok", { ms: Date.now() - t0, turns: turns.length, session: sessionId });
|
|
1526
1699
|
} catch (e) {
|
|
1527
1700
|
log.warn(harness, "session write-back failed", {
|
|
1528
|
-
error:
|
|
1701
|
+
error: describeError(e)
|
|
1529
1702
|
});
|
|
1530
1703
|
diag(harness, "retain_failed", {
|
|
1531
1704
|
ms: Date.now() - t0,
|
|
1532
|
-
error:
|
|
1705
|
+
error: describeError(e),
|
|
1533
1706
|
session: sessionId
|
|
1534
1707
|
});
|
|
1535
1708
|
}
|
|
@@ -1549,16 +1722,22 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
|
|
|
1549
1722
|
setLogLevel(cfg.logLevel);
|
|
1550
1723
|
if (cfg.disabled) return;
|
|
1551
1724
|
if (!transcriptPath) return;
|
|
1552
|
-
const
|
|
1725
|
+
const sessionRoot = sessionRootDir(spec.harness, sessionId, cwd);
|
|
1726
|
+
const resolved = applyBankConfig(cfg, deriveBankId(cfg, cwd, spec.harness, sessionRoot), cwd);
|
|
1553
1727
|
cfg = resolved.cfg;
|
|
1554
1728
|
const bankId = resolved.bankId;
|
|
1555
1729
|
if (cfg.disabled) return;
|
|
1730
|
+
if (!cfg.retainSessions) {
|
|
1731
|
+
diag(spec.harness, "retain_disabled", { bank: bankId, session: sessionId });
|
|
1732
|
+
return;
|
|
1733
|
+
}
|
|
1556
1734
|
await ensureDaemon(cfg, spec.harness, { waitMs: DAEMON_WAIT_RETAIN_MS });
|
|
1557
1735
|
const client = makeClient({
|
|
1558
1736
|
apiUrl: cfg.apiUrl,
|
|
1559
1737
|
apiToken: cfg.apiToken,
|
|
1560
1738
|
bank: bankId,
|
|
1561
|
-
maxParallelRetains: cfg.maxParallelRetains
|
|
1739
|
+
maxParallelRetains: cfg.maxParallelRetains,
|
|
1740
|
+
observationScopes: cfg.observationScopes
|
|
1562
1741
|
});
|
|
1563
1742
|
await buildRetain({
|
|
1564
1743
|
harness: spec.harness,
|
|
@@ -1569,6 +1748,7 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
|
|
|
1569
1748
|
retryUntil: hostDeadline,
|
|
1570
1749
|
stamp: buildRetainStamp(cfg, {
|
|
1571
1750
|
directory: cwd,
|
|
1751
|
+
sessionRoot,
|
|
1572
1752
|
harness: spec.harness,
|
|
1573
1753
|
bankId,
|
|
1574
1754
|
sessionId: sessionId || "no-session"
|