repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

feat(pi): add adaptive reflection workflow

e6817a21672598141cb6fc45c7e99ab3e2af8757

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (5)

pi/agent/prompts/reflect.md

Deleted
deleted file mode 100644
1 ----
2 -description: Mine Pi sessions for next high-impact workflow asset
3 -mask: astra
4 -argument-hint: "[focus]"
5 ----
7 -# Mine Pi sessions for next high-impact workflow asset
9 -Reflect on Pi usage and propose workflow assets.
11 -**Focus**:
12 -$ARGUMENTS
14 -Inputs:
16 -- Load the `pi-sessions` skill.
17 - Use its `scripts/inspect.mjs` helper for discovery and bounded metadata.
18 - Inspect branch-aware timelines before drawing conclusions.
19 - Start with `list`; narrow by name/cwd/date before requesting safe text excerpts.
20 - Do not invent JSONL parsers or scan HOME.
21 -- Count persisted user turns.
22 - Exclude abandoned branches, retained-tail copies, and test fixtures.
23 - Report sample scope and cite session IDs plus entry IDs/lines.
24 - Tool errors alone are not evidence of product defects.
25 -- Check existing prompts for style:
26 - `~/.pi/agent/prompts/*.md`, `.pi/prompts/*.md`, `prompts/*.md`.
27 -- Check existing skills/prompts/extensions:
28 - global, project, and package dirs.
30 -Find:
32 -1. Repeated tasks, friction, manual rituals, missed checks.
33 -2. Existing prompt/skill/ext to improve or merge into.
34 -3. Candidate new prompts, skills, extensions.
35 -4. Best location:
36 - global vs project/package.
38 -Output:
40 -- `Findings`:
41 - terse bullets with evidence.
42 -- `Candidates`:
43 - prompt / skill / extension, one-line value each.
44 -- `Pick`:
45 - select one highest-impact candidate and explain why.
46 -- `Draft`:
47 - minimal outline or file path + core behavior.
48 -- `Nothing`:
49 - if no worthy candidate, say so and explain why.
51 -Rules:
53 -- Keep wording terse.
54 - No fluff.
55 - No bullshit.
56 -- Match style of existing prompts.
57 -- Do not implement unless explicitly asked.

pi/agent/skills/pi-sessions/SKILL.md

Modified
62 62 - Branch counts cover persisted messages.
63 63 Context counts include retained-tail messages separately.
64 64 - Report malformed/unsupported sessions by file/line, never their contents.
65 - List reports partial results and exits nonzero if any file fails.
65 + Unfiltered lists validate every discovered session. With date or cwd filters,
66 + a valid supported header proven outside scope may skip body validation.
67 + Invalid headers and in-scope sessions remain errors; query and pagination never
68 + permit skipping. `complete` means every file was fully parsed or safely excluded.
69 + `scanned` counts discovered candidates, `parsed` counts successfully parsed
70 + sessions before query/paging, and `skipped` counts header-proven exclusions.
71 + List exits nonzero when any unresolved file fails validation.
66 72 An unfinished live JSONL line is an error; retry when the writer finishes.
67 73 - Check installed Pi docs when format or storage behavior changes:
68 74 `docs/session-format.md` and `docs/settings.md`.

pi/agent/skills/pi-sessions/scripts/inspect.mjs

Modified
119 119 return row;
122 -async function readSession(file, withText) {
122 +async function readSession(file, withText, scope) {
123 123 const stat = await info(file);
124 124 if (!stat?.isFile()) fail(file, null, "session must be a regular file");
125 125 if (!stat.size) fail(file, 1, "empty session");
153 153 fail(file, line, "invalid session header");
154 154 if (entry.version !== 3) fail(file, line, "unsupported session version; expected 3");
155 155 header = { file, id: entry.id, cwd: entry.cwd, started: new Date(entry.timestamp).toISOString() };
156 + if (scope && !scope(header)) return null;
156 157 continue;
335 336 command === "show"
336 337 ? store.files.filter((file) => file === resolve(cwd, query) || basename(file) === query)
339 + const cwdFilter = values.cwd ? resolve(cwd, values.cwd) : undefined;
340 + // Only a validated header outside explicit scope may bypass body validation.
341 + const scope =
342 + command === "list" && (cwdFilter || since || until)
343 + ? (header) =>
344 + (!cwdFilter || header.cwd === cwdFilter) &&
345 + (!since || header.started.slice(0, 10) >= since) &&
346 + (!until || header.started.slice(0, 10) <= until)
347 + : undefined;
338 348 const sessions = [];
339 349 const errors = [];
350 + let skipped = 0;
340 351 for (const file of direct.length ? direct : store.files) {
342 - sessions.push(await readSession(file, values.text));
353 + const session = await readSession(file, values.text, scope);
354 + if (session) sessions.push(session);
355 + else skipped++;
343 356 } catch (error) {
344 357 if (direct.length === 1) throw error;
345 358 errors.push({ file, error: error.message });
349 362 root: store.root,
350 363 source: store.source,
351 364 scanned: direct.length || store.files.length,
365 + parsed: sessions.length,
366 + skipped,
352 367 complete: errors.length === 0,
353 368 errorCount: errors.length,
354 369 errors: errors.slice(0, limit),
359 374 .filter(
360 375 (s) =>
361 376 (!queryLower || [s.name, s.id, s.cwd].some((v) => v?.toLowerCase().includes(queryLower))) &&
362 - (!values.cwd || s.cwd === resolve(cwd, values.cwd)) &&
377 + (!cwdFilter || s.cwd === cwdFilter) &&
363 378 (!since || s.started.slice(0, 10) >= since) &&
364 379 (!until || s.started.slice(0, 10) <= until),

pi/agent/skills/pi-sessions/scripts/inspect.test.mjs

Modified
117 117 await assert.rejects(inspect(["list", "--offset", "-1"], f.ctx), /offset/i);
120 +test("scoped lists skip only valid headers proven outside date and cwd bounds", async (t) => {
121 + const f = fixture(t);
122 + f.add("inside", "inside", [], { timestamp: "2026-09-01T00:00:00Z" });
123 + const before = f.add("before", "before", [], { timestamp: "2026-08-31T23:59:59Z" });
124 + const after = f.add("after", "after", [], { timestamp: "2026-09-03T00:00:00Z" });
125 + const other = f.add("other", "other", [], { cwd: join(f.cwd, "other") });
126 + for (const file of [before, after, other])
127 + writeFileSync(file, `${readFileSync(file, "utf8")}{"MALFORMED_BODY":`);
129 + const scoped = await inspect(
130 + ["list", "--cwd", f.cwd, "--since", "2026-09-01", "--until", "2026-09-02"],
131 + f.ctx,
132 + );
133 + assert.equal(scoped.complete, true);
134 + assert.equal(scoped.scanned, 4);
135 + assert.equal(scoped.parsed, 1);
136 + assert.equal(scoped.skipped, 3);
137 + assert.equal(scoped.errorCount, 0);
138 + assert.equal(scoped.sessions[0].id, "inside");
139 + assert.equal(scoped.scanned, scoped.parsed + scoped.skipped + scoped.errorCount);
141 + const unscoped = await inspect(["list"], f.ctx);
142 + assert.equal(unscoped.complete, false);
143 + assert.equal(unscoped.scanned, 4);
144 + assert.equal(unscoped.parsed, 1);
145 + assert.equal(unscoped.skipped, 0);
146 + assert.equal(unscoped.errorCount, 3);
147 + assert.equal(unscoped.scanned, unscoped.parsed + unscoped.skipped + unscoped.errorCount);
148 + await assert.rejects(inspect(["show", before, "--since", "2026-09-01"], f.ctx), /line 3/);
149 +});
151 +test("scoped lists retain unknown and in-scope errors before query filtering", async (t) => {
152 + const f = fixture(t);
153 + f.add("name-hit", "wanted by name", [], { timestamp: "2026-09-01T12:00:00Z" });
154 + const broken = f.add("broken", "unrelated", [], { timestamp: "2026-09-01T12:00:00Z" });
155 + writeFileSync(broken, `${readFileSync(broken, "utf8")}{"MALFORMED_BODY":`);
156 + const unknown = f.add("unknown", "unknown", [], { timestamp: "2026-08-01T12:00:00Z" });
157 + f.json(unknown, {
158 + type: "session",
159 + version: 99,
160 + id: "unknown",
161 + cwd: f.cwd,
162 + timestamp: "2026-08-01T12:00:00Z",
163 + });
165 + const result = await inspect(["list", "wanted by name", "--since", "2026-09-01"], f.ctx);
166 + assert.equal(result.complete, false);
167 + assert.equal(result.scanned, 3);
168 + assert.equal(result.parsed, 1);
169 + assert.equal(result.skipped, 0);
170 + assert.equal(result.errorCount, 2);
171 + assert.equal(result.sessions[0].id, "name-hit");
172 + assert.match(result.errors.find((error) => error.file === broken).error, /line 3/);
173 + assert.match(result.errors.find((error) => error.file === unknown).error, /version/i);
174 + assert.equal(result.scanned, result.parsed + result.skipped + result.errorCount);
175 +});
120 177 test("duplicate names and ID prefixes require disambiguation; discovered paths work", async (t) => {
121 178 const f = fixture(t);
122 179 const file = f.add("abc-1", "duplicate");

pi/agent/workflows/reflect.json

Added
new file mode 100644
1 +{
2 + "name": "reflect",
3 + "description": "Mine Pi usage through adaptive parallel scans, develop three ideas, and have an adversarial judge select one terse proposal.",
4 + "args": {
5 + "hint": "[focus]",
6 + "params": ["focus"]
7 + },
8 + "schemas": {
9 + "PartitionPlan": {
10 + "type": "object",
11 + "properties": {
12 + "focus": { "type": "string", "maxLength": 1200 },
13 + "coverage": {
14 + "type": "array",
15 + "maxItems": 12,
16 + "items": { "type": "string", "maxLength": 1200 }
17 + },
18 + "uncovered_scope": {
19 + "type": "array",
20 + "maxItems": 12,
21 + "items": { "type": "string", "maxLength": 1200 }
22 + },
23 + "tasks": {
24 + "type": "array",
25 + "minItems": 1,
26 + "maxItems": 24,
27 + "items": {
28 + "type": "object",
29 + "properties": {
30 + "id": {
31 + "type": "string",
32 + "maxLength": 96,
33 + "pattern": "^[A-Za-z0-9_-]+$"
34 + },
35 + "source": {
36 + "type": "string",
37 + "enum": ["sessions", "config", "extensions"]
38 + },
39 + "label": { "type": "string", "maxLength": 240 },
40 + "scope": { "type": "string", "maxLength": 1200 },
41 + "locators": {
42 + "type": "array",
43 + "minItems": 1,
44 + "maxItems": 24,
45 + "items": { "type": "string", "maxLength": 1200 }
46 + },
47 + "instructions": {
48 + "type": "array",
49 + "minItems": 1,
50 + "maxItems": 12,
51 + "items": { "type": "string", "maxLength": 1200 }
52 + },
53 + "exclusions": {
54 + "type": "array",
55 + "maxItems": 12,
56 + "items": { "type": "string", "maxLength": 1200 }
57 + }
58 + },
59 + "required": [
60 + "id",
61 + "source",
62 + "label",
63 + "scope",
64 + "locators",
65 + "instructions",
66 + "exclusions"
67 + ]
68 + }
69 + }
70 + },
71 + "required": ["focus", "coverage", "uncovered_scope", "tasks"]
72 + },
73 + "ScanResult": {
74 + "type": "object",
75 + "properties": {
76 + "task_id": { "type": "string", "maxLength": 96 },
77 + "source": {
78 + "type": "string",
79 + "enum": ["sessions", "config", "extensions"]
80 + },
81 + "label": { "type": "string", "maxLength": 240 },
82 + "inspected": {
83 + "type": "array",
84 + "maxItems": 16,
85 + "items": { "type": "string", "maxLength": 1200 }
86 + },
87 + "observations": {
88 + "type": "array",
89 + "maxItems": 4,
90 + "items": {
91 + "type": "object",
92 + "properties": {
93 + "id": {
94 + "type": "string",
95 + "maxLength": 120,
96 + "pattern": "^[A-Za-z0-9_-]+$"
97 + },
98 + "finding": { "type": "string", "maxLength": 1600 },
99 + "evidence": { "type": "string", "maxLength": 2400 },
100 + "locator": { "type": "string", "maxLength": 1600 }
101 + },
102 + "required": ["id", "finding", "evidence", "locator"]
104 + },
105 + "counterevidence": {
106 + "type": "array",
107 + "maxItems": 6,
108 + "items": { "type": "string", "maxLength": 1600 }
109 + },
110 + "gaps": {
111 + "type": "array",
112 + "maxItems": 8,
113 + "items": { "type": "string", "maxLength": 1600 }
115 + },
116 + "required": [
117 + "task_id",
118 + "source",
119 + "label",
120 + "inspected",
121 + "observations",
122 + "counterevidence",
123 + "gaps"
125 + },
126 + "Candidate": {
127 + "type": "object",
128 + "properties": {
129 + "source": { "type": "string", "maxLength": 120 },
130 + "name": { "type": "string", "maxLength": 240 },
131 + "idea": { "type": "string", "maxLength": 2000 },
132 + "change": { "type": "string", "maxLength": 3200 },
133 + "suggested_destination": { "type": "string", "maxLength": 1200 },
134 + "impact": { "type": "string", "maxLength": 2400 },
135 + "current_state": { "type": "string", "maxLength": 2400 },
136 + "expected_state": { "type": "string", "maxLength": 2400 },
137 + "evidence": {
138 + "type": "array",
139 + "minItems": 1,
140 + "maxItems": 10,
141 + "items": {
142 + "type": "object",
143 + "properties": {
144 + "claim": { "type": "string", "maxLength": 1600 },
145 + "detail": { "type": "string", "maxLength": 2400 },
146 + "locator": { "type": "string", "maxLength": 1600 },
147 + "source": { "type": "string", "maxLength": 120 },
148 + "newly_inspected": { "type": "boolean" }
149 + },
150 + "required": [
151 + "claim",
152 + "detail",
153 + "locator",
154 + "source",
155 + "newly_inspected"
158 + },
159 + "existing_asset_comparison": {
160 + "type": "array",
161 + "maxItems": 8,
162 + "items": {
163 + "type": "object",
164 + "properties": {
165 + "path": { "type": "string", "maxLength": 1200 },
166 + "relation": { "type": "string", "maxLength": 1600 }
167 + },
168 + "required": ["path", "relation"]
170 + },
171 + "counterevidence": {
172 + "type": "array",
173 + "maxItems": 8,
174 + "items": { "type": "string", "maxLength": 1600 }
175 + },
176 + "gaps": {
177 + "type": "array",
178 + "maxItems": 12,
179 + "items": { "type": "string", "maxLength": 1600 }
181 + },
182 + "required": [
183 + "source",
184 + "name",
185 + "idea",
186 + "change",
187 + "suggested_destination",
188 + "impact",
189 + "current_state",
190 + "expected_state",
191 + "evidence",
192 + "existing_asset_comparison",
193 + "counterevidence",
194 + "gaps"
196 + },
197 + "FinalReport": {
198 + "type": "object",
199 + "properties": {
200 + "choice": { "type": "string", "minLength": 1, "maxLength": 1200 },
201 + "report": { "type": "string", "minLength": 1, "maxLength": 8000 }
202 + },
203 + "required": ["choice", "report"]
205 + },
206 + "phases": [
208 + "id": "partition",
209 + "kind": "single",
210 + "step": {
211 + "summary": "partition reflection evidence sources",
212 + "prompt": "partition evidence collection for this reflection focus: {args.focus}. an empty focus means overall pi usage.\n\n- inspect source metadata and sizes, not substantive evidence\n- read and follow applicable agent instructions\n- read and follow the pi-sessions skill when inspecting session metadata\n- cover pi sessions; non-secret global and project pi agent config; and existing extensions from active global, project, and configured package roots\n- discover active roots from pi settings and package manifests rather than crawling home\n- never read auth files, decrypted secrets, secret-bearing files, or raw session files\n- split work along natural boundaries so tasks have roughly comparable evidence volume\n- use one config task unless observed size requires more\n- split extensions by active root or large subtree\n- split sessions by bounded date or discovered-session groups\n- allocate task count according to observed volume, with no more than 24 total tasks\n- make every task self-contained with exact locators, instructions, and exclusions\n- record omitted or sampled scope explicitly\n- use only read-only inspection and do not invoke nested agents\n\nreturn PartitionPlan.",
213 + "tools": ["read", "grep", "ls", "bash"],
214 + "model": "small",
215 + "schema": "PartitionPlan"
217 + },
219 + "id": "scan",
220 + "kind": "fanout",
221 + "over": "{partition.results[].tasks[]}",
222 + "concurrency": 12,
223 + "step": {
224 + "summary": "scan evidence partition {item}",
225 + "prompt": "scan this assigned evidence partition: {item}. reflection focus: {args.focus}.\n\n- inspect only the assigned scope and exact locators\n- follow every supplied instruction and exclusion\n- read and follow applicable agent instructions\n- for sessions, read and follow pi-sessions without inventing another inspection method\n- collect concrete evidence of repeated friction, manual rituals, missed checks, duplication, or relevant existing capability\n- distinguish direct observations from interpretation\n- cite session evidence by session id plus entry id or source line, and cite file evidence by exact path and relevant locator\n- count independent occurrences, not copied summaries, retained transcript material, abandoned branches, or repeated discussion of one incident\n- return no more than four strongest observations\n- include counterevidence, blockers, sampling limits, and uncovered scope\n- do not propose solutions\n- do not expose protected data, modify anything, use network access, or invoke nested agents\n\nreturn ScanResult and echo the task id, source, and label exactly.",
226 + "tools": ["read", "grep", "ls", "bash"],
227 + "model": "tiny",
228 + "schema": "ScanResult"
230 + },
232 + "id": "analyze",
233 + "kind": "fanout",
234 + "over": "{scan.results | groupBy source}",
235 + "concurrency": 3,
236 + "step": {
237 + "summary": "develop one source-owned improvement idea from {item}",
238 + "prompt": "develop exactly one high-impact pi workflow improvement from this source group: {item}. reflection focus: {args.focus}. partition failures: {partition.failures}. scanner failures: {scan.failures}.\n\n- treat the group key as the assigned source and its items as the complete scanner evidence packet\n- keep primary investigation within the assigned source\n- inspect additional detail when it can change the idea\n- inspect relevant existing assets outside the source only to test overlap, feasibility, or destination\n- follow applicable agent instructions and the pi-sessions skill for any added session inspection\n- prefer improving or merging an existing asset over creating another asset\n- select one concrete idea for this source, even when evidence is imperfect\n- include every fact used to support the idea in the returned evidence array\n- mark evidence gathered during this analysis as newly inspected\n- give exact session or file locators for all evidence, including newly inspected evidence\n- compare the idea with relevant existing assets at exact paths\n- include material counterevidence, relevant failed scans, sampling limits, and uncertainty in gaps\n- describe current and expected states plainly so another agent can draw them\n- never rely on tool history or hidden context because the final judge receives only this returned candidate\n- never invent evidence, expose protected data, modify anything, use network access, or invoke nested agents\n\nreturn Candidate. echo the source group key exactly in source and give the idea a short distinctive name.",
239 + "tools": ["read", "grep", "ls", "bash"],
240 + "model": "medium",
241 + "schema": "Candidate"
243 + },
245 + "id": "devil",
246 + "kind": "single",
247 + "step": {
248 + "summary": "adversarially select one reflection proposal",
249 + "prompt": "act as adversarial final judge for these source-owned candidate ideas: {analyze.results}. analyzer failures: {analyze.failures}. reflection focus: {args.focus}.\n\n- challenge recurrence, causality, impact, novelty, scope, maintenance cost, and evidence quality\n- compare the independently sourced ideas and detect duplicated, already-solved, overly broad, or weakly supported proposals\n- pick the strongest available idea and improve its proposal\n- name every supplied idea exactly once in a short ideas list\n- mark the picked idea with ✓ followed by two spaces\n- mark each rejected idea with ✗ followed by two spaces and one short reason\n- never invent evidence or claim independent verification\n- keep the whole report terse and human-readable, not a structured field dump\n- begin with one line shaped as an icon, two spaces, a concise action, scope, kind, and @path\n- choose the icon, action, scope, kind, and path language that best fits the proposal; do not use a fixed taxonomy\n- use that same opening action line without its icon as the terse choice value\n- follow the report opening with one sentence describing the proposal\n- use tasteful icons with two spaces of padding for compact section labels\n- give at most three short why bullets, five evidence bullets, and three caveat bullets\n- include minimal current and expected mermaid diagrams\n- do not include a status, acceptance check, process recap, raw candidate dump, or rigid key-value layout\n- output markdown only inside the report field\n\nreturn FinalReport with choice and report.",
250 + "model": "huge",
251 + "schema": "FinalReport"
254 + ],
255 + "return": "{devil.results[].choice}",
256 + "report": "{devil.results[].report}"