intent-prompt-graph 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +110 -2
- package/integrations/claude/commands/ipg-log.md +10 -0
- package/integrations/claude/commands/ipg-rejected.md +10 -0
- package/integrations/claude/commands/ipg.md +10 -0
- package/integrations/omp/intent-graph.ts +65 -0
- package/integrations/omp/types.d.ts +30 -0
- package/package.json +47 -4
- package/src/cli.ts +212 -0
- package/src/config.ts +114 -0
- package/src/export.ts +71 -0
- package/src/harness/claude.ts +343 -0
- package/src/harness/harness.ts +32 -0
- package/src/harness/omp.ts +225 -0
- package/src/heuristic.ts +440 -0
- package/src/labeler.ts +496 -0
- package/src/model.ts +67 -0
- package/src/server.ts +173 -0
- package/src/session.ts +203 -0
- package/src/store.ts +122 -0
- package/src/tail.ts +89 -0
- package/web/app.ts +349 -0
- package/web/index.html +70 -0
- package/web/layout.ts +359 -0
- package/web/style.css +640 -0
- package/web/view.ts +654 -0
package/src/server.ts
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import type { Config } from "./config";
|
|
3
|
+
import { type Harness, harnessById, type SessionRef } from "./harness/harness";
|
|
4
|
+
import type { ServerEvent } from "./model";
|
|
5
|
+
import { openSession, type Session } from "./session";
|
|
6
|
+
|
|
7
|
+
export const APP = "intent-prompt-graph";
|
|
8
|
+
/** A session pipeline stops this long after its last SSE client leaves. */
|
|
9
|
+
const LINGER_MS = 60_000;
|
|
10
|
+
const PAGE = join(import.meta.dir, "../web/index.html");
|
|
11
|
+
const encoder = new TextEncoder();
|
|
12
|
+
|
|
13
|
+
interface Pipeline {
|
|
14
|
+
session: Promise<Session>;
|
|
15
|
+
clients: number;
|
|
16
|
+
linger?: Timer;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface Daemon {
|
|
20
|
+
readonly port: number;
|
|
21
|
+
stop(): void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Loopback HTTP daemon: the page, the SSE event stream, and a health check. */
|
|
25
|
+
export function startDaemon(opts: { config: Config; port: number; onIdle: () => void }): Daemon {
|
|
26
|
+
const { config } = opts;
|
|
27
|
+
const pipelines = new Map<string, Pipeline>();
|
|
28
|
+
let clients = 0;
|
|
29
|
+
let idle: Timer | undefined;
|
|
30
|
+
|
|
31
|
+
const armIdle = () => {
|
|
32
|
+
clearTimeout(idle);
|
|
33
|
+
idle = setTimeout(opts.onIdle, config.idleExitMinutes * 60_000);
|
|
34
|
+
idle.unref();
|
|
35
|
+
};
|
|
36
|
+
armIdle();
|
|
37
|
+
|
|
38
|
+
/** Returns the shared pipeline for a session, opening it on first use. */
|
|
39
|
+
function pipelineFor(id: string, harness: Harness, ref: SessionRef): Pipeline {
|
|
40
|
+
const have = pipelines.get(id);
|
|
41
|
+
if (have) return have;
|
|
42
|
+
const p: Pipeline = { session: openSession({ harness, ref, config }), clients: 0 };
|
|
43
|
+
pipelines.set(id, p);
|
|
44
|
+
p.session.catch(() => forget(id, p));
|
|
45
|
+
lingerUntilUnused(id, p);
|
|
46
|
+
return p;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function lingerUntilUnused(id: string, p: Pipeline) {
|
|
50
|
+
clearTimeout(p.linger);
|
|
51
|
+
p.linger = setTimeout(() => forget(id, p), LINGER_MS);
|
|
52
|
+
p.linger.unref();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function forget(id: string, p: Pipeline) {
|
|
56
|
+
if (pipelines.get(id) !== p) return;
|
|
57
|
+
clearTimeout(p.linger);
|
|
58
|
+
pipelines.delete(id);
|
|
59
|
+
void p.session.then((s) => s.stop(), () => {});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function sse(req: Request, srv: Bun.Server<undefined>, harnessId: string, key: string): Promise<Response> {
|
|
63
|
+
const found = await resolveRef(harnessId, key);
|
|
64
|
+
if (!found) return new Response("not found", { status: 404 });
|
|
65
|
+
const id = `${found.harness.id}/${found.ref.key}`;
|
|
66
|
+
const p = pipelineFor(id, found.harness, found.ref);
|
|
67
|
+
let session: Session;
|
|
68
|
+
try {
|
|
69
|
+
session = await p.session;
|
|
70
|
+
} catch (err) {
|
|
71
|
+
return new Response(`ipg: ${(err as Error).message}`, { status: 500 });
|
|
72
|
+
}
|
|
73
|
+
if (req.signal.aborted) return new Response(null, { status: 204 });
|
|
74
|
+
|
|
75
|
+
srv.timeout(req, 0); // SSE connections stay open; the default idle timeout would cut them.
|
|
76
|
+
clearTimeout(p.linger);
|
|
77
|
+
p.clients += 1;
|
|
78
|
+
clients += 1;
|
|
79
|
+
clearTimeout(idle);
|
|
80
|
+
|
|
81
|
+
let unsubscribe: (() => void) | undefined;
|
|
82
|
+
let detached = false;
|
|
83
|
+
const detach = () => {
|
|
84
|
+
if (detached) return;
|
|
85
|
+
detached = true;
|
|
86
|
+
unsubscribe?.();
|
|
87
|
+
p.clients -= 1;
|
|
88
|
+
if (p.clients === 0) lingerUntilUnused(id, p);
|
|
89
|
+
clients -= 1;
|
|
90
|
+
if (clients === 0) armIdle();
|
|
91
|
+
};
|
|
92
|
+
req.signal.addEventListener("abort", detach);
|
|
93
|
+
|
|
94
|
+
const body = new ReadableStream<Uint8Array>({
|
|
95
|
+
start(controller) {
|
|
96
|
+
const send = (ev: ServerEvent) => controller.enqueue(encoder.encode(`data: ${JSON.stringify(ev)}\n\n`));
|
|
97
|
+
// snapshot() and subscribe() run in one synchronous step, so no event falls between them.
|
|
98
|
+
send(session.snapshot());
|
|
99
|
+
unsubscribe = session.subscribe(send);
|
|
100
|
+
},
|
|
101
|
+
cancel: detach,
|
|
102
|
+
});
|
|
103
|
+
return new Response(body, {
|
|
104
|
+
headers: { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" },
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const server = Bun.serve({
|
|
109
|
+
port: opts.port,
|
|
110
|
+
hostname: "127.0.0.1",
|
|
111
|
+
fetch(req, srv) {
|
|
112
|
+
if (!hostAllowed(req.headers.get("host"), srv.port ?? 0)) return new Response("forbidden", { status: 403 });
|
|
113
|
+
const { pathname } = new URL(req.url);
|
|
114
|
+
if (pathname === "/health") return Response.json({ app: APP });
|
|
115
|
+
const events = /^\/api\/s\/([^/]+)\/([^/]+)\/events$/.exec(pathname);
|
|
116
|
+
if (events) return sse(req, srv, events[1] ?? "", events[2] ?? "");
|
|
117
|
+
const page = /^\/s\/([^/]+)\/([^/]+)$/.exec(pathname);
|
|
118
|
+
if (page) return pageFor(page[1] ?? "", page[2] ?? "");
|
|
119
|
+
const asset = /^\/_web\/([^/]+)$/.exec(pathname);
|
|
120
|
+
if (asset) return assetFor(asset[1] ?? "");
|
|
121
|
+
return new Response("not found", { status: 404 });
|
|
122
|
+
},
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
return {
|
|
126
|
+
port: server.port ?? opts.port,
|
|
127
|
+
stop() {
|
|
128
|
+
clearTimeout(idle);
|
|
129
|
+
server.stop(true);
|
|
130
|
+
for (const [id, p] of pipelines) forget(id, p);
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function resolveRef(harnessId: string, key: string): Promise<{ harness: Harness; ref: SessionRef } | undefined> {
|
|
136
|
+
const harness = harnessById(harnessId);
|
|
137
|
+
if (!harness) return undefined;
|
|
138
|
+
try {
|
|
139
|
+
return { harness, ref: await harness.resolve(key) };
|
|
140
|
+
} catch {
|
|
141
|
+
return undefined;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function pageFor(harnessId: string, key: string): Promise<Response> {
|
|
146
|
+
if (!(await resolveRef(harnessId, key))) return new Response("not found", { status: 404 });
|
|
147
|
+
const html = (await webBundle()).get("index.html");
|
|
148
|
+
if (!html) throw new Error("ipg: web bundle has no index.html");
|
|
149
|
+
return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function assetFor(name: string): Promise<Response> {
|
|
153
|
+
const file = (await webBundle()).get(name);
|
|
154
|
+
return file ? new Response(file) : new Response("not found", { status: 404 });
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
let bundle: Promise<Map<string, Blob>> | undefined;
|
|
158
|
+
|
|
159
|
+
/** Bundles the page once per process: HTML, TS and CSS become files served under /_web/. */
|
|
160
|
+
function webBundle(): Promise<Map<string, Blob>> {
|
|
161
|
+
bundle ??= buildPage();
|
|
162
|
+
return bundle;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function buildPage(): Promise<Map<string, Blob>> {
|
|
166
|
+
const out = await Bun.build({ entrypoints: [PAGE], publicPath: "/_web/" });
|
|
167
|
+
if (!out.success) throw new AggregateError(out.logs, "ipg: web build failed");
|
|
168
|
+
return new Map(out.outputs.map((o) => [o.path.replace(/^\.\//, ""), o] as const));
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function hostAllowed(host: string | null, port: number): boolean {
|
|
172
|
+
return host === `127.0.0.1:${port}` || host === `localhost:${port}`;
|
|
173
|
+
}
|
package/src/session.ts
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { isLabelerConfigured, type Config } from "./config";
|
|
2
|
+
import type { Harness, SessionRef } from "./harness/harness";
|
|
3
|
+
import { buildHeuristicGraph } from "./heuristic";
|
|
4
|
+
import { extractGraph, payloadText, redactTurn, type GraphExtractInput } from "./labeler";
|
|
5
|
+
import type { ServerEvent, SessionGraph, Turn } from "./model";
|
|
6
|
+
import { openStore } from "./store";
|
|
7
|
+
import { tailJsonl, type TailEvent } from "./tail";
|
|
8
|
+
|
|
9
|
+
export const BATCH_TURNS = 16;
|
|
10
|
+
export const BATCH_CHARS = 12_000;
|
|
11
|
+
export const RETRY_MS = 60_000;
|
|
12
|
+
|
|
13
|
+
export type SnapshotEvent = Extract<ServerEvent, { type: "snapshot" }>;
|
|
14
|
+
|
|
15
|
+
export interface Session {
|
|
16
|
+
snapshot(): SnapshotEvent;
|
|
17
|
+
/** Returns an unsubscribe function. */
|
|
18
|
+
subscribe(fn: (ev: ServerEvent) => void): () => void;
|
|
19
|
+
stop(): void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Opens one live session pipeline: tails the transcript, emits each turn immediately (I1),
|
|
24
|
+
* builds an instant heuristic Decision & Path Graph, and asynchronously upgrades it via the
|
|
25
|
+
* configured LLM extractor when available.
|
|
26
|
+
*
|
|
27
|
+
* Args:
|
|
28
|
+
* opts ({ harness: Harness; ref: SessionRef; config: Config }): Session dependencies.
|
|
29
|
+
*
|
|
30
|
+
* Returns:
|
|
31
|
+
* Promise<Session>: Live session handle with snapshot(), subscribe(), and stop().
|
|
32
|
+
*/
|
|
33
|
+
export async function openSession(opts: { harness: Harness; ref: SessionRef; config: Config }): Promise<Session> {
|
|
34
|
+
const { harness, ref, config } = opts;
|
|
35
|
+
const store = openStore(harness.id, ref.key);
|
|
36
|
+
const labelerCfg = config.labeler ?? {};
|
|
37
|
+
const llmEnabled = isLabelerConfigured(config.labeler);
|
|
38
|
+
const turns = new Map<string, Turn>();
|
|
39
|
+
const subs = new Set<(ev: ServerEvent) => void>();
|
|
40
|
+
let reader = harness.reader(ref, { config });
|
|
41
|
+
let busy = false;
|
|
42
|
+
let stopped = false;
|
|
43
|
+
let ready = false;
|
|
44
|
+
let labelerError: string | undefined;
|
|
45
|
+
let retry: Timer | undefined;
|
|
46
|
+
let heuristicGraph: SessionGraph = buildHeuristicGraph([], ref.title);
|
|
47
|
+
|
|
48
|
+
const emit = (ev: ServerEvent) => {
|
|
49
|
+
for (const fn of subs) fn(ev);
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/** Returns the active graph: persisted LLM graph when available, otherwise the live heuristic graph. */
|
|
53
|
+
function currentGraph(): SessionGraph {
|
|
54
|
+
if (store.graph && store.graph.nodes.length > 0) return store.graph;
|
|
55
|
+
return heuristicGraph;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function refreshHeuristic(shouldEmit: boolean): void {
|
|
59
|
+
heuristicGraph = buildHeuristicGraph([...turns.values()], ref.title);
|
|
60
|
+
if (shouldEmit && !store.graph) {
|
|
61
|
+
emit({ type: "graph", graph: heuristicGraph });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function setLabelerError(error: string | undefined): void {
|
|
66
|
+
if (error === undefined) {
|
|
67
|
+
clearTimeout(retry);
|
|
68
|
+
retry = undefined;
|
|
69
|
+
}
|
|
70
|
+
if (error === labelerError) return;
|
|
71
|
+
labelerError = error;
|
|
72
|
+
emit(error === undefined ? { type: "labeler" } : { type: "labeler", error });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function scheduleRetry(): void {
|
|
76
|
+
clearTimeout(retry);
|
|
77
|
+
retry = setTimeout(() => {
|
|
78
|
+
retry = undefined;
|
|
79
|
+
void drain();
|
|
80
|
+
}, RETRY_MS);
|
|
81
|
+
retry.unref();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Collects the next batch of closed, unprocessed turns in file order. */
|
|
85
|
+
function nextBatch(): Turn[] {
|
|
86
|
+
const batch: Turn[] = [];
|
|
87
|
+
let chars = 0;
|
|
88
|
+
for (const turn of turns.values()) {
|
|
89
|
+
if (turn.open) break;
|
|
90
|
+
if (store.processedTurnIds.has(turn.id)) continue;
|
|
91
|
+
const size = payloadText(turn).length;
|
|
92
|
+
if (batch.length > 0 && (batch.length >= BATCH_TURNS || chars + size > BATCH_CHARS)) break;
|
|
93
|
+
batch.push(turn);
|
|
94
|
+
chars += size;
|
|
95
|
+
}
|
|
96
|
+
return batch;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function buildInput(batch: Turn[]): GraphExtractInput {
|
|
100
|
+
const input: GraphExtractInput = {
|
|
101
|
+
sessionTitle: ref.title,
|
|
102
|
+
turns: batch.map(redactTurn),
|
|
103
|
+
};
|
|
104
|
+
if (store.graph) {
|
|
105
|
+
// Outline only: the reply is a patch that the labeler merges into store.graph locally.
|
|
106
|
+
input.existingGraph = {
|
|
107
|
+
title: store.graph.title,
|
|
108
|
+
nodes: store.graph.nodes.map((n) => ({
|
|
109
|
+
id: n.id,
|
|
110
|
+
kind: n.kind,
|
|
111
|
+
title: n.title,
|
|
112
|
+
...(n.rounds !== undefined ? { rounds: n.rounds } : {}),
|
|
113
|
+
})),
|
|
114
|
+
edges: store.graph.edges.map((e) => ({ from: e.from, to: e.to, kind: e.kind })),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
return input;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function timestampsMap(): Map<string, number> {
|
|
121
|
+
const map = new Map<string, number>();
|
|
122
|
+
for (const [id, t] of turns) map.set(id, t.at);
|
|
123
|
+
return map;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function extractFrom(batch: Turn[]): Promise<void> {
|
|
127
|
+
if (batch.length === 0 || stopped) return;
|
|
128
|
+
const graph = await extractGraph(labelerCfg, buildInput(batch), timestampsMap(), store.graph);
|
|
129
|
+
if (stopped) return;
|
|
130
|
+
store.saveGraph(graph, batch.map((t) => t.id));
|
|
131
|
+
setLabelerError(undefined);
|
|
132
|
+
emit({ type: "graph", graph });
|
|
133
|
+
return extractFrom(nextBatch());
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function drain(): Promise<void> {
|
|
137
|
+
if (!llmEnabled || busy || stopped) return;
|
|
138
|
+
busy = true;
|
|
139
|
+
try {
|
|
140
|
+
await extractFrom(nextBatch());
|
|
141
|
+
} catch (err) {
|
|
142
|
+
if (stopped) return;
|
|
143
|
+
setLabelerError(err instanceof Error ? err.message : String(err));
|
|
144
|
+
scheduleRetry();
|
|
145
|
+
} finally {
|
|
146
|
+
busy = false;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const onTail = (ev: TailEvent) => {
|
|
151
|
+
if (stopped) return;
|
|
152
|
+
if (ev.type === "reset") {
|
|
153
|
+
turns.clear();
|
|
154
|
+
reader = harness.reader(ref, { config });
|
|
155
|
+
ready = false;
|
|
156
|
+
emit({ type: "reset" });
|
|
157
|
+
setImmediate(() => {
|
|
158
|
+
ready = true;
|
|
159
|
+
refreshHeuristic(true);
|
|
160
|
+
if (store.graph) emit({ type: "graph", graph: store.graph });
|
|
161
|
+
void drain();
|
|
162
|
+
});
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
let changed = false;
|
|
166
|
+
for (const turn of reader.push(ev.record)) {
|
|
167
|
+
turns.set(turn.id, turn);
|
|
168
|
+
emit({ type: "turn", turn });
|
|
169
|
+
changed = true;
|
|
170
|
+
}
|
|
171
|
+
if (ready && changed) {
|
|
172
|
+
refreshHeuristic(true);
|
|
173
|
+
void drain();
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
const tail = await tailJsonl(ref.file, onTail, { follow: true });
|
|
178
|
+
ready = true;
|
|
179
|
+
refreshHeuristic(false);
|
|
180
|
+
void drain();
|
|
181
|
+
|
|
182
|
+
return {
|
|
183
|
+
snapshot: () => ({
|
|
184
|
+
type: "snapshot",
|
|
185
|
+
session: ref.key,
|
|
186
|
+
turns: [...turns.values()],
|
|
187
|
+
graph: currentGraph(),
|
|
188
|
+
labelerError,
|
|
189
|
+
}),
|
|
190
|
+
subscribe(fn) {
|
|
191
|
+
subs.add(fn);
|
|
192
|
+
return () => {
|
|
193
|
+
subs.delete(fn);
|
|
194
|
+
};
|
|
195
|
+
},
|
|
196
|
+
stop() {
|
|
197
|
+
stopped = true;
|
|
198
|
+
tail.stop();
|
|
199
|
+
clearTimeout(retry);
|
|
200
|
+
subs.clear();
|
|
201
|
+
},
|
|
202
|
+
};
|
|
203
|
+
}
|
package/src/store.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import type { SessionGraph } from "./model";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Computes the per-session append-only JSONL state file path under XDG_STATE_HOME.
|
|
8
|
+
*
|
|
9
|
+
* Args:
|
|
10
|
+
* harness (string): Harness identifier (e.g. "omp").
|
|
11
|
+
* key (string): Session key/id.
|
|
12
|
+
* env (NodeJS.ProcessEnv): Environment map for resolving XDG_STATE_HOME.
|
|
13
|
+
*
|
|
14
|
+
* Returns:
|
|
15
|
+
* string: Absolute path to the session's state JSONL file.
|
|
16
|
+
*/
|
|
17
|
+
export function storeFile(harness: string, key: string, env: NodeJS.ProcessEnv = process.env): string {
|
|
18
|
+
const base = env.XDG_STATE_HOME || join(homedir(), ".local", "state");
|
|
19
|
+
return join(base, "intent-prompt-graph", harness, `${key}.jsonl`);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface Store {
|
|
23
|
+
readonly file: string;
|
|
24
|
+
/** Latest persisted LLM SessionGraph, if any. */
|
|
25
|
+
graph: SessionGraph | undefined;
|
|
26
|
+
/** Turn IDs already processed by the persisted LLM graph. */
|
|
27
|
+
readonly processedTurnIds: Set<string>;
|
|
28
|
+
/** Appends a new validated LLM graph snapshot and its covered turn IDs. */
|
|
29
|
+
saveGraph(graph: SessionGraph, processedIds: Iterable<string>): void;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface GraphRecord {
|
|
33
|
+
t: "graph";
|
|
34
|
+
graph: SessionGraph;
|
|
35
|
+
processedTurnIds: string[];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Parses one JSONL line from the store file, ignoring corrupt or legacy intent/label lines.
|
|
40
|
+
*
|
|
41
|
+
* Args:
|
|
42
|
+
* line (string): Single line from the store file.
|
|
43
|
+
*
|
|
44
|
+
* Returns:
|
|
45
|
+
* GraphRecord | undefined: Parsed graph record or undefined if not a valid graph line.
|
|
46
|
+
*/
|
|
47
|
+
function parseLine(line: string): GraphRecord | undefined {
|
|
48
|
+
if (!line.trim()) return undefined;
|
|
49
|
+
let v: unknown;
|
|
50
|
+
try {
|
|
51
|
+
v = JSON.parse(line);
|
|
52
|
+
} catch {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
if (typeof v !== "object" || v === null) return undefined;
|
|
56
|
+
const rec = v as Record<string, unknown>;
|
|
57
|
+
if (rec.t !== "graph") return undefined;
|
|
58
|
+
if (typeof rec.graph !== "object" || rec.graph === null) return undefined;
|
|
59
|
+
const g = rec.graph as Record<string, unknown>;
|
|
60
|
+
if (typeof g.title !== "string" || !Array.isArray(g.nodes) || !Array.isArray(g.edges)) return undefined;
|
|
61
|
+
const processedTurnIds = Array.isArray(rec.processedTurnIds)
|
|
62
|
+
? rec.processedTurnIds.filter((x): x is string => typeof x === "string")
|
|
63
|
+
: [];
|
|
64
|
+
return {
|
|
65
|
+
t: "graph",
|
|
66
|
+
graph: rec.graph as SessionGraph,
|
|
67
|
+
processedTurnIds,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Opens or initializes the per-session append-only graph store.
|
|
73
|
+
*
|
|
74
|
+
* Args:
|
|
75
|
+
* harness (string): Harness identifier.
|
|
76
|
+
* key (string): Session key/id.
|
|
77
|
+
* env (NodeJS.ProcessEnv): Environment map for resolving XDG_STATE_HOME.
|
|
78
|
+
*
|
|
79
|
+
* Returns:
|
|
80
|
+
* Store: Store handle with replayed graph state and saveGraph() writer.
|
|
81
|
+
*/
|
|
82
|
+
export function openStore(harness: string, key: string, env: NodeJS.ProcessEnv = process.env): Store {
|
|
83
|
+
const file = storeFile(harness, key, env);
|
|
84
|
+
let graph: SessionGraph | undefined;
|
|
85
|
+
const processedTurnIds = new Set<string>();
|
|
86
|
+
let needsNewline = false;
|
|
87
|
+
|
|
88
|
+
if (existsSync(file)) {
|
|
89
|
+
const text = readFileSync(file, "utf8");
|
|
90
|
+
for (const line of text.split("\n")) {
|
|
91
|
+
const rec = parseLine(line);
|
|
92
|
+
if (!rec) continue;
|
|
93
|
+
graph = rec.graph;
|
|
94
|
+
for (const id of rec.processedTurnIds) processedTurnIds.add(id);
|
|
95
|
+
}
|
|
96
|
+
needsNewline = text.length > 0 && !text.endsWith("\n");
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return {
|
|
100
|
+
file,
|
|
101
|
+
get graph() {
|
|
102
|
+
return graph;
|
|
103
|
+
},
|
|
104
|
+
set graph(next) {
|
|
105
|
+
graph = next;
|
|
106
|
+
},
|
|
107
|
+
processedTurnIds,
|
|
108
|
+
saveGraph(nextGraph, ids) {
|
|
109
|
+
for (const id of ids) processedTurnIds.add(id);
|
|
110
|
+
graph = nextGraph;
|
|
111
|
+
const record: GraphRecord = {
|
|
112
|
+
t: "graph",
|
|
113
|
+
graph: nextGraph,
|
|
114
|
+
processedTurnIds: [...processedTurnIds],
|
|
115
|
+
};
|
|
116
|
+
const out = `${needsNewline ? "\n" : ""}${JSON.stringify(record)}\n`;
|
|
117
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
118
|
+
appendFileSync(file, out);
|
|
119
|
+
needsNewline = false;
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|
package/src/tail.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { closeSync, fstatSync, openSync, readSync, watch } from "node:fs";
|
|
2
|
+
|
|
3
|
+
export type TailEvent = { type: "record"; record: unknown } | { type: "reset" };
|
|
4
|
+
export interface Tail {
|
|
5
|
+
stop(): void;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
const CHUNK = 1 << 20;
|
|
9
|
+
const POLL_MS = 1000;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Streams a JSONL file from byte 0 and emits one event per complete line.
|
|
13
|
+
* follow=false returns after the first catch-up (used by `ipg turns`); follow=true keeps watching.
|
|
14
|
+
* A changed inode or a shrunken file emits `reset` and re-reads from 0.
|
|
15
|
+
*/
|
|
16
|
+
export async function tailJsonl(
|
|
17
|
+
file: string,
|
|
18
|
+
emit: (ev: TailEvent) => void,
|
|
19
|
+
opts: { follow: boolean },
|
|
20
|
+
): Promise<Tail> {
|
|
21
|
+
let ino = -1;
|
|
22
|
+
let offset = 0;
|
|
23
|
+
let carry: Buffer = Buffer.alloc(0);
|
|
24
|
+
let stopped = false;
|
|
25
|
+
const out = (ev: TailEvent) => {
|
|
26
|
+
if (!stopped) emit(ev);
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const sync = () => {
|
|
30
|
+
const fd = openSync(file, "r");
|
|
31
|
+
try {
|
|
32
|
+
const st = fstatSync(fd);
|
|
33
|
+
if (ino !== -1 && (st.ino !== ino || st.size < offset)) {
|
|
34
|
+
out({ type: "reset" });
|
|
35
|
+
offset = 0;
|
|
36
|
+
carry = Buffer.alloc(0);
|
|
37
|
+
}
|
|
38
|
+
ino = st.ino;
|
|
39
|
+
while (offset < st.size) {
|
|
40
|
+
const buf = Buffer.allocUnsafe(Math.min(CHUNK, st.size - offset));
|
|
41
|
+
const n = readSync(fd, buf, 0, buf.length, offset);
|
|
42
|
+
if (n === 0) break;
|
|
43
|
+
offset += n;
|
|
44
|
+
carry = drainLines(Buffer.concat([carry, buf.subarray(0, n)]), out);
|
|
45
|
+
}
|
|
46
|
+
} finally {
|
|
47
|
+
closeSync(fd);
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
sync();
|
|
52
|
+
if (!opts.follow) return { stop() {} };
|
|
53
|
+
|
|
54
|
+
// Follow-mode errors (e.g. a file briefly missing during rename) are swallowed: the next tick retries.
|
|
55
|
+
const kick = () => {
|
|
56
|
+
if (stopped) return;
|
|
57
|
+
try {
|
|
58
|
+
sync();
|
|
59
|
+
} catch {}
|
|
60
|
+
};
|
|
61
|
+
const watcher = watch(file, kick);
|
|
62
|
+
// A dead watch must not crash the process; the poll keeps following.
|
|
63
|
+
watcher.on("error", () => {});
|
|
64
|
+
const timer = setInterval(kick, POLL_MS);
|
|
65
|
+
return {
|
|
66
|
+
stop() {
|
|
67
|
+
stopped = true;
|
|
68
|
+
clearInterval(timer);
|
|
69
|
+
watcher.close();
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function drainLines(buf: Buffer, out: (ev: TailEvent) => void): Buffer {
|
|
75
|
+
let start = 0;
|
|
76
|
+
for (let nl = buf.indexOf(0x0a, start); nl !== -1; nl = buf.indexOf(0x0a, start)) {
|
|
77
|
+
const text = buf.toString("utf8", start, nl).trim();
|
|
78
|
+
start = nl + 1;
|
|
79
|
+
if (!text) continue;
|
|
80
|
+
let record: unknown;
|
|
81
|
+
try {
|
|
82
|
+
record = JSON.parse(text);
|
|
83
|
+
} catch {
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
out({ type: "record", record });
|
|
87
|
+
}
|
|
88
|
+
return buf.subarray(start);
|
|
89
|
+
}
|