@vectorize-io/hindsight-coding-agents 0.3.4 → 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 +101 -32
- package/dist/antigravity-hook.js +424 -263
- package/dist/antigravity-statusline.js +130 -27
- package/dist/antigravity-stop-hook.js +431 -265
- package/dist/claude-hook.js +424 -263
- package/dist/claude-sessionstart-hook.js +436 -269
- package/dist/claude-stop-hook.js +431 -265
- package/dist/cline.js +627 -329
- package/dist/codex-hook.js +424 -263
- package/dist/codex-sessionstart-hook.js +436 -269
- package/dist/codex-stop-hook.js +431 -265
- package/dist/copilot-hook.js +424 -263
- package/dist/copilot-sessionstart-hook.js +436 -269
- package/dist/copilot-stop-hook.js +431 -265
- package/dist/cursor-hook.js +424 -263
- package/dist/cursor-sessionstart-hook.js +436 -269
- package/dist/cursor-stop-hook.js +431 -265
- package/dist/daemon-start.js +101 -45
- package/dist/deepen.js +289 -130
- package/dist/devin-hook.js +424 -263
- package/dist/devin-sessionstart-hook.js +436 -269
- package/dist/devin-stop-hook.js +431 -265
- package/dist/dsh.js +870 -573
- package/dist/grok-hook.js +424 -263
- package/dist/grok-sessionstart-hook.js +436 -269
- package/dist/grok-stop-hook.js +431 -265
- package/dist/hindsight-seed.js +122 -24
- package/dist/index.js +665 -366
- package/dist/installer.js +40 -48
- package/dist/kilo.js +665 -366
- package/dist/mcp-server.js +525 -299
- package/dist/prime-agent.js +881 -581
- package/dist/status.js +419 -244
- package/package.json +10 -2
- package/skill/SKILL.md +20 -4
package/dist/claude-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;
|
|
@@ -364,21 +191,6 @@ function describeError(value, maxChars = 200) {
|
|
|
364
191
|
return (parts.join(": ") || String(value)).slice(0, maxChars);
|
|
365
192
|
}
|
|
366
193
|
|
|
367
|
-
// src/core/diag.ts
|
|
368
|
-
function diagFilePath() {
|
|
369
|
-
return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
|
|
370
|
-
}
|
|
371
|
-
function diag(harness, event, extra = {}) {
|
|
372
|
-
log.debug(harness, `diag:${event}`, extra);
|
|
373
|
-
try {
|
|
374
|
-
appendFileSync2(
|
|
375
|
-
diagFilePath(),
|
|
376
|
-
JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
|
|
377
|
-
);
|
|
378
|
-
} catch {
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
|
|
382
194
|
// src/core/missions.ts
|
|
383
195
|
var GIT_MISSION = "You are ingesting a single git commit: its message and its full diff. Extract the concrete technical DECISION and the CAUSE/INVARIANT it encodes, bound to the specific code entities (functions, methods, files) and behaviors it changes. Preserve exact identifiers, paths, and literal values verbatim. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Capture both WHAT changed and WHY. Issue/PR references (#123, GH-123, PROJ-123) are load-bearing: keep them VERBATIM in the fact text and emit each as an ENTITY, so a later question about that issue or PR retrieves this decision.";
|
|
384
196
|
var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, newest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
|
|
@@ -454,7 +266,10 @@ var KNOWLEDGE_LABELS = {
|
|
|
454
266
|
}
|
|
455
267
|
]
|
|
456
268
|
};
|
|
457
|
-
|
|
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 = [
|
|
458
273
|
{
|
|
459
274
|
name: "Component map",
|
|
460
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.",
|
|
@@ -481,11 +296,23 @@ var PAGES = [
|
|
|
481
296
|
tags: ["knowledge:feature-work"]
|
|
482
297
|
}
|
|
483
298
|
];
|
|
299
|
+
function pagesFor(project) {
|
|
300
|
+
const scope = pageScopeRule(project);
|
|
301
|
+
return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
|
|
302
|
+
}
|
|
484
303
|
var PAGE_MAX_TOKENS = 4096;
|
|
485
|
-
var
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
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
|
+
}
|
|
489
316
|
var CODING_BANK_TEMPLATE = {
|
|
490
317
|
version: "1",
|
|
491
318
|
bank: {
|
|
@@ -540,6 +367,7 @@ async function pool(items, n, fn, onError, onProgress) {
|
|
|
540
367
|
}
|
|
541
368
|
|
|
542
369
|
// src/core/hindsight.ts
|
|
370
|
+
var DEFAULT_OBSERVATION_SCOPES = "shared";
|
|
543
371
|
var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
|
|
544
372
|
var RateLimitedError = class extends Error {
|
|
545
373
|
constructor(retryAfterMs2) {
|
|
@@ -572,8 +400,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
|
|
|
572
400
|
var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
|
|
573
401
|
var HindsightClient = class {
|
|
574
402
|
apiUrl;
|
|
575
|
-
|
|
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;
|
|
576
407
|
bank;
|
|
408
|
+
project;
|
|
577
409
|
opIds = [];
|
|
578
410
|
// async operation ids collected by retain(), for drain()
|
|
579
411
|
/** Tri-state capability probe: unknown until the first page request, then cached. */
|
|
@@ -582,34 +414,81 @@ var HindsightClient = class {
|
|
|
582
414
|
idempotentRetain;
|
|
583
415
|
log;
|
|
584
416
|
maxParallelRetains;
|
|
417
|
+
observationScopes;
|
|
585
418
|
constructor(o) {
|
|
586
419
|
this.apiUrl = o.apiUrl.replace(/\/$/, "");
|
|
587
|
-
this.
|
|
420
|
+
this.token = o.apiToken;
|
|
421
|
+
this.tokenProvider = o.tokenProvider;
|
|
588
422
|
this.bank = o.bank;
|
|
423
|
+
this.project = o.project;
|
|
589
424
|
this.log = o.log ?? (() => {
|
|
590
425
|
});
|
|
591
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;
|
|
592
432
|
}
|
|
593
433
|
headers() {
|
|
594
434
|
const h = { "Content-Type": "application/json" };
|
|
595
|
-
if (this.
|
|
435
|
+
if (this.token) h["Authorization"] = `Bearer ${this.token}`;
|
|
596
436
|
return h;
|
|
597
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
|
+
}
|
|
598
476
|
bankUrl(suffix = "") {
|
|
599
477
|
return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
|
|
600
478
|
}
|
|
601
479
|
/** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
|
|
602
480
|
async req(method, url, body, tolerate = []) {
|
|
603
|
-
const r = await
|
|
481
|
+
const r = await this.fetchWithAuth(url, {
|
|
604
482
|
method,
|
|
605
|
-
headers: this.headers(),
|
|
606
483
|
body: body ? JSON.stringify(body) : void 0,
|
|
607
484
|
signal: AbortSignal.timeout(15e3)
|
|
608
485
|
});
|
|
609
486
|
if (r.status === 429 && !tolerate.includes(429))
|
|
610
487
|
throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
|
|
611
488
|
if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
|
|
612
|
-
throw new Error(
|
|
489
|
+
throw new Error(
|
|
490
|
+
`${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
|
|
491
|
+
);
|
|
613
492
|
return r;
|
|
614
493
|
}
|
|
615
494
|
/** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
|
|
@@ -620,7 +499,11 @@ var HindsightClient = class {
|
|
|
620
499
|
context,
|
|
621
500
|
document_id: documentId,
|
|
622
501
|
tags,
|
|
623
|
-
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
|
|
624
507
|
};
|
|
625
508
|
if (opts.timestamp) item.timestamp = opts.timestamp;
|
|
626
509
|
if (opts.metadata) item.metadata = opts.metadata;
|
|
@@ -699,7 +582,7 @@ var HindsightClient = class {
|
|
|
699
582
|
this.log(
|
|
700
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}`
|
|
701
584
|
);
|
|
702
|
-
await this.seedPages();
|
|
585
|
+
await this.seedPages(opts.pageTrigger);
|
|
703
586
|
}
|
|
704
587
|
/**
|
|
705
588
|
* Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
|
|
@@ -757,7 +640,7 @@ var HindsightClient = class {
|
|
|
757
640
|
let backoffMs = POLL_CYCLE_MS;
|
|
758
641
|
await pool([...pending], this.maxParallelRetains, async (id) => {
|
|
759
642
|
try {
|
|
760
|
-
const r = await
|
|
643
|
+
const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
|
|
761
644
|
if (r.status === 429) {
|
|
762
645
|
backoffMs = Math.min(
|
|
763
646
|
RETRY_AFTER_CEILING_MS,
|
|
@@ -783,18 +666,23 @@ var HindsightClient = class {
|
|
|
783
666
|
`[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
|
|
784
667
|
);
|
|
785
668
|
}
|
|
786
|
-
/**
|
|
787
|
-
|
|
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) {
|
|
788
677
|
const ctrl = new AbortController();
|
|
789
|
-
const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs
|
|
678
|
+
const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
|
|
790
679
|
try {
|
|
791
|
-
const resp = await
|
|
680
|
+
const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
|
|
792
681
|
method: "POST",
|
|
793
|
-
headers: this.headers(),
|
|
794
682
|
body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
|
|
795
683
|
signal: ctrl.signal
|
|
796
684
|
});
|
|
797
|
-
if (!resp.ok) throw new Error(`reflect ${resp.status}`);
|
|
685
|
+
if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
|
|
798
686
|
const data = await resp.json();
|
|
799
687
|
return (data.text || "").trim();
|
|
800
688
|
} finally {
|
|
@@ -878,16 +766,18 @@ var HindsightClient = class {
|
|
|
878
766
|
}));
|
|
879
767
|
}
|
|
880
768
|
/**
|
|
881
|
-
* Seed the fixed
|
|
769
|
+
* Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
|
|
882
770
|
*
|
|
883
771
|
* Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
|
|
884
772
|
* client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
|
|
885
773
|
* off a slug). Names are unique per folder server-side, which makes them a sound key.
|
|
886
774
|
*
|
|
887
775
|
* An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
|
|
888
|
-
* `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.
|
|
889
778
|
*/
|
|
890
|
-
async seedPages() {
|
|
779
|
+
async seedPages(pageTrigger = buildPageTrigger()) {
|
|
780
|
+
const pages = pagesFor(this.project ?? this.bank);
|
|
891
781
|
const existing = /* @__PURE__ */ new Map();
|
|
892
782
|
let roots;
|
|
893
783
|
try {
|
|
@@ -904,14 +794,14 @@ var HindsightClient = class {
|
|
|
904
794
|
}
|
|
905
795
|
let created = 0;
|
|
906
796
|
let updated = 0;
|
|
907
|
-
for (const page of
|
|
797
|
+
for (const page of pages) {
|
|
908
798
|
const hit = existing.get(page.name.toLowerCase());
|
|
909
799
|
const body = {
|
|
910
800
|
name: page.name,
|
|
911
801
|
source_query: page.source_query,
|
|
912
802
|
tags: page.tags,
|
|
913
803
|
max_tokens: PAGE_MAX_TOKENS,
|
|
914
|
-
trigger:
|
|
804
|
+
trigger: pageTrigger
|
|
915
805
|
};
|
|
916
806
|
if (!hit) {
|
|
917
807
|
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
|
|
@@ -940,7 +830,7 @@ var HindsightClient = class {
|
|
|
940
830
|
}
|
|
941
831
|
}
|
|
942
832
|
this.log(
|
|
943
|
-
`[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`
|
|
944
834
|
);
|
|
945
835
|
}
|
|
946
836
|
/** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
|
|
@@ -950,7 +840,8 @@ var HindsightClient = class {
|
|
|
950
840
|
/**
|
|
951
841
|
* Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
|
|
952
842
|
* New initiative → creates a page under the Initiatives folder tagged `relatedPageId:<pageId>`.
|
|
953
|
-
*
|
|
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.
|
|
954
845
|
*/
|
|
955
846
|
async captureInitiative(args) {
|
|
956
847
|
let pageId = args.relatesToPageId;
|
|
@@ -961,10 +852,7 @@ var HindsightClient = class {
|
|
|
961
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.`,
|
|
962
853
|
parent_id: folderId,
|
|
963
854
|
tags: ["knowledge:feature-work"],
|
|
964
|
-
trigger:
|
|
965
|
-
fact_types: ["world", "experience", "observation"],
|
|
966
|
-
refresh_after_consolidation: true
|
|
967
|
-
}
|
|
855
|
+
trigger: args.pageTrigger ?? buildPageTrigger()
|
|
968
856
|
});
|
|
969
857
|
try {
|
|
970
858
|
const j = await r.json();
|
|
@@ -973,7 +861,7 @@ var HindsightClient = class {
|
|
|
973
861
|
}
|
|
974
862
|
pageId ||= `initiative-${this.slugify(args.title)}`;
|
|
975
863
|
}
|
|
976
|
-
const verb = args.relatesToPageId ? "
|
|
864
|
+
const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
|
|
977
865
|
const content = `${verb}: ${args.title}. ${args.summary}`;
|
|
978
866
|
const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
|
|
979
867
|
const tags = [
|
|
@@ -1011,6 +899,260 @@ var HindsightClient = class {
|
|
|
1011
899
|
}
|
|
1012
900
|
};
|
|
1013
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
|
+
|
|
1014
1156
|
// src/core/session-cache.ts
|
|
1015
1157
|
import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "fs";
|
|
1016
1158
|
import { tmpdir as tmpdir2 } from "os";
|
|
@@ -1029,6 +1171,23 @@ function writeFileAtomic(path, body) {
|
|
|
1029
1171
|
throw e;
|
|
1030
1172
|
}
|
|
1031
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
|
+
}
|
|
1032
1191
|
function cursorFile(harness, sessionId) {
|
|
1033
1192
|
return join5(tmpdir2(), `hindsight-${harness}`, `${sessionId}.retain.json`);
|
|
1034
1193
|
}
|
|
@@ -1334,7 +1493,7 @@ function resolversFor(ctx) {
|
|
|
1334
1493
|
return {
|
|
1335
1494
|
// Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
|
|
1336
1495
|
// otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
|
|
1337
|
-
gitProject: () => projectNameOf(ctx.directory),
|
|
1496
|
+
gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
|
|
1338
1497
|
project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
|
|
1339
1498
|
harness: () => ctx.harness,
|
|
1340
1499
|
bankId: () => ctx.bankId,
|
|
@@ -1563,16 +1722,22 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
|
|
|
1563
1722
|
setLogLevel(cfg.logLevel);
|
|
1564
1723
|
if (cfg.disabled) return;
|
|
1565
1724
|
if (!transcriptPath) return;
|
|
1566
|
-
const
|
|
1725
|
+
const sessionRoot = sessionRootDir(spec.harness, sessionId, cwd);
|
|
1726
|
+
const resolved = applyBankConfig(cfg, deriveBankId(cfg, cwd, spec.harness, sessionRoot), cwd);
|
|
1567
1727
|
cfg = resolved.cfg;
|
|
1568
1728
|
const bankId = resolved.bankId;
|
|
1569
1729
|
if (cfg.disabled) return;
|
|
1730
|
+
if (!cfg.retainSessions) {
|
|
1731
|
+
diag(spec.harness, "retain_disabled", { bank: bankId, session: sessionId });
|
|
1732
|
+
return;
|
|
1733
|
+
}
|
|
1570
1734
|
await ensureDaemon(cfg, spec.harness, { waitMs: DAEMON_WAIT_RETAIN_MS });
|
|
1571
1735
|
const client = makeClient({
|
|
1572
1736
|
apiUrl: cfg.apiUrl,
|
|
1573
1737
|
apiToken: cfg.apiToken,
|
|
1574
1738
|
bank: bankId,
|
|
1575
|
-
maxParallelRetains: cfg.maxParallelRetains
|
|
1739
|
+
maxParallelRetains: cfg.maxParallelRetains,
|
|
1740
|
+
observationScopes: cfg.observationScopes
|
|
1576
1741
|
});
|
|
1577
1742
|
await buildRetain({
|
|
1578
1743
|
harness: spec.harness,
|
|
@@ -1583,6 +1748,7 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
|
|
|
1583
1748
|
retryUntil: hostDeadline,
|
|
1584
1749
|
stamp: buildRetainStamp(cfg, {
|
|
1585
1750
|
directory: cwd,
|
|
1751
|
+
sessionRoot,
|
|
1586
1752
|
harness: spec.harness,
|
|
1587
1753
|
bankId,
|
|
1588
1754
|
sessionId: sessionId || "no-session"
|