portable-agent-layer 0.117.0-canary.21 → 0.117.0-canary.22
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 +1 -0
- package/package.json +1 -1
- package/src/bronze/events.ts +13 -0
- package/src/cli/algorithm-run.ts +102 -0
- package/src/cli/tree.ts +2 -0
- package/src/hooks/lib/algorithm-run-facts.ts +67 -0
- package/src/hooks/lib/algorithm-run-replay.ts +201 -0
- package/src/hooks/lib/algorithm-run-report.ts +146 -0
- package/src/hooks/lib/algorithm-runs.ts +160 -0
- package/src/hooks/lib/interaction.ts +5 -0
- package/src/hooks/lib/progress-session.ts +4 -0
- package/src/hooks/lib/stop.ts +5 -0
- package/src/hooks/lib/turn-extras.ts +1 -1
- package/src/tools/agent/algorithm-reflect.ts +2 -0
package/README.md
CHANGED
|
@@ -114,6 +114,7 @@ pal cli status # check your setup
|
|
|
114
114
|
| `pal cli rule` | Review the rules drafted from your corrections — `list [--all] [--json]`, `approve <id>`, `opinion <id>`, `deny <id>`, `retire <id>`, `add-opinion --kind --when --steering`. A draft steers nothing until approved; a denied one is never drafted again. An opinion has no trigger and steers every session, at most 8 of them and one per correction kind; `list --all` shows each one's correction-kind rate before and after approval |
|
|
115
115
|
| `pal cli correction` | The kinds of mistakes you corrected — `kinds [--days N] [--split DATE] [--json]` shows each kind per 100 turns, before and after a date with `--split`; `backfill` labels confirmed corrections without a kind or with one from an older prompt, and `--relabel` labels every one again |
|
|
116
116
|
| `pal cli compaction backtest` | Score the shadow "compaction is close" rule against logged history. Labels each auto compaction `threshold`, `idle`, `no_context` or `unexplained`, and per margin reports the threshold compactions it warned and missed, its false alarms, and the median lead in minutes and tokens. `--margin <fraction>[,...]` (default 0.2), `--days <n>` (default 30), `--window <tokens>[@<until>]` (repeatable), `--json` |
|
|
117
|
+
| `pal cli algorithm-run report` | Shadow numbers for ALGORITHM runs, recorded per progress-tree node: turns and runs started, how runs ended (finished, superseded, open), verdicts with the share of `no-node`, turns without a reflection by the last phase reached, and every `over-open-run` case to label. Records only; warns and blocks nothing. `--since <date>`, `--json` |
|
|
117
118
|
| `pal cli server` | The morning screen: a local page to open before a terminal — three moves for today, an urgent/important grid over every project *and* every stated goal, where you left off, and a drawer holding the signal and the action ledger — `start [--port <n>]`, `stop`, `status`. Loopback only, default port 7250. No model runs on page load |
|
|
118
119
|
| `pal cli skill link <name>` | Link a personal `~/.pal/skills/<name>/` into every installed agent so it is discoverable |
|
|
119
120
|
| `pal cli skill doctor <name>` | Evaluate a skill against the authoring best practices (folder/file-name match, name, description, body length, point-of-view, reference depth) |
|
package/package.json
CHANGED
package/src/bronze/events.ts
CHANGED
|
@@ -194,6 +194,19 @@ export const EVENT_FIELDS = {
|
|
|
194
194
|
"predicted",
|
|
195
195
|
"idleMinTokens",
|
|
196
196
|
],
|
|
197
|
+
algorithm_run: [
|
|
198
|
+
"mode",
|
|
199
|
+
"change",
|
|
200
|
+
"run",
|
|
201
|
+
"node",
|
|
202
|
+
"turn",
|
|
203
|
+
"phases",
|
|
204
|
+
"header",
|
|
205
|
+
"headerFirst",
|
|
206
|
+
"startsNew",
|
|
207
|
+
"verdict",
|
|
208
|
+
"source",
|
|
209
|
+
],
|
|
197
210
|
worktree_pruned: ["branch"],
|
|
198
211
|
git_state_injected: ["trigger", "source", "changed", "committedFiles", "chars"],
|
|
199
212
|
hook_run: ["hook", "event", "durationMs", "exitCode"],
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The algorithm-run command: the shadow numbers for ALGORITHM runs, read from the event log.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { allEventsSince } from "../bronze/events";
|
|
6
|
+
import {
|
|
7
|
+
type AlgorithmRunReport,
|
|
8
|
+
algorithmRunReport,
|
|
9
|
+
type ReportedEvent,
|
|
10
|
+
} from "../hooks/lib/algorithm-run-report";
|
|
11
|
+
import { readEvents } from "../hooks/lib/progress-tree";
|
|
12
|
+
import { group, leaf, UsageError } from "../tools/lib/command";
|
|
13
|
+
|
|
14
|
+
function parseSince(raw: string | undefined): Date {
|
|
15
|
+
if (raw === undefined) return new Date(0);
|
|
16
|
+
const since = new Date(raw);
|
|
17
|
+
if (Number.isNaN(since.getTime()))
|
|
18
|
+
throw new UsageError(`--since must be a date such as 2026-11-15, got "${raw}"`);
|
|
19
|
+
|
|
20
|
+
return since;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function nodeTitles(): Map<string, string> {
|
|
24
|
+
return new Map(
|
|
25
|
+
readEvents().flatMap((e) => (e.type === "open" ? [[e.node, e.title] as const] : []))
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function reportSince(since: Date): AlgorithmRunReport {
|
|
30
|
+
const events = allEventsSince(since);
|
|
31
|
+
const replyModes = new Map(
|
|
32
|
+
events
|
|
33
|
+
.filter((e) => e.type === "reply")
|
|
34
|
+
.map((e) => [e.turn as string, (e.mode as string | null) ?? null])
|
|
35
|
+
);
|
|
36
|
+
const titles = nodeTitles();
|
|
37
|
+
|
|
38
|
+
return algorithmRunReport({
|
|
39
|
+
events: events.filter(
|
|
40
|
+
(e) => e.type === "algorithm_run"
|
|
41
|
+
) as unknown as ReportedEvent[],
|
|
42
|
+
replyModes,
|
|
43
|
+
nodeTitle: (node) => titles.get(node) ?? null,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function percent(value: number | null): string {
|
|
48
|
+
return value === null ? "-" : `${Math.round(value * 100)}%`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function counts(record: Record<string, number>): string {
|
|
52
|
+
const entries = Object.entries(record);
|
|
53
|
+
|
|
54
|
+
return entries.length ? entries.map(([k, n]) => `${k} ${n}`).join(", ") : "none";
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function formatReport(report: AlgorithmRunReport): string[] {
|
|
58
|
+
const { runs, overOpenRun } = report;
|
|
59
|
+
|
|
60
|
+
return [
|
|
61
|
+
`ALGORITHM turns: ${report.algorithmTurns} (reply.mode tagged ${report.taggedByReplyMode})`,
|
|
62
|
+
`Runs started: ${runs.started} (finished ${runs.finished}, superseded ${runs.superseded}, open ${runs.open})`,
|
|
63
|
+
`Finished runs with all five phases: ${report.finishedWithAllPhases}`,
|
|
64
|
+
`Turns by verdict: ${counts(report.verdicts)} (no-node ${percent(report.noNodeShare)})`,
|
|
65
|
+
`ALGORITHM turns without a reflection, by last phase: ${counts(report.unreflectedByLastPhase)}`,
|
|
66
|
+
`Reflections outside a run: ${report.reflectionsOutsideRun}`,
|
|
67
|
+
`Turns from agents that cannot tie a reflection to a turn: ${report.turnsWithoutSessionTie}`,
|
|
68
|
+
`over-open-run: ${overOpenRun.cases.length} (OBSERVE written ${overOpenRun.withObserve}, not ${overOpenRun.withoutObserve})`,
|
|
69
|
+
...overOpenRun.cases.map(
|
|
70
|
+
(c) =>
|
|
71
|
+
` ${c.date} ${c.project ?? "-"} "${c.nodeTitle ?? c.node ?? "-"}" old [${c.oldPhases.join(" ")}] observe ${c.observe ? "yes" : "no"} turns ${c.oldTurn ?? "-"} -> ${c.newTurn ?? "-"}`
|
|
72
|
+
),
|
|
73
|
+
];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function printReport(report: AlgorithmRunReport, json: boolean | undefined): number {
|
|
77
|
+
const lines = json ? [JSON.stringify(report, null, 2)] : formatReport(report);
|
|
78
|
+
|
|
79
|
+
for (const line of lines) console.log(line);
|
|
80
|
+
|
|
81
|
+
return 0;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export const algorithmRunCommand = group({
|
|
85
|
+
summary: "ALGORITHM runs recorded in shadow mode",
|
|
86
|
+
commands: {
|
|
87
|
+
report: leaf({
|
|
88
|
+
summary:
|
|
89
|
+
"Count ALGORITHM runs, their verdicts and endings, and list the cases to label",
|
|
90
|
+
options: {
|
|
91
|
+
since: {
|
|
92
|
+
type: "string",
|
|
93
|
+
value: "<date>",
|
|
94
|
+
description: "Only events from this date on (default: all)",
|
|
95
|
+
},
|
|
96
|
+
json: { type: "boolean", description: "Machine-readable output" },
|
|
97
|
+
},
|
|
98
|
+
run: ({ values }) =>
|
|
99
|
+
printReport(reportSince(parseSince(values.since)), values.json),
|
|
100
|
+
}),
|
|
101
|
+
},
|
|
102
|
+
});
|
package/src/cli/tree.ts
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
type OptionSpec,
|
|
14
14
|
type OptionSpecs,
|
|
15
15
|
} from "../tools/lib/command";
|
|
16
|
+
import { algorithmRunCommand } from "./algorithm-run";
|
|
16
17
|
import { authCommand } from "./auth";
|
|
17
18
|
import { builtinTools, builtinToolVerbs } from "./builtin-tools";
|
|
18
19
|
import { compactionCommand } from "./compaction";
|
|
@@ -220,6 +221,7 @@ export function cliTree(admin: AdminHandlers): Group {
|
|
|
220
221
|
rule: ruleCommand,
|
|
221
222
|
correction: correctionCommand,
|
|
222
223
|
compaction: compactionCommand,
|
|
224
|
+
"algorithm-run": algorithmRunCommand,
|
|
223
225
|
progress: progressCommand,
|
|
224
226
|
timebox: timeboxCommand,
|
|
225
227
|
unattended: unattendedCommand,
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What one turn's assistant texts say about an ALGORITHM run, read in code.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { MODE_RE } from "./turn-extras";
|
|
6
|
+
|
|
7
|
+
export const PHASES = ["OBSERVE", "PLAN", "EXECUTE", "VERIFY", "LEARN"] as const;
|
|
8
|
+
|
|
9
|
+
type AlgorithmHeader = "pal" | "format";
|
|
10
|
+
|
|
11
|
+
export type RunVerdict = "no-node" | "started" | "over-open-run";
|
|
12
|
+
|
|
13
|
+
export interface AlgorithmTurnFacts {
|
|
14
|
+
header: AlgorithmHeader;
|
|
15
|
+
headerFirst: boolean;
|
|
16
|
+
phases: string[];
|
|
17
|
+
startsNew: boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const LINE_START = "^[ \\t]*";
|
|
21
|
+
const PAL_HEADER_RE = new RegExp(`${LINE_START}${MODE_RE.source}`, "gm");
|
|
22
|
+
const FORMAT_HEADER_RE = /^[ \t]*♻️?\s*ALGORITHM\s*═{3,}/mu;
|
|
23
|
+
const PHASE_MARKER_RE =
|
|
24
|
+
/^[ \t]*━━━[^\n]*?(OBSERVE|PLAN|EXECUTE|VERIFY|LEARN)[^\n]*?[1-5]\/5/gm;
|
|
25
|
+
|
|
26
|
+
function headerIn(text: string): AlgorithmHeader | null {
|
|
27
|
+
const modes = Array.from(text.matchAll(PAL_HEADER_RE), (m) => m[1]);
|
|
28
|
+
if (modes.includes("ALGORITHM")) return "pal";
|
|
29
|
+
|
|
30
|
+
return FORMAT_HEADER_RE.test(text) ? "format" : null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The phase markers across the texts, each named once, in the order first seen. */
|
|
34
|
+
export function phasesIn(texts: string[]): string[] {
|
|
35
|
+
const seen = texts.flatMap((text) =>
|
|
36
|
+
Array.from(text.matchAll(PHASE_MARKER_RE), (m) => m[1] as string)
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
return [...new Set(seen)];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function algorithmTurnFacts(texts: string[]): AlgorithmTurnFacts | null {
|
|
43
|
+
const headers = texts.map(headerIn);
|
|
44
|
+
const header = headers.find((h) => h !== null);
|
|
45
|
+
if (!header) return null;
|
|
46
|
+
const phases = phasesIn(texts);
|
|
47
|
+
|
|
48
|
+
return {
|
|
49
|
+
header,
|
|
50
|
+
headerFirst: Boolean(headers[0]),
|
|
51
|
+
phases,
|
|
52
|
+
startsNew: phases.includes("OBSERVE"),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function runVerdict(node: string | null, openRun: unknown): RunVerdict {
|
|
57
|
+
if (node === null) return "no-node";
|
|
58
|
+
|
|
59
|
+
return openRun ? "over-open-run" : "started";
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The furthest phase reached, by the phase order, or null when none was written. */
|
|
63
|
+
export function lastPhase(phases: readonly string[]): string | null {
|
|
64
|
+
const reached = PHASES.filter((phase) => phases.includes(phase));
|
|
65
|
+
|
|
66
|
+
return reached.at(-1) ?? null;
|
|
67
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ALGORITHM runs as a fold over their algorithm_run events, and the events one
|
|
3
|
+
* stop adds. Pure: the cache, the stop and the report all fold the same way.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { type AlgorithmTurnFacts, runVerdict } from "./algorithm-run-facts";
|
|
7
|
+
|
|
8
|
+
type RunChange = "turn" | "reflected" | "finished" | "superseded";
|
|
9
|
+
|
|
10
|
+
type RunOutcome = "open" | "finished" | "superseded";
|
|
11
|
+
|
|
12
|
+
export interface RunEvent {
|
|
13
|
+
id: string;
|
|
14
|
+
ts: string;
|
|
15
|
+
change: RunChange;
|
|
16
|
+
run?: string | null;
|
|
17
|
+
node: string | null;
|
|
18
|
+
turn: string | null;
|
|
19
|
+
phases?: string[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface OpenRun {
|
|
23
|
+
run: string;
|
|
24
|
+
node: string;
|
|
25
|
+
startedAt: string;
|
|
26
|
+
phases: string[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface PendingReflection {
|
|
30
|
+
turn: string;
|
|
31
|
+
node: string | null;
|
|
32
|
+
at: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface RunState {
|
|
36
|
+
open: Record<string, OpenRun>;
|
|
37
|
+
pending: Record<string, PendingReflection>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface RunRecord {
|
|
41
|
+
run: string;
|
|
42
|
+
node: string | null;
|
|
43
|
+
startedAt: string;
|
|
44
|
+
startTurn: string | null;
|
|
45
|
+
phases: string[];
|
|
46
|
+
outcome: RunOutcome;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface Replay extends RunState {
|
|
50
|
+
runs: Record<string, RunRecord>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const PENDING_KEPT_MS = 24 * 60 * 60 * 1000;
|
|
54
|
+
|
|
55
|
+
export function emptyRunState(): RunState {
|
|
56
|
+
return { open: {}, pending: {} };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function union(a: readonly string[], b: readonly string[] = []): string[] {
|
|
60
|
+
return [...new Set([...a, ...b])];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function openRun(replay: Replay, event: RunEvent, run: string): void {
|
|
64
|
+
const phases = event.phases ?? [];
|
|
65
|
+
replay.runs[run] = {
|
|
66
|
+
run,
|
|
67
|
+
node: event.node,
|
|
68
|
+
startedAt: event.ts,
|
|
69
|
+
startTurn: event.turn,
|
|
70
|
+
phases,
|
|
71
|
+
outcome: "open",
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
if (event.node)
|
|
75
|
+
replay.open[event.node] = { run, node: event.node, startedAt: event.ts, phases };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function closeRun(
|
|
79
|
+
replay: Replay,
|
|
80
|
+
event: RunEvent,
|
|
81
|
+
run: string,
|
|
82
|
+
outcome: RunOutcome
|
|
83
|
+
): void {
|
|
84
|
+
const record = replay.runs[run];
|
|
85
|
+
if (record)
|
|
86
|
+
replay.runs[run] = { ...record, outcome, phases: union(record.phases, event.phases) };
|
|
87
|
+
|
|
88
|
+
for (const [node, open] of Object.entries(replay.open)) {
|
|
89
|
+
if (open.run === run) delete replay.open[node];
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function settleTurn(replay: Replay, turn: string | null): void {
|
|
94
|
+
delete replay.pending[String(turn)];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function apply(replay: Replay, event: RunEvent): void {
|
|
98
|
+
const run = event.run;
|
|
99
|
+
|
|
100
|
+
if (event.change === "reflected") {
|
|
101
|
+
if (event.turn)
|
|
102
|
+
replay.pending[event.turn] = { turn: event.turn, node: event.node, at: event.ts };
|
|
103
|
+
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (!run) return;
|
|
108
|
+
|
|
109
|
+
if (event.change === "turn") openRun(replay, event, run);
|
|
110
|
+
else closeRun(replay, event, run, event.change);
|
|
111
|
+
|
|
112
|
+
settleTurn(replay, event.turn);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function replayRuns(
|
|
116
|
+
events: readonly RunEvent[],
|
|
117
|
+
from: RunState = emptyRunState()
|
|
118
|
+
): Replay {
|
|
119
|
+
const replay: Replay = {
|
|
120
|
+
open: { ...from.open },
|
|
121
|
+
pending: { ...from.pending },
|
|
122
|
+
runs: {},
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
for (const event of events) apply(replay, event);
|
|
126
|
+
|
|
127
|
+
return replay;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** What the cache keeps: open runs, and reflections younger than a day still waiting for their stop. */
|
|
131
|
+
export function cachedState(state: RunState, now: Date): RunState {
|
|
132
|
+
const keptFrom = new Date(now.getTime() - PENDING_KEPT_MS).toISOString();
|
|
133
|
+
const pending = Object.entries(state.pending).filter(([, p]) => p.at >= keptFrom);
|
|
134
|
+
|
|
135
|
+
return { open: state.open, pending: Object.fromEntries(pending) };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export interface StopTurn {
|
|
139
|
+
facts: AlgorithmTurnFacts | null;
|
|
140
|
+
phases: string[];
|
|
141
|
+
node: string | null;
|
|
142
|
+
turn: string | null;
|
|
143
|
+
reflected: boolean;
|
|
144
|
+
open: OpenRun | undefined;
|
|
145
|
+
newRun: string;
|
|
146
|
+
source: "transcript" | "final-reply";
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export interface PlannedEvent {
|
|
150
|
+
id?: string;
|
|
151
|
+
fields: Record<string, unknown> & { change: RunChange };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function shadow(fields: PlannedEvent["fields"]): PlannedEvent["fields"] {
|
|
155
|
+
return { ...fields, mode: "shadow" };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function algorithmTurnEvents(stop: StopTurn, facts: AlgorithmTurnFacts): PlannedEvent[] {
|
|
159
|
+
const { node, turn, open, newRun } = stop;
|
|
160
|
+
const verdict = runVerdict(node, open);
|
|
161
|
+
const superseded: PlannedEvent[] =
|
|
162
|
+
open && verdict === "over-open-run"
|
|
163
|
+
? [{ fields: shadow({ change: "superseded", run: open.run, node, turn }) }]
|
|
164
|
+
: [];
|
|
165
|
+
const started: PlannedEvent = {
|
|
166
|
+
id: newRun,
|
|
167
|
+
fields: shadow({
|
|
168
|
+
change: "turn",
|
|
169
|
+
run: newRun,
|
|
170
|
+
node,
|
|
171
|
+
turn,
|
|
172
|
+
...facts,
|
|
173
|
+
verdict,
|
|
174
|
+
source: stop.source,
|
|
175
|
+
}),
|
|
176
|
+
};
|
|
177
|
+
const finished: PlannedEvent[] = stop.reflected
|
|
178
|
+
? [{ fields: shadow({ change: "finished", run: newRun, node, turn }) }]
|
|
179
|
+
: [];
|
|
180
|
+
|
|
181
|
+
return [...superseded, started, ...finished];
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The events a stop appends for the turn it records; none for a turn that touched no run. */
|
|
185
|
+
export function stopEvents(stop: StopTurn): PlannedEvent[] {
|
|
186
|
+
if (stop.facts) return algorithmTurnEvents(stop, stop.facts);
|
|
187
|
+
|
|
188
|
+
if (!stop.reflected || !stop.open) return [];
|
|
189
|
+
|
|
190
|
+
return [
|
|
191
|
+
{
|
|
192
|
+
fields: shadow({
|
|
193
|
+
change: "finished",
|
|
194
|
+
run: stop.open.run,
|
|
195
|
+
node: stop.node,
|
|
196
|
+
turn: stop.turn,
|
|
197
|
+
phases: stop.phases,
|
|
198
|
+
}),
|
|
199
|
+
},
|
|
200
|
+
];
|
|
201
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shadow numbers for ALGORITHM runs, counted from their events.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { lastPhase, PHASES } from "./algorithm-run-facts";
|
|
6
|
+
import { type RunEvent, type RunRecord, replayRuns } from "./algorithm-run-replay";
|
|
7
|
+
import { shellKnowsSession } from "./progress-session";
|
|
8
|
+
|
|
9
|
+
export interface ReportedEvent extends RunEvent {
|
|
10
|
+
project?: string | null;
|
|
11
|
+
runtime?: string;
|
|
12
|
+
verdict?: string;
|
|
13
|
+
startsNew?: boolean;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface OverOpenRunCase {
|
|
17
|
+
date: string;
|
|
18
|
+
project: string | null;
|
|
19
|
+
node: string | null;
|
|
20
|
+
nodeTitle: string | null;
|
|
21
|
+
oldPhases: string[];
|
|
22
|
+
observe: boolean;
|
|
23
|
+
oldTurn: string | null;
|
|
24
|
+
newTurn: string | null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface AlgorithmRunReport {
|
|
28
|
+
algorithmTurns: number;
|
|
29
|
+
taggedByReplyMode: number;
|
|
30
|
+
runs: { started: number; finished: number; superseded: number; open: number };
|
|
31
|
+
finishedWithAllPhases: number;
|
|
32
|
+
verdicts: Record<string, number>;
|
|
33
|
+
noNodeShare: number | null;
|
|
34
|
+
unreflectedByLastPhase: Record<string, number>;
|
|
35
|
+
reflectionsOutsideRun: number;
|
|
36
|
+
turnsWithoutSessionTie: number;
|
|
37
|
+
overOpenRun: {
|
|
38
|
+
withObserve: number;
|
|
39
|
+
withoutObserve: number;
|
|
40
|
+
cases: OverOpenRunCase[];
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface ReportInputs {
|
|
45
|
+
events: ReportedEvent[];
|
|
46
|
+
replyModes: Map<string, string | null>;
|
|
47
|
+
nodeTitle: (node: string) => string | null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function countBy<T>(items: T[], key: (item: T) => string): Record<string, number> {
|
|
51
|
+
const counts: Record<string, number> = {};
|
|
52
|
+
|
|
53
|
+
for (const item of items) counts[key(item)] = (counts[key(item)] ?? 0) + 1;
|
|
54
|
+
|
|
55
|
+
return counts;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function ofChange(events: ReportedEvent[], change: RunEvent["change"]): ReportedEvent[] {
|
|
59
|
+
return events.filter((e) => e.change === change);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function sawEveryPhase(run: RunRecord): boolean {
|
|
63
|
+
return PHASES.every((phase) => run.phases.includes(phase));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function finishedInItsTurn(turn: ReportedEvent, finished: ReportedEvent[]): boolean {
|
|
67
|
+
return finished.some((f) => f.turn === turn.turn);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function overOpenRunCase(
|
|
71
|
+
turn: ReportedEvent,
|
|
72
|
+
inputs: ReportInputs,
|
|
73
|
+
superseded: ReportedEvent[],
|
|
74
|
+
runs: Record<string, RunRecord>
|
|
75
|
+
): OverOpenRunCase {
|
|
76
|
+
const oldRunId = superseded.find((s) => s.turn === turn.turn)?.run;
|
|
77
|
+
const oldRun = oldRunId ? runs[oldRunId] : undefined;
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
date: turn.ts.slice(0, 10),
|
|
81
|
+
project: turn.project ?? null,
|
|
82
|
+
node: turn.node,
|
|
83
|
+
nodeTitle: turn.node ? inputs.nodeTitle(turn.node) : null,
|
|
84
|
+
oldPhases: oldRun?.phases ?? [],
|
|
85
|
+
observe: turn.startsNew === true,
|
|
86
|
+
oldTurn: oldRun?.startTurn ?? null,
|
|
87
|
+
newTurn: turn.turn,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function reflectionsOutsideRun(events: ReportedEvent[]): number {
|
|
92
|
+
const settled = new Set(
|
|
93
|
+
events
|
|
94
|
+
.filter((e) => e.change === "turn" || e.change === "finished")
|
|
95
|
+
.map((e) => e.turn)
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
return ofChange(events, "reflected").filter((e) => !settled.has(e.turn)).length;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function share(part: number, whole: number): number | null {
|
|
102
|
+
return whole === 0 ? null : part / whole;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function algorithmRunReport(inputs: ReportInputs): AlgorithmRunReport {
|
|
106
|
+
const { events, replyModes } = inputs;
|
|
107
|
+
const turns = ofChange(events, "turn");
|
|
108
|
+
const finished = ofChange(events, "finished");
|
|
109
|
+
const superseded = ofChange(events, "superseded");
|
|
110
|
+
const runs = replayRuns(events).runs;
|
|
111
|
+
const started = turns.flatMap((t) => (t.run ? [runs[t.run] as RunRecord] : []));
|
|
112
|
+
const outcomes = countBy(started, (run) => run.outcome);
|
|
113
|
+
const verdicts = countBy(turns, (t) => t.verdict ?? "unknown");
|
|
114
|
+
const overOpen = turns.filter((t) => t.verdict === "over-open-run");
|
|
115
|
+
const cases = overOpen.map((t) => overOpenRunCase(t, inputs, superseded, runs));
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
algorithmTurns: turns.length,
|
|
119
|
+
taggedByReplyMode: turns.filter(
|
|
120
|
+
(t) => t.turn && replyModes.get(t.turn) === "ALGORITHM"
|
|
121
|
+
).length,
|
|
122
|
+
runs: {
|
|
123
|
+
started: started.length,
|
|
124
|
+
finished: outcomes.finished ?? 0,
|
|
125
|
+
superseded: outcomes.superseded ?? 0,
|
|
126
|
+
open: outcomes.open ?? 0,
|
|
127
|
+
},
|
|
128
|
+
finishedWithAllPhases: started.filter(
|
|
129
|
+
(r) => r.outcome === "finished" && sawEveryPhase(r)
|
|
130
|
+
).length,
|
|
131
|
+
verdicts,
|
|
132
|
+
noNodeShare: share(verdicts["no-node"] ?? 0, turns.length),
|
|
133
|
+
unreflectedByLastPhase: countBy(
|
|
134
|
+
turns.filter((t) => !finishedInItsTurn(t, finished)),
|
|
135
|
+
(t) => lastPhase(t.phases ?? []) ?? "none"
|
|
136
|
+
),
|
|
137
|
+
reflectionsOutsideRun: reflectionsOutsideRun(events),
|
|
138
|
+
turnsWithoutSessionTie: turns.filter((t) => !shellKnowsSession(String(t.runtime)))
|
|
139
|
+
.length,
|
|
140
|
+
overOpenRun: {
|
|
141
|
+
withObserve: cases.filter((c) => c.observe).length,
|
|
142
|
+
withoutObserve: cases.filter((c) => !c.observe).length,
|
|
143
|
+
cases,
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ALGORITHM runs in shadow mode: the stop records each run's turns and verdict,
|
|
3
|
+
* a reflection records itself, and nothing is warned, injected or blocked.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { resolve } from "node:path";
|
|
8
|
+
import { appendEvent, eventsSince, logQuietly } from "../../bronze/events";
|
|
9
|
+
import { paths } from "../../core/paths";
|
|
10
|
+
import { sessionDir } from "../../core/session-dir";
|
|
11
|
+
import { eventLogEnabled } from "../../core/settings";
|
|
12
|
+
import { algorithmTurnFacts, phasesIn } from "./algorithm-run-facts";
|
|
13
|
+
import {
|
|
14
|
+
cachedState,
|
|
15
|
+
type PlannedEvent,
|
|
16
|
+
type RunEvent,
|
|
17
|
+
type RunState,
|
|
18
|
+
replayRuns,
|
|
19
|
+
stopEvents,
|
|
20
|
+
} from "./algorithm-run-replay";
|
|
21
|
+
import { lastTurnIdOf } from "./interaction";
|
|
22
|
+
import { progressSession } from "./progress-session";
|
|
23
|
+
import { activePath, readTree, scopeOf } from "./progress-tree";
|
|
24
|
+
import { extractContent, type Message } from "./transcript";
|
|
25
|
+
|
|
26
|
+
export type TurnSource = "transcript" | "final-reply";
|
|
27
|
+
|
|
28
|
+
const REBUILD_DAYS = 30;
|
|
29
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
30
|
+
|
|
31
|
+
export function algorithmRunsCacheFile(): string {
|
|
32
|
+
return resolve(paths.cache(), "algorithm-runs.json");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function readCache(): RunState | null {
|
|
36
|
+
try {
|
|
37
|
+
const cached = JSON.parse(String(readFileSync(algorithmRunsCacheFile())));
|
|
38
|
+
|
|
39
|
+
return cached?.open && cached.pending ? cached : null;
|
|
40
|
+
} catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function writeCache(state: RunState, now: Date): void {
|
|
46
|
+
const file = algorithmRunsCacheFile();
|
|
47
|
+
const partial = `${file}.${process.pid}.tmp`;
|
|
48
|
+
writeFileSync(partial, `${JSON.stringify(cachedState(state, now))}\n`);
|
|
49
|
+
renameSync(partial, file);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function rebuiltRunState(now: Date): RunState {
|
|
53
|
+
const since = new Date(now.getTime() - REBUILD_DAYS * DAY_MS);
|
|
54
|
+
const events = eventsSince("algorithm_run", since) as unknown as RunEvent[];
|
|
55
|
+
|
|
56
|
+
return cachedState(replayRuns(events), now);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The cached state, rebuilt from the event log and written back when the file is missing. */
|
|
60
|
+
export function loadRunState(now: Date = new Date()): RunState {
|
|
61
|
+
const cached = readCache();
|
|
62
|
+
if (cached) return cached;
|
|
63
|
+
const rebuilt = rebuiltRunState(now);
|
|
64
|
+
writeCache(rebuilt, now);
|
|
65
|
+
|
|
66
|
+
return rebuilt;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function activeNodeOf(session: string): string | null {
|
|
70
|
+
const tree = readTree(scopeOf(sessionDir()), undefined, progressSession(session));
|
|
71
|
+
|
|
72
|
+
return activePath(tree).at(-1)?.id ?? null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function appendRunEvents(
|
|
76
|
+
planned: PlannedEvent[],
|
|
77
|
+
session: string,
|
|
78
|
+
now: Date
|
|
79
|
+
): RunEvent[] {
|
|
80
|
+
const ts = now.toISOString();
|
|
81
|
+
|
|
82
|
+
return planned.flatMap(({ id, fields }) => {
|
|
83
|
+
const appended = appendEvent("algorithm_run", fields, { id, ts, session });
|
|
84
|
+
|
|
85
|
+
return appended ? [{ ...fields, id: appended, ts } as RunEvent] : [];
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function recordRunEvents(
|
|
90
|
+
planned: PlannedEvent[],
|
|
91
|
+
state: RunState,
|
|
92
|
+
session: string,
|
|
93
|
+
now: Date
|
|
94
|
+
): void {
|
|
95
|
+
const appended = appendRunEvents(planned, session, now);
|
|
96
|
+
writeCache(replayRuns(appended, state), now);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The assistant texts after the turn's prompt, in order. */
|
|
100
|
+
export function turnTexts(messages: Message[]): string[] {
|
|
101
|
+
const prompt = messages.findLastIndex((m) => m.role === "user");
|
|
102
|
+
|
|
103
|
+
return messages
|
|
104
|
+
.slice(prompt + 1)
|
|
105
|
+
.filter((m) => m.role === "assistant")
|
|
106
|
+
.map(extractContent);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function recordAlgorithmTurn(
|
|
110
|
+
session: string,
|
|
111
|
+
texts: string[],
|
|
112
|
+
source: TurnSource,
|
|
113
|
+
now: Date = new Date()
|
|
114
|
+
): void {
|
|
115
|
+
if (!eventLogEnabled()) return;
|
|
116
|
+
const facts = algorithmTurnFacts(texts);
|
|
117
|
+
const turn = lastTurnIdOf(session);
|
|
118
|
+
if (!facts && !turn) return;
|
|
119
|
+
const state = loadRunState(now);
|
|
120
|
+
const reflected = Object.hasOwn(state.pending, String(turn));
|
|
121
|
+
if (!facts && !reflected) return;
|
|
122
|
+
const node = activeNodeOf(session);
|
|
123
|
+
const planned = stopEvents({
|
|
124
|
+
facts,
|
|
125
|
+
phases: phasesIn(texts),
|
|
126
|
+
node,
|
|
127
|
+
turn,
|
|
128
|
+
reflected,
|
|
129
|
+
open: node ? state.open[node] : undefined,
|
|
130
|
+
newRun: crypto.randomUUID(),
|
|
131
|
+
source,
|
|
132
|
+
});
|
|
133
|
+
recordRunEvents(planned, state, session, now);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function recordAlgorithmTurnQuietly(
|
|
137
|
+
session: string | undefined,
|
|
138
|
+
texts: string[],
|
|
139
|
+
source: TurnSource
|
|
140
|
+
): void {
|
|
141
|
+
if (!session) return;
|
|
142
|
+
logQuietly("algorithm_run", () => recordAlgorithmTurn(session, texts, source));
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function recordAlgorithmReflection(
|
|
146
|
+
session: string | undefined = progressSession(),
|
|
147
|
+
now: Date = new Date()
|
|
148
|
+
): void {
|
|
149
|
+
if (!session || !eventLogEnabled()) return;
|
|
150
|
+
const turn = lastTurnIdOf(session);
|
|
151
|
+
if (!turn) return;
|
|
152
|
+
const reflected: PlannedEvent = {
|
|
153
|
+
fields: { change: "reflected", node: activeNodeOf(session), turn, mode: "shadow" },
|
|
154
|
+
};
|
|
155
|
+
recordRunEvents([reflected], loadRunState(now), session, now);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function recordAlgorithmReflectionQuietly(): void {
|
|
159
|
+
logQuietly("algorithm_run", () => recordAlgorithmReflection());
|
|
160
|
+
}
|
|
@@ -310,6 +310,11 @@ function trackOf(session: string): SessionTrack {
|
|
|
310
310
|
return readTracks()[session] ?? { updated: "", recent: [] };
|
|
311
311
|
}
|
|
312
312
|
|
|
313
|
+
/** The id of the session's latest `turn` event, or null when none was logged. */
|
|
314
|
+
export function lastTurnIdOf(session: string): string | null {
|
|
315
|
+
return trackOf(session).lastTurnId ?? null;
|
|
316
|
+
}
|
|
317
|
+
|
|
313
318
|
/** Called when the agent finishes a reply, so the next turn can be measured against it. */
|
|
314
319
|
export function recordReply(
|
|
315
320
|
session: string,
|
|
@@ -17,6 +17,10 @@ const SHELL_SESSION_ENV: Partial<Record<AgentType, string>> = {
|
|
|
17
17
|
cursor: "CURSOR_CONVERSATION_ID",
|
|
18
18
|
};
|
|
19
19
|
|
|
20
|
+
export function shellKnowsSession(runtime: string): boolean {
|
|
21
|
+
return Object.hasOwn(SHELL_SESSION_ENV, runtime);
|
|
22
|
+
}
|
|
23
|
+
|
|
20
24
|
export function progressSession(
|
|
21
25
|
hookSession?: string,
|
|
22
26
|
env: NodeJS.ProcessEnv = process.env,
|
package/src/hooks/lib/stop.ts
CHANGED
|
@@ -26,6 +26,7 @@ import { runSynthesis } from "../handlers/synthesis";
|
|
|
26
26
|
import { resetTab } from "../handlers/tab";
|
|
27
27
|
import { updateCounts } from "../handlers/update-counts";
|
|
28
28
|
import { captureWorkSession } from "../handlers/work-session";
|
|
29
|
+
import { recordAlgorithmTurnQuietly, turnTexts } from "./algorithm-runs";
|
|
29
30
|
import { spawnCollectIfDue } from "./collect-trigger";
|
|
30
31
|
import { acknowledgeMentioned } from "./daily-nudge";
|
|
31
32
|
import { spawnDetachedInference } from "./detached-inference";
|
|
@@ -157,6 +158,8 @@ async function runTurnStop(
|
|
|
157
158
|
|
|
158
159
|
logDebug("stopTurn", "No readable transcript; filing only the final reply");
|
|
159
160
|
fileFinalReply(payload);
|
|
161
|
+
const finalReply = hookFinalReply(payload) ?? "";
|
|
162
|
+
recordAlgorithmTurnQuietly(hookSessionId(payload), [finalReply], "final-reply");
|
|
160
163
|
}
|
|
161
164
|
|
|
162
165
|
interface RunStopHandlersOptions {
|
|
@@ -182,6 +185,8 @@ export async function runStopHandlers(
|
|
|
182
185
|
|
|
183
186
|
if (options.sessionId) recordFinalReply(messages, options.sessionId);
|
|
184
187
|
|
|
188
|
+
recordAlgorithmTurnQuietly(options.sessionId, turnTexts(messages), "transcript");
|
|
189
|
+
|
|
185
190
|
// Always persist last exchange — drives CompactRecover + "Pick Up Where You Left Off"
|
|
186
191
|
if (options.sessionId) persistLastExchange(messages, options.sessionId);
|
|
187
192
|
|
|
@@ -25,7 +25,7 @@ const PASTED_RE = /<pasted_content\b[^>]*>([\s\S]*?)<\/pasted_content[^>]*>/gi;
|
|
|
25
25
|
const IMAGE_RE = /\[Image #\d+\]/g;
|
|
26
26
|
const COMMAND_TAG_RE = /<command-name>\s*\/?([\w:-]+)\s*<\/command-name>/;
|
|
27
27
|
const SLASH_RE = /^\/([\w:-]+)(?:\s|$)/;
|
|
28
|
-
const MODE_RE = /═+\s*PAL(?:\s*\|\s*([A-Z]+))?\s*═+/;
|
|
28
|
+
export const MODE_RE = /═+\s*PAL(?:\s*\|\s*([A-Z]+))?\s*═+/;
|
|
29
29
|
|
|
30
30
|
function tokens(text: string): string[] {
|
|
31
31
|
return text.toLowerCase().match(/[\p{L}']+/gu) ?? [];
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
import { appendFileSync } from "node:fs";
|
|
13
13
|
import { storeDir } from "../../bronze/bronze";
|
|
14
14
|
import { paths } from "../../core/paths";
|
|
15
|
+
import { recordAlgorithmReflectionQuietly } from "../../hooks/lib/algorithm-runs";
|
|
15
16
|
import { progressSession } from "../../hooks/lib/progress-session";
|
|
16
17
|
import { buildReflection, intOr, reflectionLine } from "../lib/algorithm-reflect";
|
|
17
18
|
import { leaf, runCommand, UsageError } from "../lib/command";
|
|
@@ -101,6 +102,7 @@ function reflectionsPath(): string {
|
|
|
101
102
|
function appendReflection(reflection: ReturnType<typeof buildReflection>): undefined {
|
|
102
103
|
const path = reflectionsPath();
|
|
103
104
|
appendFileSync(path, reflectionLine(reflection), "utf-8");
|
|
105
|
+
recordAlgorithmReflectionQuietly();
|
|
104
106
|
emit.receipt(path, {
|
|
105
107
|
passed: reflection.criteria_passed,
|
|
106
108
|
of: reflection.criteria_count,
|