@agentproto/worktree 0.12.0 → 0.14.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.
package/dist/index.d.ts CHANGED
@@ -233,6 +233,18 @@ interface ExecResult {
233
233
  /** Extra `AGENTPROTO_*` (or any) vars, merged onto `process.env` for the child. */
234
234
  interface ExecOptions {
235
235
  env?: Record<string, string>;
236
+ /**
237
+ * Cancels the child. When given, the child is spawned as the leader of its
238
+ * own process group (POSIX), and an abort signals the WHOLE group, so a
239
+ * `sh -c "pnpm install"` takes its `pnpm` and every worker underneath it
240
+ * down too instead of orphaning them. SIGTERM first, SIGKILL after
241
+ * {@link killGraceMs}. Already-aborted signals reject before spawning.
242
+ * The promise still resolves (with the child's real exit code) once the
243
+ * tree is gone; callers decide what an aborted run means.
244
+ */
245
+ signal?: AbortSignal;
246
+ /** Grace between SIGTERM and SIGKILL on abort. Default 5000ms. */
247
+ killGraceMs?: number;
236
248
  }
237
249
  /** Run an argv (no shell — args pass through verbatim, no injection risk). */
238
250
  declare function execArgv(command: string, args: readonly string[], cwd: string, opts?: ExecOptions): Promise<ExecResult>;
@@ -262,18 +274,21 @@ declare function execGit(repoRoot: string, args: readonly string[]): Promise<Exe
262
274
  * are authorized to die; only the cost is being moved.
263
275
  * 2. `git worktree prune` — git forgets the (now missing) registration.
264
276
  * The worktree disappears from `git worktree list` immediately.
265
- * 3. `rm -rf` on the trash dir runs in a DETACHED child
266
- * (`spawn("rm", ["-rf", trashDir], { detached: true, stdio: "ignore" })`
267
- * + `.unref()`) — the parent never waits for the hundreds of thousands
268
- * of unlinks, and survives its own exit. The next `gc` apply also
277
+ * 3. `rm -rf` on the trash dirs runs in ONE DETACHED, serialized deleter
278
+ * per pool (`ensureTrashDeleter`; a `.trash/.deleting` pid file stops a
279
+ * second one spawning while it lives) — the parent never waits for the
280
+ * hundreds of thousands of unlinks, survives its own exit, and a burst
281
+ * of reclaims doesn't storm the disk with parallel `rm`s. The next `gc` apply also
269
282
  * sweeps stale `.trash` dirs (`sweepWorktreeTrash`) so nothing leaks
270
283
  * even if a child is killed mid-delete.
271
284
  *
272
285
  * SAFETY — the plain/forced `git worktree remove` semantics this must not
273
- * weaken, verified empirically against git (see the brief):
274
- * - A non-force removal must refuse a dirty tree: the caller passes
275
- * `force: false` only for a tree already checked clean, and
276
- * `removeWorktreeFast` re-checks `git status --porcelain` itself and
286
+ * weaken, verified empirically against git:
287
+ * - Plain `git worktree remove` ACCEPTS gitignored files (`node_modules`,
288
+ * `dist`) and refuses only modified/staged tracked files, unignored
289
+ * untracked files, dirty submodules and locked worktrees. A non-force
290
+ * `removeWorktreeFast` gates on `git status --porcelain
291
+ * --ignore-submodules=none` (no `--ignored`) plus a locked check, and
277
292
  * throws (leaving the worktree in place) rather than renaming dirt away.
278
293
  * - A forced removal is only ever passed after a salvage snapshot or an
279
294
  * explicit user-granted discard flag upstream — this module doesn't
@@ -288,7 +303,7 @@ declare const WORKTREE_TRASH_DIRNAME = ".trash";
288
303
  interface RemoveWorktreeFastOptions {
289
304
  /**
290
305
  * `false` (default): re-verify the tree is clean via `git status
291
- * --porcelain` and refuse (throw) on any dirt — the same refusal a plain
306
+ * --porcelain --untracked-files=normal --ignore-submodules=none` and refuse (throw) on any dirt — the same refusal a plain
292
307
  * `git worktree remove` performs. `true`: skip the cleanliness gate,
293
308
  * exactly like `git worktree remove --force` — only pass this when dirt
294
309
  * has been authorized (salvage snapshot durable / discard flags granted)
@@ -301,11 +316,18 @@ interface RemoveWorktreeFastOptions {
301
316
  */
302
317
  now?: () => number;
303
318
  /**
304
- * Test seam — overrides the detached `rm -rf` child (e.g. an in-process
305
- * spy). Receives the trash dir path. Default: a detached
306
- * `spawn("rm", ["-rf", …])` the parent never waits on.
319
+ * Test seam — overrides background deletion per trash dir (e.g. an
320
+ * in-process spy). Receives the trash dir path. Default: one detached,
321
+ * serialized deleter per pool (`ensureTrashDeleter`) the parent never
322
+ * waits on.
307
323
  */
308
324
  spawnRemoval?: (trashDir: string) => void;
325
+ /**
326
+ * Test seam — replaces spawning the pool's single serialized background
327
+ * deleter (see `ensureTrashDeleter`). Receives the `.trash` parent and
328
+ * returns the spawned pid. Ignored when `spawnRemoval` is set.
329
+ */
330
+ spawnDeleter?: (trashParent: string) => number | undefined;
309
331
  }
310
332
  /**
311
333
  * Remove a linked git worktree instantly: validate → rename to trash →
@@ -323,12 +345,191 @@ declare function removeWorktreeFast(repoRoot: string, path: string, options?: Re
323
345
  */
324
346
  declare function sweepWorktreeTrash(root: string, options?: {
325
347
  spawnRemoval?: (dir: string) => void;
348
+ spawnDeleter?: (trashParent: string) => number | undefined;
326
349
  }): void;
327
350
 
328
351
  /** Compile a `/`-separated glob (supporting `*`, `?`, `**`) into an anchored regex. */
329
352
  declare function globToRegExp(pattern: string): RegExp;
330
353
  /** Expand a glob against `root`, returning root-relative posix paths of matching files. */
331
354
  declare function expandGlob(root: string, pattern: string): Promise<string[]>;
355
+ /** A `cloneGlobs`/`copyGlobs` pattern that could resolve outside its root — a
356
+ * leading `/`, or a literal `..` path segment. */
357
+ declare class GlobTraversalError extends Error {
358
+ constructor(pattern: string);
359
+ }
360
+ /**
361
+ * Expand a glob against `root` for CLONING a whole entry. Unlike
362
+ * {@link expandGlob} — which enumerates individual FILES and deliberately
363
+ * skips descending into `node_modules` — this matches whole entries (files
364
+ * OR directories) and never descends past a match: a matching directory is
365
+ * returned as a single unit for the caller to clone as a whole tree, so a
366
+ * pattern like `node_modules` costs one `readdir`, not a walk of everything
367
+ * inside it. `**` is not supported (a clone target must be a single named
368
+ * entry per level, not an arbitrary-depth wildcard) and throws.
369
+ *
370
+ * Throws {@link GlobTraversalError} on a pattern that could resolve outside
371
+ * `root` (a leading `/`, or any `..` segment) — checked before any
372
+ * filesystem access.
373
+ */
374
+ declare function expandCloneGlob(root: string, pattern: string): Promise<string[]>;
375
+
376
+ /**
377
+ * Clone every entry matched by `patterns` (see {@link expandCloneGlob}) from
378
+ * `repoRoot` into `cwd`, meant to run BEFORE `depsCmd` so a gitignored,
379
+ * expensive-to-recreate tree (e.g. `node_modules`) is already present when
380
+ * the package manager runs — turning `depsCmd` into a quick verify/repair
381
+ * instead of a full reinstall. Skips an entry whose destination already
382
+ * exists — same never-clobber rule `linkPaths`/`writeFiles` follow in
383
+ * `provision-worktree.body.ts`. `signal` cancels mid-copy (the `cp` process
384
+ * group is killed) with {@link ProvisionCancelledError}.
385
+ */
386
+ declare function cloneEntries(repoRoot: string, cwd: string, patterns: readonly string[], signal?: AbortSignal): Promise<void>;
387
+
388
+ /**
389
+ * Daemon-wide scheduler for the HEAVY phases of worktree provisioning
390
+ * (`cloneGlobs`, `depsCmd`, `copyGlobs`, the `worktree.setup` hooks).
391
+ *
392
+ * Incident 2026-09-28: five `agent_start({worktree})` spawns provisioned at
393
+ * once, each ran a full `pnpm install` against one pnpm store on one SSD, the
394
+ * load average hit 170, and every install took ~14 min instead of ~4 while the
395
+ * sessions sat in `starting` looking stalled. The cure is admission control:
396
+ * at most N heavy segments run at once, the rest wait in a queue that can be
397
+ * observed and cancelled.
398
+ *
399
+ * One provisioning takes ONE slot for its whole heavy segment (clone → deps →
400
+ * copy → setup) rather than one per phase, so a half-built worktree never
401
+ * re-queues behind newer arrivals. `git worktree add` and the cheap steps
402
+ * around it stay outside the slot.
403
+ *
404
+ * Dispatch order is FIFO with a fair-share tiebreak: among the waiters whose
405
+ * repo is under its cap, the next one is the waiter whose CALLER currently
406
+ * holds the fewest running slots, oldest first on ties. One caller that
407
+ * spawns ten worktrees therefore cannot starve another caller's single spawn,
408
+ * and with a single caller this is plain FIFO.
409
+ */
410
+ /** Default cap on concurrently running heavy segments. */
411
+ declare const DEFAULT_PROVISION_CONCURRENCY = 2;
412
+ /** Env override for the global cap; wins over `worktrees.provisionConcurrency`. */
413
+ declare const PROVISION_CONCURRENCY_ENV = "AGENTPROTO_WORKTREES_PROVISION_CONCURRENCY";
414
+ /** The phases a provisioning moves through, in order. `worktree` is the
415
+ * unthrottled `git worktree add` + cheap prep; the rest are the heavy ones. */
416
+ type ProvisionPhase = "worktree" | "clone" | "deps" | "copy" | "setup";
417
+ /** Resolved, validated scheduler limits. `Infinity` means "no cap". */
418
+ interface ProvisionLimits {
419
+ /** Max heavy segments running at once, across every repo. */
420
+ concurrency: number;
421
+ /** Extra per-repo caps (also bounded by `concurrency`). Keys are absolute
422
+ * repo-root paths or bare repo directory names. */
423
+ perRepo: Readonly<Record<string, number>>;
424
+ /** Load guard: hold back a new heavy segment while the 1-minute load
425
+ * average exceeds `cores x loadFactor`. `0` = off (the default). */
426
+ loadFactor: number;
427
+ }
428
+ declare const DEFAULT_PROVISION_LIMITS: ProvisionLimits;
429
+ /**
430
+ * Parse the `worktrees` section of `~/.agentproto/config.json` (plus env)
431
+ * into {@link ProvisionLimits}. Never throws: an invalid value falls back to
432
+ * the default for that field so a typo can't take provisioning down.
433
+ *
434
+ * - `provisionConcurrency`: integer >= 0 (`0` = unlimited). Env
435
+ * `AGENTPROTO_WORKTREES_PROVISION_CONCURRENCY` wins over the config field.
436
+ * - `provisionConcurrencyByRepo`: `{ "<repo path or dir name>": cap }`.
437
+ * - `provisionLoadFactor`: number > 0 enables the load guard.
438
+ */
439
+ declare function parseProvisionLimits(raw: unknown, env?: Readonly<Record<string, string | undefined>>): ProvisionLimits;
440
+ /** Thrown when a provisioning is cancelled: while queued (its slot request is
441
+ * dropped) or while running (its child process tree is killed). */
442
+ declare class ProvisionCancelledError extends Error {
443
+ constructor(message?: string);
444
+ }
445
+ /** Progress a provisioning reports to whoever spawned it. `queued` repeats
446
+ * whenever the projected position moves. */
447
+ type ProvisionProgress = {
448
+ kind: "queued";
449
+ position: number;
450
+ phase: ProvisionPhase;
451
+ } | {
452
+ kind: "started";
453
+ phase: ProvisionPhase;
454
+ } | {
455
+ kind: "phase";
456
+ phase: ProvisionPhase;
457
+ } | {
458
+ kind: "done";
459
+ outcome: "ok" | "failed" | "cancelled";
460
+ };
461
+ /** Ambient, per-provisioning context. Carried through `AsyncLocalStorage`
462
+ * because the `worktree.provision` tool contract has no room for callbacks,
463
+ * and the runner's own abort signal is bound to the tool's 30s default
464
+ * timeout, which must never cancel a multi-minute install. */
465
+ interface ProvisionRunContext {
466
+ /** Whose spawn this is, for fair-share. Typically the parent session id. */
467
+ callerKey?: string;
468
+ /** Cancels this provisioning (queued or running). */
469
+ signal?: AbortSignal;
470
+ onProgress?: (progress: ProvisionProgress) => void;
471
+ }
472
+ declare function runWithProvisionContext<T>(ctx: ProvisionRunContext, fn: () => T): T;
473
+ declare function currentProvisionContext(): ProvisionRunContext | undefined;
474
+ interface AcquireRequest {
475
+ /** Absolute repo root; matched against `perRepo` caps. */
476
+ repoKey: string;
477
+ callerKey?: string;
478
+ signal?: AbortSignal;
479
+ /** Called with the projected 1-based queue position when this request
480
+ * starts waiting and whenever its position changes. Never called when the
481
+ * slot is granted immediately. */
482
+ onQueued?: (position: number) => void;
483
+ }
484
+ /** A held slot. `release` is idempotent. */
485
+ interface ProvisionLease {
486
+ release(): void;
487
+ }
488
+ interface SchedulerOptions {
489
+ limits?: ProvisionLimits;
490
+ /** Test seams. */
491
+ loadavg1?: () => number;
492
+ cpuCount?: () => number;
493
+ /** How often a load-guarded queue re-checks the load. Default 5000ms. */
494
+ loadPollMs?: number;
495
+ }
496
+ interface SchedulerSnapshot {
497
+ running: number;
498
+ queued: number;
499
+ limit: number;
500
+ }
501
+ declare class ProvisionScheduler {
502
+ private limits;
503
+ private readonly queue;
504
+ private readonly running;
505
+ private seq;
506
+ private loadTimer;
507
+ private readonly loadavg1;
508
+ private readonly cpuCount;
509
+ private readonly loadPollMs;
510
+ constructor(opts?: SchedulerOptions);
511
+ /** Replace the limits (config is re-read per provision). Raising a cap
512
+ * admits waiters immediately; lowering one never interrupts a running
513
+ * segment, it just delays the next admission. */
514
+ configure(limits: ProvisionLimits): void;
515
+ snapshot(): SchedulerSnapshot;
516
+ /**
517
+ * Request a heavy-phase slot. Resolves with a lease once admitted; rejects
518
+ * with {@link ProvisionCancelledError} when `signal` aborts first (the
519
+ * queue entry is dropped, so a cancelled spawn never occupies a slot).
520
+ */
521
+ acquire(req: AcquireRequest): Promise<ProvisionLease>;
522
+ private repoCap;
523
+ private runningFor;
524
+ /** Waiters in the order they would be admitted absent per-repo caps. */
525
+ private projectedOrder;
526
+ private loadGuardBlocks;
527
+ private pump;
528
+ private notifyPositions;
529
+ private armLoadTimer;
530
+ }
531
+ /** The process-wide (daemon-wide) scheduler every worktree provisioning shares. */
532
+ declare const provisionScheduler: ProvisionScheduler;
332
533
 
333
534
  /**
334
535
  * `agentproto.json` — the declarative per-repo worktree lifecycle.
@@ -390,6 +591,71 @@ declare function getScript(config: AgentprotoConfig, name: string): NamedScript
390
591
  */
391
592
  declare function loadConfigFromBase(repoRoot: string, base?: string): Promise<AgentprotoConfig | null>;
392
593
 
594
+ /**
595
+ * `<workspace>/.agentproto/worktree.json` — a LOCAL, host-owned worktree
596
+ * lifecycle default, read straight off disk (never `git show`, never a
597
+ * worktree's own tree). Same idea as `<workspace>/.agentproto/allowed-
598
+ * commands.json` (`command-allowlist.ts`): a per-machine setting that lets
599
+ * one host declare what a fresh worktree needs (a `node_modules` clone, a
600
+ * per-worktree pnpm store) without committing that machine's paths into the
601
+ * repo. `.agentproto/` is gitignored repo-wide (see this repo's own
602
+ * `.gitignore`), so this file can never ride in on a branch — there is
603
+ * nothing here for `config.ts`'s "only what a reviewer merged" guarantee to
604
+ * defend against; the trust model is simply "whoever owns this machine's
605
+ * filesystem".
606
+ *
607
+ * `workspace` is the SOURCE checkout — the same directory passed as
608
+ * `provisionWorktreeTool`'s `repoRoot` — never the freshly created worktree
609
+ * (which starts with no `.agentproto/worktree.json` of its own, since the
610
+ * dir is gitignored and nothing copies it in).
611
+ */
612
+ declare const LOCAL_WORKTREE_CONFIG_REL = ".agentproto/worktree.json";
613
+ declare const localWriteFileEntrySchema: z.ZodObject<{
614
+ path: z.ZodString;
615
+ content: z.ZodString;
616
+ mode: z.ZodOptional<z.ZodEnum<{
617
+ create: "create";
618
+ append: "append";
619
+ }>>;
620
+ }, z.core.$strip>;
621
+ declare const localWorktreeConfigSchema: z.ZodObject<{
622
+ copyGlobs: z.ZodOptional<z.ZodArray<z.ZodString>>;
623
+ cloneGlobs: z.ZodOptional<z.ZodArray<z.ZodString>>;
624
+ writeFiles: z.ZodOptional<z.ZodArray<z.ZodObject<{
625
+ path: z.ZodString;
626
+ content: z.ZodString;
627
+ mode: z.ZodOptional<z.ZodEnum<{
628
+ create: "create";
629
+ append: "append";
630
+ }>>;
631
+ }, z.core.$strip>>>;
632
+ depsCmd: z.ZodOptional<z.ZodString>;
633
+ linkPaths: z.ZodOptional<z.ZodArray<z.ZodString>>;
634
+ }, z.core.$strip>;
635
+ type LocalWriteFileEntry = z.infer<typeof localWriteFileEntrySchema>;
636
+ type LocalWorktreeConfig = z.infer<typeof localWorktreeConfigSchema>;
637
+ /**
638
+ * Parse + validate raw `worktree.json` text. Throws {@link ConfigError} on
639
+ * malformed JSON or a schema violation — same failure shape as
640
+ * `config.ts`'s `parseConfig`, so callers can handle both uniformly.
641
+ */
642
+ declare function parseLocalWorktreeConfig(raw: string): LocalWorktreeConfig;
643
+ /**
644
+ * Load `<workspace>/.agentproto/worktree.json` straight off disk. Returns
645
+ * `null` when the file is absent (the common case — most workspaces don't
646
+ * opt in). Throws {@link ConfigError} on a present-but-invalid file.
647
+ */
648
+ declare function loadLocalWorktreeConfig(workspace: string): Promise<LocalWorktreeConfig | null>;
649
+ /** Substitute the literal `{slug}` token for `slug` in `text`. */
650
+ declare function applySlugPlaceholder(text: string, slug: string): string;
651
+ /**
652
+ * Resolve a local config's `writeFiles` for one concrete worktree: expands
653
+ * `{slug}` in `path`/`content` so a declarative entry (e.g. a pnpm
654
+ * `virtualStoreDir` pointed outside the worktree) can be written once and
655
+ * still land at a distinct, collision-free path per worktree.
656
+ */
657
+ declare function resolveLocalWriteFiles(files: readonly LocalWriteFileEntry[] | undefined, slug: string): LocalWriteFileEntry[];
658
+
393
659
  /**
394
660
  * Typed env surface for worktree lifecycle hooks, scripts, and services.
395
661
  *
@@ -548,10 +814,15 @@ declare class HookError extends Error {
548
814
  * Both attempts are logged (when `logPath` is given); the thrown
549
815
  * `HookError` carries the RETRY's own result, since that's the one the
550
816
  * caller is actually giving up on.
817
+ *
818
+ * `opts.signal` cancels the run: the running hook's whole process tree is
819
+ * killed (see `ExecOptions.signal`) and {@link ProvisionCancelledError} is
820
+ * thrown instead of a `HookError`, with no retry.
551
821
  */
552
822
  declare function runSetup(config: AgentprotoConfig, ctx: WorktreeEnvContext, opts?: {
553
823
  logPath?: string;
554
824
  retryOnFailure?: boolean;
825
+ signal?: AbortSignal;
555
826
  }): Promise<HookRun[]>;
556
827
  /**
557
828
  * Run the `worktree.teardown` hooks sequentially. Unlike setup, a failing
@@ -2157,4 +2428,4 @@ declare function recordBranchVerdict(input: {
2157
2428
  now?: () => string;
2158
2429
  }): Promise<BranchVerdictRecord>;
2159
2430
 
2160
- export { type AgentprotoConfig, type ApplyBranchGcOptions, type ApplyGcOptions, BRANCH_GC_SCOPES, BRANCH_GC_STATE_DIR, BRANCH_TRIAGE_VERDICTS, BRANCH_VERDICTS_PATH, type BaseDivergence, type BranchCoverage, type BranchGcApplyOutcome, type BranchGcApplyResult, type BranchGcClass, type BranchGcHoldReason, type BranchGcPlan, type BranchGcPlanEntry, type BranchGcReclaimReason, type BranchGcRestoreEntry, type BranchGcRestoreLog, type BranchGcSummary, type BranchHistory, type BranchPushState, type BranchRef, type BranchRefKind, type BranchReviewCandidate, type BranchReviewQueue, type BranchStatus, type BranchTriageVerdict, type BranchVerdict, BranchVerdictError, type BranchVerdictRecord, type BranchVerdictStore, type BranchVerdictSummary, CONFIG_FILENAME, type Classification, type ClassifyForGcOptions, type ComputeProvenanceOptions, type ComputeTreeStateOptions, type ComputeWorktreeStatusInput, ConfigError, DEFAULT_BRANCH_GC_MIN_AGE_DAYS, DEFAULT_GC_NOISE_PATHS, DEFAULT_PROXY_PORT, type DaemonAgentSessionHost, type DaemonClient, ENV_VARS, type ExecOptions, type ExecResult, FileBranchVerdictStore, FileVerdictMemoStore, type ForgeClient, type ForgePullRequestRef, ForgeUnavailableError, type GateState, type GcApplyOutcome, type GcClass, type GcHoldReason, type GcPlanEntry, type GcReclaimReason, GhCliForgeClient, type GitWorktreeRef, HookError, type HookRun, type HostnameParts, type InBaseReclaimReason, InMemoryBranchVerdictStore, InMemoryVerdictMemoStore, type IntegrationState, type LadderContext, type ListWorktreeStatusesInput, type LivenessState, type NamedScript, type PeerService, type PlanBranchGcInput, type PlanGcInput, type ProvenanceConfidence, type ProvenanceInfo, ProxyTable, type ReconcileIntegrationInput, type RemoveWorktreeFastOptions, type ResolveGcClassOptions, type ResolveSupervisorInput, type ResolvedGcClass, type ResolvedWorktreeRuntime, RestForgeClient, type RunningProxy, SALVAGE_ROOT, SESSIONS_BUCKETS_ROOT, SESSIONS_FILE_PATH, type SalvageManifest, type SalvageResult, type SalvageWorktreeInput, type ScriptConfig, type ServiceRuntime, type ServiceStatus, ServiceSupervisor, type SessionRef, type SupervisorOptions, type TipClassification, type TreeIndex, type TreeState, UnreachableForgeClient, VERDICT_MEMO_PATH, type VerdictMemoRecord, type VerdictMemoStore, WORKTREES_TURBO_CACHE_DIR_ENV, WORKTREE_TRASH_DIRNAME, type WorktreeAgentInput, type WorktreeClass, type WorktreeEnvContext, type WorktreeMarker, WorktreeNotRemovableError, type WorktreeStatusEntry, allocatePort, applyBranchGc, applyGc, branchReviewQueue, branchVerdictSchema, classify, classifyForGc, classifyTip, classifyTipAgainstBase, computeBaseDivergence, computeLiveness, computeProvenance, computeTreeState, computeWorktreeStatus, connectDaemonAgentSessionHost, createForgeClient, createLadderContext, createProxyServer, detectAnchor, detectDefaultBranch, disposeSupervisor, ephemeralPort, execArgv, execGit, execShell, expandGlob, getScript, getSupervisor, globToRegExp, hookEnv, isMechanicalDepBumpRange, isPortFree, listGitWorktrees, listScripts, listServices, listWorktreeStatuses, loadConfigFromBase, makeDaemonAgentSessionHost, normalizeHook, parseConfig, parseGithubOwnerRepo, peerEnv, peerEnvKey, planBranchGc, planGc, readBranchGcRestoreLog, readSessionsRegistry, readWorktreeMarker, reclaimOneWorktree, reconcileIntegration, recordBranchVerdict, removeWorktreeFast, repoLabel, resolveGcClass, resolveSupervisor, resolveWorktreesTurboCacheDir, runSetup, runTeardown, salvageWorktree, serviceEnv, serviceEnvToken, serviceHostname, serviceUrl, sessionInWorktree, sharedProxyTable, slugify, startProxy, stripPort, summarizeBranchGcPlan, sweepWorktreeTrash, worktreeAgentInputSchema, worktreeAgentWorkflow, writeWorktreeMarker };
2431
+ export { type AcquireRequest, type AgentprotoConfig, type ApplyBranchGcOptions, type ApplyGcOptions, BRANCH_GC_SCOPES, BRANCH_GC_STATE_DIR, BRANCH_TRIAGE_VERDICTS, BRANCH_VERDICTS_PATH, type BaseDivergence, type BranchCoverage, type BranchGcApplyOutcome, type BranchGcApplyResult, type BranchGcClass, type BranchGcHoldReason, type BranchGcPlan, type BranchGcPlanEntry, type BranchGcReclaimReason, type BranchGcRestoreEntry, type BranchGcRestoreLog, type BranchGcSummary, type BranchHistory, type BranchPushState, type BranchRef, type BranchRefKind, type BranchReviewCandidate, type BranchReviewQueue, type BranchStatus, type BranchTriageVerdict, type BranchVerdict, BranchVerdictError, type BranchVerdictRecord, type BranchVerdictStore, type BranchVerdictSummary, CONFIG_FILENAME, type Classification, type ClassifyForGcOptions, type ComputeProvenanceOptions, type ComputeTreeStateOptions, type ComputeWorktreeStatusInput, ConfigError, DEFAULT_BRANCH_GC_MIN_AGE_DAYS, DEFAULT_GC_NOISE_PATHS, DEFAULT_PROVISION_CONCURRENCY, DEFAULT_PROVISION_LIMITS, DEFAULT_PROXY_PORT, type DaemonAgentSessionHost, type DaemonClient, ENV_VARS, type ExecOptions, type ExecResult, FileBranchVerdictStore, FileVerdictMemoStore, type ForgeClient, type ForgePullRequestRef, ForgeUnavailableError, type GateState, type GcApplyOutcome, type GcClass, type GcHoldReason, type GcPlanEntry, type GcReclaimReason, GhCliForgeClient, type GitWorktreeRef, GlobTraversalError, HookError, type HookRun, type HostnameParts, type InBaseReclaimReason, InMemoryBranchVerdictStore, InMemoryVerdictMemoStore, type IntegrationState, LOCAL_WORKTREE_CONFIG_REL, type LadderContext, type ListWorktreeStatusesInput, type LivenessState, type LocalWorktreeConfig, type LocalWriteFileEntry, type NamedScript, PROVISION_CONCURRENCY_ENV, type PeerService, type PlanBranchGcInput, type PlanGcInput, type ProvenanceConfidence, type ProvenanceInfo, ProvisionCancelledError, type ProvisionLease, type ProvisionLimits, type ProvisionPhase, type ProvisionProgress, type ProvisionRunContext, ProvisionScheduler, ProxyTable, type ReconcileIntegrationInput, type RemoveWorktreeFastOptions, type ResolveGcClassOptions, type ResolveSupervisorInput, type ResolvedGcClass, type ResolvedWorktreeRuntime, RestForgeClient, type RunningProxy, SALVAGE_ROOT, SESSIONS_BUCKETS_ROOT, SESSIONS_FILE_PATH, type SalvageManifest, type SalvageResult, type SalvageWorktreeInput, type SchedulerOptions, type SchedulerSnapshot, type ScriptConfig, type ServiceRuntime, type ServiceStatus, ServiceSupervisor, type SessionRef, type SupervisorOptions, type TipClassification, type TreeIndex, type TreeState, UnreachableForgeClient, VERDICT_MEMO_PATH, type VerdictMemoRecord, type VerdictMemoStore, WORKTREES_TURBO_CACHE_DIR_ENV, WORKTREE_TRASH_DIRNAME, type WorktreeAgentInput, type WorktreeClass, type WorktreeEnvContext, type WorktreeMarker, WorktreeNotRemovableError, type WorktreeStatusEntry, allocatePort, applyBranchGc, applyGc, applySlugPlaceholder, branchReviewQueue, branchVerdictSchema, classify, classifyForGc, classifyTip, classifyTipAgainstBase, cloneEntries, computeBaseDivergence, computeLiveness, computeProvenance, computeTreeState, computeWorktreeStatus, connectDaemonAgentSessionHost, createForgeClient, createLadderContext, createProxyServer, currentProvisionContext, detectAnchor, detectDefaultBranch, disposeSupervisor, ephemeralPort, execArgv, execGit, execShell, expandCloneGlob, expandGlob, getScript, getSupervisor, globToRegExp, hookEnv, isMechanicalDepBumpRange, isPortFree, listGitWorktrees, listScripts, listServices, listWorktreeStatuses, loadConfigFromBase, loadLocalWorktreeConfig, makeDaemonAgentSessionHost, normalizeHook, parseConfig, parseGithubOwnerRepo, parseLocalWorktreeConfig, parseProvisionLimits, peerEnv, peerEnvKey, planBranchGc, planGc, provisionScheduler, readBranchGcRestoreLog, readSessionsRegistry, readWorktreeMarker, reclaimOneWorktree, reconcileIntegration, recordBranchVerdict, removeWorktreeFast, repoLabel, resolveGcClass, resolveLocalWriteFiles, resolveSupervisor, resolveWorktreesTurboCacheDir, runSetup, runTeardown, runWithProvisionContext, salvageWorktree, serviceEnv, serviceEnvToken, serviceHostname, serviceUrl, sessionInWorktree, sharedProxyTable, slugify, startProxy, stripPort, summarizeBranchGcPlan, sweepWorktreeTrash, worktreeAgentInputSchema, worktreeAgentWorkflow, writeWorktreeMarker };
package/dist/index.mjs CHANGED
@@ -1,9 +1,9 @@
1
- export { connectDaemonAgentSessionHost, makeDaemonAgentSessionHost, worktreeAgentInputSchema, worktreeAgentWorkflow } from './chunk-5SDH2V6M.mjs';
1
+ export { connectDaemonAgentSessionHost, makeDaemonAgentSessionHost, worktreeAgentInputSchema, worktreeAgentWorkflow } from './chunk-FC3I5NTS.mjs';
2
2
  import './chunk-E3EM24BS.mjs';
3
- import { computeProvenance, execArgv, classify, computeWorktreeStatus, sweepWorktreeTrash, listGitWorktrees, execGit, worktreeProvider } from './chunk-EVHLUKC7.mjs';
4
- export { CONFIG_FILENAME, ConfigError, DEFAULT_PROXY_PORT, ENV_VARS, FileVerdictMemoStore, HookError, InMemoryVerdictMemoStore, ProxyTable, SESSIONS_BUCKETS_ROOT, SESSIONS_FILE_PATH, ServiceSupervisor, VERDICT_MEMO_PATH, WORKTREES_TURBO_CACHE_DIR_ENV, WORKTREE_TRASH_DIRNAME, WorktreeNotRemovableError, allocatePort, classify, computeBaseDivergence, computeLiveness, computeProvenance, computeTreeState, computeWorktreeStatus, detectDefaultBranch, disposeSupervisor, ephemeralPort, execArgv, execGit, execShell, expandGlob, getScript, getSupervisor, globToRegExp, hookEnv, isPortFree, listGitWorktrees, listScripts, listServices, listWorktreeStatuses, loadConfigFromBase, normalizeHook, parseConfig, peerEnv, peerEnvKey, readSessionsRegistry, readWorktreeMarker, reconcileIntegration, removeWorktreeFast, repoLabel, resolveSupervisor, resolveWorktreesTurboCacheDir, runSetup, runTeardown, serviceEnv, serviceEnvToken, serviceHostname, serviceUrl, sessionInWorktree, sharedProxyTable, slugify, stripPort, sweepWorktreeTrash, worktreeProvider, writeWorktreeMarker } from './chunk-EVHLUKC7.mjs';
5
- import { cleanupWorktreeTool } from './chunk-EK5BH2YL.mjs';
6
- export { cleanupWorktreeTool, listServicesTool, provisionWorktreeTool, runGateTool, runScriptTool, serviceStatusSchema, startServiceTool, stopServiceTool } from './chunk-EK5BH2YL.mjs';
3
+ import { computeProvenance, execArgv, classify, computeWorktreeStatus, sweepWorktreeTrash, listGitWorktrees, execGit, worktreeProvider } from './chunk-IEW2O3PF.mjs';
4
+ export { CONFIG_FILENAME, ConfigError, DEFAULT_PROVISION_CONCURRENCY, DEFAULT_PROVISION_LIMITS, DEFAULT_PROXY_PORT, ENV_VARS, FileVerdictMemoStore, GlobTraversalError, HookError, InMemoryVerdictMemoStore, LOCAL_WORKTREE_CONFIG_REL, PROVISION_CONCURRENCY_ENV, ProvisionCancelledError, ProvisionScheduler, ProxyTable, SESSIONS_BUCKETS_ROOT, SESSIONS_FILE_PATH, ServiceSupervisor, VERDICT_MEMO_PATH, WORKTREES_TURBO_CACHE_DIR_ENV, WORKTREE_TRASH_DIRNAME, WorktreeNotRemovableError, allocatePort, applySlugPlaceholder, classify, cloneEntries, computeBaseDivergence, computeLiveness, computeProvenance, computeTreeState, computeWorktreeStatus, currentProvisionContext, detectDefaultBranch, disposeSupervisor, ephemeralPort, execArgv, execGit, execShell, expandCloneGlob, expandGlob, getScript, getSupervisor, globToRegExp, hookEnv, isPortFree, listGitWorktrees, listScripts, listServices, listWorktreeStatuses, loadConfigFromBase, loadLocalWorktreeConfig, normalizeHook, parseConfig, parseLocalWorktreeConfig, parseProvisionLimits, peerEnv, peerEnvKey, provisionScheduler, readSessionsRegistry, readWorktreeMarker, reconcileIntegration, removeWorktreeFast, repoLabel, resolveLocalWriteFiles, resolveSupervisor, resolveWorktreesTurboCacheDir, runSetup, runTeardown, runWithProvisionContext, serviceEnv, serviceEnvToken, serviceHostname, serviceUrl, sessionInWorktree, sharedProxyTable, slugify, stripPort, sweepWorktreeTrash, worktreeProvider, writeWorktreeMarker } from './chunk-IEW2O3PF.mjs';
5
+ import { cleanupWorktreeTool } from './chunk-3FZWPMLF.mjs';
6
+ export { cleanupWorktreeTool, listServicesTool, provisionWorktreeTool, runGateTool, runScriptTool, serviceStatusSchema, startServiceTool, stopServiceTool } from './chunk-3FZWPMLF.mjs';
7
7
  import { mkdir, copyFile, readFile, writeFile, open, rename, readdir, realpath, rm, stat } from 'fs/promises';
8
8
  import { homedir } from 'os';
9
9
  import { resolve, join, dirname, basename, sep, relative, isAbsolute } from 'path';
@@ -1,4 +1,4 @@
1
- export { worktreeProvider } from '../chunk-EVHLUKC7.mjs';
2
- import '../chunk-EK5BH2YL.mjs';
1
+ export { worktreeProvider } from '../chunk-IEW2O3PF.mjs';
2
+ import '../chunk-3FZWPMLF.mjs';
3
3
  //# sourceMappingURL=index.mjs.map
4
4
  //# sourceMappingURL=index.mjs.map
@@ -14,6 +14,7 @@ declare const provisionWorktreeTool: _agentproto_tool.ToolHandle<{
14
14
  dir?: string | undefined;
15
15
  depsCmd?: string | undefined;
16
16
  copyGlobs?: string[] | undefined;
17
+ cloneGlobs?: string[] | undefined;
17
18
  linkPaths?: string[] | undefined;
18
19
  writeFiles?: {
19
20
  path: string;
@@ -1,4 +1,4 @@
1
1
  import '../chunk-E3EM24BS.mjs';
2
- export { cleanupWorktreeTool, listServicesTool, provisionWorktreeTool, runGateTool, runScriptTool, serviceStatusSchema, startServiceTool, stopServiceTool } from '../chunk-EK5BH2YL.mjs';
2
+ export { cleanupWorktreeTool, listServicesTool, provisionWorktreeTool, runGateTool, runScriptTool, serviceStatusSchema, startServiceTool, stopServiceTool } from '../chunk-3FZWPMLF.mjs';
3
3
  //# sourceMappingURL=index.mjs.map
4
4
  //# sourceMappingURL=index.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentproto/worktree",
3
- "version": "0.12.0",
3
+ "version": "0.14.0",
4
4
  "description": "AIP-14 TOOL contracts + builtin AIP-30 PROVIDER for provisioning, gating, and cleaning up a git worktree — the primitive an AgentStep binds its `cwd` to for a launch-agent-in-a-worktree workflow.",
5
5
  "keywords": [
6
6
  "agentproto",
@@ -57,19 +57,19 @@
57
57
  "access": "public"
58
58
  },
59
59
  "dependencies": {
60
- "@modelcontextprotocol/sdk": "^1.30.0",
60
+ "@modelcontextprotocol/sdk": "^1.30.1",
61
61
  "zod": "^4.6.5",
62
- "@agentproto/driver": "0.2.4",
63
- "@agentproto/harness": "0.4.6",
64
- "@agentproto/tool": "0.3.1",
65
- "@agentproto/workflow-runtime": "0.14.0"
62
+ "@agentproto/driver": "0.2.5",
63
+ "@agentproto/harness": "0.4.7",
64
+ "@agentproto/tool": "0.3.2",
65
+ "@agentproto/workflow-runtime": "0.15.0"
66
66
  },
67
67
  "devDependencies": {
68
68
  "@types/node": "^25.9.5",
69
69
  "tsup": "^8.5.1",
70
70
  "typescript": "^5.9.3",
71
71
  "vitest": "^3.2.7",
72
- "@agentproto/routine": "0.3.0",
72
+ "@agentproto/routine": "0.3.1",
73
73
  "@agentproto/tooling": "0.1.0"
74
74
  },
75
75
  "scripts": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/tools/provision-worktree.tool.ts","../src/tools/cleanup-worktree.tool.ts","../src/tools/run-gate.tool.ts","../src/tools/run-script.tool.ts","../src/tools/service.schema.ts","../src/tools/start-service.tool.ts","../src/tools/stop-service.tool.ts","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AI,CAAC,CAAA,CAAE,IAAI,KAAK,CAAA,CAAE,QAAA,EAAS,CAAE,SAAS,gDAAgD;AAAA,GACnH,CAAA;AAAA,EACD,YAAA,EAAcA,EAAE,MAAA,CAAO;AAAA,IACrB,QAAA,EAAUA,CAAAA,CAAE,KAAA,CAAM,mBAAmB;AAAA,GACtC,CAAA;AAAA,EACD,SAAS,EAAC;AAAA,EACV,QAAA,EAAU,MAAA;AAAA,EACV,SAAA,EAAW;AACb,CAAC","file":"chunk-EK5BH2YL.mjs","sourcesContent":["import { z } from \"zod\"\nimport { defineTool } from \"@agentproto/tool\"\n\n/**\n * AIP-14 contract: create a git worktree off a base ref, on its own branch,\n * optionally installing deps and copying gitignored files (secrets) into it.\n * Agnostic — no hardcoded package manager or env layout; both are inputs.\n */\nexport const provisionWorktreeTool = defineTool({\n id: \"worktree.provision\",\n description:\n \"Create a git worktree for `repoRoot` at a sibling '_worktrees/<slug>' \" +\n \"directory (or `dir`, when given), on a new branch 'wt/<slug>' (or \" +\n \"`branch`, when given) cut from `base`. If `depsCmd` is given, it runs \" +\n \"inside the new worktree afterwards (e.g. install deps). If `copyGlobs` \" +\n \"is given, matching files under `repoRoot` (including gitignored ones, \" +\n \"e.g. local secrets) are copied into the worktree at the same relative \" +\n \"path. If `linkPaths` is given, each is symlinked from `repoRoot` into \" +\n \"the worktree before `depsCmd` runs — for gitignored, expensive-to-\" +\n \"recreate trees a fresh worktree lacks (node_modules, sibling workspace \" +\n \"repos) so the workspace graph resolves without a full reinstall. When \" +\n \"`depsCmd`/`linkPaths` are omitted, they fall back to `worktree.depsCmd`/\" +\n \"`worktree.linkPaths` declared in the base tree's agentproto.json (same \" +\n \"`runSetup` gate as the setup hooks below) — an explicit input always \" +\n \"wins over the declarative default. If \" +\n \"`writeFiles` is given, each entry's `content` is written into the \" +\n \"worktree at `path` before `depsCmd` runs — for generated, worktree-\" +\n \"specific config a tool invoked by `depsCmd` needs to see (e.g. a \" +\n \"package-manager config pointing a cache/store dir outside the \" +\n \"worktree, so it isn't shared with — or clobbered by — a sibling \" +\n \"worktree). `mode: \\\"create\\\"` (default) skips an entry whose path \" +\n \"already exists, matching `linkPaths`' never-clobber rule; \" +\n \"`mode: \\\"append\\\"` always appends (creating the file if missing) and, \" +\n \"if git already tracks that path, marks it `skip-worktree` afterwards \" +\n \"so the tweak never shows up as a local modification the caller could \" +\n \"accidentally commit — callers are responsible for making the content \" +\n \"itself idempotent (e.g. checking `repoRoot`'s copy of the file for the \" +\n \"line before including the entry, since a fresh worktree's tracked \" +\n \"files start as a byte-identical checkout). Also writes a creation-\" +\n \"provenance marker into the worktree's private gitdir.\",\n version: \"0.2.0\",\n inputSchema: z.object({\n repoRoot: z.string().describe(\"Absolute path to the git repository root.\"),\n base: z\n .string()\n .optional()\n .describe(\"Ref the new branch is cut from. Default 'origin/main'.\"),\n slug: z\n .string()\n .regex(/^[a-z0-9][a-z0-9-]*$/, \"slug must be lowercase kebab-case\")\n .describe(\"Short identifier — names both the worktree directory and its branch.\"),\n branch: z\n .string()\n .optional()\n .describe(\"Branch name for the new worktree. Default 'wt/<slug>'.\"),\n dir: z\n .string()\n .optional()\n .describe(\"Absolute path for the new worktree. Default '<repoRoot>/../_worktrees/<slug>'.\"),\n depsCmd: z\n .string()\n .optional()\n .describe(\"Shell command run inside the worktree after creation, e.g. 'pnpm install --prefer-offline'.\"),\n copyGlobs: z\n .array(z.string())\n .optional()\n .describe(\"Glob patterns (relative to repoRoot) of gitignored files to copy into the worktree, e.g. 'envs/**/.env.local'.\"),\n linkPaths: z\n .array(z.string())\n .optional()\n .describe(\"Relative paths (dirs or files) symlinked from repoRoot into the worktree before depsCmd, e.g. 'node_modules' or a gitignored sibling workspace repo. Lets the workspace graph resolve without a full reinstall.\"),\n writeFiles: z\n .array(\n z.object({\n path: z.string().describe(\"Path relative to the worktree root.\"),\n content: z.string().describe(\"File content, written or appended verbatim.\"),\n mode: z\n .enum([\"create\", \"append\"])\n .optional()\n .describe(\"'create' (default): write only if path doesn't already exist. 'append': always append (creating if missing); if git tracks the path, it's marked skip-worktree afterwards so the change never shows as a local modification.\"),\n }),\n )\n .optional()\n .describe(\"Files written into the worktree before depsCmd runs, e.g. a package-manager config generated for this specific worktree.\"),\n runSetup: z\n .boolean()\n .optional()\n .describe(\"Read the base tree's agentproto.json and apply its declarative worktree lifecycle: `worktree.depsCmd`/`worktree.linkPaths` as fallbacks for the inputs above, then the `worktree.setup` hooks after creation. Default true; a failing setup hook fails provisioning.\"),\n setupLogPath: z\n .string()\n .optional()\n .describe(\"Absolute path to append the FULL, unfiltered stdout+stderr of every `worktree.setup` hook command to (success or failure). Caller-provided — typically a path under the spawning session's own directory, so the full output outlives a subsequently-reclaimed worktree. Best-effort: a write failure never fails provisioning. When omitted, only a short, noise-filtered tail survives in a failing hook's own error message.\"),\n retrySetupOnFailure: z\n .boolean()\n .optional()\n .describe(\"Re-run a failing `worktree.setup` command exactly once before giving up — a complement to (never a substitute for) a real root-cause fix, meant for unattended callers with no way to retry themselves short of provisioning an entirely new worktree. Default false: an interactive caller (e.g. `agentproto worktree new`) sees a genuine failure on the first try rather than waiting through an identical rerun.\"),\n }),\n outputSchema: z.object({\n cwd: z.string().describe(\"Absolute path to the created worktree.\"),\n branch: z.string().describe(\"The branch the worktree was created on.\"),\n }),\n mutates: [\"fs:write\"],\n approval: \"auto\",\n riskLevel: 1,\n})\n","import { z } from \"zod\"\nimport { defineTool } from \"@agentproto/tool\"\n\n/**\n * AIP-14 contract: remove a git worktree, optionally deleting its branch.\n *\n * Guarded by default (PLAN.md §5.2 layer 3): with neither discard flag set,\n * this runs a plain `git worktree remove` — git itself is the final arbiter\n * and refuses on modified or unignored-untracked files, tolerating gitignored\n * trees like `node_modules/`. `discardUntracked` / `discardModified` each\n * authorize exactly one class of destruction git otherwise refuses; only\n * when the flags cover everything actually dirty does `--force` get passed\n * through. This replaces an unconditional `--force` that used to destroy\n * real edits indiscriminately (the incident this contract change exists to\n * prevent) — hence `riskLevel: 2`, up from the old unconditional-force `1`.\n */\nexport const cleanupWorktreeTool = defineTool({\n id: \"worktree.cleanup\",\n description:\n \"Remove a git worktree created by 'worktree.provision'. Refuses if the \" +\n \"worktree has modified tracked files or unignored untracked files, \" +\n \"unless the matching `discardModified` / `discardUntracked` flag is \" +\n \"set — a clean or gitignore-only tree (e.g. installed deps) always \" +\n \"removes with no flags. If `deleteBranch` is true and `branch` is \" +\n \"given, also force-delete that branch (only ever called for merged \" +\n \"branches by this package's own callers).\",\n version: \"0.2.0\",\n inputSchema: z.object({\n repoRoot: z.string().describe(\"Absolute path to the git repository root.\"),\n cwd: z.string().describe(\"Absolute path to the worktree to remove.\"),\n branch: z.string().optional().describe(\"The worktree's branch, for deleteBranch.\"),\n deleteBranch: z.boolean().optional().describe(\"Also force-delete `branch` after removing the worktree.\"),\n base: z.string().optional().describe(\"Ref whose committed agentproto.json supplies teardown hooks. Default 'origin/main'.\"),\n runTeardown: z.boolean().optional().describe(\"Run the `worktree.teardown` hooks before removal. Default true; teardown failures are logged, never blocking.\"),\n discardUntracked: z.boolean().optional().describe(\"Authorize discarding unignored untracked files. Default false: refuse if any are present.\"),\n discardModified: z.boolean().optional().describe(\"Authorize discarding modified tracked files (staged or unstaged). Default false: refuse if any are present.\"),\n }),\n outputSchema: z.object({\n removed: z.literal(true),\n }),\n mutates: [\"fs:write\"],\n approval: \"auto\",\n riskLevel: 2,\n})\n","import { z } from \"zod\"\nimport { defineTool } from \"@agentproto/tool\"\n\n/**\n * AIP-14 contract: run a caller-provided gate/check command inside a\n * directory (typically a provisioned worktree) and report pass/fail.\n * `cmd` is a trusted, developer-authored config value (same trust model as\n * a CI job's `script:` line), run through a shell so it may include flags.\n */\nexport const runGateTool = defineTool({\n id: \"worktree.run-gate\",\n description:\n \"Run a gate command (e.g. 'pnpm test') inside `cwd` and report pass/fail \" +\n \"from its exit code, along with captured stdout/stderr.\",\n version: \"0.1.0\",\n inputSchema: z.object({\n cwd: z.string().describe(\"Directory to run the command in.\"),\n cmd: z.string().describe(\"Shell command to run, e.g. 'pnpm test'.\"),\n }),\n outputSchema: z.object({\n passed: z.boolean(),\n exitCode: z.number().int(),\n stdout: z.string(),\n stderr: z.string(),\n }),\n mutates: [],\n approval: \"auto\",\n riskLevel: 1,\n})\n","import { z } from \"zod\"\nimport { defineTool } from \"@agentproto/tool\"\n\n/**\n * AIP-14 contract: run a one-shot named `scripts.<name>` command from the\n * repo's committed `agentproto.json` inside a worktree, with the\n * `AGENTPROTO_*` context env injected. For long-running services use\n * `worktree.start-service` instead.\n */\nexport const runScriptTool = defineTool({\n id: \"worktree.run-script\",\n description:\n \"Run a declared `scripts.<name>` command (from the base tree's \" +\n \"agentproto.json) inside `worktreePath`, injecting AGENTPROTO_* env, and \" +\n \"report pass/fail with captured stdout/stderr. For a `type: \\\"service\\\"` \" +\n \"script prefer `worktree.start-service`.\",\n version: \"0.1.0\",\n inputSchema: z.object({\n repoRoot: z.string().describe(\"Absolute path to the source git repository root.\"),\n worktreePath: z.string().describe(\"Absolute path to the worktree to run in.\"),\n branch: z.string().describe(\"The worktree's branch name (for AGENTPROTO_BRANCH_NAME).\"),\n script: z.string().describe(\"Name of the script under `scripts` to run.\"),\n base: z.string().optional().describe(\"Ref whose committed agentproto.json is read. Default 'origin/main'.\"),\n }),\n outputSchema: z.object({\n passed: z.boolean(),\n exitCode: z.number().int(),\n stdout: z.string(),\n stderr: z.string(),\n }),\n mutates: [\"fs:write\"],\n approval: \"auto\",\n riskLevel: 1,\n})\n","import { z } from \"zod\"\n\n/** Shared shape of a supervised service's status across the service tools. */\nexport const serviceStatusSchema = z.object({\n name: z.string().describe(\"The declared script name.\"),\n hostname: z.string().describe(\"The *.localhost host the reverse proxy routes to this service.\"),\n port: z.number().int().describe(\"The port the service listens on.\"),\n url: z.string().describe(\"The service's reverse-proxy URL.\"),\n pid: z.number().int().nullable().describe(\"Child process id while running, else null.\"),\n status: z.enum([\"running\", \"exited\"]).describe(\"Whether the service process is up.\"),\n exitCode: z.number().int().nullable().describe(\"Exit code once it has exited, else null.\"),\n startedAt: z.string().nullable().describe(\"ISO timestamp of the last start, else null.\"),\n})\n\nexport type ServiceStatusOutput = z.infer<typeof serviceStatusSchema>\n","import { z } from \"zod\"\nimport { defineTool } from \"@agentproto/tool\"\nimport { serviceStatusSchema } from \"./service.schema.js\"\n\n/**\n * AIP-14 contract: start a declared `type: \"service\"` script for a worktree.\n * Allocates the service's port (declared port if free, else ephemeral),\n * injects AGENTPROTO_PORT/URL + peer env, and registers its hostname with the\n * reverse proxy. Idempotent per worktree+name.\n */\nexport const startServiceTool = defineTool({\n id: \"worktree.start-service\",\n description:\n \"Start a declared `scripts.<name>` service for a worktree as a supervised \" +\n \"long-running child process. Allocates a port, injects AGENTPROTO_PORT / \" +\n \"AGENTPROTO_URL and AGENTPROTO_SERVICE_<PEER>_PORT|URL for siblings, and \" +\n \"registers a `<script>--<branch>--<repo>.localhost` proxy route.\",\n version: \"0.1.0\",\n inputSchema: z.object({\n repoRoot: z.string().describe(\"Absolute path to the source git repository root.\"),\n worktreePath: z.string().describe(\"Absolute path to the worktree.\"),\n branch: z.string().describe(\"The worktree's branch name.\"),\n script: z.string().describe(\"Name of the `type: \\\"service\\\"` script to start.\"),\n base: z.string().optional().describe(\"Ref whose committed agentproto.json is read. Default 'origin/main'.\"),\n proxyPort: z.number().int().min(1).max(65535).optional().describe(\"Reverse-proxy port used to build the service URL.\"),\n }),\n outputSchema: serviceStatusSchema,\n mutates: [\"process:spawn\"],\n approval: \"auto\",\n riskLevel: 1,\n})\n","import { z } from \"zod\"\nimport { defineTool } from \"@agentproto/tool\"\n\n/** AIP-14 contract: stop a running supervised service for a worktree. */\nexport const stopServiceTool = defineTool({\n id: \"worktree.stop-service\",\n description:\n \"Stop a supervised service (SIGTERM) for a worktree and drop its reverse-\" +\n \"proxy route. A no-op (stopped: false) if the service isn't running.\",\n version: \"0.1.0\",\n inputSchema: z.object({\n worktreePath: z.string().describe(\"Absolute path to the worktree.\"),\n script: z.string().describe(\"Name of the service to stop.\"),\n }),\n outputSchema: z.object({\n stopped: z.boolean().describe(\"Whether a running service was actually stopped.\"),\n }),\n mutates: [\"process:spawn\"],\n approval: \"auto\",\n riskLevel: 1,\n})\n","import { z } from \"zod\"\nimport { defineTool } from \"@agentproto/tool\"\nimport { serviceStatusSchema } from \"./service.schema.js\"\n\n/**\n * AIP-14 contract: list every declared service for a worktree with its\n * resolved port / proxy URL and current run status. Resolves (allocating\n * ports for) the worktree's services on first call so declared-but-unstarted\n * services still appear.\n */\nexport const listServicesTool = defineTool({\n id: \"worktree.list-services\",\n description:\n \"List the declared services for a worktree — each with its allocated \" +\n \"port, `*.localhost` proxy URL, and running/exited status.\",\n version: \"0.1.0\",\n inputSchema: z.object({\n repoRoot: z.string().describe(\"Absolute path to the source git repository root.\"),\n worktreePath: z.string().describe(\"Absolute path to the worktree.\"),\n branch: z.string().describe(\"The worktree's branch name.\"),\n base: z.string().optional().describe(\"Ref whose committed agentproto.json is read. Default 'origin/main'.\"),\n proxyPort: z.number().int().min(1).max(65535).optional().describe(\"Reverse-proxy port used to build service URLs.\"),\n }),\n outputSchema: z.object({\n services: z.array(serviceStatusSchema),\n }),\n mutates: [],\n approval: \"auto\",\n riskLevel: 0,\n})\n"]}