vouchington-tooling 0.41.0 → 0.43.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.
Files changed (65) hide show
  1. package/bin/policy-runner.mjs +26 -0
  2. package/dist/agent-blackboard/feedback-codec.d.mts +1 -0
  3. package/dist/agent-blackboard/feedback-codec.mjs +1 -1
  4. package/dist/cli/usage.d.mts +1 -1
  5. package/dist/cli/usage.mjs +3 -1
  6. package/dist/gh-cli/pr-create.d.mts +2 -0
  7. package/dist/gh-cli/pr-create.mjs +5 -1
  8. package/dist/mcp-server/context.d.mts +22 -2
  9. package/dist/mcp-server/context.mjs +14 -1
  10. package/dist/mcp-server/dispatch.d.mts +11 -0
  11. package/dist/mcp-server/dispatch.mjs +12 -0
  12. package/dist/mcp-server/handlers-journal.d.mts +14 -1
  13. package/dist/mcp-server/handlers-journal.mjs +14 -9
  14. package/dist/mcp-server/handlers-pr.d.mts +4 -0
  15. package/dist/mcp-server/handlers-pr.mjs +143 -0
  16. package/dist/mcp-server/handlers-retrospective.d.mts +12 -0
  17. package/dist/mcp-server/handlers-retrospective.mjs +154 -0
  18. package/dist/mcp-server/harness.test-helpers.d.mts +10 -1
  19. package/dist/mcp-server/harness.test-helpers.mjs +4 -1
  20. package/dist/mcp-server/journal-read.d.mts +9 -0
  21. package/dist/mcp-server/journal-read.mjs +33 -0
  22. package/dist/mcp-server/policy-config.d.mts +6 -0
  23. package/dist/mcp-server/policy-config.mjs +60 -0
  24. package/dist/mcp-server/policy-run.d.mts +40 -0
  25. package/dist/mcp-server/policy-run.mjs +116 -0
  26. package/dist/mcp-server/policy-spawn.d.mts +24 -0
  27. package/dist/mcp-server/policy-spawn.mjs +97 -0
  28. package/dist/mcp-server/pr-body-file.d.mts +4 -0
  29. package/dist/mcp-server/pr-body-file.mjs +22 -0
  30. package/dist/mcp-server/pr-body.d.mts +20 -0
  31. package/dist/mcp-server/pr-body.mjs +47 -0
  32. package/dist/mcp-server/pr-defaults.d.mts +16 -0
  33. package/dist/mcp-server/pr-defaults.mjs +35 -0
  34. package/dist/mcp-server/pr-gh.d.mts +16 -0
  35. package/dist/mcp-server/pr-gh.mjs +56 -0
  36. package/dist/mcp-server/pr-input.d.mts +26 -0
  37. package/dist/mcp-server/pr-input.mjs +62 -0
  38. package/dist/mcp-server/pr-journal.d.mts +12 -0
  39. package/dist/mcp-server/pr-journal.mjs +86 -0
  40. package/dist/mcp-server/pr-live.d.mts +24 -0
  41. package/dist/mcp-server/pr-live.mjs +49 -0
  42. package/dist/mcp-server/pr-tools.test-helpers.d.mts +54 -0
  43. package/dist/mcp-server/pr-tools.test-helpers.mjs +67 -0
  44. package/dist/mcp-server/retrospective-facts-input.d.mts +6 -0
  45. package/dist/mcp-server/retrospective-facts-input.mjs +25 -0
  46. package/dist/mcp-server/retrospective-front-matter.d.mts +22 -0
  47. package/dist/mcp-server/retrospective-front-matter.mjs +88 -0
  48. package/dist/mcp-server/retrospective-input.d.mts +29 -0
  49. package/dist/mcp-server/retrospective-input.mjs +145 -0
  50. package/dist/mcp-server/retrospective-resolve.d.mts +15 -0
  51. package/dist/mcp-server/retrospective-resolve.mjs +41 -0
  52. package/dist/mcp-server/tools-pr.d.mts +2 -0
  53. package/dist/mcp-server/tools-pr.mjs +69 -0
  54. package/dist/mcp-server/tools-retrospective.d.mts +2 -0
  55. package/dist/mcp-server/tools-retrospective.mjs +48 -0
  56. package/dist/mcp-server/tools-schema.d.mts +54 -0
  57. package/dist/mcp-server/tools-schema.mjs +70 -0
  58. package/dist/mcp-server/tools.d.mts +1 -18
  59. package/dist/mcp-server/tools.mjs +6 -70
  60. package/dist/mcp-server/worktree.d.mts +11 -4
  61. package/dist/mcp-server/worktree.mjs +31 -6
  62. package/docs/mcp-server.md +164 -16
  63. package/package.json +1 -1
  64. package/skills/pr-description/SKILL.md +8 -0
  65. package/skills/retrospective/SKILL.md +5 -2
@@ -0,0 +1,26 @@
1
+ // Runs one export of a consumer's policy module in this fresh process, so the MCP server never
2
+ // imports checkout code. argv[2] is the real path of the module. stdin is one JSON object,
3
+ // { policyVersion: 1, export, input }. stdout is one JSON object, { ok: true, result },
4
+ // { ok: true, skipped: true } when the module has no such export, or { ok: false, error }.
5
+ // Console output and direct stdout writes from the policy go to stderr so they cannot corrupt the
6
+ // reply.
7
+ import { readFileSync } from 'node:fs'
8
+ import { pathToFileURL } from 'node:url'
9
+
10
+ const writeReply = process.stdout.write.bind(process.stdout)
11
+ process.stdout.write = process.stderr.write.bind(process.stderr)
12
+ console.log = console.info = console.debug = console.error
13
+
14
+ async function run() {
15
+ const request = JSON.parse(readFileSync(0, 'utf8'))
16
+ if (request.policyVersion !== 1) throw new Error('unsupported policyVersion')
17
+ const policy = await import(pathToFileURL(process.argv[2]).href)
18
+ if (typeof policy[request.export] !== 'function') return { ok: true, skipped: true }
19
+ return { ok: true, result: await policy[request.export](request.input) }
20
+ }
21
+
22
+ const reply = await run().catch((error) => ({
23
+ ok: false,
24
+ error: String((error && error.stack) || error),
25
+ }))
26
+ writeReply(JSON.stringify(reply), () => process.exit(0))
@@ -1,5 +1,6 @@
1
1
  export { normalizeRepositories } from './feedback-fields.mts';
2
2
  import type { FeedbackEnvelope } from './feedback-types.mts';
3
+ export declare const FEEDBACK_MARKDOWN_MAX_BYTES = 12000;
3
4
  export declare function validateFeedbackEnvelope(value: unknown): asserts value is FeedbackEnvelope;
4
5
  export declare function redactFeedbackText(value: string, knownSensitiveValues?: string[]): string;
5
6
  /** Bytes by which the envelope exceeds its markdown or whole-envelope limit; 0 when it fits. */
@@ -2,7 +2,7 @@ import { normalizeRepositories, validateFeedbackText, validateFeedbackReferences
2
2
  export { normalizeRepositories } from "./feedback-fields.mjs";
3
3
  import { isCount, isObject } from "./snapshot-partition-guards.mjs";
4
4
  const FEEDBACK_MAX_BYTES = 16_384;
5
- const FEEDBACK_MARKDOWN_MAX_BYTES = 12_000;
5
+ export const FEEDBACK_MARKDOWN_MAX_BYTES = 12_000;
6
6
  const OUTCOMES = [
7
7
  'in-progress',
8
8
  'success',
@@ -1,4 +1,4 @@
1
- export declare const USAGE = "Usage: vouchington <command> [options]\n\nCommands:\n runner-port-policy Print or validate a runner port policy\n with-host-lock Run a command under a host-wide lock\n gha-runtime-audit Audit successful GitHub Actions job runtimes\n require-up-to-date Require HEAD to include a fetched remote branch\n gitleaks-directory-scan Scan a directory with Gitleaks\n ast-grep-examples Run AST-grep rule examples\n ast-grep-pack Print shipped unconditional AST-grep pack paths as JSON\n gha-workspace-policy Check GitHub Actions workspace safety policy\n gha-output Write a collision-safe multiline GITHUB_OUTPUT record\n gha-needs-results Fail if required GitHub Actions job results failed\n download-with-diagnostics Download a URL and report HTTP status on failure\n download-optional-run-artifacts Download optional artifacts from the current run\n host-pressure-diagnostics Print a bounded host memory/OOM/PSI snapshot\n allocate-browser-safe-ports Allocate Fetch-safe localhost ports\n diagnose-port-collision Capture bounded localhost port diagnostics\n prepare-trivy-db Download the Trivy vulnerability database\n gha-artifacts-cleanup Delete classified GitHub Actions artifacts\n http-origin Validate an optional HTTP(S) origin\n vitest-blob-manifest Stamp a vitest-blob-manifest:v1 identity file\n vitest-report-attempt Write or read a Vitest report-attempt marker\n prepare-vitest-reports Validate and select Vitest report JSON files\n pnpm-install Install a pnpm workspace with retry and release-age fail-fast\n check-cache-size Measure a path and decide whether to save a GHA cache\n make-shard-matrix Emit a [1..N] GitHub Actions shard matrix\n load-runner-env Overlay a runner env file onto GITHUB_ENV with injection guards\n clean-workspace Reset a persistent-runner workspace with a fork-PR trust gate\n install-github-release Download a checksum-verified GitHub Release binary\n run-with-timeout Run a command with GNU timeout or a Perl fallback\n lint-links Two-pass lychee: internal links fail, external warn\n materialize-pr-context Dump PR title/body/files/diff/comments and #N crawl\n wait-for-apt-locks Wait until apt/dpkg lock files are free\n install-playwright-chromium-arm64 Install Playwright Chromium from browsers.json\n ghcr-package-retention Delete old GHCR package versions past KEEP_MIN\n harness-admission-lane Compute a GITHUB_RUN_ID admission lane for fleet fan-out\n harness-assert-gates Fail if any named HARNESS_*_ENABLED gate is enabled\n gha-collaborator-trust Classify authors as write-access collaborators or not\n nuget-central-version Validate a Directory.Packages.props PackageVersion delta\n swift-semantic-equal Compare Swift sources ignoring comments and whitespace\n post-review Post one COMMENT review from a staged payload file\n stage-review-payload Validate a review payload file into a staging directory\n retrospective-transcript Format facts from Claude-compatible, Codex, or Grok transcripts\n link-skill Link one packaged skill into an explicit consumer directory\n retrospective-facts Gather immutable facts for a retrospective\n agent-blackboard Probe and journal an Agent Blackboard deployment\n mcp Serve the agent-blackboard journal tools over stdio (MCP)\n\nOptions:\n -h, --help Show this help\n -v, --version Print the package version\n\nrunner-port-policy\n (no args) Print the shipped policy as JSON\n --file <path> Validate and print a policy file\n --reserved <port> Print true if the port is reserved\n\nwith-host-lock\n --name <family>\n [--slots <n>]\n --timeout-seconds <n>\n [--command-timeout-seconds <n>]\n [--failure-diagnostics <absolute-script>]\n [--on-acquire-timeout fail|run-unlocked]\n -- <command> [args...]\n\ngha-runtime-audit\n [--repository owner/name] Default GITHUB_REPOSITORY\n [--branch main]\n [--median-threshold-floor <seconds>] Off unless set. Must be below the ceiling\n [--median-threshold-ceiling <seconds>] Default 360. Flags a five-sample median above this\n --pr-workflow <name|/regex/> Repeatable\n --push-workflow <name|/regex/> Repeatable\n\nrequire-up-to-date --remote <name> --branch <name>\ngitleaks-directory-scan --config <path> [--directory <path>]\nast-grep-examples --rules <directory> --config <path>\nast-grep-pack\ngha-workspace-policy [--root <directory>] [--workflow-directory <directory>] [--action-directory <directory>]\n\ngha-output <name>\ngha-needs-results [label]\ndownload-with-diagnostics <url> <destination> [-- curl-args...]\ndownload-optional-run-artifacts (--name <name>... | --pattern <pattern>) --dir <directory>\nhost-pressure-diagnostics\nallocate-browser-safe-ports <count> [--policy path] [--forbidden-ports path]\ndiagnose-port-collision [--ports \"2200 2216\"] [--output-dir PATH]\nprepare-trivy-db\ngha-artifacts-cleanup run --run-id <id> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\ngha-artifacts-cleanup sweep --older-than-hours <n> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\nhttp-origin [--field NAME] [value]\nvitest-blob-manifest <suite> [reports-directory]\nvitest-report-attempt <write DIRECTORY SUITE|read ROOT>\nprepare-vitest-reports [primary-directory] [fallback-directory] [output-directory]\npnpm-install --runner-lifecycle persistent|ephemeral|ephemeral-full --install-scripts true|false\ncheck-cache-size <path> <max-bytes> <label>\nmake-shard-matrix <total>\nload-runner-env\nclean-workspace\ninstall-github-release --repo owner/name --version X --asset 'name-{platform}.tar.gz' --bin name [--tag-prefix PREFIX] [--expected-sha256 SHA256] [--no-checksum] [--checksums-asset NAME] [--version-flag FLAG] [--bin-dir DIR]\nrun-with-timeout <timeout-seconds> <kill-after-seconds> <command...>\nlint-links [--offline] [--config PATH] [--glob PATTERN] [files...]\nmaterialize-pr-context\nwait-for-apt-locks\ninstall-playwright-chromium-arm64 [name:archive...]\nghcr-package-retention <url-encoded-package>...\nharness-admission-lane <lanes>\nharness-assert-gates <gate>...\ngha-collaborator-trust <owner/repo> [--allow-bot <login>]... < authors.json\nnuget-central-version <trusted-props> <candidate-props> <metadata-json> <output-props>\nswift-semantic-equal <base> <head> <file.swift>\npost-review\nstage-review-payload optional|required <source> <destination>\nretrospective-transcript [--session-id ID] [--jsonl PATH] [--projects-dir PATH] [--codex-sessions-dir PATH] [--grok-sessions-dir PATH]\nlink-skill <name> --source-root <skills-dir> --target-root <consumer-skills-dir> Link a packaged or repository-local skill\nretrospective-facts (--pr NUMBER | --branch NAME | --no-pr) [--repo OWNER/NAME] [--raw]\nagent-blackboard probe\nagent-blackboard journal append --mode interactive|autonomous --source-event-id ID --work-outcome OUTCOME --coverage-status STATUS --session-id UUID --agent NAME --version VERSION --file PATH --repository OWNER/NAME [--repository OWNER/NAME ...] [--parent-session-id UUID] [--timestamp ISO8601] [--coverage-source SOURCE,...] [--dropped-count N] [--outbox-directory PATH]\nagent-blackboard journal entries --session-id UUID\nagent-blackboard journal status --session-id UUID --outbox-directory PATH\nagent-blackboard journal flush --outbox-directory PATH [--session-id UUID]\nInteractive journal append requires --outbox-directory PATH.\nagent-blackboard journal is deprecated and being phased out: agents journal through the mcp server.\nagent-blackboard snapshot partition --snapshot PATH --checksum SHA256 --counts '{\"sessions\":N,\"entries\":N,\"records\":N,\"bytes\":N}'\nagent-blackboard snapshot cleanup [--snapshot PATH] [--partition-directory PATH --receipt JSON]\nmcp\n (no args) Serve journal_append, journal_entries, outbox_status, outbox_flush,\n session_ensure, snapshot_export, and session_archive over stdio.\n Needs the optional @modelcontextprotocol/sdk peer (and zod).\n Launch it from inside the repository's git worktree.\n";
1
+ export declare const USAGE = "Usage: vouchington <command> [options]\n\nCommands:\n runner-port-policy Print or validate a runner port policy\n with-host-lock Run a command under a host-wide lock\n gha-runtime-audit Audit successful GitHub Actions job runtimes\n require-up-to-date Require HEAD to include a fetched remote branch\n gitleaks-directory-scan Scan a directory with Gitleaks\n ast-grep-examples Run AST-grep rule examples\n ast-grep-pack Print shipped unconditional AST-grep pack paths as JSON\n gha-workspace-policy Check GitHub Actions workspace safety policy\n gha-output Write a collision-safe multiline GITHUB_OUTPUT record\n gha-needs-results Fail if required GitHub Actions job results failed\n download-with-diagnostics Download a URL and report HTTP status on failure\n download-optional-run-artifacts Download optional artifacts from the current run\n host-pressure-diagnostics Print a bounded host memory/OOM/PSI snapshot\n allocate-browser-safe-ports Allocate Fetch-safe localhost ports\n diagnose-port-collision Capture bounded localhost port diagnostics\n prepare-trivy-db Download the Trivy vulnerability database\n gha-artifacts-cleanup Delete classified GitHub Actions artifacts\n http-origin Validate an optional HTTP(S) origin\n vitest-blob-manifest Stamp a vitest-blob-manifest:v1 identity file\n vitest-report-attempt Write or read a Vitest report-attempt marker\n prepare-vitest-reports Validate and select Vitest report JSON files\n pnpm-install Install a pnpm workspace with retry and release-age fail-fast\n check-cache-size Measure a path and decide whether to save a GHA cache\n make-shard-matrix Emit a [1..N] GitHub Actions shard matrix\n load-runner-env Overlay a runner env file onto GITHUB_ENV with injection guards\n clean-workspace Reset a persistent-runner workspace with a fork-PR trust gate\n install-github-release Download a checksum-verified GitHub Release binary\n run-with-timeout Run a command with GNU timeout or a Perl fallback\n lint-links Two-pass lychee: internal links fail, external warn\n materialize-pr-context Dump PR title/body/files/diff/comments and #N crawl\n wait-for-apt-locks Wait until apt/dpkg lock files are free\n install-playwright-chromium-arm64 Install Playwright Chromium from browsers.json\n ghcr-package-retention Delete old GHCR package versions past KEEP_MIN\n harness-admission-lane Compute a GITHUB_RUN_ID admission lane for fleet fan-out\n harness-assert-gates Fail if any named HARNESS_*_ENABLED gate is enabled\n gha-collaborator-trust Classify authors as write-access collaborators or not\n nuget-central-version Validate a Directory.Packages.props PackageVersion delta\n swift-semantic-equal Compare Swift sources ignoring comments and whitespace\n post-review Post one COMMENT review from a staged payload file\n stage-review-payload Validate a review payload file into a staging directory\n retrospective-transcript Format facts from Claude-compatible, Codex, or Grok transcripts\n link-skill Link one packaged skill into an explicit consumer directory\n retrospective-facts Gather immutable facts for a retrospective\n agent-blackboard Probe and journal an Agent Blackboard deployment\n mcp Serve the agent-blackboard journal tools over stdio (MCP)\n\nOptions:\n -h, --help Show this help\n -v, --version Print the package version\n\nrunner-port-policy\n (no args) Print the shipped policy as JSON\n --file <path> Validate and print a policy file\n --reserved <port> Print true if the port is reserved\n\nwith-host-lock\n --name <family>\n [--slots <n>]\n --timeout-seconds <n>\n [--command-timeout-seconds <n>]\n [--failure-diagnostics <absolute-script>]\n [--on-acquire-timeout fail|run-unlocked]\n -- <command> [args...]\n\ngha-runtime-audit\n [--repository owner/name] Default GITHUB_REPOSITORY\n [--branch main]\n [--median-threshold-floor <seconds>] Off unless set. Must be below the ceiling\n [--median-threshold-ceiling <seconds>] Default 360. Flags a five-sample median above this\n --pr-workflow <name|/regex/> Repeatable\n --push-workflow <name|/regex/> Repeatable\n\nrequire-up-to-date --remote <name> --branch <name>\ngitleaks-directory-scan --config <path> [--directory <path>]\nast-grep-examples --rules <directory> --config <path>\nast-grep-pack\ngha-workspace-policy [--root <directory>] [--workflow-directory <directory>] [--action-directory <directory>]\n\ngha-output <name>\ngha-needs-results [label]\ndownload-with-diagnostics <url> <destination> [-- curl-args...]\ndownload-optional-run-artifacts (--name <name>... | --pattern <pattern>) --dir <directory>\nhost-pressure-diagnostics\nallocate-browser-safe-ports <count> [--policy path] [--forbidden-ports path]\ndiagnose-port-collision [--ports \"2200 2216\"] [--output-dir PATH]\nprepare-trivy-db\ngha-artifacts-cleanup run --run-id <id> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\ngha-artifacts-cleanup sweep --older-than-hours <n> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\nhttp-origin [--field NAME] [value]\nvitest-blob-manifest <suite> [reports-directory]\nvitest-report-attempt <write DIRECTORY SUITE|read ROOT>\nprepare-vitest-reports [primary-directory] [fallback-directory] [output-directory]\npnpm-install --runner-lifecycle persistent|ephemeral|ephemeral-full --install-scripts true|false\ncheck-cache-size <path> <max-bytes> <label>\nmake-shard-matrix <total>\nload-runner-env\nclean-workspace\ninstall-github-release --repo owner/name --version X --asset 'name-{platform}.tar.gz' --bin name [--tag-prefix PREFIX] [--expected-sha256 SHA256] [--no-checksum] [--checksums-asset NAME] [--version-flag FLAG] [--bin-dir DIR]\nrun-with-timeout <timeout-seconds> <kill-after-seconds> <command...>\nlint-links [--offline] [--config PATH] [--glob PATTERN] [files...]\nmaterialize-pr-context\nwait-for-apt-locks\ninstall-playwright-chromium-arm64 [name:archive...]\nghcr-package-retention <url-encoded-package>...\nharness-admission-lane <lanes>\nharness-assert-gates <gate>...\ngha-collaborator-trust <owner/repo> [--allow-bot <login>]... < authors.json\nnuget-central-version <trusted-props> <candidate-props> <metadata-json> <output-props>\nswift-semantic-equal <base> <head> <file.swift>\npost-review\nstage-review-payload optional|required <source> <destination>\nretrospective-transcript [--session-id ID] [--jsonl PATH] [--projects-dir PATH] [--codex-sessions-dir PATH] [--grok-sessions-dir PATH]\nlink-skill <name> --source-root <skills-dir> --target-root <consumer-skills-dir> Link a packaged or repository-local skill\nretrospective-facts (--pr NUMBER | --branch NAME | --no-pr) [--repo OWNER/NAME] [--raw]\nagent-blackboard probe\nagent-blackboard journal append --mode interactive|autonomous --source-event-id ID --work-outcome OUTCOME --coverage-status STATUS --session-id UUID --agent NAME --version VERSION --file PATH --repository OWNER/NAME [--repository OWNER/NAME ...] [--parent-session-id UUID] [--timestamp ISO8601] [--coverage-source SOURCE,...] [--dropped-count N] [--outbox-directory PATH]\nagent-blackboard journal entries --session-id UUID\nagent-blackboard journal status --session-id UUID --outbox-directory PATH\nagent-blackboard journal flush --outbox-directory PATH [--session-id UUID]\nInteractive journal append requires --outbox-directory PATH.\nagent-blackboard journal is deprecated and being phased out: agents journal through the mcp server.\nagent-blackboard snapshot partition --snapshot PATH --checksum SHA256 --counts '{\"sessions\":N,\"entries\":N,\"records\":N,\"bytes\":N}'\nagent-blackboard snapshot cleanup [--snapshot PATH] [--partition-directory PATH --receipt JSON]\nmcp\n (no args) Serve journal_append, journal_entries, outbox_status, outbox_flush,\n session_ensure, retrospective_check, retrospective_save,\n pr_validate, pr_create, pr_update,\n snapshot_export, and session_archive over stdio.\n Needs the optional @modelcontextprotocol/sdk peer (and zod).\n Launch it from inside the repository's git worktree.\n";
2
2
  export declare function printUsage(stream?: NodeJS.WritableStream): void;
3
3
  export declare function commandNames(usage?: string): string[];
4
4
  export declare function commandUsage(command: string, usage?: string): string;
@@ -126,7 +126,9 @@ agent-blackboard snapshot partition --snapshot PATH --checksum SHA256 --counts '
126
126
  agent-blackboard snapshot cleanup [--snapshot PATH] [--partition-directory PATH --receipt JSON]
127
127
  mcp
128
128
  (no args) Serve journal_append, journal_entries, outbox_status, outbox_flush,
129
- session_ensure, snapshot_export, and session_archive over stdio.
129
+ session_ensure, retrospective_check, retrospective_save,
130
+ pr_validate, pr_create, pr_update,
131
+ snapshot_export, and session_archive over stdio.
130
132
  Needs the optional @modelcontextprotocol/sdk peer (and zod).
131
133
  Launch it from inside the repository's git worktree.
132
134
  `;
@@ -39,6 +39,8 @@ export type BuildGhPrCreateArgsOptions = {
39
39
  draft?: boolean;
40
40
  head: string;
41
41
  labels?: readonly string[];
42
+ milestone?: string;
43
+ projects?: readonly string[];
42
44
  reviewers?: readonly string[];
43
45
  title: string;
44
46
  };
@@ -53,7 +53,7 @@ export async function assertHeadPushed(runGit, { branch, remote = 'origin' }) {
53
53
  }
54
54
  /** Pure argv builder for `gh pr create`. `head` is always passed explicitly (never omitted). */
55
55
  export function buildGhPrCreateArgs(options) {
56
- const { base, bodyFile, draft = false, head, labels = [], reviewers = [], title } = options;
56
+ const { base, bodyFile, draft = false, head, labels = [], milestone, projects = [], reviewers = [], title, } = options;
57
57
  const args = ['pr', 'create', '--title', title, '--body-file', bodyFile, '--head', head];
58
58
  if (base !== undefined)
59
59
  args.push('--base', base);
@@ -61,6 +61,10 @@ export function buildGhPrCreateArgs(options) {
61
61
  args.push('--draft');
62
62
  for (const label of labels)
63
63
  args.push('--label', label);
64
+ if (milestone !== undefined)
65
+ args.push('--milestone', milestone);
66
+ for (const project of projects)
67
+ args.push('--project', project);
64
68
  for (const reviewer of reviewers)
65
69
  args.push('--reviewer', reviewer);
66
70
  return args;
@@ -1,12 +1,28 @@
1
1
  import type { BlackboardClientDependencies } from '../agent-blackboard/client.mts';
2
2
  import type { FeedbackIdentity } from '../agent-blackboard/feedback-types.mts';
3
+ import type { RunTextCommand } from '../gh-cli/exec.mts';
4
+ import type { GhRunner } from './pr-gh.mts';
5
+ import type { PolicySpawner } from './policy-spawn.mts';
3
6
  import { type Args } from './args.mts';
4
7
  /** What a handler may rely on: every field here was validated before the handler ran. */
5
- type ToolContext = {
8
+ export type ToolContext = {
6
9
  sessionId: string;
7
10
  worktree: string;
8
11
  env: NodeJS.ProcessEnv;
9
12
  dependencies: BlackboardClientDependencies;
13
+ /** The launch directory's worktree top level, or undefined when it is not inside one. */
14
+ launchRoot: string | undefined;
15
+ /** Test seam: replaces the child process a policy export runs in. */
16
+ spawnPolicy?: PolicySpawner;
17
+ /** Runs git with the isolated environment; callers add their own `-C <worktree>`. */
18
+ runGit: RunTextCommand;
19
+ /** Test seam: replaces locating and running gh. */
20
+ runGh?: GhRunner;
21
+ /** Test seam: replaces the operating system user and host name. */
22
+ device?: () => {
23
+ user: string;
24
+ host: string;
25
+ };
10
26
  };
11
27
  export type ToolHandler = (args: Args, context: ToolContext) => Promise<Record<string, unknown>>;
12
28
  /**
@@ -15,5 +31,9 @@ export type ToolHandler = (args: Args, context: ToolContext) => Promise<Record<s
15
31
  */
16
32
  export declare function outboxDirectory(worktree: string): string;
17
33
  export declare function readSessionId(args: Args): string;
34
+ /** The caller identity, fully validated before any policy runs or anything is written. */
18
35
  export declare function readIdentity(args: Args, sessionId: string): FeedbackIdentity;
19
- export {};
36
+ /** Policy modules run only for a server whose launch repository bounds the worktrees it acts on. */
37
+ export declare function assertPolicyAllowed(context: {
38
+ launchRoot: string | undefined;
39
+ }): void;
@@ -1,5 +1,6 @@
1
1
  import { join } from 'node:path';
2
2
  import { assertSessionId } from "../agent-blackboard/session-id.mjs";
3
+ import { validateFeedbackIdentity } from "../agent-blackboard/feedback-identity.mjs";
3
4
  import { requiredNullableString, requiredString } from "./args.mjs";
4
5
  /**
5
6
  * The consumer convention for the interactive outbox. It is derived, never accepted from the
@@ -13,11 +14,23 @@ export function readSessionId(args) {
13
14
  assertSessionId(value);
14
15
  return value;
15
16
  }
17
+ /** The caller identity, fully validated before any policy runs or anything is written. */
16
18
  export function readIdentity(args, sessionId) {
17
- return {
19
+ const identity = {
18
20
  sessionId,
19
21
  parentSessionId: requiredNullableString(args, 'parentSessionId'),
20
22
  agent: requiredString(args, 'agent'),
21
23
  version: requiredString(args, 'version'),
22
24
  };
25
+ validateFeedbackIdentity(identity);
26
+ return identity;
27
+ }
28
+ /** Policy modules run only for a server whose launch repository bounds the worktrees it acts on. */
29
+ export function assertPolicyAllowed(context) {
30
+ // Policy and facts children are reaped by Unix process group; Windows has no equivalent here.
31
+ if (process.platform === 'win32')
32
+ throw new Error('policy tools are not supported on Windows: run the server on macOS or Linux');
33
+ if (context.launchRoot === undefined)
34
+ throw new Error('policy tools require the server to be launched inside a repository worktree: relaunch ' +
35
+ 'it from the repository so the worktree argument is bound to that repository');
23
36
  }
@@ -1,5 +1,7 @@
1
1
  import type { BlackboardClientDependencies } from '../agent-blackboard/client.mts';
2
2
  import type { RunTextCommand } from '../gh-cli/exec.mts';
3
+ import type { GhRunner } from './pr-gh.mts';
4
+ import type { PolicySpawner } from './policy-spawn.mts';
3
5
  export type ServerEnvironment = {
4
6
  /** The launch directory's worktree top level, or undefined when it is not inside one. */
5
7
  launchRoot: string | undefined;
@@ -9,6 +11,15 @@ export type ServerEnvironment = {
9
11
  resolveFrom?: string | URL;
10
12
  /** Test seam: replaces how the consumer's `agent-blackboard` client is loaded. */
11
13
  blackboard?: BlackboardClientDependencies;
14
+ /** Test seam: replaces the child process a policy export runs in. */
15
+ spawnPolicy?: PolicySpawner;
16
+ /** Test seam: replaces locating and running gh. */
17
+ runGh?: GhRunner;
18
+ /** Test seam: replaces the operating system user and host name. */
19
+ device?: () => {
20
+ user: string;
21
+ host: string;
22
+ };
12
23
  };
13
24
  export type ToolCallResult = {
14
25
  content: Array<{
@@ -2,8 +2,10 @@ import { FeedbackDeliveryError } from "../agent-blackboard/index.mjs";
2
2
  import { optionalString, rejectUnknown, requireObject } from "./args.mjs";
3
3
  import { readSessionId } from "./context.mjs";
4
4
  import { journalAppend, journalEntries } from "./handlers-journal.mjs";
5
+ import { retrospectiveCheck, retrospectiveSave } from "./handlers-retrospective.mjs";
5
6
  import { outboxFlush, outboxStatus } from "./handlers-outbox.mjs";
6
7
  import { sessionArchive, sessionEnsure, snapshotExport } from "./handlers-session.mjs";
8
+ import { handlePrCreate, handlePrUpdate, handlePrValidate } from "./handlers-pr.mjs";
7
9
  import { TOOLS } from "./tools.mjs";
8
10
  import { resolveWorktree } from "./worktree.mjs";
9
11
  const HANDLERS = {
@@ -12,6 +14,11 @@ const HANDLERS = {
12
14
  outbox_status: outboxStatus,
13
15
  outbox_flush: outboxFlush,
14
16
  session_ensure: sessionEnsure,
17
+ retrospective_check: retrospectiveCheck,
18
+ retrospective_save: retrospectiveSave,
19
+ pr_validate: handlePrValidate,
20
+ pr_create: handlePrCreate,
21
+ pr_update: handlePrUpdate,
15
22
  snapshot_export: snapshotExport,
16
23
  session_archive: sessionArchive,
17
24
  };
@@ -51,6 +58,11 @@ export async function callTool(name, rawArguments, environment) {
51
58
  sessionId,
52
59
  worktree,
53
60
  env: environment.env,
61
+ launchRoot: environment.launchRoot,
62
+ runGit: environment.runGit,
63
+ ...(environment.runGh === undefined ? {} : { runGh: environment.runGh }),
64
+ ...(environment.device === undefined ? {} : { device: environment.device }),
65
+ ...(environment.spawnPolicy === undefined ? {} : { spawnPolicy: environment.spawnPolicy }),
54
66
  // The client resolves from this package's install, like the SDK, never from the worktree.
55
67
  dependencies: {
56
68
  ...environment.blackboard,
@@ -1,4 +1,17 @@
1
- import { type ToolHandler } from './context.mts';
1
+ import { type FeedbackCoverage, type FeedbackDeliveryResult, type WorkOutcome } from '../agent-blackboard/index.mts';
2
+ import { type Args } from './args.mts';
3
+ import { type ToolContext, type ToolHandler } from './context.mts';
4
+ export declare const MODES: readonly ["interactive", "autonomous"];
5
+ export declare const OUTCOMES: readonly WorkOutcome[];
6
+ export declare function readCoverage(args: Args): FeedbackCoverage;
2
7
  export declare const journalAppend: ToolHandler;
8
+ /**
9
+ * The tool result for a write: the delivery result plus the server-owned timestamp (a first
10
+ * append takes the current time; a retry of the same event reports the one already stored or
11
+ * retained) and the outbox counts. Autonomous delivery never uses an outbox, so it has nothing
12
+ * pending; interactive delivery reports the outbox as it is after delivery.
13
+ */
14
+ export declare function deliveryResponse(result: FeedbackDeliveryResult, context: ToolContext, mode: (typeof MODES)[number]): Record<string, unknown>;
15
+ export declare function byCreatedAt(left: unknown, right: unknown): number;
3
16
  /** Every entry as the client returns it, oldest first. Nothing is filtered or rewritten. */
4
17
  export declare const journalEntries: ToolHandler;
@@ -2,8 +2,8 @@ import { appendJournalMarkdown, readJournal, } from "../agent-blackboard/index.m
2
2
  import { optionalRecord, optionalString, requiredChoice, requiredString, requiredStringArray, rejectUnknown, } from "./args.mjs";
3
3
  import { outboxDirectory, readIdentity } from "./context.mjs";
4
4
  import { outboxCounts } from "./handlers-outbox.mjs";
5
- const MODES = ['interactive', 'autonomous'];
6
- const OUTCOMES = [
5
+ export const MODES = ['interactive', 'autonomous'];
6
+ export const OUTCOMES = [
7
7
  'in-progress',
8
8
  'success',
9
9
  'failure',
@@ -20,7 +20,7 @@ const COVERAGE_STATUSES = [
20
20
  'not-assessed',
21
21
  'not-started',
22
22
  ];
23
- function readCoverage(args) {
23
+ export function readCoverage(args) {
24
24
  const coverage = optionalRecord(args, 'feedbackCoverage');
25
25
  if (coverage === undefined)
26
26
  throw new Error('feedbackCoverage is required');
@@ -60,11 +60,16 @@ export const journalAppend = async (args, context) => {
60
60
  env: context.env,
61
61
  dependencies: context.dependencies,
62
62
  });
63
- // The server owns the timestamp: a first append takes the current time, and a retry of the same
64
- // event (same session, sourceEventId, and content) reports the one already stored or retained.
63
+ return deliveryResponse(result, context, mode);
64
+ };
65
+ /**
66
+ * The tool result for a write: the delivery result plus the server-owned timestamp (a first
67
+ * append takes the current time; a retry of the same event reports the one already stored or
68
+ * retained) and the outbox counts. Autonomous delivery never uses an outbox, so it has nothing
69
+ * pending; interactive delivery reports the outbox as it is after delivery.
70
+ */
71
+ export function deliveryResponse(result, context, mode) {
65
72
  const timestamp = result.status === 'delivered' ? result.receipt.timestamp : result.timestamp;
66
- // Autonomous delivery never uses an outbox, so it has nothing pending. Interactive delivery
67
- // reports the outbox as it is after delivery, split into the caller's session and the worktree.
68
73
  const counts = mode === 'interactive'
69
74
  ? outboxCounts(context.worktree, context.sessionId)
70
75
  : { pendingCount: 0, worktreePendingCount: 0 };
@@ -77,14 +82,14 @@ export const journalAppend = async (args, context) => {
77
82
  ...(storedVersion === undefined ? {} : { storedVersion }),
78
83
  ...counts,
79
84
  };
80
- };
85
+ }
81
86
  // `Entries.get` documents no order, and `createdAt` is a service-generated ISO 8601 UTC time whose
82
87
  // text order is time order. An entry without a usable `createdAt` sorts first rather than throwing.
83
88
  function createdAtOf(entry) {
84
89
  const createdAt = entry?.createdAt;
85
90
  return typeof createdAt === 'string' ? createdAt : '';
86
91
  }
87
- function byCreatedAt(left, right) {
92
+ export function byCreatedAt(left, right) {
88
93
  const leftAt = createdAtOf(left);
89
94
  const rightAt = createdAtOf(right);
90
95
  if (leftAt === rightAt)
@@ -0,0 +1,4 @@
1
+ import { type ToolHandler } from './context.mts';
2
+ export declare const handlePrValidate: ToolHandler;
3
+ export declare const handlePrCreate: ToolHandler;
4
+ export declare const handlePrUpdate: ToolHandler;
@@ -0,0 +1,143 @@
1
+ import { hostname, userInfo } from 'node:os';
2
+ import { validateGitHubBodyLength } from "../gh-cli/body-length.mjs";
3
+ import { createPullRequest } from "../gh-cli/pr-create.mjs";
4
+ import { assertPolicyAllowed } from "./context.mjs";
5
+ import { runValidator } from "./policy-run.mjs";
6
+ import { renderPullRequestBody, worktreeLabel } from "./pr-body.mjs";
7
+ import { pullRequestNumber, withBodyFile } from "./pr-body-file.mjs";
8
+ import { pullRequestDefaults } from "./pr-defaults.mjs";
9
+ import { createGhRunner, ghEnvironment } from "./pr-gh.mjs";
10
+ import { checkTitleLength, positiveInteger, readPullRequestInput, } from "./pr-input.mjs";
11
+ import { preserveShepherdJournal } from "./pr-journal.mjs";
12
+ import { assertJournalUnchanged, credentials, liveBase, livePullRequest, redactCredentials, } from "./pr-live.mjs";
13
+ import { parseWorktreeList } from "./worktree.mjs";
14
+ function gitIn(context) {
15
+ return (args) => context.runGit(['-C', context.worktree, ...args]);
16
+ }
17
+ function ghIn(context) {
18
+ const run = context.runGh ?? createGhRunner(context.env);
19
+ const env = ghEnvironment(context.env);
20
+ return (args) => run(args, { cwd: context.worktree, env });
21
+ }
22
+ async function currentBranch(git) {
23
+ const branch = (await git(['rev-parse', '--abbrev-ref', 'HEAD'])).trim();
24
+ if (branch === 'HEAD')
25
+ throw new Error('the worktree has a detached HEAD: check out a branch');
26
+ return branch;
27
+ }
28
+ async function label(context, git) {
29
+ const listing = await git(['worktree', 'list', '--porcelain', '-z']);
30
+ return worktreeLabel(context.worktree, parseWorktreeList(listing)[0]);
31
+ }
32
+ function readPr(args, required) {
33
+ if (args.pr === undefined && !required)
34
+ return undefined;
35
+ return positiveInteger(args.pr, 'pr');
36
+ }
37
+ function policyFor(context) {
38
+ return {
39
+ worktree: context.worktree,
40
+ env: context.env,
41
+ ...(context.spawnPolicy === undefined ? {} : { spawn: context.spawnPolicy }),
42
+ };
43
+ }
44
+ /** Renders the body, preserves the live journal for an update, and runs the policy validator. */
45
+ async function prepare(args, context, pr) {
46
+ assertPolicyAllowed(context);
47
+ // No server credential may reach the policy or gh, whatever the caller wrote: every field is
48
+ // redacted before anything is rendered or forwarded.
49
+ const secrets = credentials(context.env);
50
+ const given = redactCredentials(readPullRequestInput(args), secrets);
51
+ checkTitleLength(given.title);
52
+ const git = gitIn(context);
53
+ const head = await currentBranch(git);
54
+ // Branch names are refs passed to gh as is: redacting one would name a branch that does not exist.
55
+ if (secrets.some((secret) => head.includes(secret)))
56
+ throw new Error('the worktree branch name contains a server credential: rename the branch');
57
+ if (secrets.some((secret) => args.base?.includes(secret)))
58
+ throw new Error('base contains a server credential: use another base branch');
59
+ const live = pr === undefined ? undefined : await livePullRequest(ghIn(context), pr);
60
+ if (live !== undefined && live.headRefName !== head)
61
+ throw new Error(`pull request ${pr} has head ${live.headRefName}, not the worktree branch ${head}`);
62
+ const base = live === undefined
63
+ ? given.base
64
+ : liveBase(pr, live, redactCredentials(args.base, secrets));
65
+ const input = { ...given, base };
66
+ if (head === base)
67
+ throw new Error(`head branch ${head} must differ from base ${base}`);
68
+ const device = (context.device ?? (() => ({ user: userInfo().username, host: hostname() })))();
69
+ let body = renderPullRequestBody(input, {
70
+ sessionId: context.sessionId,
71
+ ...device,
72
+ worktree: await label(context, git),
73
+ });
74
+ if (live !== undefined)
75
+ body = preserveShepherdJournal(body, live.body);
76
+ body = redactCredentials(body, secrets);
77
+ const length = validateGitHubBodyLength(body);
78
+ if (!length.ok)
79
+ throw new Error(`the rendered body has ${length.characterCount} characters; GitHub allows ${length.maxCharacterCount}`);
80
+ const report = await runValidator({
81
+ ...policyFor(context),
82
+ export: 'validatePullRequest',
83
+ input: {
84
+ title: input.title,
85
+ body,
86
+ base: input.base,
87
+ head,
88
+ mode: input.mode,
89
+ ...(pr === undefined ? {} : { pr }),
90
+ },
91
+ });
92
+ const errors = 'errors' in report ? report.errors : [];
93
+ const warnings = 'warnings' in report ? report.warnings : [];
94
+ return {
95
+ input,
96
+ head,
97
+ body,
98
+ errors,
99
+ warnings,
100
+ ...(live === undefined ? {} : { liveBody: live.body }),
101
+ };
102
+ }
103
+ function rejectErrors(prepared) {
104
+ if (prepared.errors.length)
105
+ throw new Error(`policy rejected the pull request:\n- ${prepared.errors.join('\n- ')}`);
106
+ }
107
+ export const handlePrValidate = async (args, context) => {
108
+ const { body, errors, warnings } = await prepare(args, context, readPr(args, false));
109
+ return { body, errors, warnings };
110
+ };
111
+ export const handlePrCreate = async (args, context) => {
112
+ const prepared = await prepare(args, context, undefined);
113
+ rejectErrors(prepared);
114
+ const { input, head, body } = prepared;
115
+ const defaults = await pullRequestDefaults(policyFor(context), input);
116
+ const url = await withBodyFile(body, (bodyFile) => createPullRequest({ runGh: ghIn(context), runGit: gitIn(context) }, {
117
+ bodyFile,
118
+ draft: true,
119
+ title: input.title,
120
+ base: input.base,
121
+ head,
122
+ labels: defaults.labels,
123
+ ...(defaults.milestone === undefined ? {} : { milestone: defaults.milestone }),
124
+ ...(defaults.project === undefined ? {} : { projects: [defaults.project] }),
125
+ }));
126
+ return { number: pullRequestNumber(url), url, warnings: prepared.warnings };
127
+ };
128
+ export const handlePrUpdate = async (args, context) => {
129
+ const pr = readPr(args, true);
130
+ const prepared = await prepare(args, context, pr);
131
+ rejectErrors(prepared);
132
+ await assertJournalUnchanged(ghIn(context), pr, prepared.liveBody, prepared.input.base);
133
+ const url = await withBodyFile(prepared.body, async (bodyFile) => (await ghIn(context)([
134
+ 'pr',
135
+ 'edit',
136
+ String(pr),
137
+ '--title',
138
+ prepared.input.title,
139
+ '--body-file',
140
+ bodyFile,
141
+ ])).trim());
142
+ return { number: pr, url, warnings: prepared.warnings };
143
+ };
@@ -0,0 +1,12 @@
1
+ import { type ToolHandler } from './context.mts';
2
+ /** Whether the session already holds a retrospective, and which (sourceEventId, issues, prs). */
3
+ export declare const retrospectiveCheck: ToolHandler;
4
+ /** The default event id, hashed when the session id would push it past the 256-byte limit. */
5
+ export declare function defaultSourceEventId(sessionId: string): string;
6
+ /**
7
+ * Saves the session's retrospective: composes it when `compose` is given, checks the arguments
8
+ * against the document's front matter, runs the checkout's `validateRetrospective` policy (in a
9
+ * child process) and writes nothing if it reports errors, then writes through the same verified
10
+ * path as `journal_append`.
11
+ */
12
+ export declare const retrospectiveSave: ToolHandler;