@vectorize-io/hindsight-coding-agents 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +334 -0
- package/dist/antigravity-hook.js +1556 -0
- package/dist/antigravity-statusline.js +194 -0
- package/dist/antigravity-stop-hook.js +1453 -0
- package/dist/claude-hook.js +1556 -0
- package/dist/claude-sessionstart-hook.js +1814 -0
- package/dist/claude-stop-hook.js +1453 -0
- package/dist/cline.js +16373 -0
- package/dist/codex-hook.js +1556 -0
- package/dist/codex-sessionstart-hook.js +1814 -0
- package/dist/codex-stop-hook.js +1453 -0
- package/dist/copilot-hook.js +1556 -0
- package/dist/copilot-sessionstart-hook.js +1814 -0
- package/dist/copilot-stop-hook.js +1453 -0
- package/dist/cursor-hook.js +1556 -0
- package/dist/cursor-sessionstart-hook.js +1814 -0
- package/dist/cursor-stop-hook.js +1453 -0
- package/dist/deepen.js +1175 -0
- package/dist/devin-hook.js +1556 -0
- package/dist/devin-sessionstart-hook.js +1814 -0
- package/dist/devin-stop-hook.js +1453 -0
- package/dist/grok-hook.js +1556 -0
- package/dist/grok-sessionstart-hook.js +1814 -0
- package/dist/grok-stop-hook.js +1453 -0
- package/dist/hindsight-seed.js +180 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +28853 -0
- package/dist/installer.js +1313 -0
- package/dist/kilo.js +28853 -0
- package/dist/mcp-server.js +31888 -0
- package/dist/status.js +793 -0
- package/package.json +65 -0
- package/skill/SKILL.md +122 -0
|
@@ -0,0 +1,1453 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/core/hook.ts
|
|
4
|
+
import { existsSync, readFileSync as readFileSync3 } from "fs";
|
|
5
|
+
|
|
6
|
+
// src/core/bank.ts
|
|
7
|
+
import { execFileSync } from "child_process";
|
|
8
|
+
import { homedir } from "os";
|
|
9
|
+
import { basename, dirname, join, normalize, sep } from "path";
|
|
10
|
+
var DEFAULT_BANK_NAME = "coding";
|
|
11
|
+
var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
|
|
12
|
+
var PLACEHOLDER = /\{([a-zA-Z]+)\}/g;
|
|
13
|
+
function getProjectRootFromGit(directory) {
|
|
14
|
+
if (!directory) return null;
|
|
15
|
+
try {
|
|
16
|
+
const commonDir = execFileSync(
|
|
17
|
+
"git",
|
|
18
|
+
["rev-parse", "--path-format=absolute", "--git-common-dir"],
|
|
19
|
+
{ cwd: directory, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 1e3 }
|
|
20
|
+
).trim();
|
|
21
|
+
if (!commonDir) return null;
|
|
22
|
+
return basename(commonDir) === ".git" ? dirname(commonDir) : commonDir;
|
|
23
|
+
} catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function gitProjectName(directory, resolveWorktrees) {
|
|
28
|
+
if (resolveWorktrees) {
|
|
29
|
+
const root = getProjectRootFromGit(directory);
|
|
30
|
+
if (root) return basename(root);
|
|
31
|
+
}
|
|
32
|
+
return directory ? basename(directory) : "unknown";
|
|
33
|
+
}
|
|
34
|
+
function mapLookup(map, directory) {
|
|
35
|
+
const cwd = normalize(directory);
|
|
36
|
+
let best;
|
|
37
|
+
for (const [dir, bank] of Object.entries(map)) {
|
|
38
|
+
const expanded = dir === "~" || dir.startsWith("~/") ? join(homedir(), dir.slice(1)) : dir;
|
|
39
|
+
const p = normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
|
|
40
|
+
if (cwd === p || cwd.startsWith(p + sep)) {
|
|
41
|
+
if (!best || p.length > best.len) best = { len: p.length, bank };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return best?.bank;
|
|
45
|
+
}
|
|
46
|
+
function deriveBankId(config, directory, harness = "coding") {
|
|
47
|
+
const mapped = directory && config.mapPathToBank ? mapLookup(config.mapPathToBank, directory) : void 0;
|
|
48
|
+
if (mapped) return mapped;
|
|
49
|
+
const dynamic = config.dynamicBankId ?? !config.bankId;
|
|
50
|
+
if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
|
|
51
|
+
const resolvers = {
|
|
52
|
+
harness: () => harness,
|
|
53
|
+
project: () => directory ? basename(directory) : "unknown",
|
|
54
|
+
gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true),
|
|
55
|
+
channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
|
|
56
|
+
user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
|
|
57
|
+
};
|
|
58
|
+
return (config.bankIdTemplate || DEFAULT_TEMPLATE).replace(PLACEHOLDER, (_, name) => {
|
|
59
|
+
const r = resolvers[name];
|
|
60
|
+
if (!r) {
|
|
61
|
+
console.error(
|
|
62
|
+
`hindsight: unknown bankIdTemplate placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
|
|
63
|
+
);
|
|
64
|
+
return "unknown";
|
|
65
|
+
}
|
|
66
|
+
return r();
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// src/core/config.ts
|
|
71
|
+
import { readFileSync } from "fs";
|
|
72
|
+
import { homedir as homedir2 } from "os";
|
|
73
|
+
import { join as join3 } from "path";
|
|
74
|
+
|
|
75
|
+
// src/core/seed.ts
|
|
76
|
+
import { spawn as realSpawn } from "child_process";
|
|
77
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
78
|
+
import { fileURLToPath } from "url";
|
|
79
|
+
var DEFAULT_SEED_LIMIT = 300;
|
|
80
|
+
|
|
81
|
+
// src/core/config.ts
|
|
82
|
+
var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
|
|
83
|
+
function resolveConfig(raw = {}) {
|
|
84
|
+
return {
|
|
85
|
+
apiUrl: raw.apiUrl ?? "https://api.hindsight.vectorize.io",
|
|
86
|
+
apiToken: raw.apiToken || void 0,
|
|
87
|
+
bankId: raw.bankId,
|
|
88
|
+
dynamicBankId: raw.dynamicBankId,
|
|
89
|
+
bankIdTemplate: raw.bankIdTemplate,
|
|
90
|
+
mapPathToBank: raw.mapPathToBank,
|
|
91
|
+
resolveWorktrees: raw.resolveWorktrees,
|
|
92
|
+
harness: raw.harness ?? "opencode",
|
|
93
|
+
disabled: raw.disabled ?? false,
|
|
94
|
+
retainSessions: raw.retainSessions ?? true,
|
|
95
|
+
// opencode: write back by default (parity with hook-harness Stop)
|
|
96
|
+
retainEveryTurns: raw.retainEveryTurns || 1,
|
|
97
|
+
reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
|
|
98
|
+
autoReflect: raw.autoReflect ?? true,
|
|
99
|
+
pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
|
|
100
|
+
autoSeed: raw.autoSeed ?? true,
|
|
101
|
+
seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
|
|
102
|
+
codebaseSurvey: raw.codebaseSurvey ?? true,
|
|
103
|
+
surveyModel: raw.surveyModel || "haiku",
|
|
104
|
+
surveyBudgetUsd: raw.surveyBudgetUsd || 2,
|
|
105
|
+
surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
|
|
106
|
+
gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
|
|
107
|
+
banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
|
|
108
|
+
logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
function readRaw(path) {
|
|
112
|
+
try {
|
|
113
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
114
|
+
} catch (e) {
|
|
115
|
+
if (e?.code !== "ENOENT") {
|
|
116
|
+
console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
|
|
117
|
+
}
|
|
118
|
+
return {};
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function mergeRaw(a, b) {
|
|
122
|
+
const { harnesses: _drop, ...flat } = b;
|
|
123
|
+
return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
|
|
124
|
+
}
|
|
125
|
+
function applyLayer(raw, layer, harness) {
|
|
126
|
+
let out = mergeRaw(raw, layer);
|
|
127
|
+
const perHarness = harness ? layer.harnesses?.[harness] : void 0;
|
|
128
|
+
if (perHarness) out = mergeRaw(out, perHarness);
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
function loadConfig(opts = {}) {
|
|
132
|
+
const o = typeof opts === "string" ? { path: opts } : opts;
|
|
133
|
+
return resolveConfig(applyLayer({}, readRaw(o.path ?? CONFIG_PATH), o.harness));
|
|
134
|
+
}
|
|
135
|
+
var BANK_OVERRIDE_EXCLUDED = [
|
|
136
|
+
"bankId",
|
|
137
|
+
"bankIdTemplate",
|
|
138
|
+
"mapPathToBank",
|
|
139
|
+
"dynamicBankId",
|
|
140
|
+
"resolveWorktrees",
|
|
141
|
+
"harness"
|
|
142
|
+
];
|
|
143
|
+
function applyBankConfig(cfg, resolvedId) {
|
|
144
|
+
const section = cfg.banks[resolvedId];
|
|
145
|
+
if (!section) return { cfg, bankId: resolvedId };
|
|
146
|
+
const safe = { ...section };
|
|
147
|
+
for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
|
|
148
|
+
delete safe.banks;
|
|
149
|
+
const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
|
|
150
|
+
delete safe.bank;
|
|
151
|
+
return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
|
|
152
|
+
}
|
|
153
|
+
function resolvePartial(cfg, patch) {
|
|
154
|
+
const full = resolveConfig(patch);
|
|
155
|
+
const out = {};
|
|
156
|
+
for (const key of Object.keys(patch)) {
|
|
157
|
+
if (key in full)
|
|
158
|
+
out[key] = full[key];
|
|
159
|
+
}
|
|
160
|
+
return out;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// src/core/diag.ts
|
|
164
|
+
import { appendFileSync as appendFileSync2 } from "fs";
|
|
165
|
+
|
|
166
|
+
// src/core/log.ts
|
|
167
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
168
|
+
import { tmpdir } from "os";
|
|
169
|
+
import { dirname as dirname3, join as join4 } from "path";
|
|
170
|
+
var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
|
|
171
|
+
var current = ["debug", "info", "warn", "error"].find(
|
|
172
|
+
(l) => l === process.env.HINDSIGHT_LOG_LEVEL
|
|
173
|
+
) ?? "info";
|
|
174
|
+
function setLogLevel(level) {
|
|
175
|
+
if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
|
|
176
|
+
}
|
|
177
|
+
function logFilePath() {
|
|
178
|
+
return process.env.HINDSIGHT_LOG_FILE || join4(tmpdir(), "hindsight-coding-agent", "plugin.log");
|
|
179
|
+
}
|
|
180
|
+
function write(level, scope, msg, extra) {
|
|
181
|
+
if (WEIGHT[level] < WEIGHT[current]) return;
|
|
182
|
+
try {
|
|
183
|
+
const file = logFilePath();
|
|
184
|
+
mkdirSync(dirname3(file), { recursive: true });
|
|
185
|
+
appendFileSync(
|
|
186
|
+
file,
|
|
187
|
+
`${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
|
|
188
|
+
);
|
|
189
|
+
} catch {
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
var log = {
|
|
193
|
+
debug: (scope, msg, extra) => write("debug", scope, msg, extra),
|
|
194
|
+
info: (scope, msg, extra) => write("info", scope, msg, extra),
|
|
195
|
+
warn: (scope, msg, extra) => write("warn", scope, msg, extra),
|
|
196
|
+
error: (scope, msg, extra) => write("error", scope, msg, extra)
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
// src/core/diag.ts
|
|
200
|
+
function diag(harness, event, extra = {}) {
|
|
201
|
+
log.debug(harness, `diag:${event}`, extra);
|
|
202
|
+
try {
|
|
203
|
+
appendFileSync2(
|
|
204
|
+
process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log",
|
|
205
|
+
JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
|
|
206
|
+
);
|
|
207
|
+
} catch {
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// src/core/missions.ts
|
|
212
|
+
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.";
|
|
213
|
+
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.";
|
|
214
|
+
var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSONL transcript (one {role, content} turn per line): the user's requests, the assistant's narration, and compact 'action' turns naming each tool use and its target (e.g. "Edit boltons/strutils.py") with no arguments or outputs. It may be a SHORT decision chat or a LONG working session \u2014 scale the facts to the substance, never to the message count. Extract the FEWEST facts that capture the OUTCOME: the settled DECISIONS and their exact rules/values (quote literals VERBATIM); concrete CHANGES to specific code entities; problems and how they were resolved; conventions or invariants established; at most one fact for a notable REJECTED alternative ('initially proposed X, changed to Y because Z'). A short decision chat usually yields 1-2 facts; a substantial working session several. CRITICAL: a conversation REVISES itself \u2014 record ONLY the FINAL state as what is in effect; a superseded proposal appears ONLY inside the rejected fact, NEVER as its own 'decided' fact; if the same setting changes several times keep only the LAST, and make unmistakably clear which choice WON. Do NOT emit one fact per message, per intermediate proposal, or per action turn. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Do not invent; capture only what was actually settled.`;
|
|
215
|
+
var REFLECT_MISSION = "You are a debugging assistant with the project's past decisions in memory (git rationale and developer chats). Given a bug's SYMPTOM, find the past decision whose rationale explains the ROOT CAUSE \u2014 not one that merely shares vocabulary. Answer with the PRECISE fix: state the EXACT rule and the LITERAL values, identifiers, strings, numbers, or set members that were decided \u2014 quote them VERBATIM, never paraphrase, generalize, or omit them (give the actual decided value, not 'the project standard'). If memories CONFLICT on the same rule, the LATEST decision wins \u2014 prefer facts that explicitly amend or supersede an earlier one, state the superseded rule as no longer in effect, and never present it as the fix. Name the function/file to change and cite the REF-ID(s). If NOTHING in memory genuinely explains THIS symptom, say exactly that in one short sentence \u2014 a wrong-but-confident nearest match is worse than an honest miss; never stretch an unrelated decision to fit.";
|
|
216
|
+
var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
|
|
217
|
+
var OBSERVATIONS_MISSION = "Consolidate durable knowledge about THIS codebase \u2014 recurring patterns, conventions, module responsibilities, and how components relate \u2014 from the ingested commits and conversations. Favor stable structural understanding over one-off details.";
|
|
218
|
+
var RETAIN_STRATEGIES = {
|
|
219
|
+
git: { retain_mission: GIT_MISSION, retain_extraction_mode: "verbose" },
|
|
220
|
+
// ONE big aggregated document (last N commit messages, no diffs) -> a larger chunk size so it stays
|
|
221
|
+
// in as few chunks as possible and the extractor sees the whole history arc at once.
|
|
222
|
+
gitlog: {
|
|
223
|
+
retain_mission: GITLOG_MISSION,
|
|
224
|
+
retain_extraction_mode: "verbose",
|
|
225
|
+
retain_chunk_size: 12e3
|
|
226
|
+
},
|
|
227
|
+
// ONE strategy for ALL developer conversations — backfilled decision chats and live working
|
|
228
|
+
// sessions alike (they are the same content type in the same JSON transcript format; the mission
|
|
229
|
+
// scales extraction to the substance, final-state-wins). Chunk big enough to hold a whole typical
|
|
230
|
+
// conversation in ONE chunk so the extractor sees the full proposal→revision arc (the 3000
|
|
231
|
+
// default SPLIT them into per-chunk fragments); very long sessions still split and fall back to
|
|
232
|
+
// the consolidation layer.
|
|
233
|
+
conversation: {
|
|
234
|
+
retain_mission: CONVERSATION_MISSION,
|
|
235
|
+
retain_extraction_mode: "verbose",
|
|
236
|
+
retain_chunk_size: 12e3
|
|
237
|
+
},
|
|
238
|
+
// Structural documents (e.g. the codebase survey's ingested findings) aren't dialogue — the
|
|
239
|
+
// chat strategy's "final decision vs rejected proposal" extraction doesn't apply. Verbose mode
|
|
240
|
+
// with a bigger chunk size (documents can run long) captures the concrete facts/structure instead.
|
|
241
|
+
document: {
|
|
242
|
+
retain_mission: DOCUMENT_MISSION,
|
|
243
|
+
retain_extraction_mode: "verbose",
|
|
244
|
+
retain_chunk_size: 12e3
|
|
245
|
+
},
|
|
246
|
+
// Codebase-SURVEY lifecycle documents, ONE strategy with conditional rules: the survey's
|
|
247
|
+
// internal status markers ("researching…"/"completed" baselines) must yield ZERO memories,
|
|
248
|
+
// while any actual survey findings routed here extract as concrete structural facts.
|
|
249
|
+
survey: {
|
|
250
|
+
retain_extraction_mode: "custom",
|
|
251
|
+
retain_custom_instructions: "This document belongs to the Hindsight codebase-survey lifecycle. Apply ONE of two rules: (1) If the content is an internal status marker \u2014 it says it is an internal marker, or merely announces that a survey started/completed at some commit \u2014 extract NOTHING: return an empty list of facts. (2) Otherwise the content is survey FINDINGS about the codebase: extract the concrete structural facts it states (components and their responsibilities, key concepts, conventions, tech stack), preserving identifiers verbatim.",
|
|
252
|
+
retain_chunk_size: 12e3
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
var KNOWLEDGE_LABELS = {
|
|
256
|
+
key: "knowledge",
|
|
257
|
+
type: "multi-values",
|
|
258
|
+
// 0, 1, or several — empty is normal
|
|
259
|
+
optional: true,
|
|
260
|
+
tag: true,
|
|
261
|
+
// emits knowledge:<value> onto the fact's tags
|
|
262
|
+
description: "Routing labels for this project's Hindsight KNOWLEDGE PAGES \u2014 curated, human-readable summaries of the repo's DURABLE engineering knowledge (architecture, key decisions, conventions, ongoing initiatives), each page rebuilt automatically from the facts labeled for it. Mark a fact only when it is durable, reusable knowledge a developer would still want surfaced in future sessions. IMPORTANT: leave this EMPTY for routine, transient, or operational facts \u2014 a passing test, a one-off command, a status update, a debugging dead-end. MOST facts should get no label here. Assign more than one value only when the fact genuinely fits several.",
|
|
263
|
+
values: [
|
|
264
|
+
{
|
|
265
|
+
value: "feature-work",
|
|
266
|
+
description: "A new feature, initiative, or enhancement being planned or built \u2014 the capability being added and the intent behind it. Not routine bug-fixes or chores."
|
|
267
|
+
},
|
|
268
|
+
{
|
|
269
|
+
value: "decision",
|
|
270
|
+
description: "A technical decision that will constrain future work, with its rationale \u2014 why this approach was chosen over alternatives, or a rule deliberately adopted."
|
|
271
|
+
},
|
|
272
|
+
{
|
|
273
|
+
value: "convention",
|
|
274
|
+
description: "An established way this project does things \u2014 naming, structure, testing, error handling, or another recurring pattern a contributor is expected to follow."
|
|
275
|
+
},
|
|
276
|
+
{
|
|
277
|
+
value: "component",
|
|
278
|
+
description: "What a specific module, file, service, or subsystem is responsible for, or how components depend on and connect to one another."
|
|
279
|
+
},
|
|
280
|
+
{
|
|
281
|
+
value: "concept",
|
|
282
|
+
description: "A domain concept, key abstraction, or piece of project vocabulary a new contributor must understand to work effectively."
|
|
283
|
+
}
|
|
284
|
+
]
|
|
285
|
+
};
|
|
286
|
+
var PAGES = [
|
|
287
|
+
{
|
|
288
|
+
name: "Component map",
|
|
289
|
+
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.",
|
|
290
|
+
tags: ["knowledge:component"]
|
|
291
|
+
},
|
|
292
|
+
{
|
|
293
|
+
name: "Core concepts",
|
|
294
|
+
source_query: "What are the core concepts, domain abstractions, and key entities in this project \u2014 the vocabulary a developer must understand? For each, explain what it represents and its role, drawn from how they are introduced and discussed across the history and conversations.",
|
|
295
|
+
tags: ["knowledge:concept"]
|
|
296
|
+
},
|
|
297
|
+
{
|
|
298
|
+
name: "Conventions and patterns",
|
|
299
|
+
source_query: "What conventions, idioms, and recurring patterns does this project follow \u2014 its approach to testing, error handling, naming, structure, and how changes are typically made? Describe how THIS project does things, as evidenced across its history and discussions.",
|
|
300
|
+
tags: ["knowledge:convention"]
|
|
301
|
+
},
|
|
302
|
+
{
|
|
303
|
+
name: "Key decisions and rationale",
|
|
304
|
+
source_query: "What are the significant technical decisions made in this project and the rationale behind them \u2014 the durable 'why we do it this way' a developer should know? Summarize the decisions and their reasoning from the commit rationales and past conversations.",
|
|
305
|
+
tags: ["knowledge:decision"]
|
|
306
|
+
},
|
|
307
|
+
{
|
|
308
|
+
name: "Initiatives and enhancements",
|
|
309
|
+
source_query: "Based on this repository's commit history, what are the major initiatives, features, and enhancements the project has worked on? Summarize the themes and notable changes over time. When a source memory carries a tag of the form `relatedPageId:<id>`, include a Markdown link `[[page:<id>]]` to that page in the summary, so each initiative links to its detailed page.",
|
|
310
|
+
tags: ["knowledge:feature-work"]
|
|
311
|
+
}
|
|
312
|
+
];
|
|
313
|
+
var PAGE_MAX_TOKENS = 4096;
|
|
314
|
+
var PAGE_TRIGGER = {
|
|
315
|
+
fact_types: ["world", "experience", "observation"],
|
|
316
|
+
refresh_after_consolidation: true
|
|
317
|
+
};
|
|
318
|
+
var CODING_BANK_TEMPLATE = {
|
|
319
|
+
version: "1",
|
|
320
|
+
bank: {
|
|
321
|
+
reflect_mission: REFLECT_MISSION,
|
|
322
|
+
enable_observations: true,
|
|
323
|
+
observations_mission: OBSERVATIONS_MISSION,
|
|
324
|
+
retain_mission: GIT_MISSION,
|
|
325
|
+
retain_extraction_mode: "verbose",
|
|
326
|
+
retain_default_strategy: "git",
|
|
327
|
+
retain_strategies: RETAIN_STRATEGIES,
|
|
328
|
+
entity_labels: [KNOWLEDGE_LABELS],
|
|
329
|
+
entities_allow_free_form: true
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
|
|
333
|
+
// src/core/util.ts
|
|
334
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
335
|
+
|
|
336
|
+
// src/core/hindsight.ts
|
|
337
|
+
var KnowledgePagesUnavailableError = class extends Error {
|
|
338
|
+
code = "knowledge_pages_unavailable";
|
|
339
|
+
constructor() {
|
|
340
|
+
super("Hindsight server does not support knowledge pages");
|
|
341
|
+
this.name = "KnowledgePagesUnavailableError";
|
|
342
|
+
}
|
|
343
|
+
};
|
|
344
|
+
var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
|
|
345
|
+
var HindsightClient = class {
|
|
346
|
+
apiUrl;
|
|
347
|
+
apiToken;
|
|
348
|
+
bank;
|
|
349
|
+
opIds = [];
|
|
350
|
+
// async operation ids collected by retain(), for drain()
|
|
351
|
+
/** Tri-state capability probe: unknown until the first page request, then cached. */
|
|
352
|
+
knowledgePagesSupported;
|
|
353
|
+
log;
|
|
354
|
+
constructor(o) {
|
|
355
|
+
this.apiUrl = o.apiUrl.replace(/\/$/, "");
|
|
356
|
+
this.apiToken = o.apiToken;
|
|
357
|
+
this.bank = o.bank;
|
|
358
|
+
this.log = o.log ?? (() => {
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
headers() {
|
|
362
|
+
const h = { "Content-Type": "application/json" };
|
|
363
|
+
if (this.apiToken) h["Authorization"] = `Bearer ${this.apiToken}`;
|
|
364
|
+
return h;
|
|
365
|
+
}
|
|
366
|
+
bankUrl(suffix = "") {
|
|
367
|
+
return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
|
|
368
|
+
}
|
|
369
|
+
/** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
|
|
370
|
+
async req(method, url, body, tolerate = []) {
|
|
371
|
+
const r = await fetch(url, {
|
|
372
|
+
method,
|
|
373
|
+
headers: this.headers(),
|
|
374
|
+
body: body ? JSON.stringify(body) : void 0,
|
|
375
|
+
signal: AbortSignal.timeout(15e3)
|
|
376
|
+
});
|
|
377
|
+
if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
|
|
378
|
+
throw new Error(`${method} ${url} -> ${r.status} ${await r.text()}`);
|
|
379
|
+
return r;
|
|
380
|
+
}
|
|
381
|
+
/** Retain one memory. Async by default: enqueue extraction server-side and collect its op-id for drain(). */
|
|
382
|
+
async retain(content, context, documentId, tags, strategy, opts = {}) {
|
|
383
|
+
const item = {
|
|
384
|
+
content,
|
|
385
|
+
context,
|
|
386
|
+
document_id: documentId,
|
|
387
|
+
tags,
|
|
388
|
+
strategy
|
|
389
|
+
};
|
|
390
|
+
if (opts.timestamp) item.timestamp = opts.timestamp;
|
|
391
|
+
if (opts.metadata) item.metadata = opts.metadata;
|
|
392
|
+
const isAsync = opts.async !== false;
|
|
393
|
+
const r = await this.req("POST", this.bankUrl("/memories"), { items: [item], async: isAsync });
|
|
394
|
+
if (isAsync) {
|
|
395
|
+
try {
|
|
396
|
+
const j = await r.json();
|
|
397
|
+
if (j.operation_id) this.opIds.push(j.operation_id);
|
|
398
|
+
} catch {
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Every document_id currently in the bank under a strategy tag (e.g. `source:git`), paginated into a
|
|
404
|
+
* Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
|
|
405
|
+
* with document_id `git:<sha>`, the returned Set lets a caller diff a ref's commits against memory.
|
|
406
|
+
*/
|
|
407
|
+
async listDocumentIds(tag) {
|
|
408
|
+
const ids = /* @__PURE__ */ new Set();
|
|
409
|
+
const limit = 500;
|
|
410
|
+
for (let offset = 0; ; offset += limit) {
|
|
411
|
+
const q = `?tags=${encodeURIComponent(tag)}&tags_match=all&limit=${limit}&offset=${offset}`;
|
|
412
|
+
const r = await this.req("GET", this.bankUrl(`/documents${q}`));
|
|
413
|
+
let items = [];
|
|
414
|
+
let total = 0;
|
|
415
|
+
try {
|
|
416
|
+
const j = await r.json();
|
|
417
|
+
items = j.items || [];
|
|
418
|
+
total = j.total ?? 0;
|
|
419
|
+
} catch {
|
|
420
|
+
break;
|
|
421
|
+
}
|
|
422
|
+
for (const it of items) if (it.id) ids.add(it.id);
|
|
423
|
+
if (items.length < limit || ids.size >= total) break;
|
|
424
|
+
}
|
|
425
|
+
return ids;
|
|
426
|
+
}
|
|
427
|
+
/** Configure the bank: POST the coding bank template manifest to /import (missions, retain
|
|
428
|
+
* strategies, entity labels), then seed knowledge pages when the server supports them. Both
|
|
429
|
+
* halves are idempotent, so the deepen engine can re-run this every pass. Creates the bank if
|
|
430
|
+
* missing; legacy servers continue with the template-only path. */
|
|
431
|
+
async configureBank(opts = {}) {
|
|
432
|
+
if (opts.reset) {
|
|
433
|
+
await this.req("DELETE", this.bankUrl());
|
|
434
|
+
this.log(`[bank] reset ${this.bank}`);
|
|
435
|
+
}
|
|
436
|
+
await this.req("POST", this.bankUrl("/import"), CODING_BANK_TEMPLATE);
|
|
437
|
+
this.log(
|
|
438
|
+
`[bank] template applied to ${this.bank}: missions, entity_labels {knowledge}, strategies {git, gitlog, conversation, document}`
|
|
439
|
+
);
|
|
440
|
+
await this.seedPages();
|
|
441
|
+
}
|
|
442
|
+
/** Delete one document (cascades its memory units/links). Used by deepen's self-cleanup. */
|
|
443
|
+
async deleteDocument(documentId) {
|
|
444
|
+
await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
|
|
445
|
+
}
|
|
446
|
+
/** Count of operations still ACTIVE on this bank — the list includes terminal ops (completed/
|
|
447
|
+
* failed/cancelled), so filter by status. Powers syncStatus's "extractions drained" check. */
|
|
448
|
+
async activeOperations() {
|
|
449
|
+
const r = await this.req("GET", this.bankUrl("/operations"));
|
|
450
|
+
try {
|
|
451
|
+
const j = await r.json();
|
|
452
|
+
const ops = j.operations ?? j.items ?? [];
|
|
453
|
+
return ops.filter((o) => !TERMINAL.has((o?.status || "").toLowerCase())).length;
|
|
454
|
+
} catch {
|
|
455
|
+
return 0;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
/** Poll each enqueued operation by id until terminal. LIST only shows active ops, so per-id GET is reliable. */
|
|
459
|
+
async drain(ids, label, maxMs = 60 * 60 * 1e3) {
|
|
460
|
+
if (!ids.length) return;
|
|
461
|
+
this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
|
|
462
|
+
const start = Date.now();
|
|
463
|
+
const pending = new Set(ids);
|
|
464
|
+
let failed = 0;
|
|
465
|
+
while (pending.size && Date.now() - start < maxMs) {
|
|
466
|
+
await Promise.all(
|
|
467
|
+
[...pending].map(async (id) => {
|
|
468
|
+
try {
|
|
469
|
+
const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
|
|
470
|
+
if (!r.ok) return;
|
|
471
|
+
const st = ((await r.json()).status || "").toLowerCase();
|
|
472
|
+
if (TERMINAL.has(st)) {
|
|
473
|
+
pending.delete(id);
|
|
474
|
+
if (st !== "completed") failed++;
|
|
475
|
+
}
|
|
476
|
+
} catch {
|
|
477
|
+
}
|
|
478
|
+
})
|
|
479
|
+
);
|
|
480
|
+
if (pending.size) {
|
|
481
|
+
this.log(` \u2026 ${pending.size}/${ids.length} ${label} ops pending`);
|
|
482
|
+
await sleep(5e3);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
this.log(
|
|
486
|
+
`[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
|
|
487
|
+
);
|
|
488
|
+
}
|
|
489
|
+
/** Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a caller. */
|
|
490
|
+
async reflect(query, opts = {}) {
|
|
491
|
+
const ctrl = new AbortController();
|
|
492
|
+
const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 12e4);
|
|
493
|
+
try {
|
|
494
|
+
const resp = await fetch(this.bankUrl("/reflect"), {
|
|
495
|
+
method: "POST",
|
|
496
|
+
headers: this.headers(),
|
|
497
|
+
body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
|
|
498
|
+
signal: ctrl.signal
|
|
499
|
+
});
|
|
500
|
+
if (!resp.ok) throw new Error(`reflect ${resp.status}`);
|
|
501
|
+
const data = await resp.json();
|
|
502
|
+
return (data.text || "").trim();
|
|
503
|
+
} finally {
|
|
504
|
+
clearTimeout(timer);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
|
|
509
|
+
* queries and staleness but NOT synthesized content, so it is cheap enough to poll.
|
|
510
|
+
*/
|
|
511
|
+
async tree() {
|
|
512
|
+
if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
|
|
513
|
+
const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
|
|
514
|
+
if ([404, 405, 501].includes(r.status)) {
|
|
515
|
+
this.knowledgePagesSupported = false;
|
|
516
|
+
throw new KnowledgePagesUnavailableError();
|
|
517
|
+
}
|
|
518
|
+
this.knowledgePagesSupported = true;
|
|
519
|
+
try {
|
|
520
|
+
return (await r.json()).roots ?? [];
|
|
521
|
+
} catch {
|
|
522
|
+
return [];
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* List knowledge pages (ids + names only — no synthesized content), flattened out of the tree
|
|
527
|
+
* and shaped as `{items:[…]}` for `parsePageList`. Folders are dropped: they carry no content
|
|
528
|
+
* to read, and a caller enumerating pages wants leaves, not structure.
|
|
529
|
+
*
|
|
530
|
+
* NOTE the ids are knowledge-base node ids (`kp-…`), NOT the backing mental-model ids. Every
|
|
531
|
+
* page read/update in this client goes through the same knowledge-base ids, so a page id from
|
|
532
|
+
* here, from `searchKnowledgePages`, or from a `[[page:<id>]]` link all resolve identically.
|
|
533
|
+
*/
|
|
534
|
+
async listPages() {
|
|
535
|
+
const items = [];
|
|
536
|
+
const walk = (nodes, folder) => {
|
|
537
|
+
for (const n of nodes) {
|
|
538
|
+
if (!n?.id || !n?.name) continue;
|
|
539
|
+
if (n.kind === "page") {
|
|
540
|
+
items.push({
|
|
541
|
+
id: n.id,
|
|
542
|
+
name: n.name,
|
|
543
|
+
...n.description ? { description: n.description } : {},
|
|
544
|
+
...folder ? { folder } : {}
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
if (n.children?.length) walk(n.children, n.kind === "folder" ? n.name : folder);
|
|
548
|
+
}
|
|
549
|
+
};
|
|
550
|
+
walk(await this.tree());
|
|
551
|
+
return { items };
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
|
|
555
|
+
* (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
|
|
556
|
+
* the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
|
|
557
|
+
* token cap.
|
|
558
|
+
*/
|
|
559
|
+
async getPage(pageId) {
|
|
560
|
+
if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
|
|
561
|
+
const r = await this.req(
|
|
562
|
+
"GET",
|
|
563
|
+
this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
|
|
564
|
+
);
|
|
565
|
+
if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
|
|
566
|
+
return await r.json();
|
|
567
|
+
}
|
|
568
|
+
/** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
|
|
569
|
+
* Returns page-level hits with a relevance snippet — the real search behind
|
|
570
|
+
* hindsight_search_knowledge_pages. */
|
|
571
|
+
async searchKnowledgePages(query, limit = 3) {
|
|
572
|
+
if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
|
|
573
|
+
const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
|
|
574
|
+
const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
|
|
575
|
+
const j = await r.json();
|
|
576
|
+
return (j.results ?? []).map((x) => ({
|
|
577
|
+
id: x.id,
|
|
578
|
+
name: x.name,
|
|
579
|
+
snippet: x.snippet ?? "",
|
|
580
|
+
score: x.score ?? 0
|
|
581
|
+
}));
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* Seed the fixed `PAGES` taxonomy as knowledge-base pages at the tree root, idempotently.
|
|
585
|
+
*
|
|
586
|
+
* Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
|
|
587
|
+
* client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
|
|
588
|
+
* off a slug). Names are unique per folder server-side, which makes them a sound key.
|
|
589
|
+
*
|
|
590
|
+
* An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
|
|
591
|
+
* `source_query` re-syncs onto the live page instead of orphaning its synthesized content.
|
|
592
|
+
*/
|
|
593
|
+
async seedPages() {
|
|
594
|
+
const existing = /* @__PURE__ */ new Map();
|
|
595
|
+
let roots;
|
|
596
|
+
try {
|
|
597
|
+
roots = await this.tree();
|
|
598
|
+
} catch (e) {
|
|
599
|
+
if (e instanceof KnowledgePagesUnavailableError) {
|
|
600
|
+
this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
throw e;
|
|
604
|
+
}
|
|
605
|
+
for (const n of roots) {
|
|
606
|
+
if (n.kind === "page" && n.name) existing.set(n.name.toLowerCase(), n);
|
|
607
|
+
}
|
|
608
|
+
let created = 0;
|
|
609
|
+
let updated = 0;
|
|
610
|
+
for (const page of PAGES) {
|
|
611
|
+
const hit = existing.get(page.name.toLowerCase());
|
|
612
|
+
const body = {
|
|
613
|
+
name: page.name,
|
|
614
|
+
source_query: page.source_query,
|
|
615
|
+
tags: page.tags,
|
|
616
|
+
max_tokens: PAGE_MAX_TOKENS,
|
|
617
|
+
trigger: PAGE_TRIGGER
|
|
618
|
+
};
|
|
619
|
+
if (!hit) {
|
|
620
|
+
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
|
|
621
|
+
if ([404, 405, 501].includes(r.status)) {
|
|
622
|
+
this.knowledgePagesSupported = false;
|
|
623
|
+
this.log(
|
|
624
|
+
`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
|
|
625
|
+
);
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
if (r.status !== 409) created++;
|
|
629
|
+
} else if (hit.description !== page.source_query) {
|
|
630
|
+
const r = await this.req(
|
|
631
|
+
"PATCH",
|
|
632
|
+
this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
|
|
633
|
+
{ source_query: page.source_query, tags: page.tags }
|
|
634
|
+
);
|
|
635
|
+
if ([404, 405, 501].includes(r.status)) {
|
|
636
|
+
this.knowledgePagesSupported = false;
|
|
637
|
+
this.log(
|
|
638
|
+
`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
|
|
639
|
+
);
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
updated++;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
this.log(
|
|
646
|
+
`[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
|
|
647
|
+
);
|
|
648
|
+
}
|
|
649
|
+
/** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
|
|
650
|
+
slugify(s) {
|
|
651
|
+
return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
|
|
655
|
+
* New initiative → creates a page under the Initiatives folder tagged `relatedPageId:<pageId>`.
|
|
656
|
+
* Enhancement (relatesToPageId) → no new page; only a marker accruing to the existing page.
|
|
657
|
+
*/
|
|
658
|
+
async captureInitiative(args) {
|
|
659
|
+
let pageId = args.relatesToPageId;
|
|
660
|
+
if (!pageId) {
|
|
661
|
+
const folderId = await this.ensureFolder("Initiatives");
|
|
662
|
+
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
|
|
663
|
+
name: args.title,
|
|
664
|
+
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.`,
|
|
665
|
+
parent_id: folderId,
|
|
666
|
+
tags: ["knowledge:feature-work"],
|
|
667
|
+
trigger: {
|
|
668
|
+
fact_types: ["world", "experience", "observation"],
|
|
669
|
+
refresh_after_consolidation: true
|
|
670
|
+
}
|
|
671
|
+
});
|
|
672
|
+
try {
|
|
673
|
+
const j = await r.json();
|
|
674
|
+
pageId = j.page_id ?? j.id;
|
|
675
|
+
} catch {
|
|
676
|
+
}
|
|
677
|
+
pageId ||= `initiative-${this.slugify(args.title)}`;
|
|
678
|
+
}
|
|
679
|
+
const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
|
|
680
|
+
const content = `${verb}: ${args.title}. ${args.summary}`;
|
|
681
|
+
const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
|
|
682
|
+
await this.retain(
|
|
683
|
+
content,
|
|
684
|
+
"initiative marker",
|
|
685
|
+
markerId,
|
|
686
|
+
["knowledge:feature-work", `relatedPageId:${pageId}`],
|
|
687
|
+
"document",
|
|
688
|
+
{ async: true }
|
|
689
|
+
);
|
|
690
|
+
return { page_id: pageId };
|
|
691
|
+
}
|
|
692
|
+
/** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
|
|
693
|
+
async ensureFolder(name) {
|
|
694
|
+
try {
|
|
695
|
+
const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
|
|
696
|
+
const hit = (tree.roots || []).find(
|
|
697
|
+
(n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
|
|
698
|
+
);
|
|
699
|
+
if (hit?.id) return hit.id;
|
|
700
|
+
} catch {
|
|
701
|
+
}
|
|
702
|
+
try {
|
|
703
|
+
const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
|
|
704
|
+
return (await r.json()).id;
|
|
705
|
+
} catch {
|
|
706
|
+
return void 0;
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
};
|
|
710
|
+
|
|
711
|
+
// src/core/session-cache.ts
|
|
712
|
+
import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync } from "fs";
|
|
713
|
+
import { tmpdir as tmpdir2 } from "os";
|
|
714
|
+
import { dirname as dirname4, join as join5 } from "path";
|
|
715
|
+
|
|
716
|
+
// src/core/retain-hook.ts
|
|
717
|
+
import { readFileSync as readFileSync5 } from "fs";
|
|
718
|
+
|
|
719
|
+
// src/core/chat.ts
|
|
720
|
+
function withRefId(refId, turns, baseTs) {
|
|
721
|
+
return [{ role: "system", content: `REF-ID: ${refId}`, timestamp: baseTs }, ...turns];
|
|
722
|
+
}
|
|
723
|
+
function renderSessionJsonl(refId, turns, baseTs) {
|
|
724
|
+
return withRefId(refId, turns, baseTs).map((t) => JSON.stringify(t)).join("\n");
|
|
725
|
+
}
|
|
726
|
+
async function retainLiveSession(client, sessionId, turns, startTs, harness) {
|
|
727
|
+
const refId = `conversation:${sessionId}`;
|
|
728
|
+
await client.retain(
|
|
729
|
+
renderSessionJsonl(refId, turns, startTs),
|
|
730
|
+
"coding agent session",
|
|
731
|
+
refId,
|
|
732
|
+
["source:chat", ...harness ? [`harness:${harness}`] : []],
|
|
733
|
+
"conversation",
|
|
734
|
+
{
|
|
735
|
+
timestamp: startTs,
|
|
736
|
+
async: true,
|
|
737
|
+
metadata: {
|
|
738
|
+
source: "chat",
|
|
739
|
+
session_id: sessionId,
|
|
740
|
+
ref_id: refId,
|
|
741
|
+
...harness ? { harness } : {}
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
);
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
// src/core/transcript.ts
|
|
748
|
+
import { readFileSync as readFileSync4 } from "fs";
|
|
749
|
+
|
|
750
|
+
// src/core/transcript-util.ts
|
|
751
|
+
var MEMORY_TAG_RE = /<(hook_prompt|hindsight_memory|hindsight_memories|hindsight_bank|relevant_memories|user_feedback|hindsight_knowledge|hindsight_knowledge_refresh)\b[\s\S]*?<\/\1>/g;
|
|
752
|
+
function stripInjectedMemory(s) {
|
|
753
|
+
return s.replace(MEMORY_TAG_RE, "");
|
|
754
|
+
}
|
|
755
|
+
var TARGET_KEYS = [
|
|
756
|
+
"file_path",
|
|
757
|
+
"path",
|
|
758
|
+
"notebook_path",
|
|
759
|
+
"command",
|
|
760
|
+
"pattern",
|
|
761
|
+
"query",
|
|
762
|
+
"url",
|
|
763
|
+
"name",
|
|
764
|
+
"id"
|
|
765
|
+
];
|
|
766
|
+
var ACTION_TARGET_CAP = 100;
|
|
767
|
+
function actionLine(tool, input) {
|
|
768
|
+
let target = "";
|
|
769
|
+
if (input && typeof input === "object") {
|
|
770
|
+
const rec = input;
|
|
771
|
+
for (const k of TARGET_KEYS) {
|
|
772
|
+
const v = rec[k];
|
|
773
|
+
if (typeof v === "string" && v.trim()) {
|
|
774
|
+
target = v.trim().split("\n")[0];
|
|
775
|
+
break;
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
} else if (typeof input === "string") {
|
|
779
|
+
target = input.trim().split("\n")[0];
|
|
780
|
+
}
|
|
781
|
+
if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
|
|
782
|
+
return target ? `${tool} ${target}` : tool;
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
// src/core/transcript.ts
|
|
786
|
+
function renderLine(content, type) {
|
|
787
|
+
if (typeof content === "string") {
|
|
788
|
+
const text = stripInjectedMemory(content).trim();
|
|
789
|
+
return text ? [{ role: type, content: text }] : [];
|
|
790
|
+
}
|
|
791
|
+
if (!Array.isArray(content)) return [];
|
|
792
|
+
const texts = [];
|
|
793
|
+
const actions = [];
|
|
794
|
+
for (const b of content) {
|
|
795
|
+
if (!b || typeof b !== "object") continue;
|
|
796
|
+
if (b.type === "text" && typeof b.text === "string") {
|
|
797
|
+
const t = stripInjectedMemory(b.text).trim();
|
|
798
|
+
if (t) texts.push(t);
|
|
799
|
+
} else if (b.type === "tool_use" && typeof b.name === "string") {
|
|
800
|
+
actions.push({ role: "action", content: actionLine(b.name, b.input) });
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
const out = [];
|
|
804
|
+
const joined = texts.join("\n").trim();
|
|
805
|
+
if (joined) out.push({ role: type, content: joined });
|
|
806
|
+
out.push(...actions);
|
|
807
|
+
return out;
|
|
808
|
+
}
|
|
809
|
+
function readClaudeTranscript(path) {
|
|
810
|
+
let raw;
|
|
811
|
+
try {
|
|
812
|
+
raw = readFileSync4(path, "utf8");
|
|
813
|
+
} catch {
|
|
814
|
+
return [];
|
|
815
|
+
}
|
|
816
|
+
const turns = [];
|
|
817
|
+
for (const rawLine of raw.split("\n")) {
|
|
818
|
+
const trimmed = rawLine.trim();
|
|
819
|
+
if (!trimmed) continue;
|
|
820
|
+
let parsed;
|
|
821
|
+
try {
|
|
822
|
+
parsed = JSON.parse(trimmed);
|
|
823
|
+
} catch {
|
|
824
|
+
continue;
|
|
825
|
+
}
|
|
826
|
+
if (typeof parsed !== "object" || parsed === null) continue;
|
|
827
|
+
const line = parsed;
|
|
828
|
+
if (line.type !== "user" && line.type !== "assistant") continue;
|
|
829
|
+
if (line.isMeta === true) continue;
|
|
830
|
+
if (line.isSidechain === true) continue;
|
|
831
|
+
if (typeof line.message !== "object" || line.message === null) continue;
|
|
832
|
+
for (const rendered of renderLine(line.message.content, line.type)) {
|
|
833
|
+
const turn = { role: rendered.role, content: rendered.content };
|
|
834
|
+
if (typeof line.timestamp === "string") turn.timestamp = line.timestamp;
|
|
835
|
+
turns.push(turn);
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
return turns;
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
// src/core/retain-hook.ts
|
|
842
|
+
async function buildRetain(args) {
|
|
843
|
+
const { harness, sessionId, transcriptPath, client } = args;
|
|
844
|
+
const readTranscript = args.readTranscript ?? readClaudeTranscript;
|
|
845
|
+
const turns = readTranscript(transcriptPath);
|
|
846
|
+
if (turns.length === 0) return;
|
|
847
|
+
const startTs = turns[0]?.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
848
|
+
const t0 = Date.now();
|
|
849
|
+
try {
|
|
850
|
+
await retainLiveSession(client, sessionId, turns, startTs, harness);
|
|
851
|
+
diag(harness, "retain_ok", { ms: Date.now() - t0, turns: turns.length, session: sessionId });
|
|
852
|
+
} catch (e) {
|
|
853
|
+
log.warn(harness, "session write-back failed", {
|
|
854
|
+
error: String(e?.message || e).slice(0, 200)
|
|
855
|
+
});
|
|
856
|
+
diag(harness, "retain_failed", {
|
|
857
|
+
ms: Date.now() - t0,
|
|
858
|
+
error: String(e?.message || e).slice(0, 200),
|
|
859
|
+
session: sessionId
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
|
|
864
|
+
if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
|
|
865
|
+
let ev = {};
|
|
866
|
+
try {
|
|
867
|
+
ev = JSON.parse(readFileSync5(0, "utf8"));
|
|
868
|
+
} catch {
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
const { sessionId, transcriptPath, cwd: rawCwd } = spec.parse(ev);
|
|
872
|
+
const cwd = rawCwd || process.cwd();
|
|
873
|
+
let cfg = loadConfig({ harness: spec.harness });
|
|
874
|
+
setLogLevel(cfg.logLevel);
|
|
875
|
+
if (cfg.disabled) return;
|
|
876
|
+
if (!transcriptPath) return;
|
|
877
|
+
const resolved = applyBankConfig(cfg, deriveBankId(cfg, cwd, spec.harness));
|
|
878
|
+
cfg = resolved.cfg;
|
|
879
|
+
const bankId = resolved.bankId;
|
|
880
|
+
if (cfg.disabled) return;
|
|
881
|
+
const client = makeClient({ apiUrl: cfg.apiUrl, apiToken: cfg.apiToken, bank: bankId });
|
|
882
|
+
await buildRetain({
|
|
883
|
+
harness: spec.harness,
|
|
884
|
+
sessionId: sessionId || "no-session",
|
|
885
|
+
transcriptPath,
|
|
886
|
+
client,
|
|
887
|
+
readTranscript: spec.readTranscript
|
|
888
|
+
});
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
// src/core/session-start.ts
|
|
892
|
+
import { readFileSync as readFileSync7 } from "fs";
|
|
893
|
+
|
|
894
|
+
// src/core/git.ts
|
|
895
|
+
import { execFileSync as execFileSync2 } from "child_process";
|
|
896
|
+
import { resolve } from "path";
|
|
897
|
+
|
|
898
|
+
// src/core/status.ts
|
|
899
|
+
import { execFileSync as execFileSync3 } from "child_process";
|
|
900
|
+
|
|
901
|
+
// src/core/survey.ts
|
|
902
|
+
import { spawn as realSpawn2 } from "child_process";
|
|
903
|
+
import { accessSync, constants, existsSync as existsSync2 } from "fs";
|
|
904
|
+
import { homedir as homedir3 } from "os";
|
|
905
|
+
import { delimiter, dirname as dirname5, join as join6 } from "path";
|
|
906
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
907
|
+
|
|
908
|
+
// src/core/skill-sync.ts
|
|
909
|
+
import { cpSync, existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
|
|
910
|
+
import { homedir as homedir4 } from "os";
|
|
911
|
+
import { dirname as dirname6, join as join7 } from "path";
|
|
912
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
913
|
+
|
|
914
|
+
// src/core/transcript-codex.ts
|
|
915
|
+
import { readFileSync as readFileSync8 } from "fs";
|
|
916
|
+
function isSyntheticUserText(text) {
|
|
917
|
+
const s = text.trimStart();
|
|
918
|
+
return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
|
|
919
|
+
}
|
|
920
|
+
function messageText(payload) {
|
|
921
|
+
return (payload.content || []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
|
|
922
|
+
}
|
|
923
|
+
function readCodexTranscript(path) {
|
|
924
|
+
let raw;
|
|
925
|
+
try {
|
|
926
|
+
raw = readFileSync8(path, "utf8");
|
|
927
|
+
} catch {
|
|
928
|
+
return [];
|
|
929
|
+
}
|
|
930
|
+
const turns = [];
|
|
931
|
+
for (const rawLine of raw.split("\n")) {
|
|
932
|
+
const trimmed = rawLine.trim();
|
|
933
|
+
if (!trimmed) continue;
|
|
934
|
+
let parsed;
|
|
935
|
+
try {
|
|
936
|
+
parsed = JSON.parse(trimmed);
|
|
937
|
+
} catch {
|
|
938
|
+
continue;
|
|
939
|
+
}
|
|
940
|
+
if (typeof parsed !== "object" || parsed === null) continue;
|
|
941
|
+
const line = parsed;
|
|
942
|
+
if (line.type !== "response_item") continue;
|
|
943
|
+
const p = line.payload;
|
|
944
|
+
if (!p || typeof p !== "object") continue;
|
|
945
|
+
if (p.type === "message") {
|
|
946
|
+
if (p.role !== "user" && p.role !== "assistant") continue;
|
|
947
|
+
const text = stripInjectedMemory(messageText(p)).trim();
|
|
948
|
+
if (!text) continue;
|
|
949
|
+
if (p.role === "user" && isSyntheticUserText(text)) continue;
|
|
950
|
+
turns.push({ role: p.role, content: text });
|
|
951
|
+
} else if (p.type === "function_call" && typeof p.name === "string") {
|
|
952
|
+
let input;
|
|
953
|
+
try {
|
|
954
|
+
input = JSON.parse(p.arguments || "");
|
|
955
|
+
} catch {
|
|
956
|
+
input = void 0;
|
|
957
|
+
}
|
|
958
|
+
turns.push({ role: "action", content: actionLine(p.name, input) });
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
return turns;
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
// src/core/transcript-cursor.ts
|
|
965
|
+
import { readFileSync as readFileSync9 } from "fs";
|
|
966
|
+
function withTimestamp(turn, timestamp) {
|
|
967
|
+
return timestamp ? { ...turn, timestamp } : turn;
|
|
968
|
+
}
|
|
969
|
+
function textFrom(content) {
|
|
970
|
+
if (typeof content === "string") return content;
|
|
971
|
+
if (!Array.isArray(content)) return "";
|
|
972
|
+
return content.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
|
|
973
|
+
}
|
|
974
|
+
function readCursorTranscript(path) {
|
|
975
|
+
let raw;
|
|
976
|
+
try {
|
|
977
|
+
raw = readFileSync9(path, "utf8");
|
|
978
|
+
} catch {
|
|
979
|
+
return [];
|
|
980
|
+
}
|
|
981
|
+
const turns = [];
|
|
982
|
+
for (const rawLine of raw.split("\n")) {
|
|
983
|
+
let parsed;
|
|
984
|
+
try {
|
|
985
|
+
parsed = JSON.parse(rawLine);
|
|
986
|
+
} catch {
|
|
987
|
+
continue;
|
|
988
|
+
}
|
|
989
|
+
if (typeof parsed !== "object" || parsed === null) continue;
|
|
990
|
+
const line = parsed;
|
|
991
|
+
const role = line.message?.role ?? line.role ?? (line.type === "user" || line.type === "assistant" ? line.type : void 0);
|
|
992
|
+
const content = line.message?.content ?? line.content;
|
|
993
|
+
if (role === "user" || role === "assistant") {
|
|
994
|
+
const text = stripInjectedMemory(textFrom(content)).trim();
|
|
995
|
+
if (text) turns.push(withTimestamp({ role, content: text }, line.timestamp));
|
|
996
|
+
if (role === "assistant" && Array.isArray(content)) {
|
|
997
|
+
for (const block of content) {
|
|
998
|
+
if (block?.type === "tool_use" && typeof block.name === "string") {
|
|
999
|
+
turns.push(
|
|
1000
|
+
withTimestamp(
|
|
1001
|
+
{ role: "action", content: actionLine(block.name, block.input) },
|
|
1002
|
+
line.timestamp
|
|
1003
|
+
)
|
|
1004
|
+
);
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
} else if (line.type === "tool_call" && typeof line.name === "string") {
|
|
1009
|
+
turns.push(
|
|
1010
|
+
withTimestamp({ role: "action", content: actionLine(line.name, line.args) }, line.timestamp)
|
|
1011
|
+
);
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
return turns;
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
// src/core/transcript-antigravity.ts
|
|
1018
|
+
import { readFileSync as readFileSync10 } from "fs";
|
|
1019
|
+
function readAntigravityTranscript(path) {
|
|
1020
|
+
if (!path) return [];
|
|
1021
|
+
let raw;
|
|
1022
|
+
try {
|
|
1023
|
+
raw = readFileSync10(path, "utf8");
|
|
1024
|
+
} catch {
|
|
1025
|
+
return [];
|
|
1026
|
+
}
|
|
1027
|
+
const turns = [];
|
|
1028
|
+
for (const line of raw.split("\n")) {
|
|
1029
|
+
try {
|
|
1030
|
+
const event = JSON.parse(line);
|
|
1031
|
+
const role = event.role ?? event.message?.role ?? event.type;
|
|
1032
|
+
const normalizedRole = role === "user" || role === "USER_INPUT" ? "user" : role === "assistant" || role === "model" || role === "PLANNER_RESPONSE" ? "assistant" : void 0;
|
|
1033
|
+
const content = event.content ?? event.text ?? event.message?.content ?? event.message?.text;
|
|
1034
|
+
const clean = typeof content === "string" ? stripInjectedMemory(content).trim() : "";
|
|
1035
|
+
if (normalizedRole && clean) {
|
|
1036
|
+
turns.push({
|
|
1037
|
+
role: normalizedRole,
|
|
1038
|
+
content: clean,
|
|
1039
|
+
...event.timestamp ? { timestamp: event.timestamp } : {}
|
|
1040
|
+
});
|
|
1041
|
+
}
|
|
1042
|
+
} catch {
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
return turns;
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
// src/core/transcript-copilot.ts
|
|
1049
|
+
import { readFileSync as readFileSync11 } from "fs";
|
|
1050
|
+
function readCopilotTranscript(path) {
|
|
1051
|
+
let raw;
|
|
1052
|
+
try {
|
|
1053
|
+
raw = readFileSync11(path, "utf8");
|
|
1054
|
+
} catch {
|
|
1055
|
+
return [];
|
|
1056
|
+
}
|
|
1057
|
+
const turns = [];
|
|
1058
|
+
for (const rawLine of raw.split("\n")) {
|
|
1059
|
+
try {
|
|
1060
|
+
const event = JSON.parse(rawLine);
|
|
1061
|
+
const role = event.type === "user.message" ? "user" : event.type === "assistant.message" ? "assistant" : void 0;
|
|
1062
|
+
const content = typeof event.data?.content === "string" ? stripInjectedMemory(event.data.content).trim() : "";
|
|
1063
|
+
if (!role || !content) continue;
|
|
1064
|
+
turns.push({ role, content, ...event.timestamp ? { timestamp: event.timestamp } : {} });
|
|
1065
|
+
} catch {
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
return turns;
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
// src/core/transcript-grok.ts
|
|
1072
|
+
import { existsSync as existsSync4, readFileSync as readFileSync12, readdirSync } from "fs";
|
|
1073
|
+
import { homedir as homedir5 } from "os";
|
|
1074
|
+
import { join as join8 } from "path";
|
|
1075
|
+
var CHAT_HISTORY = "chat_history.jsonl";
|
|
1076
|
+
function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join8(homedir5(), ".grok")) {
|
|
1077
|
+
const sessionsDir = join8(grokHome, "sessions");
|
|
1078
|
+
const direct = join8(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
|
|
1079
|
+
if (existsSync4(direct)) return direct;
|
|
1080
|
+
try {
|
|
1081
|
+
for (const candidate of readdirSync(sessionsDir)) {
|
|
1082
|
+
const directory = join8(sessionsDir, candidate);
|
|
1083
|
+
if (readFileSync12(join8(directory, ".cwd"), "utf8").trim() === cwd) {
|
|
1084
|
+
return join8(directory, sessionId, CHAT_HISTORY);
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
} catch {
|
|
1088
|
+
}
|
|
1089
|
+
return direct;
|
|
1090
|
+
}
|
|
1091
|
+
function readGrokTranscript(path) {
|
|
1092
|
+
let raw;
|
|
1093
|
+
try {
|
|
1094
|
+
raw = readFileSync12(path, "utf8");
|
|
1095
|
+
} catch {
|
|
1096
|
+
return [];
|
|
1097
|
+
}
|
|
1098
|
+
const turns = [];
|
|
1099
|
+
for (const rawLine of raw.split("\n")) {
|
|
1100
|
+
try {
|
|
1101
|
+
const event = JSON.parse(rawLine);
|
|
1102
|
+
if (event.type !== "user" && event.type !== "assistant") continue;
|
|
1103
|
+
if (event.type === "user" && typeof event.prompt_index !== "number") continue;
|
|
1104
|
+
const content = typeof event.content === "string" ? event.content : Array.isArray(event.content) ? event.content.filter((part) => part.type === "text").map((part) => part.text ?? "").join("\n") : "";
|
|
1105
|
+
const clean = stripInjectedMemory(content).trim();
|
|
1106
|
+
if (clean) turns.push({ role: event.type, content: clean });
|
|
1107
|
+
for (const toolCall of event.tool_calls ?? []) {
|
|
1108
|
+
if (!toolCall.name) continue;
|
|
1109
|
+
let input = toolCall.arguments;
|
|
1110
|
+
if (typeof input === "string") {
|
|
1111
|
+
try {
|
|
1112
|
+
input = JSON.parse(input);
|
|
1113
|
+
} catch {
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
turns.push({ role: "action", content: actionLine(toolCall.name, input) });
|
|
1117
|
+
}
|
|
1118
|
+
} catch {
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
return turns;
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
// src/core/transcript-devin.ts
|
|
1125
|
+
import { execFileSync as execFileSync4 } from "child_process";
|
|
1126
|
+
import { homedir as homedir6 } from "os";
|
|
1127
|
+
import { join as join9 } from "path";
|
|
1128
|
+
var sessionDb = join9(homedir6(), ".local", "share", "devin", "cli", "sessions.db");
|
|
1129
|
+
function parseDevinMessages(nodes) {
|
|
1130
|
+
const messages = /* @__PURE__ */ new Map();
|
|
1131
|
+
for (const node of nodes) {
|
|
1132
|
+
try {
|
|
1133
|
+
const message = JSON.parse(node.chat_message);
|
|
1134
|
+
if (message.role !== "user" && message.role !== "assistant" || !message.content?.trim())
|
|
1135
|
+
continue;
|
|
1136
|
+
const content = stripInjectedMemory(message.content).trim();
|
|
1137
|
+
if (!content) continue;
|
|
1138
|
+
const id = message.message_id || `node:${node.node_id}`;
|
|
1139
|
+
messages.set(id, {
|
|
1140
|
+
index: messages.get(id)?.index ?? node.node_id,
|
|
1141
|
+
role: message.role,
|
|
1142
|
+
content
|
|
1143
|
+
});
|
|
1144
|
+
} catch {
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
return [...messages.values()].sort((a, b) => a.index - b.index).map(({ role, content }) => ({ role, content }));
|
|
1148
|
+
}
|
|
1149
|
+
function readDevinTranscript(sessionId) {
|
|
1150
|
+
if (!sessionId) return [];
|
|
1151
|
+
try {
|
|
1152
|
+
const quotedId = sessionId.replace(/'/g, "''");
|
|
1153
|
+
const raw = execFileSync4(
|
|
1154
|
+
"sqlite3",
|
|
1155
|
+
[
|
|
1156
|
+
"-json",
|
|
1157
|
+
sessionDb,
|
|
1158
|
+
`SELECT node_id, chat_message FROM message_nodes WHERE session_id = '${quotedId}' ORDER BY node_id`
|
|
1159
|
+
],
|
|
1160
|
+
{ encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2e3 }
|
|
1161
|
+
);
|
|
1162
|
+
return parseDevinMessages(JSON.parse(raw));
|
|
1163
|
+
} catch {
|
|
1164
|
+
return [];
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
// src/harness/hook-lifecycle.ts
|
|
1169
|
+
var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
|
|
1170
|
+
var claudePrompt = {
|
|
1171
|
+
harness: "claude-code",
|
|
1172
|
+
parse: (ev) => ({
|
|
1173
|
+
prompt: ev.prompt,
|
|
1174
|
+
cwd: ev.cwd,
|
|
1175
|
+
sessionId: ev.session_id
|
|
1176
|
+
}),
|
|
1177
|
+
emit: (context, notice) => ({
|
|
1178
|
+
...notice ? { systemMessage: notice } : {},
|
|
1179
|
+
hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context }
|
|
1180
|
+
})
|
|
1181
|
+
};
|
|
1182
|
+
var codexPrompt = {
|
|
1183
|
+
...claudePrompt,
|
|
1184
|
+
harness: "codex",
|
|
1185
|
+
parse: (ev) => ({
|
|
1186
|
+
prompt: ev.prompt ?? ev.user_prompt,
|
|
1187
|
+
cwd: ev.cwd,
|
|
1188
|
+
sessionId: ev.session_id
|
|
1189
|
+
})
|
|
1190
|
+
};
|
|
1191
|
+
var antigravityCwd = (ev) => Array.isArray(ev.workspacePaths) ? ev.workspacePaths[0] : void 0;
|
|
1192
|
+
var antigravityPrompt = {
|
|
1193
|
+
harness: "antigravity-cli",
|
|
1194
|
+
requireCwd: true,
|
|
1195
|
+
parse: (ev) => ({
|
|
1196
|
+
// Antigravity's PreInvocation payload deliberately omits the prompt. Its transcript is already
|
|
1197
|
+
// persisted at that point, so recover the latest real user turn from the supplied JSONL path.
|
|
1198
|
+
prompt: readAntigravityTranscript(ev.transcriptPath).filter((turn) => turn.role === "user").at(-1)?.content,
|
|
1199
|
+
cwd: antigravityCwd(ev),
|
|
1200
|
+
sessionId: ev.conversationId
|
|
1201
|
+
}),
|
|
1202
|
+
emit: (context) => ({ injectSteps: context ? [{ ephemeralMessage: context }] : [] })
|
|
1203
|
+
};
|
|
1204
|
+
var cursorPrompt = {
|
|
1205
|
+
harness: "cursor-cli",
|
|
1206
|
+
parse: (ev) => ({
|
|
1207
|
+
prompt: ev.prompt ?? ev.user_prompt,
|
|
1208
|
+
cwd: cursorCwd(ev),
|
|
1209
|
+
sessionId: ev.conversation_id ?? ev.session_id
|
|
1210
|
+
}),
|
|
1211
|
+
emit: (context) => ({ continue: true, additional_context: context })
|
|
1212
|
+
};
|
|
1213
|
+
var copilotPrompt = {
|
|
1214
|
+
harness: "copilot-cli",
|
|
1215
|
+
parse: (ev) => ({
|
|
1216
|
+
prompt: ev.prompt,
|
|
1217
|
+
cwd: ev.cwd,
|
|
1218
|
+
sessionId: ev.sessionId
|
|
1219
|
+
}),
|
|
1220
|
+
emit: (context, _notice, ev) => ({
|
|
1221
|
+
// Copilot's userPromptTransformed hook replaces model-facing content rather than appending
|
|
1222
|
+
// hook context. Preserve its transformed prompt and add the shared Hindsight injection.
|
|
1223
|
+
modifiedTransformedPrompt: `${ev?.transformedPrompt ?? ""}
|
|
1224
|
+
|
|
1225
|
+
${context}`.trim()
|
|
1226
|
+
})
|
|
1227
|
+
};
|
|
1228
|
+
var devinCwd = () => process.env.DEVIN_PROJECT_DIR;
|
|
1229
|
+
var devinPrompt = {
|
|
1230
|
+
harness: "devin-cli",
|
|
1231
|
+
requireCwd: true,
|
|
1232
|
+
parse: (ev) => ({
|
|
1233
|
+
prompt: ev.prompt,
|
|
1234
|
+
cwd: devinCwd(),
|
|
1235
|
+
sessionId: ev.session_id
|
|
1236
|
+
}),
|
|
1237
|
+
emit: (context) => ({
|
|
1238
|
+
hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context }
|
|
1239
|
+
})
|
|
1240
|
+
};
|
|
1241
|
+
var standardSessionStart = (harness) => ({
|
|
1242
|
+
harness,
|
|
1243
|
+
parse: (ev) => ({
|
|
1244
|
+
cwd: ev.cwd,
|
|
1245
|
+
sessionId: ev.session_id
|
|
1246
|
+
}),
|
|
1247
|
+
emit: (out) => ({
|
|
1248
|
+
...out.systemMessage ? { systemMessage: out.systemMessage } : {},
|
|
1249
|
+
hookSpecificOutput: {
|
|
1250
|
+
hookEventName: "SessionStart",
|
|
1251
|
+
...out.additionalContext ? { additionalContext: out.additionalContext } : {}
|
|
1252
|
+
}
|
|
1253
|
+
})
|
|
1254
|
+
});
|
|
1255
|
+
var HOOK_HARNESSES = {
|
|
1256
|
+
"claude-code": {
|
|
1257
|
+
configStyle: "nested",
|
|
1258
|
+
install: {
|
|
1259
|
+
sessionStart: { event: "SessionStart", entry: "claude-sessionstart-hook.js", timeout: 30 },
|
|
1260
|
+
prompt: { event: "UserPromptSubmit", entry: "claude-hook.js", timeout: 30 },
|
|
1261
|
+
stop: { event: "Stop", entry: "claude-stop-hook.js", timeout: 60 }
|
|
1262
|
+
},
|
|
1263
|
+
sessionStart: standardSessionStart("claude-code"),
|
|
1264
|
+
prompt: claudePrompt,
|
|
1265
|
+
retain: {
|
|
1266
|
+
harness: "claude-code",
|
|
1267
|
+
parse: (ev) => ({
|
|
1268
|
+
sessionId: ev.session_id,
|
|
1269
|
+
transcriptPath: ev.transcript_path,
|
|
1270
|
+
cwd: ev.cwd
|
|
1271
|
+
})
|
|
1272
|
+
}
|
|
1273
|
+
},
|
|
1274
|
+
codex: {
|
|
1275
|
+
configStyle: "nested",
|
|
1276
|
+
install: {
|
|
1277
|
+
sessionStart: { event: "SessionStart", entry: "codex-sessionstart-hook.js", timeout: 30 },
|
|
1278
|
+
prompt: { event: "UserPromptSubmit", entry: "codex-hook.js", timeout: 30 },
|
|
1279
|
+
stop: { event: "Stop", entry: "codex-stop-hook.js", timeout: 60 }
|
|
1280
|
+
},
|
|
1281
|
+
sessionStart: standardSessionStart("codex"),
|
|
1282
|
+
prompt: codexPrompt,
|
|
1283
|
+
retain: {
|
|
1284
|
+
harness: "codex",
|
|
1285
|
+
parse: (ev) => ({
|
|
1286
|
+
sessionId: ev.session_id,
|
|
1287
|
+
transcriptPath: ev.transcript_path,
|
|
1288
|
+
cwd: ev.cwd
|
|
1289
|
+
}),
|
|
1290
|
+
readTranscript: readCodexTranscript
|
|
1291
|
+
}
|
|
1292
|
+
},
|
|
1293
|
+
"antigravity-cli": {
|
|
1294
|
+
configStyle: "flat",
|
|
1295
|
+
install: {
|
|
1296
|
+
// PreInvocation is Antigravity's only lifecycle point that can inject context. Its first
|
|
1297
|
+
// invocation also performs the SessionStart responsibilities through runHook's seed guard.
|
|
1298
|
+
sessionStart: { event: "PreInvocation", entry: "antigravity-hook.js", timeout: 30 },
|
|
1299
|
+
prompt: { event: "PreInvocation", entry: "antigravity-hook.js", timeout: 30 },
|
|
1300
|
+
stop: { event: "Stop", entry: "antigravity-stop-hook.js", timeout: 30 }
|
|
1301
|
+
},
|
|
1302
|
+
sessionStart: {
|
|
1303
|
+
harness: "antigravity-cli",
|
|
1304
|
+
parse: (ev) => ({
|
|
1305
|
+
cwd: antigravityCwd(ev),
|
|
1306
|
+
sessionId: ev.conversationId
|
|
1307
|
+
}),
|
|
1308
|
+
emit: () => ({})
|
|
1309
|
+
},
|
|
1310
|
+
prompt: antigravityPrompt,
|
|
1311
|
+
retain: {
|
|
1312
|
+
harness: "antigravity-cli",
|
|
1313
|
+
parse: (ev) => ({
|
|
1314
|
+
sessionId: ev.conversationId,
|
|
1315
|
+
transcriptPath: ev.transcriptPath,
|
|
1316
|
+
cwd: antigravityCwd(ev)
|
|
1317
|
+
}),
|
|
1318
|
+
readTranscript: readAntigravityTranscript
|
|
1319
|
+
}
|
|
1320
|
+
},
|
|
1321
|
+
"cursor-cli": {
|
|
1322
|
+
configStyle: "flat",
|
|
1323
|
+
install: {
|
|
1324
|
+
sessionStart: { event: "sessionStart", entry: "cursor-sessionstart-hook.js", timeout: 30 },
|
|
1325
|
+
prompt: { event: "beforeSubmitPrompt", entry: "cursor-hook.js" },
|
|
1326
|
+
stop: { event: "stop", entry: "cursor-stop-hook.js", timeout: 30 }
|
|
1327
|
+
},
|
|
1328
|
+
sessionStart: {
|
|
1329
|
+
harness: "cursor-cli",
|
|
1330
|
+
parse: (ev) => ({
|
|
1331
|
+
cwd: cursorCwd(ev),
|
|
1332
|
+
sessionId: ev.conversation_id ?? ev.session_id
|
|
1333
|
+
}),
|
|
1334
|
+
emit: (out) => ({
|
|
1335
|
+
...out.additionalContext ? { additional_context: out.additionalContext } : {}
|
|
1336
|
+
})
|
|
1337
|
+
},
|
|
1338
|
+
prompt: cursorPrompt,
|
|
1339
|
+
retain: {
|
|
1340
|
+
harness: "cursor-cli",
|
|
1341
|
+
parse: (ev) => ({
|
|
1342
|
+
sessionId: ev.conversation_id ?? ev.session_id,
|
|
1343
|
+
transcriptPath: ev.transcript_path,
|
|
1344
|
+
cwd: cursorCwd(ev)
|
|
1345
|
+
}),
|
|
1346
|
+
readTranscript: readCursorTranscript
|
|
1347
|
+
}
|
|
1348
|
+
},
|
|
1349
|
+
"copilot-cli": {
|
|
1350
|
+
configStyle: "flat",
|
|
1351
|
+
install: {
|
|
1352
|
+
sessionStart: { event: "sessionStart", entry: "copilot-sessionstart-hook.js", timeout: 30 },
|
|
1353
|
+
prompt: { event: "userPromptTransformed", entry: "copilot-hook.js", timeout: 30 },
|
|
1354
|
+
stop: { event: "agentStop", entry: "copilot-stop-hook.js", timeout: 60 }
|
|
1355
|
+
},
|
|
1356
|
+
sessionStart: {
|
|
1357
|
+
harness: "copilot-cli",
|
|
1358
|
+
parse: (ev) => ({
|
|
1359
|
+
cwd: ev.cwd,
|
|
1360
|
+
sessionId: ev.sessionId
|
|
1361
|
+
}),
|
|
1362
|
+
// Copilot CLI's SessionStart response only has model-facing `additionalContext`; unlike
|
|
1363
|
+
// Claude/Cursor it has no supported in-TUI system-message/banner channel. Keep memory
|
|
1364
|
+
// quiet rather than auto-submitting a synthetic prompt or showing an OS notification. When
|
|
1365
|
+
// Copilot exposes a real TUI extension point, add the banner there without changing this
|
|
1366
|
+
// shared lifecycle output.
|
|
1367
|
+
emit: (out) => ({
|
|
1368
|
+
...out.additionalContext ? { additionalContext: out.additionalContext } : {}
|
|
1369
|
+
})
|
|
1370
|
+
},
|
|
1371
|
+
prompt: copilotPrompt,
|
|
1372
|
+
retain: {
|
|
1373
|
+
harness: "copilot-cli",
|
|
1374
|
+
parse: (ev) => ({
|
|
1375
|
+
sessionId: ev.sessionId,
|
|
1376
|
+
transcriptPath: ev.transcriptPath,
|
|
1377
|
+
cwd: ev.cwd
|
|
1378
|
+
}),
|
|
1379
|
+
readTranscript: readCopilotTranscript
|
|
1380
|
+
}
|
|
1381
|
+
},
|
|
1382
|
+
"devin-cli": {
|
|
1383
|
+
configStyle: "nested",
|
|
1384
|
+
install: {
|
|
1385
|
+
sessionStart: { event: "SessionStart", entry: "devin-sessionstart-hook.js", timeout: 30 },
|
|
1386
|
+
prompt: { event: "UserPromptSubmit", entry: "devin-hook.js", timeout: 30 },
|
|
1387
|
+
stop: { event: "Stop", entry: "devin-stop-hook.js", timeout: 60 }
|
|
1388
|
+
},
|
|
1389
|
+
sessionStart: {
|
|
1390
|
+
harness: "devin-cli",
|
|
1391
|
+
parse: (ev) => ({ cwd: devinCwd(), sessionId: ev.session_id }),
|
|
1392
|
+
emit: (out) => ({
|
|
1393
|
+
hookSpecificOutput: {
|
|
1394
|
+
hookEventName: "SessionStart",
|
|
1395
|
+
...out.additionalContext ? { additionalContext: out.additionalContext } : {}
|
|
1396
|
+
}
|
|
1397
|
+
})
|
|
1398
|
+
},
|
|
1399
|
+
prompt: devinPrompt,
|
|
1400
|
+
retain: {
|
|
1401
|
+
harness: "devin-cli",
|
|
1402
|
+
parse: (ev) => {
|
|
1403
|
+
const sessionId = ev.session_id;
|
|
1404
|
+
return {
|
|
1405
|
+
sessionId,
|
|
1406
|
+
// RetainHook calls the supplied reader with transcriptPath; Devin's reader uses its
|
|
1407
|
+
// session id because the CLI persists conversations in sessions.db rather than a file.
|
|
1408
|
+
transcriptPath: sessionId,
|
|
1409
|
+
cwd: devinCwd()
|
|
1410
|
+
};
|
|
1411
|
+
},
|
|
1412
|
+
readTranscript: readDevinTranscript
|
|
1413
|
+
}
|
|
1414
|
+
},
|
|
1415
|
+
"grok-build": {
|
|
1416
|
+
configStyle: "nested",
|
|
1417
|
+
install: {
|
|
1418
|
+
sessionStart: { event: "SessionStart", entry: "grok-sessionstart-hook.js", timeout: 30 },
|
|
1419
|
+
prompt: { event: "UserPromptSubmit", entry: "grok-hook.js", timeout: 30 },
|
|
1420
|
+
stop: { event: "Stop", entry: "grok-stop-hook.js", timeout: 60 }
|
|
1421
|
+
},
|
|
1422
|
+
sessionStart: {
|
|
1423
|
+
...standardSessionStart("grok-build"),
|
|
1424
|
+
// Grok's wire envelope is camelCase, unlike Claude's similarly named hook events.
|
|
1425
|
+
parse: (ev) => ({
|
|
1426
|
+
cwd: ev.cwd,
|
|
1427
|
+
sessionId: ev.sessionId
|
|
1428
|
+
})
|
|
1429
|
+
},
|
|
1430
|
+
prompt: {
|
|
1431
|
+
...claudePrompt,
|
|
1432
|
+
harness: "grok-build",
|
|
1433
|
+
parse: (ev) => ({
|
|
1434
|
+
prompt: ev.prompt,
|
|
1435
|
+
cwd: ev.cwd,
|
|
1436
|
+
sessionId: ev.sessionId
|
|
1437
|
+
})
|
|
1438
|
+
},
|
|
1439
|
+
retain: {
|
|
1440
|
+
harness: "grok-build",
|
|
1441
|
+
parse: (ev) => ({
|
|
1442
|
+
sessionId: ev.sessionId,
|
|
1443
|
+
transcriptPath: typeof ev.cwd === "string" && typeof ev.sessionId === "string" ? grokTranscriptPath(ev.cwd, ev.sessionId) : void 0,
|
|
1444
|
+
cwd: ev.cwd
|
|
1445
|
+
}),
|
|
1446
|
+
readTranscript: readGrokTranscript
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
};
|
|
1450
|
+
var runHarnessRetain = (harness) => runRetainHook(HOOK_HARNESSES[harness].retain);
|
|
1451
|
+
|
|
1452
|
+
// src/devin-stop-hook.ts
|
|
1453
|
+
void runHarnessRetain("devin-cli");
|