@pal-code/workflow 0.0.0-stage → 0.0.18

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/src/doc.ts ADDED
@@ -0,0 +1,224 @@
1
+ /**
2
+ * The work-folder README: a handoff document, parsed and rendered.
3
+ *
4
+ * The shape is the six sections the guide names, and it is deliberately plain
5
+ * markdown with flat frontmatter — the same file must be readable by a human in
6
+ * an editor, diffable in review, and parseable here. Nothing is stored in a
7
+ * bespoke format that only this code understands.
8
+ *
9
+ * Only FLAT frontmatter is supported (`key: value`). Unlike `@pal-code/memory`
10
+ * there are no list fields to accommodate — status and timestamps are all the
11
+ * machine needs — so the simpler reader is the honest one.
12
+ */
13
+
14
+ /** Sections, in the order they are rendered. Missing ones are simply absent. */
15
+ export const SECTIONS = [
16
+ 'Goal',
17
+ 'Current state',
18
+ 'Decisions',
19
+ 'Constraints',
20
+ 'Relevant files',
21
+ 'Remaining work',
22
+ ] as const;
23
+
24
+ export type SectionName = (typeof SECTIONS)[number];
25
+
26
+ export type WorkStatus = 'open' | 'paused' | 'done';
27
+
28
+ const STATUSES: readonly WorkStatus[] = ['open', 'paused', 'done'];
29
+
30
+ /** Normalise arbitrary input to a valid status, defaulting to `open`. */
31
+ export function toStatus(value: unknown): WorkStatus {
32
+ return STATUSES.includes(value as WorkStatus) ? (value as WorkStatus) : 'open';
33
+ }
34
+
35
+ export interface WorkDoc {
36
+ /** Flat frontmatter fields, string-valued. */
37
+ fields: Record<string, string>;
38
+ /** The H1 title line, without the leading `# `. */
39
+ title: string;
40
+ /** Section name → body text. Keyed case-insensitively via {@link sectionOf}. */
41
+ sections: Record<string, string>;
42
+ /** Everything before the first `## ` heading, minus frontmatter and the H1. */
43
+ preamble: string;
44
+ /** True when the file carried no frontmatter block at all. */
45
+ noFrontmatter: boolean;
46
+ }
47
+
48
+ const FRONTMATTER_KEY = /^([A-Za-z_][\w-]*)\s*:\s*(.*)$/;
49
+
50
+ function unquote(value: string): string {
51
+ const trimmed = value.trim();
52
+ // Strip the trailing comment FIRST. A quoted value followed by a comment
53
+ // (`status: "open" # current`) does not end in a quote, so unquoting before
54
+ // this would miss it and leave the quotes in the field.
55
+ const comment = trimmed.indexOf(' #');
56
+ const body = (comment === -1 ? trimmed : trimmed.slice(0, comment)).trim();
57
+ if (body.length >= 2) {
58
+ const first = body[0];
59
+ const last = body[body.length - 1];
60
+ if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
61
+ return body.slice(1, -1);
62
+ }
63
+ }
64
+ return body;
65
+ }
66
+
67
+ /**
68
+ * Split a document into frontmatter, title, preamble and sections.
69
+ *
70
+ * A document with no frontmatter still parses — it just reports
71
+ * `noFrontmatter`, so a hand-written README works without ceremony.
72
+ */
73
+ export function parseWorkDoc(text: string): WorkDoc {
74
+ const source = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
75
+ const lines = source.split(/\r?\n/);
76
+
77
+ const fields: Record<string, string> = {};
78
+ let cursor = 0;
79
+ let sawFrontmatter = false;
80
+
81
+ if (lines[0]?.trim() === '---') {
82
+ const closing = lines.findIndex((line, i) => i > 0 && line.trim() === '---');
83
+ if (closing !== -1) {
84
+ sawFrontmatter = true;
85
+ for (const raw of lines.slice(1, closing)) {
86
+ const line = raw.trim();
87
+ if (line === '' || line.startsWith('#')) continue;
88
+ const match = FRONTMATTER_KEY.exec(line);
89
+ if (match) fields[match[1]] = unquote(match[2]);
90
+ }
91
+ cursor = closing + 1;
92
+ }
93
+ }
94
+
95
+ let title = '';
96
+ const preambleLines: string[] = [];
97
+ const sections: Record<string, string> = {};
98
+ let current: string | null = null;
99
+ let bucket: string[] = [];
100
+
101
+ const flush = (): void => {
102
+ if (current === null) {
103
+ preambleLines.push(...bucket);
104
+ } else {
105
+ sections[current] = bucket.join('\n').trim();
106
+ }
107
+ bucket = [];
108
+ };
109
+
110
+ for (let i = cursor; i < lines.length; i++) {
111
+ const line = lines[i];
112
+ const h1 = /^#\s+(.+)$/.exec(line.trim());
113
+ if (h1 && title === '' && current === null) {
114
+ title = h1[1].trim();
115
+ continue;
116
+ }
117
+ // Only level-2 headings delimit sections; anything deeper stays inside the
118
+ // section body so a `### decision` note is not promoted to its own section.
119
+ const h2 = /^##\s+(.+)$/.exec(line.trim());
120
+ if (h2) {
121
+ flush();
122
+ current = h2[1].trim();
123
+ continue;
124
+ }
125
+ bucket.push(line);
126
+ }
127
+ flush();
128
+
129
+ return {
130
+ fields,
131
+ title,
132
+ sections,
133
+ preamble: preambleLines.join('\n').trim(),
134
+ noFrontmatter: !sawFrontmatter,
135
+ };
136
+ }
137
+
138
+ /** Case-insensitive section lookup, returning `''` when absent. */
139
+ export function sectionOf(doc: WorkDoc, name: string): string {
140
+ const needle = name.trim().toLowerCase();
141
+ for (const [key, value] of Object.entries(doc.sections)) {
142
+ if (key.toLowerCase() === needle) return value;
143
+ }
144
+ return '';
145
+ }
146
+
147
+ /** True when a section exists (even if its body is empty). */
148
+ export function hasSection(doc: WorkDoc, name: string): boolean {
149
+ const needle = name.trim().toLowerCase();
150
+ return Object.keys(doc.sections).some((key) => key.toLowerCase() === needle);
151
+ }
152
+
153
+ /** Render flat frontmatter. Fields with an empty value are omitted. */
154
+ export function renderFrontmatter(fields: Record<string, string>): string {
155
+ const lines = ['---'];
156
+ for (const [key, value] of Object.entries(fields)) {
157
+ if (value.trim() === '') continue;
158
+ lines.push(`${key}: ${value}`);
159
+ }
160
+ lines.push('---');
161
+ return lines.join('\n');
162
+ }
163
+
164
+ /**
165
+ * Render a whole document.
166
+ *
167
+ * Section order follows {@link SECTIONS} so every work folder reads the same
168
+ * way, but sections absent from `doc` are skipped rather than emitted empty —
169
+ * a handoff with four real sections beats one padded with two placeholders.
170
+ * Unknown sections are appended after the known ones so nothing is ever lost.
171
+ */
172
+ export function renderWorkDoc(doc: WorkDoc): string {
173
+ const parts: string[] = [renderFrontmatter(doc.fields), '', `# ${doc.title}`.trimEnd()];
174
+
175
+ const preamble = doc.preamble.trim();
176
+ if (preamble !== '') parts.push('', preamble);
177
+
178
+ const emitted = new Set<string>();
179
+ const ordered: string[] = [];
180
+ for (const name of SECTIONS) {
181
+ const key = Object.keys(doc.sections).find((k) => k.toLowerCase() === name.toLowerCase());
182
+ if (key !== undefined) {
183
+ ordered.push(key);
184
+ emitted.add(key);
185
+ }
186
+ }
187
+ for (const key of Object.keys(doc.sections)) {
188
+ if (!emitted.has(key)) ordered.push(key);
189
+ }
190
+
191
+ for (const key of ordered) {
192
+ const body = doc.sections[key].trim();
193
+ parts.push('', `## ${key}`, body === '' ? '' : `\n${body}`);
194
+ }
195
+
196
+ return `${parts
197
+ .join('\n')
198
+ .replace(/\n{3,}/g, '\n\n')
199
+ .trimEnd()}\n`;
200
+ }
201
+
202
+ /** A fresh, empty handoff with the six sections scaffolded and marked TODO. */
203
+ export function newWorkDoc(input: {
204
+ title: string;
205
+ goal: string;
206
+ status?: WorkStatus;
207
+ fields?: Record<string, string>;
208
+ }): WorkDoc {
209
+ const sections: Record<string, string> = {
210
+ Goal: input.goal.trim(),
211
+ 'Current state': 'Not started.',
212
+ Decisions: 'None yet.',
213
+ Constraints: 'None recorded.',
214
+ 'Relevant files': 'Not yet identified.',
215
+ 'Remaining work': 'Not yet broken down.',
216
+ };
217
+ return {
218
+ fields: {kind: 'work', status: input.status ?? 'open', ...input.fields},
219
+ title: input.title,
220
+ sections,
221
+ preamble: '',
222
+ noFrontmatter: false,
223
+ };
224
+ }
package/src/health.ts ADDED
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Session-length guardrail: tell the agent when its own session has gone bad.
3
+ *
4
+ * This is the one rule from the workflow that a human cannot reliably apply to
5
+ * themselves. "Start fresh when the context gets long" is easy to state and
6
+ * hard to notice — the session feels fine right up until it isn't, and by then
7
+ * the mistakes are already in the transcript. The signals are cheap to read and
8
+ * unambiguous, so the tool reports them instead of asking the model to guess.
9
+ *
10
+ * Design constraint that shapes everything here: this must never block a turn
11
+ * and must never fail one. pal's session database is opened read-only, every
12
+ * error path returns "no facts", and the tool simply reports nothing rather
13
+ * than inventing a verdict. A guardrail that breaks the session it guards is
14
+ * worse than no guardrail.
15
+ *
16
+ * Triggers are the ones the workflow guide names, minus the two that are
17
+ * behavioural rather than measurable: "the fix is merged" and "I've corrected
18
+ * the same assumption twice" are things only the human can see, so they are
19
+ * taught in the prompt fragment instead of being faked with a heuristic.
20
+ */
21
+
22
+ import {Database} from 'bun:sqlite';
23
+ import {existsSync} from 'node:fs';
24
+ import {homedir} from 'node:os';
25
+ import {join} from 'node:path';
26
+
27
+ import type {WorkflowSettings} from './config.js';
28
+
29
+ /** What the guardrail knows about the current session. */
30
+ export interface SessionFacts {
31
+ sessionId: string;
32
+ /** Messages stored for the session. */
33
+ messageCount: number;
34
+ /** Compaction checkpoints recorded. */
35
+ compactionCount: number;
36
+ /** Total tokens billed across the session (input + output). */
37
+ totalTokens: number;
38
+ /** Wall-clock age in minutes. */
39
+ ageMinutes: number;
40
+ title?: string;
41
+ }
42
+
43
+ export type TriggerLevel = 'ok' | 'warn' | 'reset';
44
+
45
+ export interface Trigger {
46
+ level: TriggerLevel;
47
+ /** Short name of the signal, e.g. `compactions`. */
48
+ signal: string;
49
+ /** What was observed, with numbers — the model can act on a number. */
50
+ detail: string;
51
+ /** What to do about it. */
52
+ action: string;
53
+ }
54
+
55
+ /** Default pal session database location. */
56
+ export function defaultSessionDb(): string {
57
+ return join(homedir(), '.pal', 'sessions.db');
58
+ }
59
+
60
+ interface SessionRow {
61
+ id: string;
62
+ title: string | null;
63
+ input_tokens: number | null;
64
+ output_tokens: number | null;
65
+ cached_tokens: number | null;
66
+ created_at: number;
67
+ updated_at: number;
68
+ compacted_upto_seq: number | null;
69
+ message_count: number | null;
70
+ compaction_count: number | null;
71
+ }
72
+
73
+ /**
74
+ * Read facts for the most recently updated session.
75
+ *
76
+ * Returns `null` on any problem — missing file, locked database, older schema —
77
+ * because every caller treats that as "nothing to say". The connection is
78
+ * opened `readonly` so the guardrail can never corrupt the store it inspects,
79
+ * and it is closed before returning.
80
+ */
81
+ export function readFacts(settings: WorkflowSettings, sessionId?: string): SessionFacts | null {
82
+ const dbPath = settings.sessionDb ?? defaultSessionDb();
83
+ if (!existsSync(dbPath)) return null;
84
+
85
+ let db: Database | null = null;
86
+ try {
87
+ db = new Database(dbPath, {readonly: true} as never);
88
+ const where = sessionId !== undefined && sessionId !== '' ? 'WHERE s.id = ?' : '';
89
+ const query = `
90
+ SELECT s.id, s.title, s.input_tokens, s.output_tokens, s.cached_tokens,
91
+ s.created_at, s.updated_at, s.compacted_upto_seq,
92
+ (SELECT COUNT(*) FROM messages m WHERE m.session_id = s.id) AS message_count,
93
+ (SELECT COUNT(*) FROM session_compactions c WHERE c.session_id = s.id) AS compaction_count
94
+ FROM sessions s
95
+ ${where}
96
+ ORDER BY s.updated_at DESC
97
+ LIMIT 1
98
+ `;
99
+ // `where` already proves the id is a non-empty string, so the branch is
100
+ // total — the narrowing here is for the type system, not a runtime check.
101
+ const args: string[] = where === '' || sessionId === undefined ? [] : [sessionId];
102
+ const row = db.query<SessionRow, string[]>(query).get(...args);
103
+ if (!row) return null;
104
+
105
+ const totalTokens = (row.input_tokens ?? 0) + (row.output_tokens ?? 0);
106
+ return {
107
+ sessionId: row.id,
108
+ title: row.title ?? undefined,
109
+ messageCount: row.message_count ?? 0,
110
+ compactionCount: row.compaction_count ?? 0,
111
+ totalTokens,
112
+ ageMinutes: Math.max(0, Math.round((Date.now() - row.created_at) / 60_000)),
113
+ };
114
+ } catch {
115
+ // Locked, migrating, or written by a newer schema — all mean "no facts".
116
+ return null;
117
+ } finally {
118
+ try {
119
+ db?.close();
120
+ } catch {
121
+ /* closing a read handle must never throw into the caller */
122
+ }
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Evaluate the measurable triggers against the configured thresholds.
128
+ *
129
+ * Pure: same facts + settings in, same triggers out. Kept separate from the
130
+ * database read so the actual policy has a test that does not need a sqlite
131
+ * fixture to express itself.
132
+ */
133
+ export function evaluate(facts: SessionFacts, settings: WorkflowSettings): Trigger[] {
134
+ const triggers: Trigger[] = [];
135
+
136
+ if (facts.compactionCount >= settings.maxCompactions) {
137
+ triggers.push({
138
+ level: facts.compactionCount > settings.maxCompactions ? 'reset' : 'warn',
139
+ signal: 'compactions',
140
+ detail:
141
+ `this session has been compacted ${facts.compactionCount} time(s) ` +
142
+ `(threshold ${settings.maxCompactions})`,
143
+ action:
144
+ 'Compaction means older context was summarized away. Write the work folder README, ' +
145
+ 'then start a fresh session from it.',
146
+ });
147
+ }
148
+
149
+ if (facts.messageCount >= settings.maxMessages) {
150
+ triggers.push({
151
+ level: facts.messageCount > settings.maxMessages * 2 ? 'reset' : 'warn',
152
+ signal: 'messages',
153
+ detail: `this session holds ${facts.messageCount} messages (threshold ${settings.maxMessages})`,
154
+ action:
155
+ 'Long histories bury the constraints that matter. Record current state and remaining ' +
156
+ 'work, then continue in a fresh session.',
157
+ });
158
+ }
159
+
160
+ return triggers;
161
+ }
162
+
163
+ /** Highest level present, for a one-word headline. */
164
+ export function overall(triggers: readonly Trigger[]): TriggerLevel {
165
+ if (triggers.some((t) => t.level === 'reset')) return 'reset';
166
+ if (triggers.some((t) => t.level === 'warn')) return 'warn';
167
+ return 'ok';
168
+ }
169
+
170
+ /**
171
+ * Render a report.
172
+ *
173
+ * The `ok` case is deliberately one short line: this tool is meant to be
174
+ * callable at any time, and paying a paragraph of "everything is fine" for that
175
+ * would discourage the habit it exists to build.
176
+ */
177
+ export function formatReport(
178
+ facts: SessionFacts | null,
179
+ triggers: readonly Trigger[],
180
+ settings: WorkflowSettings,
181
+ ): string {
182
+ if (facts === null) {
183
+ return (
184
+ 'No session history found (pal has not stored a session yet, or the database is ' +
185
+ 'unreadable). Nothing to check.'
186
+ );
187
+ }
188
+
189
+ const header =
190
+ `session ${facts.sessionId.slice(0, 8)} · ${facts.messageCount} messages · ` +
191
+ `${facts.compactionCount} compaction(s) · ${facts.totalTokens} tokens · ` +
192
+ `${facts.ageMinutes} min old`;
193
+
194
+ const level = overall(triggers);
195
+ if (level === 'ok') {
196
+ return `${header}\nHealthy: under the reset thresholds (${settings.maxMessages} messages, ${settings.maxCompactions} compaction).`;
197
+ }
198
+
199
+ const advice =
200
+ level === 'reset'
201
+ ? 'RESET NOW: write the work folder README, then start a fresh session from it.'
202
+ : 'Consider wrapping up: update the work folder, then continue in a fresh session.';
203
+
204
+ const lines = [header, advice, ''];
205
+ for (const trigger of triggers) {
206
+ lines.push(`[${trigger.level}] ${trigger.signal}: ${trigger.detail}`);
207
+ lines.push(` → ${trigger.action}`);
208
+ }
209
+ return lines.join('\n');
210
+ }
211
+
212
+ /**
213
+ * Guidance for the two triggers that cannot be measured.
214
+ *
215
+ * These live in the prompt rather than in code because a heuristic for "the
216
+ * agent is going in circles" would be noise: it would fire on legitimately
217
+ * iterative work and teach the model to ignore the guardrail entirely.
218
+ */
219
+ export const HUMAN_TRIGGERS = [
220
+ 'the current fix is merged',
221
+ 'you have corrected the same wrong assumption twice',
222
+ 'you have been told "continue" three times in a row',
223
+ ] as const;