pi-workfeed 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.
@@ -0,0 +1,91 @@
1
+ # Versioning: three independent axes
2
+
3
+ `pi-workfeed` has three version numbers. They measure different things, they change for
4
+ different reasons, and **none of them is derived from another**. Confusing them is how a
5
+ release ends up claiming a protocol it does not implement.
6
+
7
+ | Axis | Where it lives | Changes when | Does **not** change when |
8
+ |---|---|---|---|
9
+ | **Wire (schema) version** | `v` field on every event; `SCHEMA_VERSION` in `extensions/journal/index.ts`; `const` in `schemas/workfeed-event-v1.schema.json`; the heading of `docs/schema.md` | the format breaks: a field is removed, renamed, retyped, given a new meaning, or an invariant guarantee changes | fields are added, docs improve, an analyzer gets smarter |
10
+ | **Package version** | `package.json` `version`; the README roadmap's `(this)` line; the top entry of `CHANGELOG.md` | anything installable changes: code, behaviour, dependencies, shipped docs | a git tag is cut, a release is uploaded |
11
+ | **Source version** | annotated git tag `v<package version>` on the commit that carries that `package.json` | a release is *cut*, i.e. someone decided this commit is the one to hand out | `package.json` alone changes on an ordinary commit |
12
+
13
+ Consequences worth stating out loud:
14
+
15
+ - **A patch release may still be wire `1`.** Most releases are package-only.
16
+ - **Wire `2` forces at least a minor bump**, and a breaking one (consumers must handle it),
17
+ but it does not have to be a major: the package is not a rewrite, just a new stream
18
+ format. `docs/schema.md` §10 defines what counts as breaking.
19
+ - **A tag can lag `package.json`.** `main` may run ahead of the last tag with docs-only or
20
+ test-only commits: those are real commits, not releases. A tag is never moved backwards,
21
+ and never placed on a commit whose `package.json` disagrees with the tag name.
22
+
23
+ ## Bump rules for the package version
24
+
25
+ | Bump | Use for | Examples from this repo |
26
+ |---|---|---|
27
+ | patch (`0.3.x`) | docs, tests, internal refactors, policy — nothing a consumer installing the package gets differently | a protocol doc rewrite, a consistency test |
28
+ | minor (`0.x.0`) | new capability or visible behaviour change | integrity reporting, join keys holding across restarts, removing the CLI (an install surface that changed shape) |
29
+ | major | breaking tool contract or install-time behaviour | renaming `workfeed_todo`, changing what `files` ships |
30
+
31
+ Wire version bumps follow the schema rules and are counted separately; when both change,
32
+ the package version moves at least to the next minor.
33
+
34
+ ## Cutting a release
35
+
36
+ A tag is cut only when all of these are true on the commit being tagged:
37
+
38
+ 1. `npm test` — every suite passes (`ALL SUITES PASS`).
39
+ 2. `npm pack --dry-run` — the file list is exactly what you expect: `CHANGELOG.md`, `LICENSE`,
40
+ `README.md`, `docs/`, `extensions/`, `package.json`, `schemas/`, `skills/` — nothing else.
41
+ No `test/`, no `.git`, and no `bin` field: the CLI was removed on purpose, so there is no
42
+ executable in the package and nothing to look for on `PATH`. `test/package.test.mjs` asserts
43
+ this shape, that `pi.extensions` / `pi.skills` point at entries that exist, and that **every
44
+ relative link in the README resolves to a file inside the declared ship set** — the README
45
+ travels in the tarball, so a link that only works in a checkout sends a reader nowhere.
46
+ `HISTORY.md` is at the repository root, outside `files`, and is linked by absolute URL for
47
+ that reason.
48
+ Peer dependencies (`@earendil-works/pi-ai`, `@earendil-works/pi-coding-agent`,
49
+ `@earendil-works/pi-tui`, `typebox`) are declared with `*` and stay that way: the running
50
+ pi host supplies all four, so any range would describe a copy that never loads. They are
51
+ checked for existence and for import use, not for version compatibility — a pi release that
52
+ renames a field is caught by a real run, not by npm.
53
+ 3. `package.json` version == top `CHANGELOG.md` entry == README roadmap `(this)` line;
54
+ `test/version.test.mjs` checks exactly this and fails otherwise.
55
+ 4. Wire version unchanged, or its bump documented in `docs/schema.md` §10 and reflected in
56
+ `SCHEMA_VERSION`, the JSON schema `const`, and the protocol heading. `schemaVersion = 1`
57
+ is frozen for the first release: `test/schema-freeze.test.mjs` compares the machine schema
58
+ with `test/fixtures/schema-freeze-v1.json` and fails on any added or removed field,
59
+ required flag or event type. Adding to the wire is therefore a wire-version decision —
60
+ bump the version and update the snapshot in the same commit; a plain patch cannot.
61
+ 5. `git tag -a v<package version> -m "..."`, then push the tag to **both** remotes
62
+ (`git push origin v<package version>` and `git push gitee v<package version>`) so the
63
+ mirror cannot drift. The tag name is the version in `package.json`, never a literal you
64
+ typed from memory — that is how a tag lands on the wrong commit.
65
+ 6. npm publication (when credentials exist) happens **after** the tag and **from the tagged
66
+ commit**, so `npm pack` of the published version produces the same tree the tag points at.
67
+ If a doc fix lands after the tag and before the first publish, re-point the tag to the fixed
68
+ commit (delete the old tag locally and on both remotes, cut it again) rather than publishing
69
+ a tree the tag does not describe — then run the clean-install probe on that artifact, and
70
+ verify from the registry (`npm view pi-workfeed versions`, `dist-tags.latest`) once it is out.
71
+
72
+ ## What enforces this
73
+
74
+ `test/version.test.mjs` reads the four declarations and compares them:
75
+
76
+ - `package.json` version
77
+ - first `## [x.y.z]` heading in `CHANGELOG.md`
78
+ - the roadmap's `vX.Y.Z (this)` line in `README.md`
79
+ - `SCHEMA_VERSION` in the producer vs `properties.v.const` in the JSON schema
80
+
81
+ It also looks at git, three times. If `HEAD` is tagged, the tag must be `v<package version>`.
82
+ Every tag must name the version inside **its own commit** (`dev/0.4.6` must contain `0.4.6`).
83
+ And no release tag may claim a version above `package.json` — development milestones therefore
84
+ live under `dev/` (`dev/0.3.1`, `dev/0.4.0` … `dev/0.4.6`), because a `v0.4.6` tag beside an
85
+ npm `0.1.0` reads as "the latest version is 0.4.6" and contradicts the package a reader just
86
+ installed. The two rules together are what makes a number-line reset safe *and* visible: the
87
+ per-commit rule keeps an old tag honest about its own tree, and the ceiling rule keeps the
88
+ release line the only `v*` line.
89
+
90
+ Nothing here is a substitute for the checklist: the test catches text drifting apart, not a
91
+ release that skipped its own evidence.
@@ -0,0 +1,318 @@
1
+ /**
2
+ * Digest builder — a pure function, no pi API, no I/O.
3
+ *
4
+ * The digest is derived data: it holds aggregate facts only, never advice.
5
+ * It is rebuilt from `workfeed-<sid>.jsonl`; deleting every digest file must be
6
+ * harmless, because that log is the truth.
7
+ */
8
+
9
+ export interface TokenBuckets {
10
+ input: number;
11
+ output: number;
12
+ cacheRead: number;
13
+ cacheWrite: number;
14
+ total: number;
15
+ }
16
+
17
+ export interface TaskStats {
18
+ /** 1-based user-instruction index, same value as the `task` field in events */
19
+ index: number;
20
+ /** wall clock from prompt to agent_settled, ms */
21
+ ms: number;
22
+ turns: number;
23
+ tools: number;
24
+ tokens: TokenBuckets;
25
+ aborted: boolean;
26
+ }
27
+
28
+ export interface ToolRecord {
29
+ name: string;
30
+ task: number;
31
+ item?: number;
32
+ ts: number;
33
+ /** monotonic duration reported by pi, ms (may be absent for blocked calls) */
34
+ durMs?: number;
35
+ /** wall clock from tool_call to tool_execution_end, ms */
36
+ wallMs?: number;
37
+ isError: boolean;
38
+ exitCode?: number;
39
+ outBytes?: number;
40
+ }
41
+
42
+ export interface TodoItem {
43
+ id: number;
44
+ text: string;
45
+ status: string;
46
+ elapsedMs: number;
47
+ /** true when a later snapshot dropped the item (e.g. `clear`): kept, never zeroed */
48
+ dropped?: boolean;
49
+ }
50
+
51
+ /**
52
+ * What a replay could not use, and why. Skipping a bad line is acceptable;
53
+ * skipping it silently is not — the digest has to state how much of the file it
54
+ * could read, or a clean-looking digest hides a hole in the middle of history.
55
+ */
56
+ export interface LogIntegrity {
57
+ /** non-empty lines seen */
58
+ lines: number;
59
+ /** 1-based line number of an unparsable *final* line (a killed append), else null */
60
+ tornTail: number | null;
61
+ /** 1-based line numbers that failed to parse in the middle of the file */
62
+ corrupt: number[];
63
+ /** lines that parsed but violate the envelope (wrong `v`, missing/typed-wrong key) */
64
+ badEnvelope: Array<{ line: number; reason: string }>;
65
+ /** event types this version does not know: tolerated, but reported */
66
+ unknown: Array<{ line: number; t: string }>;
67
+ }
68
+
69
+ export interface DigestInput {
70
+ sid: string;
71
+ date: string;
72
+ generatedAt: number;
73
+ model?: string;
74
+ provider?: string;
75
+ cwd: string;
76
+ events: number;
77
+ tasks: TaskStats[];
78
+ tools: ToolRecord[];
79
+ todos: TodoItem[];
80
+ /** how much of the raw stream the tables above actually cover */
81
+ quality?: {
82
+ /** calls that emitted a start line */
83
+ started: number;
84
+ /** calls that emitted both start and end */
85
+ calls: number;
86
+ /** start lines with no matching end line: crash, kill or abort */
87
+ unfinished: number;
88
+ /** finished calls carrying an `item` attribution */
89
+ attributed: number;
90
+ /** settled tasks whose token total is non-zero */
91
+ tasksWithTokens: number;
92
+ /** user prompts seen (one per task) */
93
+ prompts?: number;
94
+ /** prompts with no settle: killed, crashed, or still running */
95
+ unsettled?: number;
96
+ /** compaction runs seen; absent when none happened (no fabricated zero) */
97
+ compaction?: {
98
+ runs: number;
99
+ failed: number;
100
+ /** aborted, or "nothing to compact": an empty answer, not a failure */
101
+ skipped: number;
102
+ lastError?: string;
103
+ lastSkip?: string;
104
+ };
105
+ /** what the parser had to drop, and why */
106
+ integrity?: LogIntegrity;
107
+ };
108
+ }
109
+
110
+ const pct = (part: number, whole: number): string =>
111
+ whole > 0 ? `${Math.round((part / whole) * 100)}%` : "-";
112
+
113
+ /**
114
+ * Duration formatting for a human reading the digest.
115
+ *
116
+ * A floor-to-seconds formatter turns a whole column into `0s`, which is worse than
117
+ * useless: "which tool was slow" is the question this digest exists to answer, and
118
+ * every sub-second call then looks identical. So: milliseconds below one second, one
119
+ * decimal below ten seconds, whole seconds above it.
120
+ */
121
+ export const fmtDur = (ms: number | undefined): string => {
122
+ if (!ms || ms < 0) return "0s";
123
+ if (ms < 1000) return `${Math.round(ms)}ms`;
124
+ const secs = ms / 1000;
125
+ if (secs < 10) {
126
+ const one = secs.toFixed(1);
127
+ return `${one.endsWith(".0") ? one.slice(0, -2) : one}s`;
128
+ }
129
+ const s = Math.round(secs);
130
+ if (s < 60) return `${s}s`;
131
+ const m = Math.floor(s / 60);
132
+ if (m < 60) return `${m}m${String(s % 60).padStart(2, "0")}s`;
133
+ const h = Math.floor(m / 60);
134
+ return `${h}h${String(m % 60).padStart(2, "0")}m`;
135
+ };
136
+
137
+ const clip = (text: string, n: number): string => (text.length <= n ? text : text.slice(0, n - 1) + "…");
138
+
139
+ const fmtTokens = (t: TokenBuckets): string => {
140
+ if (!t || t.total === 0) return "0";
141
+ const k = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));
142
+ return `${k(t.input + t.cacheRead + t.cacheWrite)} in / ${k(t.output)} out / ${k(t.total)} total`;
143
+ };
144
+
145
+ /** Slowest tool calls, in duration order (monotonic duration wins over wall clock). */
146
+ export function slowestTools(tools: ToolRecord[], n = 5): ToolRecord[] {
147
+ return tools
148
+ .filter((t) => t.durMs !== undefined)
149
+ .slice()
150
+ .sort((a, b) => (b.durMs ?? 0) - (a.durMs ?? 0))
151
+ .slice(0, n);
152
+ }
153
+
154
+ /** Tool calls grouped by name, ordered by total time spent. */
155
+ export function toolRollup(tools: ToolRecord[], n = 8): Array<{ name: string; count: number; total: number; max: number; failed: number }> {
156
+ const map = new Map<string, { name: string; count: number; total: number; max: number; failed: number }>();
157
+ for (const t of tools) {
158
+ const e = map.get(t.name) ?? { name: t.name, count: 0, total: 0, max: 0, failed: 0 };
159
+ e.count += 1;
160
+ e.total += t.durMs ?? 0;
161
+ e.max = Math.max(e.max, t.durMs ?? 0);
162
+ e.failed += t.isError ? 1 : 0;
163
+ map.set(t.name, e);
164
+ }
165
+ return [...map.values()].sort((a, b) => b.total - a.total).slice(0, n);
166
+ }
167
+
168
+ export function buildDigest(input: DigestInput): string {
169
+ const { tasks, tools, todos } = input;
170
+ const lines: string[] = [];
171
+
172
+ lines.push("# workfeed digest");
173
+ lines.push("");
174
+ lines.push(`> derived from workfeed-${input.sid}.jsonl at ${new Date(input.generatedAt).toISOString()} — regenerate, do not hand-edit.`);
175
+ lines.push("");
176
+ lines.push(`- session: ${input.sid}`);
177
+ lines.push(`- date: ${input.date}`);
178
+ lines.push(`- model: ${input.model ?? "?"}${input.provider ? ` (${input.provider})` : ""}`);
179
+ lines.push(`- cwd: ${input.cwd}`);
180
+ lines.push(`- events: ${input.events}`);
181
+ lines.push("");
182
+
183
+ // ---- data quality: what the tables below cannot tell you ----
184
+ if (input.quality) {
185
+ const q = input.quality;
186
+ const pctAttr = q.calls > 0 ? `${Math.round((q.attributed / q.calls) * 100)}%` : "-";
187
+ lines.push("## data quality");
188
+ lines.push("");
189
+ lines.push(`- tool calls: ${q.calls} finished${q.unfinished > 0 ? `, ${q.unfinished} started without an end line (crash, kill or abort)` : ""}`);
190
+ lines.push(`- item attribution: ${q.attributed}/${q.calls} calls carry an item (${pctAttr})`);
191
+ lines.push(`- token totals: ${q.tasksWithTokens}/${tasks.length} tasks report a non-zero total`);
192
+ if (q.prompts !== undefined) {
193
+ const open = q.unsettled ?? 0;
194
+ lines.push(
195
+ `- task coverage: ${tasks.length}/${q.prompts} prompts have a settle${open > 0 ? ` — ${open} ${open === 1 ? "was" : "were"} killed or ${open === 1 ? "is" : "are"} still open, so ${open === 1 ? "its" : "their"} duration and tokens are unknown, not zero` : ""}`,
196
+ );
197
+ }
198
+ // A failed or aborted compaction is invisible in the tables: no task or tool row
199
+ // changes shape, the context just never shrank. Report it instead of letting a
200
+ // clean-looking digest imply the compaction happened.
201
+ if (q.compaction) {
202
+ const c = q.compaction;
203
+ const skipped = c.skipped > 0 ? `${c.skipped} skipped` : undefined;
204
+ // Failures speak first; if there are none, the skipped reason is still worth
205
+ // saying, because "nothing to compact" on a small session is the normal answer.
206
+ const why = c.lastError
207
+ ? ` — last: ${clip(c.lastError, 120)}`
208
+ : c.lastSkip
209
+ ? ` — skipped: ${clip(c.lastSkip, 120)}`
210
+ : "";
211
+ const parts = [`${c.runs} completed`, `${c.failed} failed`];
212
+ if (skipped) parts.push(skipped);
213
+ lines.push(`- compaction: ${parts.join(", ")}${why}`);
214
+ }
215
+ const integ = q.integrity;
216
+ if (integ) {
217
+ const dropped = integ.corrupt.length + integ.badEnvelope.length;
218
+ lines.push(
219
+ `- log integrity: ${integ.lines} lines, ${dropped} dropped${dropped > 0 ? ` (${integ.corrupt.length} unparsable, ${integ.badEnvelope.length} violating the envelope)` : ""}, ${integ.unknown.length} of unknown type`,
220
+ );
221
+ if (integ.tornTail !== null) {
222
+ lines.push(`- torn tail: line ${integ.tornTail} was an interrupted append; everything before it was used`);
223
+ }
224
+ if (integ.corrupt.length > 0) {
225
+ lines.push(`- corrupt lines: ${integ.corrupt.join(", ")} — facts around them survive, but any ordering near them is lost`);
226
+ }
227
+ for (const bad of integ.badEnvelope.slice(0, 3)) {
228
+ lines.push(`- rejected line ${bad.line}: ${bad.reason}`);
229
+ }
230
+ if (integ.badEnvelope.length > 3) {
231
+ lines.push(`- rejected lines: ${integ.badEnvelope.length} total, first 3 shown`);
232
+ }
233
+ if (integ.unknown.length > 0) {
234
+ lines.push(`- unknown event types: ${[...new Set(integ.unknown.map((u) => u.t))].join(", ")} (ignored; the format is forward compatible)`);
235
+ }
236
+ }
237
+ lines.push("");
238
+ }
239
+
240
+ // ---- tasks ----
241
+ const totalMs = tasks.reduce((a, t) => a + t.ms, 0);
242
+ lines.push(`## tasks (${tasks.length}, wall clock ${fmtDur(totalMs)})`);
243
+ lines.push("");
244
+ if (tasks.length === 0) {
245
+ lines.push("_none yet_");
246
+ } else {
247
+ lines.push("| # | time | turns | tools | tokens | status |");
248
+ lines.push("|---|---|---|---|---|---|");
249
+ for (const t of tasks) {
250
+ lines.push(
251
+ `| ${t.index} | ${fmtDur(t.ms)} | ${t.turns} | ${t.tools} | ${fmtTokens(t.tokens)} | ${t.aborted ? "aborted" : "ok"} |`,
252
+ );
253
+ }
254
+ }
255
+ lines.push("");
256
+
257
+ // ---- tools ----
258
+ const done = tools.filter((t) => t.durMs !== undefined || t.isError);
259
+ const fails = done.filter((t) => t.isError).length;
260
+ lines.push(`## tools (${tools.length} ${tools.length === 1 ? "call" : "calls"}, ${fails} failed)`);
261
+ lines.push("");
262
+ const rollup = toolRollup(tools);
263
+ if (rollup.length === 0) {
264
+ lines.push("_none yet_");
265
+ } else {
266
+ lines.push("| tool | calls | total | avg | max | failed |");
267
+ lines.push("|---|---|---|---|---|---|");
268
+ for (const r of rollup) {
269
+ const avg = r.count > 0 ? r.total / r.count : 0;
270
+ lines.push(`| ${r.name} | ${r.count} | ${fmtDur(r.total)} | ${fmtDur(avg)} | ${fmtDur(r.max)} | ${r.failed} |`);
271
+ }
272
+ }
273
+ lines.push("");
274
+
275
+ const slow = slowestTools(tools, 5);
276
+ if (slow.length > 0) {
277
+ lines.push("slowest calls");
278
+ lines.push("");
279
+ for (const t of slow) {
280
+ lines.push(`- ${fmtDur(t.durMs)} · ${t.name} · task ${t.task}${t.item ? ` · item ${t.item}` : ""}${t.isError ? " · FAILED" : ""}`);
281
+ }
282
+ lines.push("");
283
+ }
284
+
285
+ const failed = tools.filter((t) => t.isError).slice(-5);
286
+ if (failed.length > 0) {
287
+ lines.push("last failures");
288
+ lines.push("");
289
+ for (const t of failed) {
290
+ lines.push(`- ${t.name} · task ${t.task}${t.exitCode !== undefined ? ` · exit ${t.exitCode}` : ""} · ${new Date(t.ts).toISOString().slice(11, 19)}`);
291
+ }
292
+ lines.push("");
293
+ }
294
+
295
+ // ---- todo ----
296
+ lines.push(`## todo items (${todos.length})`);
297
+ lines.push("");
298
+ if (todos.length === 0) {
299
+ lines.push("_none_");
300
+ } else {
301
+ const doneCount = todos.filter((t) => t.status === "completed").length;
302
+ const droppedCount = todos.filter((t) => t.dropped).length;
303
+ const elapsedTotal = todos.reduce((a, t) => a + t.elapsedMs, 0);
304
+ lines.push(
305
+ `${doneCount}/${todos.length} completed · accumulated in-progress time ${fmtDur(elapsedTotal)}${droppedCount > 0 ? ` · ${droppedCount} dropped from the list (timing kept)` : ""}`,
306
+ );
307
+ lines.push("");
308
+ lines.push("| id | status | elapsed | share | text |");
309
+ lines.push("|---|---|---|---|---|");
310
+ for (const t of todos) {
311
+ const status = t.dropped ? `${t.status} · dropped` : t.status;
312
+ lines.push(`| ${t.id} | ${status} | ${fmtDur(t.elapsedMs)} | ${pct(t.elapsedMs, elapsedTotal)} | ${clip(t.text.replace(/\|/g, "\\|"), 60)} |`);
313
+ }
314
+ }
315
+ lines.push("");
316
+
317
+ return lines.join("\n");
318
+ }