pi-pstack-workflow-kit 0.1.0 → 0.1.1

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.
Files changed (120) hide show
  1. package/README.md +33 -9
  2. package/lib/catalog.ts +53 -4
  3. package/lib/models.ts +10 -9
  4. package/lib/pool.ts +4 -6
  5. package/lib/state.ts +24 -24
  6. package/lib/transcript.ts +19 -15
  7. package/package.json +17 -20
  8. package/reference/PARITY.md +1 -1
  9. package/scripts/job-input.ts +38 -39
  10. package/scripts/run-job.mjs +9 -7
  11. package/skills/architect/SKILL.md +1 -1
  12. package/skills/arena/SKILL.md +1 -1
  13. package/skills/automate-me/SKILL.md +1 -1
  14. package/skills/benchmark-checklist/SKILL.md +1 -1
  15. package/skills/blast-radius/SKILL.md +1 -1
  16. package/skills/bro/SKILL.md +1 -1
  17. package/skills/check-compiler-errors/SKILL.md +1 -1
  18. package/skills/control-cli/SKILL.md +1 -1
  19. package/skills/control-ui/SKILL.md +1 -1
  20. package/skills/correct/SKILL.md +1 -1
  21. package/skills/create-formal-verification-skill/SKILL.md +1 -1
  22. package/skills/create-verification-skill/SKILL.md +1 -1
  23. package/skills/deslop/SKILL.md +1 -1
  24. package/skills/figure-it-out/SKILL.md +1 -1
  25. package/skills/fix-ci/SKILL.md +1 -1
  26. package/skills/fix-merge-conflicts/SKILL.md +1 -1
  27. package/skills/get-pr-comments/SKILL.md +1 -1
  28. package/skills/how/SKILL.md +1 -1
  29. package/skills/in-your-own-words/SKILL.md +1 -1
  30. package/skills/interrogate/SKILL.md +1 -1
  31. package/skills/ketchup/SKILL.md +1 -1
  32. package/skills/ketchup-video/SKILL.md +1 -1
  33. package/skills/loop-on-ci/SKILL.md +1 -1
  34. package/skills/maintain-formal-verification-skill/SKILL.md +1 -1
  35. package/skills/maintain-verification-skill/SKILL.md +1 -1
  36. package/skills/make-bot-ui/SKILL.md +1 -1
  37. package/skills/make-pr-easy-to-review/SKILL.md +1 -1
  38. package/skills/new-branch-and-pr/SKILL.md +1 -1
  39. package/skills/no-comments/SKILL.md +1 -1
  40. package/skills/poteto-help/SKILL.md +1 -1
  41. package/skills/poteto-mode/SKILL.md +1 -1
  42. package/skills/poteto-mode/playbooks/authoring-a-skill.md +1 -1
  43. package/skills/poteto-mode/playbooks/autonomous-run.md +1 -1
  44. package/skills/poteto-mode/playbooks/autopilot-full.md +1 -1
  45. package/skills/poteto-mode/playbooks/autopilot-stack.md +1 -1
  46. package/skills/poteto-mode/playbooks/babysit.md +1 -1
  47. package/skills/poteto-mode/playbooks/bug-fix.md +1 -1
  48. package/skills/poteto-mode/playbooks/eval.md +1 -1
  49. package/skills/poteto-mode/playbooks/feature.md +1 -1
  50. package/skills/poteto-mode/playbooks/hillclimb.md +1 -1
  51. package/skills/poteto-mode/playbooks/investigation.md +1 -1
  52. package/skills/poteto-mode/playbooks/multi-phase-plan.md +1 -1
  53. package/skills/poteto-mode/playbooks/opening-a-pr.md +1 -1
  54. package/skills/poteto-mode/playbooks/pause-safely.md +1 -1
  55. package/skills/poteto-mode/playbooks/perf-issue.md +1 -1
  56. package/skills/poteto-mode/playbooks/prototype.md +1 -1
  57. package/skills/poteto-mode/playbooks/refactoring.md +1 -1
  58. package/skills/poteto-mode/playbooks/runtime-forensics.md +1 -1
  59. package/skills/poteto-mode/playbooks/session-pickup.md +1 -1
  60. package/skills/poteto-mode/playbooks/shipping.md +1 -1
  61. package/skills/poteto-mode/playbooks/trace-forensics.md +1 -1
  62. package/skills/poteto-mode/playbooks/visual-parity.md +1 -1
  63. package/skills/poteto-mode/playbooks/worktree-cleanup.md +1 -1
  64. package/skills/pr-review-canvas/SKILL.md +1 -1
  65. package/skills/principle-attack-the-premise/SKILL.md +1 -1
  66. package/skills/principle-boundary-discipline/SKILL.md +1 -1
  67. package/skills/principle-build-the-lever/SKILL.md +1 -1
  68. package/skills/principle-encode-lessons-in-structure/SKILL.md +1 -1
  69. package/skills/principle-exhaust-the-design-space/SKILL.md +1 -1
  70. package/skills/principle-experience-first/SKILL.md +1 -1
  71. package/skills/principle-explain-the-number/SKILL.md +1 -1
  72. package/skills/principle-fix-root-causes/SKILL.md +1 -1
  73. package/skills/principle-foundational-thinking/SKILL.md +1 -1
  74. package/skills/principle-guard-the-context-window/SKILL.md +1 -1
  75. package/skills/principle-laziness-protocol/SKILL.md +1 -1
  76. package/skills/principle-make-operations-idempotent/SKILL.md +1 -1
  77. package/skills/principle-migrate-callers-then-delete-legacy-apis/SKILL.md +1 -1
  78. package/skills/principle-minimize-reader-load/SKILL.md +1 -1
  79. package/skills/principle-model-the-domain/SKILL.md +1 -1
  80. package/skills/principle-never-block-on-the-human/SKILL.md +1 -1
  81. package/skills/principle-outcome-oriented-execution/SKILL.md +1 -1
  82. package/skills/principle-prove-it-works/SKILL.md +1 -1
  83. package/skills/principle-redesign-from-first-principles/SKILL.md +1 -1
  84. package/skills/principle-separate-before-serializing-shared-state/SKILL.md +1 -1
  85. package/skills/principle-sequence-verifiable-units/SKILL.md +1 -1
  86. package/skills/principle-subtract-before-you-add/SKILL.md +1 -1
  87. package/skills/principle-test-behavior-not-implementation/SKILL.md +1 -1
  88. package/skills/principle-type-system-discipline/SKILL.md +1 -1
  89. package/skills/recall/SKILL.md +1 -1
  90. package/skills/reflect/SKILL.md +1 -1
  91. package/skills/review-and-ship/SKILL.md +1 -1
  92. package/skills/run-smoke-tests/SKILL.md +1 -1
  93. package/skills/setup-pstack/SKILL.md +1 -1
  94. package/skills/sharpen/SKILL.md +1 -1
  95. package/skills/show-me-your-work/SKILL.md +1 -1
  96. package/skills/statechart/SKILL.md +1 -1
  97. package/skills/swarm/SKILL.md +1 -1
  98. package/skills/tdd/SKILL.md +1 -1
  99. package/skills/teach/SKILL.md +1 -1
  100. package/skills/technical-writing/SKILL.md +1 -1
  101. package/skills/thermo-nuclear-code-quality-review/SKILL.md +1 -1
  102. package/skills/typescript-best-practices/SKILL.md +1 -1
  103. package/skills/unslop/SKILL.md +1 -1
  104. package/skills/verify-this/SKILL.md +1 -1
  105. package/skills/weekly-review/SKILL.md +1 -1
  106. package/skills/what-did-i-get-done/SKILL.md +1 -1
  107. package/skills/why/SKILL.md +1 -1
  108. package/skills/workflow-from-chats/SKILL.md +1 -1
  109. package/{extensions → src}/catalog-ui.ts +2 -2
  110. package/{extensions → src}/delegate.ts +40 -30
  111. package/{extensions → src}/forge.ts +18 -17
  112. package/{extensions → src}/git.ts +6 -1
  113. package/{extensions → src}/models.ts +87 -13
  114. package/{extensions → src}/parent-diff.ts +4 -3
  115. package/{extensions → src}/plan.ts +3 -3
  116. package/{extensions → src}/records.ts +8 -4
  117. package/{extensions → src}/support.ts +3 -2
  118. package/{extensions → src}/worktrees.ts +3 -3
  119. package/{extensions → src}/index.ts +0 -0
  120. package/{extensions → src}/session.ts +1 -1
package/README.md CHANGED
@@ -60,9 +60,9 @@ The package registers 52 original slash-skill names (34 ordinary pstack and 18 T
60
60
 
61
61
  ## Configuration and workers
62
62
 
63
- `/setup-pstack` uses Pi's model registry and native selection dialogs. Nine role selections and the reasoning budget are saved atomically at `$PI_CODING_AGENT_DIR/pstack-models.json`, default `~/.pi/agent/pstack-models.json`. The file uses a `defaults: 3` marker. The parent model remains unchanged. Cursor-specific model slugs do not map reliably to Pi provider IDs, so unconfigured roles inherit the parent; explicitly choose available `provider/id` models. The picker lists models in the current scope and excludes providers registered by extensions. Both `auto` and `inherit-parent` resolve to the current parent model; setup warns if workers cannot use it. Delegation checks availability only for the workers and judge selected for that run. For arena and interrogate configure at least two panel seats. Arena uses the first available judge in the configured pool whose vendor differs from the parent and every candidate. Pi itself may clamp reasoning to model support. The `large`, `medium`, `small` budgets lower the role's reasoning target; the Gemini panel seat uses its higher target where selected.
63
+ `/setup-pstack` uses Pi's model registry and native selection dialogs. Nine role selections and the reasoning budget are saved atomically at `$PI_CODING_AGENT_DIR/pstack-models.json`, default `~/.pi/agent/pstack-models.json`. The file uses a `defaults: 3` marker. The parent model remains unchanged. Cursor-specific model slugs do not map reliably to Pi provider IDs, so unconfigured roles inherit the parent; explicitly choose available `provider/id` models. The picker lists the models in the current scope that workers can load. It includes a model of a provider registered by an extension when pstack finds that extension: pstack runs `pi --list-models` once per loaded extension that registers a slash command and uses the one that lists the model. Such a model stays excluded when its extension registers no slash command, or when Pi lists the provider without the extension, as it does for one that replaces a built-in provider. Both `auto` and `inherit-parent` resolve to the current parent model; setup warns if workers cannot use it. Delegation checks availability only for the workers and judge selected for that run. For arena and interrogate configure at least two panel seats. Arena uses the first available judge in the configured pool whose vendor differs from the parent and every candidate. Pi itself may clamp reasoning to model support. The `large`, `medium`, `small` budgets lower the role's reasoning target; the Gemini panel seat uses its higher target where selected.
64
64
 
65
- Each delegate starts a fresh Pi CLI process via `pi.exec`. `PSTACK_PI_BIN` can select the Pi binary. Concurrency is bounded to eight workers, with default three concurrent workers. Each job retains its report and native JSONL session. Only bounded output excerpts return to the parent. Read-only reviewers receive only Pi's read/grep/find/ls tools; no shell, write, edit, MCP or discovered extensions. Write delegates require explicit confirmation in the terminal UI or via Pi RPC and get separate detached Git worktrees at the selected committed ref (default HEAD). Uncommitted parent files are not copied automatically; the parent saves a repository-root-relative patch of up to 2 MiB. If tracked changes alone exceed the limit, no patch is attached. Otherwise, untracked, non-ignored files are added as whole patches while space remains, and workers are told which files were omitted. The parent inspects, reconciles and verifies worker output. Workers never automatically merge, cherry-pick, or delete worktrees. Worktrees are isolation of checkout state, not an OS security sandbox. Child processes inherit the OS environment and cannot use provider registrations supplied exclusively by disabled extensions; delegation refuses such models before starting any worker. Use a real external sandbox for untrusted code or secrets.
65
+ Each delegate starts a fresh Pi CLI process via `pi.exec`. `PSTACK_PI_BIN` can select the Pi binary. Concurrency is bounded to eight workers, with default three concurrent workers. Each job retains its report and native JSONL session. Only bounded output excerpts return to the parent. Read-only reviewers receive only Pi's read/grep/find/ls tools; no shell, write, edit, MCP or discovered extensions. Write delegates require explicit confirmation in the terminal UI or via Pi RPC and get separate detached Git worktrees at the selected committed ref (default HEAD). Uncommitted parent files are not copied automatically; the parent saves a repository-root-relative patch of up to 2 MiB. If tracked changes alone exceed the limit, no patch is attached. Otherwise, untracked, non-ignored files are added as whole patches while space remains, and workers are told which files were omitted. The parent inspects, reconciles and verifies worker output. Workers never automatically merge, cherry-pick, or delete worktrees. Worktrees are isolation of checkout state, not an OS security sandbox. Child processes inherit the OS environment. A worker whose model comes from a provider registered by an extension also loads that extension. Its code runs in the worker with the trust it has in the parent session; the tool allowlist still limits what the model can call. Delegation refuses a model whose extension it cannot find before starting any worker. Use a real external sandbox for untrusted code or secrets.
66
66
 
67
67
  Arena stores candidate sessions, removes model metadata and known model names from message projections, asks the independent judge to read the actual projected transcripts, and audits read tool calls. This is partial blinding: transcript text, tool paths or outputs can still identify an author; a read call alone cannot prove the judge read every line. It does not claim a fully controlled evaluation environment. If judging fails, the tool returns an inconclusive judgment alongside the completed candidate reports and their artifact directory.
68
68
 
@@ -84,27 +84,51 @@ Run the development checks from a source checkout:
84
84
 
85
85
  ```sh
86
86
  bun install --frozen-lockfile
87
- bun run check:ci
88
- bun run smoke
87
+ bun run check
88
+ python3 scripts/generate.py --check
89
+ node scripts/smoke.ts
89
90
  ```
90
91
 
91
- `check:ci` checks that generated files match their sources, then runs lint, format checks, the TypeScript compiler against the installed Pi SDK, and the Node test suite with an 80% gate for line, branch, and function coverage. Use `bun run check` to run the same checks with the local TSRS compiler, or `bun run test` to run only the tests. The suite uses a mock Pi host and forge, a fake child CLI for job dispatch, and temporary real Git repositories.
92
+ `bun run check` runs the `bun fmt` format check, type-aware oxlint, the TypeScript compiler against the installed Pi SDK, and the tests with the coverage gate. `bun run format` and `bun run lint:fix` apply the fixes. The formatter skips the three configuration files listed in `.prettierignore`, which are kept exactly as written. `python3 scripts/generate.py --check` reports generated files that no longer match their sources.
92
93
 
93
- `smoke` launches real Pi in an isolated RPC session without model requests. It checks discovery of all 76 native skills and 52 original slash names, then writes and reads mode state. Set `PSTACK_PI_BIN` to point to a different Pi executable. This smoke does not exercise live models, GitHub, Slack, or MCP services. Test those integrations with disposable resources before relying on them.
94
+ The tests are TypeScript on Vitest and run without a build step. `bun run test` runs them once and `bun run test:watch` reruns them as files change. They use a mock Pi host and forge, a fake child CLI for job dispatch, and temporary real Git repositories. `bun run test:coverage` also applies the gate in `vitest.config.ts`: each file in `src/` needs 80% statement, branch, function and line coverage.
95
+
96
+ `node scripts/smoke.ts` launches real Pi in an isolated RPC session without model requests. It checks discovery of all 76 native skills and 52 original slash names, writes and reads mode state, and checks that `/setup-pstack` lists the model of a provider registered by a fixture extension. Set `PSTACK_PI_BIN` to point to a different Pi executable. This smoke does not exercise live models, GitHub, Slack, or MCP services. Test those integrations with disposable resources before relying on them.
97
+
98
+ ## Continuous integration and releases
99
+
100
+ Three workflows in `.github/workflows` run on GitHub-hosted runners:
101
+
102
+ - `ci.yml` runs on every pull request. The `Lint` job runs the format check, oxlint, the TypeScript compiler and the generator check. The `Test` jobs run the tests with the coverage gate and the smoke test on Node 22.19.0, 24 and 26. The smoke test uses the Pi that `bun install` puts in `node_modules`.
103
+ - `release.yml` runs on every push to `main`. It runs the same checks, then compares `version` in `package.json` with npm. If npm does not have that version, the workflow publishes the package with provenance, then creates the tag `v<version>` and its GitHub release, with generated notes, at the published commit. Runs of this workflow do not overlap: up to 100 wait in a queue.
104
+ - `verify-lockfile.yml` runs on pull requests and on pushes to `main`. It fails when `.github/workflows/actions.lock` no longer matches the workflows or the commits it pins.
105
+
106
+ To release, change `version` in `package.json` in a pull request and merge it. Do not create the tag or the release by hand. The workflow never touches an existing tag, and it stops before publishing when the tag exists and npm does not have the version. npm refuses a prerelease version such as `1.0.0-beta.1` without a dist-tag, so the workflow cannot publish one.
107
+
108
+ If a run fails after npm accepted the version, use **Re-run all jobs**. While `package.json` still names that version, a run finds it on npm, skips publishing and creates the missing tag and release at the commit npm recorded for it. It creates neither when the tag already exists, or when npm recorded no commit, which is the case for a version published outside a Git checkout.
109
+
110
+ Publishing needs an npm [trusted publisher](https://docs.npmjs.com/trusted-publishers) for this repository, with the workflow `release.yml`, the environment `npm`, and `npm publish` allowed. No secret is involved. The workflow also accepts an npm access token in a [secret](https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/use-secrets) named `NPM_TOKEN`, which is the method in GitHub's documentation, but npm removes direct publishing with a token in January 2027.
111
+
112
+ The first release run creates the `npm` [environment](https://docs.github.com/en/actions/how-tos/deploy/configure-and-manage-deployments/manage-environments) without rules. Add a deployment branch rule for `main` so that no other branch can publish.
113
+
114
+ `actions.lock` pins every action the workflows use to a commit. After you add or change a `uses:` line, run `gh actions-lock` and commit the result. The command comes from the [`gh-actions-lock`](https://github.com/github/gh-actions-lock) extension of the GitHub CLI. Dependabot proposes new releases of the actions each week and updates the lockfile in the same pull request.
115
+
116
+ CI installs Bun 1.4.5, the release the files were formatted with. Change `BUN_VERSION` in `ci.yml` when you format with a newer Bun.
94
117
 
95
118
  ## Files
96
119
 
97
- - `extensions/`: one file per feature: `session.ts` (branch state and wake timer), `plan.ts`, `catalog-ui.ts`, `records.ts`, `models.ts`, `delegate.ts`, `parent-diff.ts`, `worktrees.ts`, `forge.ts`, with `git.ts` and `support.ts` shared.
120
+ - `src/`: the extension, one file per feature: `session.ts` (branch state and wake timer), `plan.ts`, `catalog-ui.ts`, `records.ts`, `models.ts`, `delegate.ts`, `parent-diff.ts`, `worktrees.ts`, `forge.ts`, with `git.ts` and `support.ts` shared.
98
121
  - `lib/`: type-checked TypeScript with no Pi dependency: `catalog.ts`, `models.ts`, `state.ts`, `pool.ts`, `transcript.ts`, `jobs.ts`, `validation.ts`.
99
122
  - `scripts/catalog-source.json`: the instructions written for Pi: playbook steps, principle rules, skill bodies and implementation classifications. Edit this, not the generated files.
100
- - `scripts/generate.py`: `bun run generate` rebuilds `skills/`, `lib/catalog-data.json`, `reference/parity.json` and `reference/PARITY.md` from the source map and `catalog-source.json`. Regeneration removes obsolete generator-marked skill and playbook files, not hand-authored files. `bun run check:generated` reports drift without writing.
123
+ - `scripts/generate.py`: `python3 scripts/generate.py` rebuilds `skills/`, `lib/catalog-data.json`, `reference/parity.json` and `reference/PARITY.md` from the source map and `catalog-source.json`, and formats them with `bun fmt`. Regeneration removes obsolete generator-marked skill and playbook files, not hand-authored files. With `--check` it reports drift without writing.
101
124
  - `skills/`: 76 native skill directories and 22 nested ordered playbooks (generated).
102
125
  - `agents/`: worker and reviewer contracts.
103
126
  - `reference/source-map.json`: original attachment, unchanged byte-for-byte.
104
127
  - `reference/parity.json` (generated): machine-readable original IDs, edges and views with implementation classifications.
105
128
  - `reference/PARITY.md`, `reference/GAPS.md`: audit matrix and residual gaps.
106
129
  - `reference/benny/`: dormant configuration and workflow instructions.
107
- - `scripts/run-job.mjs`, `scripts/job-input.ts`, `scripts/smoke.mjs`, `tests/`: runner, job validation and verification.
130
+ - `scripts/run-job.mjs`, `scripts/job-input.ts`, `scripts/smoke.ts`, `scripts/smoke-provider.ts`, `tests/`: runner, job validation and verification.
131
+ - `.github/`: the CI, release and lockfile workflows, the action lockfile and the Dependabot configuration.
108
132
 
109
133
  ## Official references
110
134
 
package/lib/catalog.ts CHANGED
@@ -2,6 +2,8 @@ import { readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
 
5
+ import { isRecord, parseJson } from "./validation.ts";
6
+
5
7
  export interface NodeRecord {
6
8
  id: string;
7
9
  label: string;
@@ -39,10 +41,52 @@ interface Catalog {
39
41
  implementations: Record<string, [classification: string, implementation: string]>;
40
42
  }
41
43
 
44
+ const isText = (value: unknown): value is string => typeof value === "string";
45
+ const isTexts = (value: unknown): value is string[] => Array.isArray(value) && value.every(isText);
46
+ const hasText = (value: unknown, ...keys: string[]): value is Record<string, unknown> =>
47
+ isRecord(value) && keys.every((key) => isText(value[key]));
48
+ const isRecordOf = <T>(
49
+ value: unknown,
50
+ isItem: (item: unknown) => item is T,
51
+ ): value is Record<string, T> => isRecord(value) && Object.values(value).every(isItem);
52
+
53
+ const isEdge = (value: unknown): value is Edge =>
54
+ hasText(value, "id", "from", "to", "label", "when", "kind");
55
+ const isNode = (value: unknown): value is NodeRecord =>
56
+ hasText(value, "id", "label", "kind", "what", "when", "how") &&
57
+ isTexts(value["source"]) &&
58
+ (value["opensView"] === undefined || isText(value["opensView"]));
59
+ const isView = (value: unknown): value is MapView =>
60
+ hasText(value, "id", "title", "caption") &&
61
+ (value["parent"] === null || isText(value["parent"])) &&
62
+ isTexts(value["nodeIds"]) &&
63
+ Array.isArray(value["edges"]) &&
64
+ value["edges"].every((edge) => isText(edge) || isEdge(edge));
65
+ const isSourceMap = (value: unknown): value is SourceMap =>
66
+ isRecord(value) &&
67
+ Array.isArray(value["nodes"]) &&
68
+ value["nodes"].every(isNode) &&
69
+ Array.isArray(value["edges"]) &&
70
+ value["edges"].every(isEdge) &&
71
+ Array.isArray(value["views"]) &&
72
+ value["views"].every(isView);
73
+ const isMapping = (value: unknown): value is Catalog["implementations"][string] =>
74
+ isTexts(value) && value.length === 2;
75
+ const isCatalog = (value: unknown): value is Catalog =>
76
+ isRecord(value) &&
77
+ isRecordOf(value["paths"], isText) &&
78
+ isRecordOf(value["steps"], isTexts) &&
79
+ isRecordOf(value["implementations"], isMapping);
80
+
42
81
  export const root = fileURLToPath(new URL("../", import.meta.url));
43
82
  export const packageFile = (path: string) => readFileSync(join(root, path), "utf8");
44
- export const map: SourceMap = JSON.parse(packageFile("reference/source-map.json"));
45
- export const catalog: Catalog = JSON.parse(packageFile("lib/catalog-data.json"));
83
+ function packageData<T>(path: string, isValid: (value: unknown) => value is T): T {
84
+ const value = parseJson(packageFile(path), path);
85
+ if (!isValid(value)) throw Error(`Invalid ${path}`);
86
+ return value;
87
+ }
88
+ export const map = packageData("reference/source-map.json", isSourceMap);
89
+ export const catalog = packageData("lib/catalog-data.json", isCatalog);
46
90
  export const nodes = new Map(map.nodes.map((n) => [n.id, n]));
47
91
  export const views = new Map(map.views.map((v) => [v.id, v]));
48
92
  const edges = new Map(map.edges.map((e) => [e.id, e]));
@@ -60,11 +104,16 @@ function known(id: string) {
60
104
  if (!n) throw Error(`Unknown node: ${id}`);
61
105
  return n;
62
106
  }
107
+ function mapping(id: string) {
108
+ const entry = catalog.implementations[id];
109
+ if (!entry) throw Error(`Unmapped node: ${id}`);
110
+ return entry;
111
+ }
63
112
  export const routeTriggers = () => routes.map((id) => ({ id, when: known("pb-" + id).when }));
64
113
 
65
114
  export function nativeNode(id: string) {
66
115
  const n = known(id);
67
- const [classification, implementation] = catalog.implementations[id];
116
+ const [classification, implementation] = mapping(id);
68
117
  const path = catalog.paths[id];
69
118
  return {
70
119
  id,
@@ -96,7 +145,7 @@ export function view(id: string) {
96
145
  nodes: v.nodeIds.map((n) => ({
97
146
  id: n,
98
147
  label: known(n).label,
99
- implementation: catalog.implementations[n][1],
148
+ implementation: mapping(n)[1],
100
149
  })),
101
150
  edges: v.edges.map((e) => edges.get(typeof e === "string" ? e : e.id)),
102
151
  };
package/lib/models.ts CHANGED
@@ -39,7 +39,7 @@ const baseEffort = (role: Role): Effort =>
39
39
  panelRoles.has(role) || role === "swarm workers" ? "high" : "xhigh";
40
40
  export function effort(role: Role, budget: Budget, model = ""): Effort {
41
41
  const target = panelRoles.has(role) && /gemini/i.test(model) ? "xhigh" : baseEffort(role);
42
- return levels[Math.max(0, levels.indexOf(target) - budgets.indexOf(budget))];
42
+ return levels[Math.max(0, levels.indexOf(target) - budgets.indexOf(budget))] ?? target;
43
43
  }
44
44
 
45
45
  function assertSelections(
@@ -56,7 +56,7 @@ function assertSelections(
56
56
  values.some((v) => typeof v !== "string" || !v.trim())
57
57
  )
58
58
  throw Error(`Invalid selection for ${r}`);
59
- if (r === judgeRole && values.some((v) => aliases.includes(v)))
59
+ if (r === judgeRole && values.some((v) => typeof v === "string" && aliases.includes(v)))
60
60
  throw Error("Judge pool requires explicit models");
61
61
  }
62
62
  }
@@ -64,13 +64,13 @@ function assertSelections(
64
64
  export function parseModelConfig(config: unknown): RoleConfig {
65
65
  if (
66
66
  !isRecord(config) ||
67
- config.defaults !== 3 ||
68
- !isBudget(config.budget) ||
69
- !isRecord(config.roles)
67
+ config["defaults"] !== 3 ||
68
+ !isBudget(config["budget"]) ||
69
+ !isRecord(config["roles"])
70
70
  )
71
71
  throw Error("Invalid model configuration");
72
- assertSelections(config.roles);
73
- return { defaults: config.defaults, budget: config.budget, roles: config.roles };
72
+ assertSelections(config["roles"]);
73
+ return { defaults: config["defaults"], budget: config["budget"], roles: config["roles"] };
74
74
  }
75
75
  export function defaultConfig(): RoleConfig {
76
76
  return parseModelConfig({
@@ -80,7 +80,7 @@ export function defaultConfig(): RoleConfig {
80
80
  });
81
81
  }
82
82
  export function applyConfigPatch(config: RoleConfig, patch: unknown): RoleConfig {
83
- const selections = isRecord(patch) && "roles" in patch ? patch.roles : {};
83
+ const selections = isRecord(patch) && "roles" in patch ? patch["roles"] : {};
84
84
  if (!isRecord(patch) || !isRecord(selections)) throw Error("Invalid model configuration patch");
85
85
  return parseModelConfig({ ...config, ...patch, roles: { ...config.roles, ...selections } });
86
86
  }
@@ -120,5 +120,6 @@ export function selectPanel(config: RoleConfig, role: Role, count: number) {
120
120
  throw Error("Worker count must be 1 to 8");
121
121
  const choices = config.roles[role];
122
122
  if (!choices.length) throw Error(`No models configured for ${role}`);
123
- return Array.from({ length: count }, (_, i) => choices[i % choices.length]);
123
+ const rounds = Array.from({ length: Math.ceil(count / choices.length) }, () => choices);
124
+ return rounds.flat().slice(0, count);
124
125
  }
package/lib/pool.ts CHANGED
@@ -1,8 +1,7 @@
1
1
  import { errorMessage } from "./validation.ts";
2
2
 
3
3
  export type PoolResult<T> =
4
- | { status: "fulfilled"; value: T }
5
- | { status: "rejected"; reason: string };
4
+ { status: "fulfilled"; value: T } | { status: "rejected"; reason: string };
6
5
 
7
6
  export async function pool<T, U>(
8
7
  items: readonly T[],
@@ -12,13 +11,12 @@ export async function pool<T, U>(
12
11
  if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 8)
13
12
  throw Error("Concurrency must be 1 to 8");
14
13
  const results: PoolResult<U>[] = [];
15
- let cursor = 0;
14
+ const queue = items.entries();
16
15
  async function worker() {
17
- while (cursor < items.length) {
18
- const i = cursor++;
16
+ for (const [i, item] of queue) {
19
17
  try {
20
18
  // oxlint-disable-next-line eslint/no-await-in-loop -- One item at a time per worker.
21
- results[i] = { status: "fulfilled", value: await fn(items[i], i) };
19
+ results[i] = { status: "fulfilled", value: await fn(item, i) };
22
20
  } catch (error) {
23
21
  results[i] = { status: "rejected", reason: errorMessage(error) };
24
22
  }
package/lib/state.ts CHANGED
@@ -45,45 +45,45 @@ export const isTaskStatus = (status: unknown): status is TaskStatus =>
45
45
  const optionalText = (value: unknown) => value === undefined || typeof value === "string";
46
46
  const isTask = (task: unknown, i: number): task is Task =>
47
47
  isRecord(task) &&
48
- task.id === i + 1 &&
49
- typeof task.text === "string" &&
50
- isTaskStatus(task.status) &&
51
- typeof task.evidence === "string";
48
+ task["id"] === i + 1 &&
49
+ typeof task["text"] === "string" &&
50
+ isTaskStatus(task["status"]) &&
51
+ typeof task["evidence"] === "string";
52
52
  const isPlan = (plan: unknown): plan is Plan =>
53
53
  isRecord(plan) &&
54
- typeof plan.route === "string" &&
55
- typeof plan.goal === "string" &&
56
- Array.isArray(plan.tasks) &&
57
- plan.tasks.length > 0 &&
58
- plan.tasks.every(isTask) &&
59
- optionalText(plan.finishedEvidence);
54
+ typeof plan["route"] === "string" &&
55
+ typeof plan["goal"] === "string" &&
56
+ Array.isArray(plan["tasks"]) &&
57
+ plan["tasks"].length > 0 &&
58
+ plan["tasks"].every(isTask) &&
59
+ optionalText(plan["finishedEvidence"]);
60
60
  const inRange = (value: unknown, min: number, max: number): value is number =>
61
61
  typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
62
62
  const isWake = (wake: unknown): wake is Wake =>
63
63
  isRecord(wake) &&
64
- inRange(wake.seconds, 5, 86400) &&
65
- inRange(wake.max, 1, 100) &&
66
- inRange(wake.count, 0, wake.max) &&
67
- typeof wake.predicate === "string" &&
68
- typeof wake.running === "boolean" &&
69
- optionalText(wake.stopEvidence);
64
+ inRange(wake["seconds"], 5, 86400) &&
65
+ inRange(wake["max"], 1, 100) &&
66
+ inRange(wake["count"], 0, wake["max"]) &&
67
+ typeof wake["predicate"] === "string" &&
68
+ typeof wake["running"] === "boolean" &&
69
+ optionalText(wake["stopEvidence"]);
70
70
  const isState = (state: unknown): state is State =>
71
71
  isRecord(state) &&
72
- state.version === 1 &&
73
- typeof state.mode === "boolean" &&
74
- typeof state.goal === "string" &&
75
- (state.plan === null || isPlan(state.plan)) &&
76
- (state.wake === null || isWake(state.wake));
72
+ state["version"] === 1 &&
73
+ typeof state["mode"] === "boolean" &&
74
+ typeof state["goal"] === "string" &&
75
+ (state["plan"] === null || isPlan(state["plan"])) &&
76
+ (state["wake"] === null || isWake(state["wake"]));
77
77
 
78
78
  export const stateType = "pstack-state";
79
79
  export const stopped = (wake: Wake | null, stopEvidence?: string): Wake | null =>
80
80
  wake && { ...wake, running: false, ...(stopEvidence === undefined ? {} : { stopEvidence }) };
81
81
  export function restore(entries: readonly unknown[]): State {
82
82
  const saved = entries.findLast(
83
- (entry) => isRecord(entry) && entry.type === "custom" && entry.customType === stateType,
83
+ (entry) => isRecord(entry) && entry["type"] === "custom" && entry["customType"] === stateType,
84
84
  );
85
- if (!isRecord(saved) || !isState(saved.data)) return initialState();
86
- const state = structuredClone(saved.data);
85
+ if (!isRecord(saved) || !isState(saved["data"])) return initialState();
86
+ const state = structuredClone(saved["data"]);
87
87
  return { ...state, wake: stopped(state.wake) };
88
88
  }
89
89
 
package/lib/transcript.ts CHANGED
@@ -6,18 +6,20 @@ function sessionMessages(raw: string) {
6
6
  .filter(Boolean)
7
7
  .map((line): unknown => JSON.parse(line))
8
8
  .flatMap((entry) =>
9
- isRecord(entry) && entry.type === "message" && isRecord(entry.message) ? [entry.message] : [],
9
+ isRecord(entry) && entry["type"] === "message" && isRecord(entry["message"])
10
+ ? [entry["message"]]
11
+ : [],
10
12
  );
11
13
  }
12
14
  export function blindTranscript(raw: string, model: string) {
13
15
  return sessionMessages(raw)
14
16
  .map((m) =>
15
17
  JSON.stringify({
16
- role: m.role,
17
- content: m.content,
18
- toolName: m.toolName,
19
- toolCallId: m.toolCallId,
20
- isError: m.isError,
18
+ role: m["role"],
19
+ content: m["content"],
20
+ toolName: m["toolName"],
21
+ toolCallId: m["toolCallId"],
22
+ isError: m["isError"],
21
23
  })
22
24
  .replaceAll(model, "[redacted-model]")
23
25
  .replaceAll(model.split("/").slice(1).join("/"), "[redacted-model]"),
@@ -28,17 +30,19 @@ export function readPaths(raw: string) {
28
30
  const messages = sessionMessages(raw);
29
31
  const succeeded = new Set(
30
32
  messages
31
- .filter((m) => m.role === "toolResult" && m.isError !== true && m.toolCallId)
32
- .map((m) => m.toolCallId),
33
+ .filter((m) => m["role"] === "toolResult" && m["isError"] !== true && m["toolCallId"])
34
+ .map((m) => m["toolCallId"]),
33
35
  );
34
36
  const readPath = (call: unknown) =>
35
37
  isRecord(call) &&
36
- call.type === "toolCall" &&
37
- call.name === "read" &&
38
- isRecord(call.arguments) &&
39
- typeof call.arguments.path === "string" &&
40
- succeeded.has(call.id)
41
- ? [call.arguments.path]
38
+ call["type"] === "toolCall" &&
39
+ call["name"] === "read" &&
40
+ isRecord(call["arguments"]) &&
41
+ typeof call["arguments"]["path"] === "string" &&
42
+ succeeded.has(call["id"])
43
+ ? [call["arguments"]["path"]]
42
44
  : [];
43
- return messages.flatMap((m) => (Array.isArray(m.content) ? m.content.flatMap(readPath) : []));
45
+ return messages.flatMap((m) =>
46
+ Array.isArray(m["content"]) ? m["content"].flatMap(readPath) : [],
47
+ );
44
48
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-pstack-workflow-kit",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Map-driven pstack and Team Kit workflows for Pi",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -16,12 +16,12 @@
16
16
  },
17
17
  "files": [
18
18
  "agents",
19
- "extensions",
20
19
  "lib",
21
20
  "reference",
22
21
  "scripts/job-input.ts",
23
22
  "scripts/run-job.mjs",
24
- "skills"
23
+ "skills",
24
+ "src"
25
25
  ],
26
26
  "type": "module",
27
27
  "publishConfig": {
@@ -29,27 +29,24 @@
29
29
  "registry": "https://registry.npmjs.org/"
30
30
  },
31
31
  "scripts": {
32
+ "format": "bun fmt",
33
+ "format:check": "bun fmt --check",
32
34
  "lint": "oxlint",
33
35
  "lint:fix": "oxlint --fix",
34
- "format": "oxfmt",
35
- "format:check": "oxfmt --check",
36
- "generate": "python3 scripts/generate.py",
37
- "check:generated": "python3 scripts/generate.py --check",
38
- "typecheck": "tsrs --noEmit",
39
- "typecheck:fast": "tsrs --noEmit --fast",
40
- "typecheck:ci": "tsc --noEmit",
41
- "test": "node --test tests/*.test.mjs",
42
- "test:coverage": "node --test --experimental-test-coverage --test-coverage-lines=80 --test-coverage-branches=80 --test-coverage-functions=80 --test-coverage-include='extensions/**' --test-coverage-include='lib/**' --test-coverage-include='scripts/run-job.mjs' --test-coverage-include='scripts/job-input.ts' tests/*.test.mjs",
43
- "smoke": "node scripts/smoke.mjs",
44
- "check": "bun run check:generated && oxlint && oxfmt --check && tsrs --noEmit && bun run test:coverage",
45
- "check:ci": "bun run check:generated && oxlint && oxfmt --check && tsc --noEmit && bun run test:coverage"
36
+ "typecheck": "tsc --noEmit",
37
+ "test": "vitest run",
38
+ "test:watch": "vitest",
39
+ "test:coverage": "vitest run --coverage",
40
+ "check": "bun run format:check && bun run lint && bun run typecheck && bun run test:coverage"
46
41
  },
47
42
  "devDependencies": {
48
- "@types/node": "22.20.5",
49
- "oxfmt": "0.80.0",
50
- "oxlint": "1.95.0",
43
+ "@types/node": "22",
44
+ "@vitest/coverage-v8": "^5.1.1",
45
+ "oxlint": "^1.95.0",
46
+ "oxlint-tsgolint": "^7.0.2008",
51
47
  "tsrs": "7.1.0-beta.tsrs5",
52
- "typescript": "7.0.2"
48
+ "typescript": "6",
49
+ "vitest": "^5.1.1"
53
50
  },
54
51
  "peerDependencies": {
55
52
  "@earendil-works/pi-ai": "*",
@@ -61,7 +58,7 @@
61
58
  },
62
59
  "pi": {
63
60
  "extensions": [
64
- "extensions/index.ts"
61
+ "src/index.ts"
65
62
  ],
66
63
  "skills": [
67
64
  "skills"
@@ -166,4 +166,4 @@ Every original ID is mapped. Status is implementation classification, not behavi
166
166
  | `cli-persist` | navigation | /pstack-map cli-persist |
167
167
  | `cli-integrate` | navigation | /pstack-map cli-integrate |
168
168
 
169
- <!-- Generated by scripts/generate.py from scripts/catalog-source.json. Edit the source, then run `bun run generate`. -->
169
+ <!-- Generated by scripts/generate.py from scripts/catalog-source.json. Edit the source, then run `python3 scripts/generate.py`. -->
@@ -2,7 +2,7 @@ import { createHmac, timingSafeEqual } from "node:crypto";
2
2
  import { readFile } from "node:fs/promises";
3
3
  import { isAbsolute } from "node:path";
4
4
 
5
- import { isJobKind, type BennyKind } from "../lib/jobs.ts";
5
+ import { type BennyKind, isJobKind } from "../lib/jobs.ts";
6
6
  import { isRecord, parseJson } from "../lib/validation.ts";
7
7
 
8
8
  interface BennyConfig {
@@ -15,12 +15,11 @@ interface JobBase {
15
15
  cwd: string;
16
16
  instructions: string;
17
17
  tools: string[];
18
- model?: string;
19
- thinking?: string;
18
+ model?: string | undefined;
19
+ thinking?: string | undefined;
20
20
  }
21
21
  export type Job =
22
- | (JobBase & { kind: "custom" })
23
- | (JobBase & { kind: BennyKind; config: BennyConfig });
22
+ (JobBase & { kind: "custom" }) | (JobBase & { kind: BennyKind; config: BennyConfig });
24
23
  export interface JobEvent {
25
24
  channel: string;
26
25
  thread: string;
@@ -38,7 +37,7 @@ const isToolList = (value: unknown): value is string[] =>
38
37
  Array.isArray(value) &&
39
38
  value.length > 0 &&
40
39
  value.every((t) => typeof t === "string" && /^[a-zA-Z0-9_][a-zA-Z0-9_-]*$/.test(t));
41
- const isMcp = (name: string) => name.startsWith("mcp__");
40
+ export const isMcp = (name: string) => name.startsWith("mcp__");
42
41
 
43
42
  const words = (name: string) =>
44
43
  name
@@ -93,12 +92,12 @@ function forbidden(tool: string) {
93
92
  function bennyConfig(kind: BennyKind, tools: string[], cfg: unknown): BennyConfig {
94
93
  if (
95
94
  !isRecord(cfg) ||
96
- cfg.enabled !== true ||
97
- !hasText(cfg.slackChannel) ||
95
+ cfg["enabled"] !== true ||
96
+ !hasText(cfg["slackChannel"]) ||
98
97
  requiredConfig.some((key) => !hasText(cfg[key])) ||
99
- !optionalModel(cfg.triageModel) ||
100
- !optionalModel(cfg.reproModel) ||
101
- (cfg.allowDraftPr !== undefined && typeof cfg.allowDraftPr !== "boolean")
98
+ !optionalModel(cfg["triageModel"]) ||
99
+ !optionalModel(cfg["reproModel"]) ||
100
+ (cfg["allowDraftPr"] !== undefined && typeof cfg["allowDraftPr"] !== "boolean")
102
101
  )
103
102
  throw Error("Benny configuration is incomplete or disabled");
104
103
  if (!tools.some(isMcp)) throw Error("Benny requires explicit scoped MCP tool names");
@@ -110,10 +109,10 @@ function bennyConfig(kind: BennyKind, tools: string[], cfg: unknown): BennyConfi
110
109
  throw Error(
111
110
  "Benny disallows general command execution and merge/push/deploy/delete or repository-write tools; configure narrowly scoped MCP tools instead",
112
111
  );
113
- const draftPr = kind === "benny-repro" && cfg.allowDraftPr === true;
112
+ const draftPr = kind === "benny-repro" && cfg["allowDraftPr"] === true;
114
113
  if (!draftPr && tools.some((t) => hasPair(words(t), writeVerbs, prObjects)))
115
114
  throw Error("Benny pull request tools require benny-repro with allowDraftPr");
116
- return { ...cfg, slackChannel: cfg.slackChannel };
115
+ return { ...cfg, slackChannel: cfg["slackChannel"] };
117
116
  }
118
117
 
119
118
  export function configuredModel(job: Job): string | undefined {
@@ -125,16 +124,16 @@ export async function readJob(path: string): Promise<Job> {
125
124
  const job = parseJson(await readFile(path, "utf8"), "job file");
126
125
  if (
127
126
  !isRecord(job) ||
128
- job.version !== 1 ||
129
- job.enabled !== true ||
130
- typeof job.cwd !== "string" ||
131
- !isAbsolute(job.cwd) ||
132
- !isJobKind(job.kind) ||
133
- !hasText(job.instructions) ||
134
- !isToolList(job.tools) ||
135
- !optionalModel(job.model) ||
136
- (job.thinking !== undefined &&
137
- (typeof job.thinking !== "string" || !thinkingLevels.has(job.thinking)))
127
+ job["version"] !== 1 ||
128
+ job["enabled"] !== true ||
129
+ typeof job["cwd"] !== "string" ||
130
+ !isAbsolute(job["cwd"]) ||
131
+ !isJobKind(job["kind"]) ||
132
+ !hasText(job["instructions"]) ||
133
+ !isToolList(job["tools"]) ||
134
+ !optionalModel(job["model"]) ||
135
+ (job["thinking"] !== undefined &&
136
+ (typeof job["thinking"] !== "string" || !thinkingLevels.has(job["thinking"])))
138
137
  ) {
139
138
  throw Error(
140
139
  "Job must be reviewed, enabled, and specify an absolute cwd, explicit tool allowlist, and valid model options",
@@ -144,7 +143,7 @@ export async function readJob(path: string): Promise<Job> {
144
143
  const base = { ...job, cwd, instructions, tools, model, thinking };
145
144
  return kind === "custom"
146
145
  ? { ...base, kind }
147
- : { ...base, kind, config: bennyConfig(kind, tools, job.config) };
146
+ : { ...base, kind, config: bennyConfig(kind, tools, job["config"]) };
148
147
  }
149
148
 
150
149
  export async function readEvent(
@@ -158,32 +157,32 @@ export async function readEvent(
158
157
  const envelope = parseJson(await readFile(path, "utf8"), "event envelope");
159
158
  if (
160
159
  !isRecord(envelope) ||
161
- typeof envelope.payload !== "string" ||
162
- typeof envelope.signature !== "string" ||
163
- !/^[0-9a-f]{64}$/i.test(envelope.signature)
160
+ typeof envelope["payload"] !== "string" ||
161
+ typeof envelope["signature"] !== "string" ||
162
+ !/^[0-9a-f]{64}$/i.test(envelope["signature"])
164
163
  )
165
164
  throw Error("Invalid signed event envelope");
166
- const expected = createHmac("sha256", secret).update(envelope.payload).digest();
167
- if (!timingSafeEqual(expected, Buffer.from(envelope.signature, "hex")))
165
+ const expected = createHmac("sha256", secret).update(envelope["payload"]).digest();
166
+ if (!timingSafeEqual(expected, Buffer.from(envelope["signature"], "hex")))
168
167
  throw Error("Event signature rejected");
169
- const event = parseJson(envelope.payload, "signed event payload");
168
+ const event = parseJson(envelope["payload"], "signed event payload");
170
169
  if (
171
170
  !isRecord(event) ||
172
- !hasText(event.channel) ||
173
- event.channel !== job.config.slackChannel ||
174
- !hasText(event.thread) ||
175
- !hasText(event.eventId)
171
+ !hasText(event["channel"]) ||
172
+ event["channel"] !== job.config.slackChannel ||
173
+ !hasText(event["thread"]) ||
174
+ !hasText(event["eventId"])
176
175
  )
177
176
  throw Error("Event does not match configured immutable thread coordinates");
178
- if (job.kind === "benny-triage" && (event.type !== "report" || event.topLevel !== true)) {
177
+ if (job.kind === "benny-triage" && (event["type"] !== "report" || event["topLevel"] !== true)) {
179
178
  throw Error("Expected a top-level report");
180
179
  }
181
180
  if (
182
181
  job.kind === "benny-repro" &&
183
- (event.type !== "triage-marker" ||
184
- (event.classification !== "bug" && event.classification !== "performance") ||
185
- event.trusted !== true ||
186
- !hasText(event.ticket))
182
+ (event["type"] !== "triage-marker" ||
183
+ (event["classification"] !== "bug" && event["classification"] !== "performance") ||
184
+ event["trusted"] !== true ||
185
+ !hasText(event["ticket"]))
187
186
  )
188
187
  throw Error("Expected authenticated confirmed triage marker");
189
188
  const { channel, thread, eventId } = event;