@oyasmi/pipiclaw 0.9.2-beta.1 → 0.9.2-beta.3

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 (51) hide show
  1. package/dist/agent/channel-runner.d.ts +13 -0
  2. package/dist/agent/channel-runner.js +67 -19
  3. package/dist/agent/job-manager.js +3 -0
  4. package/dist/playbooks/agent-delegation.md +1 -1
  5. package/dist/playbooks/task-driving.md +3 -3
  6. package/dist/runtime/bootstrap.js +29 -7
  7. package/dist/runtime/channel-event.d.ts +8 -0
  8. package/dist/runtime/subagent-commands.d.ts +8 -0
  9. package/dist/runtime/subagent-commands.js +28 -4
  10. package/dist/runtime/task-commands.js +7 -2
  11. package/dist/runtime/task-wake.d.ts +7 -2
  12. package/dist/runtime/task-wake.js +22 -3
  13. package/dist/settings.d.ts +12 -0
  14. package/dist/settings.js +9 -0
  15. package/dist/subagents/external/claude-code.js +20 -0
  16. package/dist/subagents/external/codex-cli.js +33 -0
  17. package/dist/subagents/external/harness.d.ts +8 -0
  18. package/dist/subagents/external/progress-tail.d.ts +14 -0
  19. package/dist/subagents/external/progress-tail.js +84 -0
  20. package/dist/subagents/external/run.d.ts +6 -0
  21. package/dist/subagents/external/run.js +123 -58
  22. package/dist/subagents/external/settlement.d.ts +7 -1
  23. package/dist/subagents/external/settlement.js +28 -7
  24. package/dist/subagents/runs.d.ts +80 -8
  25. package/dist/subagents/runs.js +260 -58
  26. package/dist/subagents/tool.d.ts +4 -5
  27. package/dist/subagents/tool.js +73 -40
  28. package/dist/subagents/verification-outcome.js +1 -1
  29. package/dist/tasks/artifact-subject.d.ts +38 -4
  30. package/dist/tasks/artifact-subject.js +282 -25
  31. package/dist/tasks/verification.d.ts +24 -2
  32. package/dist/tasks/verification.js +113 -21
  33. package/dist/tools/grep.js +4 -1
  34. package/dist/tools/subagent-manage.js +14 -14
  35. package/dist/tools/task-manage/lifecycle.js +7 -4
  36. package/dist/tools/task-manage/verification.d.ts +1 -1
  37. package/dist/tools/task-manage/verification.js +12 -7
  38. package/dist/tui/pitui-frontend.js +3 -3
  39. package/examples/sub-agents/README.md +14 -13
  40. package/examples/sub-agents/builder-hard.md +17 -16
  41. package/examples/sub-agents/builder.md +16 -12
  42. package/examples/sub-agents/documenter.md +17 -17
  43. package/examples/sub-agents/explorer.md +12 -13
  44. package/examples/sub-agents/git-committer.md +15 -26
  45. package/examples/sub-agents/log-sifter.md +13 -12
  46. package/examples/sub-agents/planner.md +11 -11
  47. package/examples/sub-agents/reviewer.md +21 -12
  48. package/examples/sub-agents/scout.md +16 -12
  49. package/examples/sub-agents/verifier.md +18 -13
  50. package/examples/sub-agents/worker.md +17 -10
  51. package/package.json +5 -5
@@ -156,12 +156,11 @@ declare function buildSubagentTools(executor: Executor, bashTimeoutSec: number,
156
156
  /** Shared by both runtimes' task envelopes and `subagent_run`'s verify follow-up (spec 040, D9). */
157
157
  export declare function buildVerificationProtocol(taskPath: string): string;
158
158
  /**
159
- * D9 verify admission — a role that admits it writes cannot also be the checker, `exec` has no
160
- * protocol terminal to prove it even ran to completion, and a target with an active write lease
161
- * is refused up front (cheaper than explaining afterward why the attestation would be worthless).
159
+ * D9 verify admission — `exec` has no protocol terminal to prove it even ran to completion, and a
160
+ * target with an active write lease is refused up front. A write-capable verifier is allowed: it
161
+ * takes the same exclusive lease as a work writer and receives an advisory attestation.
162
162
  * Spec 042 D7: exported so `subagent_run op=follow_up` runs the exact same checks the initial
163
- * dispatch does — before this function existed, follow_up on a role that had since been hot-edited
164
- * to `mutates: write` would silently take the write lease and dispatch instead of refusing.
163
+ * dispatch does, including the remaining `exec` restriction.
165
164
  */
166
165
  export declare function assertVerifyAdmissible(config: Pick<ResolvedSubAgentConfig, "name" | "mutates" | "runtime" | "harness">, purpose: "work" | "verify", workingDirectory: string): void;
167
166
  /**
@@ -1,4 +1,4 @@
1
- import { existsSync, realpathSync, statSync } from "node:fs";
1
+ import { realpathSync, statSync } from "node:fs";
2
2
  import { mkdir } from "node:fs/promises";
3
3
  import { join, resolve } from "node:path";
4
4
  import { Agent } from "@earendil-works/pi-agent-core";
@@ -16,7 +16,7 @@ import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.
16
16
  import { RecoverableToolError } from "../shared/recoverable-error.js";
17
17
  import { clipText, errorMessage, extractAssistantText } from "../shared/text-utils.js";
18
18
  import { createEmptyUsageTotals } from "../shared/types.js";
19
- import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
19
+ import { workspaceSubjectHash, workspaceSubjectSnapshot } from "../tasks/artifact-subject.js";
20
20
  import { readStoredTask } from "../tasks/store.js";
21
21
  import { writeVerificationAttestation } from "../tasks/verification.js";
22
22
  import { describeToolCall } from "../tools/presentation.js";
@@ -31,7 +31,7 @@ const workingDirectoryField = Type.Optional(Type.String({
31
31
  description: "Optional existing directory to run the sub-agent in (its shell cwd and relative-path root). Use it to work on another checkout — e.g. a `git worktree add`ed one. Defaults to this runtime's own working directory.",
32
32
  }));
33
33
  const purposeField = Type.Optional(Type.Union([Type.Literal("work"), Type.Literal("verify")], {
34
- description: 'Use "verify" for an independent, read-only task acceptance check.',
34
+ description: 'Use "verify" for an independent task acceptance check. A write-capable verifier may run tests/builds; its attestation is advisory.',
35
35
  }));
36
36
  const taskIdField = Type.Optional(Type.String({ description: "Persistent task id, required when purpose=verify." }));
37
37
  /**
@@ -170,16 +170,25 @@ export function assertWithinProjectBoundary(target, base, requested) {
170
170
  function resolveRunWorkingDirectory(requested, options) {
171
171
  const base = resolve(options.workingDirectory ?? process.cwd());
172
172
  const trimmed = requested?.trim();
173
+ // Resolve the project root once as well. Returning an alias here would leave the later lease,
174
+ // executor, subject hash, and external cwd exposed to a symlink swap after admission.
175
+ const canonicalBase = realpathOrSelf(base);
173
176
  if (!trimmed)
174
- return base;
175
- const target = resolve(base, trimmed);
176
- if (!existsSync(target) || !statSync(target).isDirectory()) {
177
+ return canonicalBase;
178
+ const target = resolve(canonicalBase, trimmed);
179
+ let canonicalTarget;
180
+ try {
181
+ canonicalTarget = realpathSync(target);
182
+ if (!statSync(canonicalTarget).isDirectory())
183
+ throw new Error("not a directory");
184
+ }
185
+ catch {
177
186
  throw new RecoverableToolError(`workingDirectory "${requested}" is not an existing directory.`);
178
187
  }
179
188
  if (options.projectBoundary === "project") {
180
- assertWithinProjectBoundary(target, base, requested ?? trimmed);
189
+ assertWithinProjectBoundary(canonicalTarget, canonicalBase, requested ?? trimmed);
181
190
  }
182
- return target;
191
+ return canonicalTarget;
183
192
  }
184
193
  async function prepareRunContext(runId, params, options) {
185
194
  const purpose = params.purpose ?? "work";
@@ -311,25 +320,23 @@ export function buildVerificationProtocol(taskPath) {
311
320
  return [
312
321
  "Verification protocol:",
313
322
  `- Independently inspect ${taskPath} and verify every DoD/Verification item against concrete evidence.`,
314
- "- You are the checker, not the maker. Do not edit files or fix failures; report them.",
323
+ "- You are the checker, not the maker. Do not modify the implementation or fix failures to make a check pass; report them.",
324
+ "- You may run npm tests/builds and other deterministic checks. Newly created outputs under recognized transient artifact paths (for example .run/, coverage/, build/, dist/ or caches) are allowed, but do not change tracked files or pre-existing untracked product files.",
325
+ "- This verification is advisory when the verifier can write or use bash: runtime cannot structurally prove that every write was harmless. Review the diff and evidence before trusting PASS.",
315
326
  "- Run deterministic checks when available and distinguish observed evidence from assumptions.",
316
327
  "- End the response with exactly one final line: VERDICT: PASS or VERDICT: FAIL.",
317
328
  ].join("\n");
318
329
  }
319
330
  /**
320
- * D9 verify admission — a role that admits it writes cannot also be the checker, `exec` has no
321
- * protocol terminal to prove it even ran to completion, and a target with an active write lease
322
- * is refused up front (cheaper than explaining afterward why the attestation would be worthless).
331
+ * D9 verify admission — `exec` has no protocol terminal to prove it even ran to completion, and a
332
+ * target with an active write lease is refused up front. A write-capable verifier is allowed: it
333
+ * takes the same exclusive lease as a work writer and receives an advisory attestation.
323
334
  * Spec 042 D7: exported so `subagent_run op=follow_up` runs the exact same checks the initial
324
- * dispatch does — before this function existed, follow_up on a role that had since been hot-edited
325
- * to `mutates: write` would silently take the write lease and dispatch instead of refusing.
335
+ * dispatch does, including the remaining `exec` restriction.
326
336
  */
327
337
  export function assertVerifyAdmissible(config, purpose, workingDirectory) {
328
338
  if (purpose !== "verify")
329
339
  return;
330
- if (config.mutates === "write") {
331
- throw new RecoverableToolError(`Sub-agent "${config.name}" declares mutates: write and cannot be used for purpose=verify.`);
332
- }
333
340
  if (config.runtime === "external" && config.harness === "exec") {
334
341
  throw new RecoverableToolError(`Sub-agent "${config.name}" uses the exec harness, which has no protocol terminal and cannot be used for purpose=verify.`);
335
342
  }
@@ -506,11 +513,11 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
506
513
  // with `subagent_run op=follow_up` (spec 042 D7) so a verify run's admission rules
507
514
  // cannot drift between the two dispatch paths.
508
515
  assertVerifyAdmissible(config, runContext.purpose, runContext.workingDirectory);
509
- // Admission: a write-mutating run takes an exclusive workspace lease before it is even
510
- // registered (spec 040, D10.1) — a rejected delegation should never count as "started".
511
- // Read runs and purpose=verify never take one. Shared by both runtimes.
516
+ // Admission: every write-mutating run, including a write-capable verifier, takes an exclusive
517
+ // workspace lease before it is even registered (spec 040, D10.1). A rejected delegation should
518
+ // never count as "started"; the lease is handed to SubAgentRunManager as the settlement owner.
512
519
  let leaseKey;
513
- if (config.mutates === "write" && runContext.purpose !== "verify") {
520
+ if (config.mutates === "write") {
514
521
  const lease = acquireWorkspaceLease({
515
522
  runId: runContext.runId,
516
523
  channelId: options.runtimeContext.channelId,
@@ -615,11 +622,12 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
615
622
  let failureReason;
616
623
  /** Set alongside failureReason only for the three self-inflicted budget aborts, distinct from an explicit cancel. */
617
624
  let budgetExceeded = false;
618
- /** Set only by the `subagent_run op=cancel` handle registered below — a real stop, unlike a budget abort. */
625
+ /** Set only by the `subagent_run op=cancel` handle registered as soon as the run is durable. */
619
626
  let externallyCancelled = false;
620
627
  /** True once the sync grace window has elapsed and a "still running" placeholder has been returned. */
621
628
  let detached = false;
622
629
  let lastUpdateText = "";
630
+ let worker;
623
631
  try {
624
632
  await runManager.register({
625
633
  runId: runContext.runId,
@@ -635,6 +643,7 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
635
643
  workingDirectory: runContext.workingDirectory,
636
644
  artifactDir: runContext.artifactDir,
637
645
  leaseKey,
646
+ mutates: config.mutates,
638
647
  });
639
648
  }
640
649
  catch (error) {
@@ -643,6 +652,14 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
643
652
  releaseWorkspaceLease(leaseKey, runContext.runId);
644
653
  throw error;
645
654
  }
655
+ // Install the cancel handle before any setup I/O (tool construction, Git snapshots, worker
656
+ // creation) can yield. Without this provisional handle, a cancel in that window was treated as
657
+ // an unreachable run: the manager released the lease and settled it while the worker could still
658
+ // start writing after the supposed cancellation (especially dangerous for a write verifier).
659
+ runManager.registerCancelHandle(runContext.runId, () => {
660
+ externallyCancelled = true;
661
+ worker?.abort();
662
+ });
646
663
  const emitUpdate = (text) => {
647
664
  // Once detached, execute() has already returned to the SDK; nothing is listening
648
665
  // for further progress on this (from its view, finished) tool call.
@@ -658,16 +675,21 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
658
675
  details: createDetails(config, runContext, usage, assistantTurns, toolCalls, Date.now() - startedAt, Boolean(failureReason), failureReason),
659
676
  });
660
677
  };
661
- let worker;
662
678
  let wallClockTimer;
663
679
  let unsubscribe;
664
680
  let verifierGitStateBefore;
665
681
  let verifierSubjectBefore;
682
+ let verifierSubjectBaseCommit;
683
+ let verifierSubjectBaselineUntrackedPaths;
666
684
  try {
667
685
  const availableTools = (options.buildTools ?? buildSubagentTools)(scopedExecutor, config.bashTimeoutSec, options, runContext);
668
686
  verifierGitStateBefore = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
669
- verifierSubjectBefore =
670
- runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
687
+ if (runContext.purpose === "verify") {
688
+ const subjectSnapshot = await workspaceSubjectSnapshot(runContext.workingDirectory);
689
+ verifierSubjectBefore = subjectSnapshot?.hash;
690
+ verifierSubjectBaseCommit = subjectSnapshot?.baseCommit;
691
+ verifierSubjectBaselineUntrackedPaths = subjectSnapshot?.baselineUntrackedPaths;
692
+ }
671
693
  worker =
672
694
  options.createWorker?.({
673
695
  subAgent: config,
@@ -690,10 +712,6 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
690
712
  getApiKey: async () => apiKey,
691
713
  streamFn: streamSimple,
692
714
  });
693
- runManager.registerCancelHandle(runContext.runId, () => {
694
- externallyCancelled = true;
695
- worker?.abort();
696
- });
697
715
  wallClockTimer = setTimeout(() => {
698
716
  failureReason = `Wall time budget exceeded (${config.maxWallTimeSec}s)`;
699
717
  budgetExceeded = true;
@@ -779,8 +797,13 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
779
797
  log.logWarning(`[${options.runtimeContext.channelId}] Sub-agent context injection failed; continuing without it`, errorMessage(error));
780
798
  return [];
781
799
  });
782
- await activeWorker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext));
783
- await activeWorker.waitForIdle();
800
+ if (externallyCancelled) {
801
+ failureReason = failureReason || "Cancelled by request.";
802
+ }
803
+ else {
804
+ await activeWorker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext));
805
+ await activeWorker.waitForIdle();
806
+ }
784
807
  // D6: a self-inflicted budget abort gets one tool-free turn to converge on a
785
808
  // conclusion instead of discarding the work outright. An explicit cancel skips
786
809
  // this — the model asked this run to stop now, not to wrap up.
@@ -828,7 +851,14 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
828
851
  ? lastAssistantMessage.errorMessage || `Sub-agent stopped with ${lastAssistantMessage.stopReason}`
829
852
  : undefined);
830
853
  const verifierGitStateAfter = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
831
- const verifierSubjectAfter = runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
854
+ const verifierSubjectAfter = runContext.purpose === "verify"
855
+ ? await workspaceSubjectHash(runContext.workingDirectory, verifierSubjectBaseCommit
856
+ ? {
857
+ baseCommit: verifierSubjectBaseCommit,
858
+ baselineUntrackedPaths: verifierSubjectBaselineUntrackedPaths,
859
+ }
860
+ : {})
861
+ : undefined;
832
862
  // Spec 042 D1: the pass/fail judgment rule is shared with the external verify path
833
863
  // (`resolveVerificationOutcome`) so there is exactly one place deciding what a verify
834
864
  // run's own output does and does not prove. Only the attestation write and the
@@ -847,14 +877,14 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
847
877
  const verificationVerdict = verification?.verdict;
848
878
  // Internal verify always keeps write/edit structurally removed from the verifier's
849
879
  // tool set (buildSubagentTools above), but `bash` stays available by default and can
850
- // write files just as well — labeling that "enforced" would be dishonest (review
851
- // 2026-08-23 §2.2). Only a role that dropped `bash` from its declared tool list earns
852
- // the stronger label. Computed once so the attestation and the run record — the
880
+ // write files just as well. A role that declares mutates: write is advisory even when
881
+ // its effective tool list happens not to contain bash: the declaration says this run is
882
+ // not structurally read-only. Computed once so the attestation and run record — the
853
883
  // latter is what the completion wake and `subagent_list` display — cannot disagree.
854
- const internalVerificationStrength = config.tools.includes("bash")
855
- ? "advisory"
856
- : "enforced";
884
+ const internalVerificationStrength = config.mutates === "write" || config.tools.includes("bash") ? "advisory" : "enforced";
857
885
  if (runContext.purpose === "verify" && runContext.taskId && verification) {
886
+ const baseSubjectAvailable = verifierSubjectBaseCommit !== undefined && verifierSubjectBaselineUntrackedPaths !== undefined;
887
+ const subjectAvailable = !verification.workspaceChanged && verifierSubjectAfter !== undefined && baseSubjectAvailable;
858
888
  await writeVerificationAttestation(options.channelDir, {
859
889
  runId: runContext.runId,
860
890
  taskId: runContext.taskId,
@@ -862,8 +892,11 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
862
892
  checkedAt: formatLocalTime(),
863
893
  evidence: verification.evidence,
864
894
  workspaceChanged: verification.workspaceChanged,
865
- subjectHash: verification.workspaceChanged ? undefined : verifierSubjectAfter,
866
- subjectDir: runContext.workingDirectory,
895
+ subjectHash: subjectAvailable ? verifierSubjectAfter : undefined,
896
+ subjectDir: subjectAvailable ? runContext.workingDirectory : undefined,
897
+ subjectMode: subjectAvailable ? "base-relative" : undefined,
898
+ subjectBaseCommit: subjectAvailable ? verifierSubjectBaseCommit : undefined,
899
+ subjectBaselineUntrackedPaths: subjectAvailable ? verifierSubjectBaselineUntrackedPaths : undefined,
867
900
  verificationStrength: internalVerificationStrength,
868
901
  });
869
902
  }
@@ -15,7 +15,7 @@ export function resolveVerificationOutcome(input) {
15
15
  const evidence = !comparable
16
16
  ? "Could not determine whether the workspace changed (not a Git checkout, or `git status` failed); refusing to record a PASS without that evidence."
17
17
  : workspaceChanged
18
- ? "Verifier changed tracked workspace files; the attestation is invalid."
18
+ ? "Verifier changed protected workspace content; the attestation is invalid."
19
19
  : !declaredVerdict
20
20
  ? "Verifier did not emit the required final VERDICT marker."
21
21
  : input.finalText.trim().slice(0, 8_000);
@@ -1,6 +1,40 @@
1
1
  /**
2
- * A compact, deterministic description of the code/artifact subject a verifier
3
- * observed. It intentionally uses only Git's own view, keeping verification
4
- * cheap and understandable for a local coding runtime.
2
+ * The legacy subject has HEAD plus separate staged/unstaged diffs in its input. It remains the
3
+ * default so attestations written before the base-relative subject was introduced can still be
4
+ * read and compared without silently changing their meaning.
5
5
  */
6
- export declare function workspaceSubjectHash(workingDirectory: string): Promise<string | undefined>;
6
+ export interface WorkspaceSubjectHashOptions {
7
+ /** Compare the checkout's current content to this commit, not to its current HEAD. */
8
+ baseCommit?: string;
9
+ /** Untracked paths, plus ignored non-transient paths, that existed when the subject was captured. */
10
+ baselineUntrackedPaths?: readonly string[];
11
+ }
12
+ /** The metadata a new purpose=verify run persists for a base-relative subject. */
13
+ export interface WorkspaceSubjectSnapshot {
14
+ hash: string;
15
+ baseCommit: string;
16
+ baselineUntrackedPaths: string[];
17
+ }
18
+ /** Exposed for focused tests and documentation that needs to describe the artifact scope. */
19
+ export declare function isTransientUntrackedPath(relativePath: string): boolean;
20
+ /**
21
+ * P2-2: a plain-language "what changed" line for a completion wake, so the agent that reads it
22
+ * does not have to spend its own first tool call finding out. `git status --porcelain` only — not
23
+ * a full subject hash — since this is a convenience for the reader, not a verification input.
24
+ * Returns `undefined` on any failure (not a git repo, `git` unavailable) or when nothing changed;
25
+ * a caller with nothing to show should simply omit the line.
26
+ */
27
+ export declare function changedPathsSummary(workingDirectory: string, limit?: number): Promise<string | undefined>;
28
+ /**
29
+ * Capture the base-relative subject and the untracked manifest needed to compare it after a test
30
+ * or build. The snapshot is deliberately a single new mode; callers that need legacy semantics
31
+ * should continue using `workspaceSubjectHash()` without options.
32
+ */
33
+ export declare function workspaceSubjectSnapshot(workingDirectory: string): Promise<WorkspaceSubjectSnapshot | undefined>;
34
+ /**
35
+ * A compact, deterministic description of the code/artifact subject a verifier observed. Without
36
+ * options this retains the original HEAD + staged/unstaged + all-untracked behavior for old
37
+ * attestations. With `baseCommit`, it compares the current checkout's content relative to that
38
+ * fixed commit so committing the already-verified content does not invalidate the attestation.
39
+ */
40
+ export declare function workspaceSubjectHash(workingDirectory: string, options?: WorkspaceSubjectHashOptions): Promise<string | undefined>;