@pal-code/workflow 0.0.0-stage → 0.0.19

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 CHANGED
@@ -1,3 +1,194 @@
1
- # Temporary Holding Version
1
+ # @pal-code/workflow
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Task continuity for pal — so a **multi-session task resumes instead of restarting**.
4
+
5
+ `@pal-code/memory` remembers what the *codebase* is. Nothing remembered what the
6
+ *task* is. Without this, every session re-reads the same files and re-derives the
7
+ same decisions, and anything settled in the previous session survives only if the
8
+ human retypes it.
9
+
10
+ Ships five tools and one prompt fragment:
11
+
12
+ | Tool | What it does |
13
+ |---|---|
14
+ | `work_start` | Create `.work/<slug>/README.md` for a task that will span sessions |
15
+ | `work_status` | List work folders, or read one folder's full README |
16
+ | `work_update` | Replace one or more README sections; set status |
17
+ | `backlog` | The durable task list in `.work/TODO.md` (list/add/start/done/drop/remove) |
18
+ | `session_health` | Whether this session has crossed the reset thresholds |
19
+
20
+ ## Install
21
+
22
+ ```sh
23
+ pal ext add @pal-code/workflow
24
+ ```
25
+
26
+ Unlike `@pal-code/memory`, no directory is required up front — `work_start`
27
+ creates `.work/` on first use. The extension reports itself unavailable only
28
+ when `write` is `false` **and** no `.work/` directory exists, so a read-only
29
+ setup stays inert instead of tempting the model with tools that can only fail.
30
+
31
+ ## Why a work folder, and not just `memory`?
32
+
33
+ They answer different questions and decay on different clocks:
34
+
35
+ | | `.memory` | `.work` |
36
+ |---|---|---|
37
+ | Describes | the codebase | one task |
38
+ | Keyed by | `covers` globs | a dated folder name |
39
+ | Goes stale when | covered code changes | time passes and nobody updates it |
40
+ | Trust model | git-computed staleness verdict | always the current truth, by definition |
41
+
42
+ A `memory` doc is *knowledge* that can be verified against code. A work folder is
43
+ *state* that only the person doing the task can assert. Trying to store task
44
+ state in `.memory` fails because there are no `covers` globs for "we decided to
45
+ use Redis" — nothing to diff against.
46
+
47
+ ## The README is a handoff document
48
+
49
+ Six sections, in this order, rendered from the same file a human edits by hand:
50
+
51
+ ```markdown
52
+ ---
53
+ kind: work
54
+ status: open
55
+ created: 2026-11-20
56
+ updated: 2026-11-20
57
+ ---
58
+
59
+ # Rate limiting
60
+
61
+ ## Goal
62
+ Return 429 above 100 requests per second, per API key.
63
+
64
+ ## Current state
65
+ Middleware drafted, not wired into the router.
66
+
67
+ ## Decisions
68
+ Redis, because it is already deployed. Token bucket, not leaky bucket.
69
+
70
+ ## Constraints
71
+ Must keep the existing `X-RateLimit-*` response headers.
72
+
73
+ ## Relevant files
74
+ - src/middleware/rate-limit.ts
75
+ - src/router.ts
76
+
77
+ ## Remaining work
78
+ - Wire the middleware into the router
79
+ - Add boundary tests
80
+ ```
81
+
82
+ `work_update` **replaces** a section body rather than appending. Append-only
83
+ editing is what turns a handoff into a log, and a log does not answer "what is
84
+ true now?" — the only question a resuming session asks.
85
+
86
+ ## The backlog is the durable `todo`
87
+
88
+ pal's native `todo` tool is a module-level array that dies with the process
89
+ (`core/src/agent/todos.ts`). That is correct for "the steps of the task in front
90
+ of me" and wrong for "what is left in this project", which is the question a
91
+ user returns to the next morning.
92
+
93
+ ```markdown
94
+ # Backlog
95
+
96
+ - [ ] Wire rate limiting → 2026-11-20-rate-limiting
97
+ - [~] Rewrite the parser
98
+ - [x] Ship the migration
99
+ ```
100
+
101
+ Items link to a work folder with `→ <slug>`. Statuses are `[ ]` todo, `[~]`
102
+ doing, `[x]` done, `[-]` dropped.
103
+
104
+ Mutations accept either a case-insensitive substring or a 1-based `#N`. An
105
+ ambiguous match is **refused** with the candidates listed — silently updating
106
+ the wrong task is worse than failing.
107
+
108
+ ## The session-length guardrail
109
+
110
+ The one rule a human cannot reliably apply to themselves. "Start fresh when the
111
+ context gets long" is easy to state and hard to notice; the session feels fine
112
+ right up until it isn't.
113
+
114
+ `session_health` reads pal's own session database **read-only** and reports:
115
+
116
+ | Signal | Threshold (configurable) |
117
+ |---|---|
118
+ | Compactions recorded | `maxCompactions` (default 1 — warn after the first) |
119
+ | Messages stored | `maxMessages` (default 150) |
120
+
121
+ It is a pull tool, not a lifecycle hook: `onTurnEnd` only receives
122
+ `{turnId, primary, messageCount}` (`core/src/agent/run.ts:486`), with no token or
123
+ compaction data, and an extension cannot inject text into the next turn's
124
+ context. So a hook could not tell the model anything useful — it would have to
125
+ write to a log the model never reads. A tool is the only surface that actually
126
+ reaches the agent.
127
+
128
+ Two triggers are deliberately **not** implemented in code: "the fix is merged"
129
+ and "I corrected the same assumption twice" are things only the human observes.
130
+ A heuristic for "the agent is going in circles" would fire on legitimately
131
+ iterative work and teach the model to ignore the guardrail entirely, so they are
132
+ taught in the prompt fragment instead.
133
+
134
+ Every failure path returns "no facts" rather than a verdict. A guardrail that
135
+ breaks the session it guards is worse than no guardrail.
136
+
137
+ ## Config
138
+
139
+ Extension-owned (per `EXTENSIONS.md`) — nothing goes in `.pal.json`:
140
+
141
+ | Level | Path |
142
+ |---|---|
143
+ | Project | `./workflow.json` |
144
+ | User | `~/.pal/workflow.json` |
145
+
146
+ ```json
147
+ {
148
+ "dir": ".work",
149
+ "write": true,
150
+ "guardrail": true,
151
+ "maxCompactions": 1,
152
+ "maxMessages": 150
153
+ }
154
+ ```
155
+
156
+ Resolution: defaults → project → user. A malformed config is ignored, never fatal.
157
+
158
+ `write` defaults to **true**, unlike `@pal-code/memory`. A workflow extension that
159
+ cannot write its first work folder is useless out of the box, and there is no
160
+ trust hazard to gate — a work folder is the agent's own scratchpad, not knowledge
161
+ a later agent will take on faith.
162
+
163
+ ## Keeping it out of git
164
+
165
+ Hide the directory **machine-wide**, never in a project `.gitignore` — the same
166
+ way `@pal-code/memory` recommends for `.memory/`. A committed `.work/` line
167
+ would leak a personal workflow into every repo you contribute to and show up as
168
+ a diff on someone else's branch:
169
+
170
+ ```sh
171
+ mkdir -p ~/.config/git
172
+ printf '.work/\n' >> ~/.config/git/ignore
173
+ git config --global core.excludesFile ~/.config/git/ignore
174
+ ```
175
+
176
+ That file is shared by every repo on the machine, so the pattern never travels.
177
+ `ripgrep` and `biome` inherit it through git, so nothing greps or lints your
178
+ scratch either.
179
+
180
+ One consequence worth knowing: pal's `grep_search` passes `--hidden` but not
181
+ `--no-ignore`, so it will **not** find `.work` content by searching. Address it
182
+ by path (`work_status`, or `read .work/TODO.md`) instead.
183
+
184
+ Commit it instead if you want a specific handoff to travel with a branch. The
185
+ file format is plain markdown either way.
186
+
187
+ ## Safety notes
188
+
189
+ - Folder names are validated against `^[a-z0-9][a-z0-9._-]*$`; `..`, absolute
190
+ paths and separators are rejected before the filesystem is touched.
191
+ - `work_start` refuses to reuse an existing slug rather than silently returning
192
+ a folder whose README describes a different goal.
193
+ - Nothing is ever deleted. `done` is a status; the folder stays readable.
194
+ - The session database is opened `readonly` and closed immediately.
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
2
  "name": "@pal-code/workflow",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.19",
4
+ "description": "Task continuity for pal — work folders with handoff READMEs, a durable backlog, and session-length guardrails",
5
+ "license": "MIT",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "type": "module",
10
+ "exports": {
11
+ ".": "./src/index.ts"
12
+ },
13
+ "files": [
14
+ "src/**/*.ts",
15
+ "!src/**/*.test.ts"
16
+ ],
17
+ "dependencies": {
18
+ "@pal-code/core": "0.0.19"
19
+ },
20
+ "engines": {
21
+ "bun": ">=1.1.0"
22
+ }
23
+ }
package/src/backlog.ts ADDED
@@ -0,0 +1,261 @@
1
+ /**
2
+ * The durable backlog: one `TODO.md` per work directory, surviving sessions.
3
+ *
4
+ * Why this exists next to the native `todo` tool: core's todo list is a
5
+ * module-level array (`core/src/agent/todos.ts`) that dies with the process.
6
+ * That is right for "what am I doing this turn" and wrong for "what is left in
7
+ * this project" — the second question is the one a user returns to tomorrow.
8
+ *
9
+ * The format is a checkbox list with an optional work-folder link, so the file
10
+ * is readable and editable by hand, and `git diff` shows what moved:
11
+ *
12
+ * - [ ] Add rate limiting → 2026-11-flow-rate-limit
13
+ * - [~] Rewrite the parser
14
+ * - [x] Ship the migration
15
+ *
16
+ * Every line is rewritten from one in-memory list on each save. That is what
17
+ * keeps the file canonical instead of accumulating three dialects of bullet.
18
+ */
19
+
20
+ import {existsSync, mkdirSync, readFileSync, writeFileSync} from 'node:fs';
21
+ import {dirname, join} from 'node:path';
22
+
23
+ import {workRoot} from './config.js';
24
+ import type {WorkflowSettings} from './config.js';
25
+
26
+ export type BacklogStatus = 'todo' | 'doing' | 'done' | 'dropped';
27
+
28
+ export interface BacklogItem {
29
+ /** Stable within the file only — the index in reading order. */
30
+ line: number;
31
+ text: string;
32
+ status: BacklogStatus;
33
+ /** Work-folder slug this item belongs to, when linked. */
34
+ work?: string;
35
+ }
36
+
37
+ const MARK: Record<BacklogStatus, string> = {
38
+ todo: '[ ]',
39
+ doing: '[~]',
40
+ done: '[x]',
41
+ dropped: '[-]',
42
+ };
43
+
44
+ const STATUS_OF: Record<string, BacklogStatus> = {
45
+ ' ': 'todo',
46
+ '': 'todo',
47
+ '~': 'doing',
48
+ x: 'done',
49
+ X: 'done',
50
+ '-': 'dropped',
51
+ };
52
+
53
+ /** `- [~] text → slug` — the arrow form is what this module writes. */
54
+ const ITEM_RE = /^[-*]\s+\[(.?)\]\s*(.+)$/;
55
+ const WORK_RE = /\s*(?:→|->)\s*([a-z0-9][a-z0-9._-]*)\s*$/i;
56
+
57
+ /** The backlog file for a repo. */
58
+ export function backlogPath(settings: WorkflowSettings, cwd: string = process.cwd()): string {
59
+ return join(workRoot(settings, cwd), 'TODO.md');
60
+ }
61
+
62
+ /**
63
+ * Parse backlog text.
64
+ *
65
+ * Unrecognised lines are ignored rather than rejected — a user's hand-written
66
+ * heading or note between items must not stop the file from being read. They
67
+ * are lost on rewrite, which is why {@link renderBacklog} is only ever called
68
+ * with a list the caller deliberately changed.
69
+ */
70
+ export function parseBacklog(text: string): BacklogItem[] {
71
+ const source = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
72
+ const items: BacklogItem[] = [];
73
+ source.split(/\r?\n/).forEach((raw, i) => {
74
+ const match = ITEM_RE.exec(raw.trim());
75
+ if (!match) return;
76
+ const status = STATUS_OF[match[1]] ?? 'todo';
77
+ let body = match[2].trim();
78
+ let work: string | undefined;
79
+ const link = WORK_RE.exec(body);
80
+ if (link) {
81
+ work = link[1];
82
+ body = body.slice(0, link.index).trim();
83
+ }
84
+ if (body === '') return;
85
+ items.push({line: i + 1, text: body, status, work});
86
+ });
87
+ return items;
88
+ }
89
+
90
+ export function renderBacklog(items: readonly BacklogItem[], title = 'Backlog'): string {
91
+ const lines = [`# ${title}`, ''];
92
+ if (items.length === 0) {
93
+ lines.push('_Empty._ Add tasks with `backlog` `add`.');
94
+ } else {
95
+ for (const item of items) {
96
+ const link = item.work !== undefined && item.work !== '' ? ` → ${item.work}` : '';
97
+ lines.push(`- ${MARK[item.status]} ${item.text}${link}`);
98
+ }
99
+ }
100
+ return `${lines.join('\n')}\n`;
101
+ }
102
+
103
+ /** Read the backlog, returning `[]` when the file does not exist yet. */
104
+ export function readBacklog(
105
+ settings: WorkflowSettings,
106
+ cwd: string = process.cwd(),
107
+ ): BacklogItem[] {
108
+ const path = backlogPath(settings, cwd);
109
+ if (!existsSync(path)) return [];
110
+ try {
111
+ return parseBacklog(readFileSync(path, 'utf-8'));
112
+ } catch {
113
+ return [];
114
+ }
115
+ }
116
+
117
+ function write(settings: WorkflowSettings, items: readonly BacklogItem[], cwd: string): void {
118
+ const path = backlogPath(settings, cwd);
119
+ // The backlog can be the first thing written in a repo — before any work
120
+ // folder exists — so the directory is not guaranteed to be there.
121
+ mkdirSync(dirname(path), {recursive: true});
122
+ writeFileSync(path, renderBacklog(items), 'utf-8');
123
+ }
124
+
125
+ /** Add items. Returns how many were added (blank text is skipped, not an error). */
126
+ export function addItems(
127
+ settings: WorkflowSettings,
128
+ texts: readonly string[],
129
+ cwd: string = process.cwd(),
130
+ work?: string,
131
+ ): {ok: true; added: number; total: number} | {ok: false; error: string} {
132
+ const items = readBacklog(settings, cwd);
133
+ let added = 0;
134
+ for (const text of texts) {
135
+ const trimmed = text.trim();
136
+ if (trimmed === '') continue;
137
+ items.push({line: 0, text: trimmed, status: 'todo', work});
138
+ added++;
139
+ }
140
+ if (added === 0) return {ok: false, error: 'No task text given.'};
141
+ try {
142
+ write(settings, items, cwd);
143
+ } catch (err) {
144
+ return {ok: false, error: err instanceof Error ? err.message : String(err)};
145
+ }
146
+ return {ok: true, added, total: items.length};
147
+ }
148
+
149
+ /**
150
+ * Find items matching a query.
151
+ *
152
+ * Matching is case-insensitive substring on the task text, with a 1-based
153
+ * ordinal accepted as a selector (`#3`) so a listing can be addressed without
154
+ * retyping prose. Ambiguity is returned as ambiguity, never resolved by
155
+ * guessing — silently updating the wrong task is worse than failing.
156
+ */
157
+ export function findItems(items: readonly BacklogItem[], query: string): BacklogItem[] {
158
+ const trimmed = query.trim();
159
+ if (trimmed === '') return [];
160
+ const ordinal = /^#(\d+)$/.exec(trimmed);
161
+ if (ordinal) {
162
+ const index = Number(ordinal[1]) - 1;
163
+ return index >= 0 && index < items.length ? [items[index]] : [];
164
+ }
165
+ const needle = trimmed.toLowerCase();
166
+ return items.filter((item) => item.text.toLowerCase().includes(needle));
167
+ }
168
+
169
+ export type BacklogMutation =
170
+ | {ok: true; item: BacklogItem; index: number}
171
+ | {ok: false; error: string};
172
+
173
+ /** Change one item's status, addressed by query. */
174
+ export function setItemStatus(
175
+ settings: WorkflowSettings,
176
+ query: string,
177
+ status: BacklogStatus,
178
+ cwd: string = process.cwd(),
179
+ ): BacklogMutation {
180
+ const items = readBacklog(settings, cwd);
181
+ const matches = findItems(items, query);
182
+ if (matches.length === 0) return {ok: false, error: `No backlog item matches "${query}".`};
183
+ if (matches.length > 1) {
184
+ const shown = matches.map((m) => ` - ${m.text}`).join('\n');
185
+ return {
186
+ ok: false,
187
+ error: `"${query}" matches ${matches.length} items — be more specific or use #N:\n${shown}`,
188
+ };
189
+ }
190
+ // `findItems` returns references from `items`, so identity lookup is exact.
191
+ const index = items.indexOf(matches[0]);
192
+ items[index] = {...items[index], status};
193
+ try {
194
+ write(settings, items, cwd);
195
+ } catch (err) {
196
+ return {ok: false, error: err instanceof Error ? err.message : String(err)};
197
+ }
198
+ return {ok: true, item: items[index], index};
199
+ }
200
+
201
+ /** Remove one item, addressed by query. Returns the removed item. */
202
+ export function removeItem(
203
+ settings: WorkflowSettings,
204
+ query: string,
205
+ cwd: string = process.cwd(),
206
+ ): BacklogMutation {
207
+ const items = readBacklog(settings, cwd);
208
+ const matches = findItems(items, query);
209
+ if (matches.length === 0) return {ok: false, error: `No backlog item matches "${query}".`};
210
+ if (matches.length > 1) {
211
+ const shown = matches.map((m) => ` - ${m.text}`).join('\n');
212
+ return {
213
+ ok: false,
214
+ error: `"${query}" matches ${matches.length} items — be more specific or use #N:\n${shown}`,
215
+ };
216
+ }
217
+ const index = items.indexOf(matches[0]);
218
+ const [removed] = items.splice(index, 1);
219
+ try {
220
+ write(settings, items, cwd);
221
+ } catch (err) {
222
+ return {ok: false, error: err instanceof Error ? err.message : String(err)};
223
+ }
224
+ return {ok: true, item: removed, index};
225
+ }
226
+
227
+ /** Rewrite every link from one slug to another after a rename. */
228
+ export function relinkWork(
229
+ settings: WorkflowSettings,
230
+ from: string,
231
+ to: string,
232
+ cwd: string = process.cwd(),
233
+ ): number {
234
+ const items = readBacklog(settings, cwd);
235
+ let changed = 0;
236
+ for (let i = 0; i < items.length; i++) {
237
+ if (items[i].work === from) {
238
+ items[i] = {...items[i], work: to};
239
+ changed++;
240
+ }
241
+ }
242
+ if (changed > 0) {
243
+ try {
244
+ write(settings, items, cwd);
245
+ } catch {
246
+ return 0;
247
+ }
248
+ }
249
+ return changed;
250
+ }
251
+
252
+ /** One-line-per-item rendering used as a tool result. */
253
+ export function formatBacklog(items: readonly BacklogItem[]): string {
254
+ if (items.length === 0) return 'Backlog is empty.';
255
+ const open = items.filter((i) => i.status === 'todo' || i.status === 'doing').length;
256
+ const lines = items.map((item, i) => {
257
+ const link = item.work !== undefined && item.work !== '' ? ` (${item.work})` : '';
258
+ return `${i + 1}. ${MARK[item.status]} ${item.text}${link}`;
259
+ });
260
+ return `${open} open of ${items.length}\n${lines.join('\n')}`;
261
+ }
package/src/config.ts ADDED
@@ -0,0 +1,93 @@
1
+ /**
2
+ * `.work` config — extension-owned, per EXTENSIONS.md.
3
+ *
4
+ * ./workflow.json project (committed)
5
+ * ~/.pal/workflow.json user
6
+ *
7
+ * Nothing here goes in `.pal.json`. Every field degrades to a default rather
8
+ * than throwing, because a bad config must never stop pal from starting.
9
+ */
10
+
11
+ import {existsSync, readFileSync} from 'node:fs';
12
+ import {homedir} from 'node:os';
13
+ import {join} from 'node:path';
14
+
15
+ export interface WorkflowSettings {
16
+ /** Directory holding work folders + the backlog, relative to the repo root. */
17
+ dir: string;
18
+ /** Allow the write tools. Reads are always allowed. */
19
+ write: boolean;
20
+ /** Turn the session-length guardrail on. */
21
+ guardrail: boolean;
22
+ /**
23
+ * Warn once a session has been compacted this many times.
24
+ *
25
+ * 1 is deliberate: the workflow rule is "start fresh on the *second*
26
+ * compaction", i.e. after the first one has already happened. Firing at 0
27
+ * would nag every session that never compacts.
28
+ */
29
+ maxCompactions: number;
30
+ /** Warn once a session holds this many messages. */
31
+ maxMessages: number;
32
+ /**
33
+ * Session database to read health from. Defaults to pal's own
34
+ * (`~/.pal/sessions.db`); overridable so tests never touch real history.
35
+ */
36
+ sessionDb?: string;
37
+ }
38
+
39
+ const DEFAULTS: WorkflowSettings = {
40
+ dir: '.work',
41
+ // Writing is on by default, unlike `@pal-code/memory`. A work folder is the
42
+ // agent's own handoff scratchpad, not knowledge that a later agent will
43
+ // trust, so there is no trust hazard to gate — and a workflow extension that
44
+ // cannot write its first work folder is useless out of the box.
45
+ write: true,
46
+ guardrail: true,
47
+ maxCompactions: 1,
48
+ maxMessages: 150,
49
+ };
50
+
51
+ function readJson(path: string): Record<string, unknown> | null {
52
+ try {
53
+ if (!existsSync(path)) return null;
54
+ const parsed: unknown = JSON.parse(readFileSync(path, 'utf-8'));
55
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
56
+ return parsed as Record<string, unknown>;
57
+ } catch {
58
+ return null; // malformed config is ignored, never fatal
59
+ }
60
+ }
61
+
62
+ function coerce(raw: Record<string, unknown>): Partial<WorkflowSettings> {
63
+ const out: Partial<WorkflowSettings> = {};
64
+ if (typeof raw.dir === 'string' && raw.dir.trim() !== '') out.dir = raw.dir.trim();
65
+ if (typeof raw.write === 'boolean') out.write = raw.write;
66
+ if (typeof raw.guardrail === 'boolean') out.guardrail = raw.guardrail;
67
+ if (typeof raw.maxCompactions === 'number' && Number.isFinite(raw.maxCompactions)) {
68
+ if (raw.maxCompactions >= 0) out.maxCompactions = Math.floor(raw.maxCompactions);
69
+ }
70
+ if (typeof raw.maxMessages === 'number' && Number.isFinite(raw.maxMessages)) {
71
+ if (raw.maxMessages > 0) out.maxMessages = Math.floor(raw.maxMessages);
72
+ }
73
+ if (typeof raw.sessionDb === 'string' && raw.sessionDb.trim() !== '') {
74
+ out.sessionDb = raw.sessionDb.trim();
75
+ }
76
+ return out;
77
+ }
78
+
79
+ /** Resolve settings: defaults → project `workflow.json` → user `~/.pal/workflow.json`. */
80
+ export function resolveWorkflowSettings(cwd: string = process.cwd()): WorkflowSettings {
81
+ const project = readJson(join(cwd, 'workflow.json'));
82
+ const user = readJson(join(homedir(), '.pal', 'workflow.json'));
83
+ return {
84
+ ...DEFAULTS,
85
+ ...(project ? coerce(project) : {}),
86
+ ...(user ? coerce(user) : {}),
87
+ };
88
+ }
89
+
90
+ /** Absolute path to the work directory for a repo. */
91
+ export function workRoot(settings: WorkflowSettings, cwd: string = process.cwd()): string {
92
+ return join(cwd, settings.dir);
93
+ }