Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998/** * `shard new` + `shard worktree` — daemon-backed worktree CLI flows (saga j8dtju.8). * * Thin L4 CLI runners over the daemon orchestrator command surface (`workspace.*`, * PROTOCOL §10.1). The CLI NEVER invokes Git itself — Git authority + branch-deletion * safety live in `shardd` (j8dtju.6). Discovery + a short-lived socket client are the only * daemon touchpoints; responses are validated with `WorkspaceResponseSchemas` + * `Value.Check` before rendering. * * Syntax (saga j8dtju.8 plan item 1): * shard new --worktree [--name <label>] [--branch <branch>] [--base <ref>] * [--integration-target <ref>] * [--title <t>] [--model <m>] [--provider <p>] [--mode <m>] [--socket <path>] * → workspace.create from cwd; allocates a fresh Agent + Session. * shard new --workspace <id> * [--title <t>] [--model <m>] [--provider <p>] [--mode <m>] [--socket <path>] * → workspace.attach; allocates a fresh Agent + Session in an existing active workspace. * shard worktree list [--all] [--include-retired] [--socket <path>] * → workspace.list. Defaults to the cwd repository scope; `--all` omits the cwd filter. * shard worktree status <id> [--socket <path>] * → workspace.status. * shard worktree retire <id> [--keep|--delete|--force-delete] [--socket <path>] * → workspace.retire. `--keep`→keep, `--delete`→delete_if_merged, `--force-delete`→ * delete_confirmed. An unproven `--delete` returns a typed `confirmation_required` * refusal: an interactive stdin prompts explicitly for cancel/keep/confirmed-delete; * a noninteractive stdin fails with actionable explicit retry flags and NEVER forces. * * Exit codes: 0 success; 1 daemon-side refusal (`success:false`); 2 unavailable daemon / * argument-validation failure. The unavailable-daemon path (no socket discovered / connect * failure) is exit 2 so a wrapper script can distinguish "daemon down" from "daemon refused". * * Boundary: L4 CLI module. Imports `@/subagent/daemon-client` (L3), `@/cli/daemon-discover` * (L4), `@/protocol/*` + `@/contracts/*` (L1), and `@sinclair/typebox`. No `@/core`, * `@/daemon`, no Git imports/calls. */import { Type } from '@sinclair/typebox';import { Value } from '@sinclair/typebox/value';import { connectSubagentClient, type SubagentClient, type SubagentClientResult } from '@/subagent/daemon-client';import { discoverDaemon } from '@/cli/daemon-discover';import { WorkspaceResponseSchemas, WorkspaceRetireRefusalSchema, type WorkspaceSummary, type WorkspaceDetail, type WorkspaceCreateResponse, type WorkspaceAttachResponse, type WorkspaceListResponse, type WorkspaceStatusResponse, type WorkspaceRetireResponse, type WorkspaceRetireRefusal,} from '@/protocol/response';import type { ResponseError } from '@/protocol/response';
// ─── Exit codes ────────────────────────────────────────────────────────────────
/** Daemon unavailable / argument validation failure (distinguishable from a refusal). */export const EXIT_DAEMON_UNAVAILABLE = 2;/** Daemon-side refusal (`success:false`) or a typed confirmation that was not confirmed. */export const EXIT_DAEMON_REFUSED = 1;/** Success. */export const EXIT_OK = 0;
// ─── Command payload type ───────────────────────────────────────────────────────
/** A workspace orchestrator command payload: a `type` + correlation `id` + payload. */export interface WorkspaceCommandPayload { readonly type: string; readonly id: string; readonly [key: string]: unknown;}
// ─── Injectable runner dependencies ────────────────────────────────────────────
/** A minimal writable stream surface (stdout/stderr) the runners write to. */export interface WritableLike { write(s: string): void;}
/** A minimal interactive-prompt surface (readline-style). */export interface PromptLike { /** Ask one question; resolve with the trimmed answer (empty on EOF/no input). */ question(query: string): Promise<string>;}
/** * Injectable dependencies so tests are hermetic: the daemon client factory, cwd, TTY * detection, prompt, and stdout/stderr are all swappable. The production wiring builds * these from `process` + `node:readline` + `discoverDaemon` + `connectSubagentClient`. */export interface WorktreeCmdDeps { /** Resolve the caller's working directory (default `process.cwd()`). */ cwd: () => string; /** Discover a running daemon socket path, or `undefined` (default `discoverDaemon`). */ discover: () => string | undefined; /** Connect a short-lived daemon client (default `connectSubagentClient`). */ connect: (socketPath: string) => Promise<SubagentClient>; /** Whether stdin is an interactive TTY (default `process.stdin.isTTY`). */ isTTY: () => boolean; /** Interactive prompt surface (used only when `isTTY()` and a confirmation is needed). */ prompt: PromptLike; /** stdout sink (default `process.stdout`). */ stdout: WritableLike; /** stderr sink (default `process.stderr`). */ stderr: WritableLike;}
/** Build production deps from `process` + `node:readline` + the daemon client. */export function defaultWorktreeCmdDeps(): WorktreeCmdDeps { return { cwd: () => process.cwd(), discover: () => discoverDaemon(), connect: (socketPath) => connectSubagentClient({ socketPath }), isTTY: () => (process.stdin as { isTTY?: boolean }).isTTY === true, prompt: makeReadlinePrompt(), stdout: process.stdout, stderr: process.stderr, };}
/** Build a readline-based prompt against stdin/stderr (lazy import — tests inject a fake). */function makeReadlinePrompt(): PromptLike { return { async question(query: string): Promise<string> { const readline = await import('node:readline/promises'); const rl = readline.createInterface({ input: process.stdin, output: process.stderr }); try { const answer = await rl.question(query); return answer.trim(); } finally { rl.close(); } }, };}
// ─── Flag parsing ───────────────────────────────────────────────────────────────
/** Sentinel thrown when `--help`/`-h` is requested (handled by the I/O wrapper). */export class WorktreeHelpRequested extends Error { constructor() { super('help'); this.name = 'WorktreeHelpRequested'; }}
/** A parsed `--socket` value (override) plus the remaining args. */export interface SocketFlag { socketPath?: string; args: string[];}
/** * Extract a `--socket <path>` / `--socket=<path>` flag from argv. Throws on a duplicate, * a missing value, or a value that itself looks like a flag. Returns the remaining args. * Pure (no I/O). */export function parseSocketFlag(args: string[]): SocketFlag { let socketPath: string | undefined; const remaining: string[] = []; for (let i = 0; i < args.length; i++) { const arg = args[i]!; let value: string | undefined; if (arg === '--socket') { value = args[++i]; if (value === undefined || value.length === 0 || value.startsWith('-')) { throw new Error('invalid --socket value'); } } else if (arg.startsWith('--socket=')) { value = arg.slice('--socket='.length); if (value.length === 0) throw new Error('invalid --socket value'); } else { remaining.push(arg); continue; } if (socketPath !== undefined) throw new Error('duplicate --socket flag'); socketPath = value; } return { ...(socketPath === undefined ? {} : { socketPath }), args: remaining };}
/** Pull the value for a `--flag <v>` / `--flag=<v>` form, rejecting flag-like values. */function takeValue(args: string[], i: number, name: string): { value: string; next: number } { const arg = args[i]!; let value: string | undefined; let next = i; if (arg === name) { value = args[++next]; } else if (arg.startsWith(`${name}=`)) { value = arg.slice(`${name}=`.length); } else { return { value: '', next }; // unreachable when called from the dispatcher below } if (value === undefined || value.length === 0 || value.startsWith('-')) { throw new Error(`invalid ${name} value`); } return { value, next };}
/** Parsed `shard new` arguments. Exactly one of `worktree`/`workspace` is set. */export interface NewArgs { /** `--worktree` (create from cwd). */ worktree: boolean; /** `--workspace <id>` (attach to an existing workspace). */ workspaceId?: string; /** `--name <label>` (workspace label; create only). */ name?: string; branch?: string; base?: string; integrationTarget?: string; /** Launch fields shared by create + attach. */ title?: string; model?: string; provider?: string; mode?: string; socketPath?: string;}
/** * Parse `shard new` arguments. Requires exactly one of `--worktree` / `--workspace <id>` * (ambiguous or missing → throw). Rejects unknown flags, duplicate value flags, and * flag-like values. `--help` throws {@link WorktreeHelpRequested}. Pure. */export function parseNewArgs(args: string[]): NewArgs { let worktree = false; let workspaceId: string | undefined; let name: string | undefined; let branch: string | undefined; let base: string | undefined; let integrationTarget: string | undefined; let title: string | undefined; let model: string | undefined; let provider: string | undefined; let mode: string | undefined; let socketPath: string | undefined;
for (let i = 0; i < args.length; i++) { const arg = args[i]!; if (arg === '-h' || arg === '--help') throw new WorktreeHelpRequested(); if (arg === '--worktree') { if (worktree) throw new Error('duplicate --worktree flag'); if (workspaceId !== undefined) throw new Error('ambiguous: --worktree and --workspace are mutually exclusive'); worktree = true; continue; } if (arg === '--workspace' || arg.startsWith('--workspace=')) { if (workspaceId !== undefined) throw new Error('duplicate --workspace flag'); if (worktree) throw new Error('ambiguous: --worktree and --workspace are mutually exclusive'); const { value, next } = takeValue(args, i, '--workspace'); workspaceId = value; i = next; continue; } if (arg === '--name' || arg.startsWith('--name=')) { if (name !== undefined) throw new Error('duplicate --name flag'); const { value, next } = takeValue(args, i, '--name'); name = value; i = next; continue; } if (arg === '--branch' || arg.startsWith('--branch=')) { if (branch !== undefined) throw new Error('duplicate --branch flag'); const { value, next } = takeValue(args, i, '--branch'); branch = value; i = next; continue; } if (arg === '--base' || arg.startsWith('--base=')) { if (base !== undefined) throw new Error('duplicate --base flag'); const { value, next } = takeValue(args, i, '--base'); base = value; i = next; continue; } if (arg === '--integration-target' || arg.startsWith('--integration-target=')) { if (integrationTarget !== undefined) throw new Error('duplicate --integration-target flag'); const { value, next } = takeValue(args, i, '--integration-target'); integrationTarget = value; i = next; continue; } if (arg === '--title' || arg.startsWith('--title=')) { if (title !== undefined) throw new Error('duplicate --title flag'); const { value, next } = takeValue(args, i, '--title'); title = value; i = next; continue; } if (arg === '--model' || arg.startsWith('--model=')) { if (model !== undefined) throw new Error('duplicate --model flag'); const { value, next } = takeValue(args, i, '--model'); model = value; i = next; continue; } if (arg === '--provider' || arg.startsWith('--provider=')) { if (provider !== undefined) throw new Error('duplicate --provider flag'); const { value, next } = takeValue(args, i, '--provider'); provider = value; i = next; continue; } if (arg === '--mode' || arg.startsWith('--mode=')) { if (mode !== undefined) throw new Error('duplicate --mode flag'); const { value, next } = takeValue(args, i, '--mode'); mode = value; i = next; continue; } if (arg === '--socket' || arg.startsWith('--socket=')) { if (socketPath !== undefined) throw new Error('duplicate --socket flag'); const { value, next } = takeValue(args, i, '--socket'); socketPath = value; i = next; continue; } throw new Error(`unknown argument: ${arg}`); }
if (!worktree && workspaceId === undefined) { throw new Error('missing required flag: --worktree or --workspace <id>'); }
return { worktree, ...(workspaceId !== undefined ? { workspaceId } : undefined), ...(name !== undefined ? { name } : undefined), ...(branch !== undefined ? { branch } : undefined), ...(base !== undefined ? { base } : undefined), ...(integrationTarget !== undefined ? { integrationTarget } : undefined), ...(title !== undefined ? { title } : undefined), ...(model !== undefined ? { model } : undefined), ...(provider !== undefined ? { provider } : undefined), ...(mode !== undefined ? { mode } : undefined), ...(socketPath !== undefined ? { socketPath } : undefined), };}
/** Parsed `shard worktree list` arguments. */export interface ListArgs { /** Omit the cwd repository filter (list across all repositories). */ all: boolean; /** Include retired tombstones. */ includeRetired: boolean; socketPath?: string;}
/** Parse `shard worktree list` arguments. Pure. */export function parseListArgs(args: string[]): ListArgs { let all = false; let includeRetired = false; let socketPath: string | undefined; for (let i = 0; i < args.length; i++) { const arg = args[i]!; if (arg === '-h' || arg === '--help') throw new WorktreeHelpRequested(); if (arg === '--all') { if (all) throw new Error('duplicate --all flag'); all = true; continue; } if (arg === '--include-retired') { if (includeRetired) throw new Error('duplicate --include-retired flag'); includeRetired = true; continue; } if (arg === '--socket' || arg.startsWith('--socket=')) { if (socketPath !== undefined) throw new Error('duplicate --socket flag'); const { value, next } = takeValue(args, i, '--socket'); socketPath = value; i = next; continue; } throw new Error(`unknown argument: ${arg}`); } return { all, includeRetired, ...(socketPath !== undefined ? { socketPath } : undefined) };}
/** A retire disposition selected on the command line. */export type RetireDisposition = 'keep' | 'delete' | 'force-delete';
/** Parsed `shard worktree retire` arguments. */export interface RetireArgs { workspaceId: string; disposition: RetireDisposition; socketPath?: string;}
/** Parse `shard worktree retire <id> [--keep|--delete|--force-delete] [--socket]`. Pure. */export function parseRetireArgs(args: string[]): RetireArgs { let workspaceId: string | undefined; let disposition: RetireDisposition | undefined; let socketPath: string | undefined; for (let i = 0; i < args.length; i++) { const arg = args[i]!; if (arg === '-h' || arg === '--help') throw new WorktreeHelpRequested(); if (arg === '--keep') { if (disposition !== undefined) throw new Error('ambiguous: only one of --keep/--delete/--force-delete may be given'); disposition = 'keep'; continue; } if (arg === '--delete') { if (disposition !== undefined) throw new Error('ambiguous: only one of --keep/--delete/--force-delete may be given'); disposition = 'delete'; continue; } if (arg === '--force-delete') { if (disposition !== undefined) throw new Error('ambiguous: only one of --keep/--delete/--force-delete may be given'); disposition = 'force-delete'; continue; } if (arg === '--socket' || arg.startsWith('--socket=')) { if (socketPath !== undefined) throw new Error('duplicate --socket flag'); const { value, next } = takeValue(args, i, '--socket'); socketPath = value; i = next; continue; } if (arg.startsWith('-')) throw new Error(`unknown argument: ${arg}`); // First bare positional is the workspace id. if (workspaceId !== undefined) throw new Error(`unexpected argument: ${arg}`); workspaceId = arg; } if (workspaceId === undefined) throw new Error('missing required workspace id'); return { workspaceId, disposition: disposition ?? 'keep', ...(socketPath !== undefined ? { socketPath } : undefined), };}
/** Parsed `shard worktree status <id>` arguments. */export interface StatusArgs { workspaceId: string; socketPath?: string;}
/** Parse `shard worktree status <id> [--socket]`. Pure. */export function parseStatusArgs(args: string[]): StatusArgs { let workspaceId: string | undefined; let socketPath: string | undefined; for (let i = 0; i < args.length; i++) { const arg = args[i]!; if (arg === '-h' || arg === '--help') throw new WorktreeHelpRequested(); if (arg === '--socket' || arg.startsWith('--socket=')) { if (socketPath !== undefined) throw new Error('duplicate --socket flag'); const { value, next } = takeValue(args, i, '--socket'); socketPath = value; i = next; continue; } if (arg.startsWith('-')) throw new Error(`unknown argument: ${arg}`); if (workspaceId !== undefined) throw new Error(`unexpected argument: ${arg}`); workspaceId = arg; } if (workspaceId === undefined) throw new Error('missing required workspace id'); return { workspaceId, ...(socketPath !== undefined ? { socketPath } : undefined) };}
// ─── Branch disposition mapping ─────────────────────────────────────────────────
/** The wire `branch_disposition` for `workspace.retire`. */type WireDisposition = 'keep' | 'delete_if_merged' | 'delete_confirmed';
/** Map a CLI retire disposition to the wire `branch_disposition`. Pure. */export function toWireDisposition(d: RetireDisposition): WireDisposition { if (d === 'keep') return 'keep'; if (d === 'delete') return 'delete_if_merged'; return 'delete_confirmed';}
// ─── Rendering ──────────────────────────────────────────────────────────────────
/** Render one workspace summary as a single concise line. Pure. */export function renderWorkspaceSummaryLine(s: WorkspaceSummary): string { const branch = s.branch !== undefined ? ` branch=${s.branch}` : ''; const target = s.integration_target !== undefined ? ` → ${s.integration_target}` : ''; // The original project's main-checkout root — the only way to tell which repository a // managed worktree (whose own cwd is a daemon-managed path) belongs to. Optional additive // field: absent from legacy daemons. const repo = s.repository_cwd !== undefined ? ` repo=${s.repository_cwd}` : ''; const counts = `bindings=${s.binding_count} live=${s.live_agent_count}/${s.live_session_count}`; return `${s.workspace_id} ${s.label} [${s.ownership}/${s.lifecycle}] ${counts}${branch}${target}${repo} cwd=${s.cwd}`;}
/** Render a workspace detail block (status / retire). Pure. */export function renderWorkspaceDetail(d: WorkspaceDetail): string { const lines: string[] = [renderWorkspaceSummaryLine(d.summary)]; if (d.last_head_commit !== undefined) lines.push(` head=${d.last_head_commit}`); if (d.last_probed_at !== undefined) lines.push(` probed=${new Date(d.last_probed_at).toISOString()}`); if (d.tombstone !== undefined) lines.push(` retired=${new Date(d.tombstone.retired_at).toISOString()} (${d.tombstone.reason})`); if (d.conflict !== undefined) lines.push(` conflict=${d.conflict.reason}`); for (const b of d.bindings) { lines.push(` agent=${b.agent_id} session=${b.session_id}`); } return lines.join('\n');}
/** Render a `workspace.create` / `workspace.attach` response. Pure. */export function renderCreateAttach(data: WorkspaceCreateResponse | WorkspaceAttachResponse): string { const lines: string[] = [renderWorkspaceDetail(data.workspace), `agent=${data.agent_id} session=${data.session_id}`]; return lines.join('\n');}
/** Render a `workspace.list` response. Pure. */export function renderList(data: WorkspaceListResponse): string { if (data.workspaces.length === 0) return 'No workspaces.'; return data.workspaces.map(renderWorkspaceSummaryLine).join('\n');}
/** Render a `workspace.status` response. Pure. */export function renderStatus(data: WorkspaceStatusResponse): string { return renderWorkspaceDetail(data);}
/** Render a `workspace.retire` response. Pure. */export function renderRetire(data: WorkspaceRetireResponse): string { const deleted = data.branch_deleted ? 'branch deleted' : 'branch kept'; return `${renderWorkspaceDetail(data.workspace)}\n${deleted}`;}
// ─── Daemon connection helpers ──────────────────────────────────────────────────
/** Resolve the daemon socket: explicit `--socket` wins, else discover. `undefined` if down. */function resolveSocket(deps: WorktreeCmdDeps, explicit?: string): string | undefined { return explicit ?? deps.discover();}
/** Write an error line to stderr. */function errLine(deps: WorktreeCmdDeps, msg: string): void { deps.stderr.write(`shard: ${msg}\n`);}
const WorkspaceRuntimeStartFailureDataSchema = Type.Object({ workspace_id: Type.String({ minLength: 1 }), agent_id: Type.String({ minLength: 1 }), session_id: Type.String({ minLength: 1 }), retryable: Type.Literal(true),}, { additionalProperties: false });
/** * Surface durable identities retained by a workspace create/attach whose runtime failed to * start. The daemon owns this partial-success contract; the CLI only renders validated * opaque IDs. Malformed error data degrades to the ordinary error line. */function renderRuntimeStartFailure(deps: WorktreeCmdDeps, error: ResponseError): void { errLine(deps, error.message); if (error.code !== 'RUNTIME_START_FAILED' || !Value.Check(WorkspaceRuntimeStartFailureDataSchema, error.data)) return; const data = error.data as { workspace_id: string; agent_id: string; session_id: string; retryable: true }; deps.stderr.write(`Workspace retained: ${data.workspace_id}\n`); deps.stderr.write(`Agent retained: ${data.agent_id}\n`); deps.stderr.write(`Session retained: ${data.session_id}\n`); deps.stderr.write(`Retry with: shard new --workspace ${data.workspace_id}\n`);}
/** * Resolve + send one workspace command, validating the response against the matching * `WorkspaceResponseSchemas` entry with `Value.Check`. Returns a discriminated result: * - `{ ok: true; data }` validated success payload * - `{ ok: false; kind: 'refused'; error }` daemon refused (`success:false`) * - `{ ok: false; kind: 'invalid'; message }` response failed schema validation * - `{ ok: false; kind: 'connect'; message }` the socket could not be opened */type SendOutcome = | { ok: true; command: string; data: unknown } | { ok: false; kind: 'refused'; command: string; error: ResponseError } | { ok: false; kind: 'invalid'; command: string; message: string } | { ok: false; kind: 'connect'; message: string };
async function sendWorkspaceCommand( deps: WorktreeCmdDeps, socketPath: string, command: WorkspaceCommandPayload,): Promise<SendOutcome> { let client: SubagentClient; try { client = await deps.connect(socketPath); } catch (e) { return { ok: false, kind: 'connect', message: e instanceof Error ? e.message : String(e) }; } try { const result: SubagentClientResult = await client.send(command as never); if (!result.ok) return { ok: false, kind: 'refused', command: result.command, error: result.error }; const schema = WorkspaceResponseSchemas[command.type as keyof typeof WorkspaceResponseSchemas]; if (schema !== undefined && !Value.Check(schema, result.data)) { return { ok: false, kind: 'invalid', command: command.type, message: `invalid ${command.type} response from daemon` }; } return { ok: true, command: command.type, data: result.data }; } catch (e) { // A transport/abort failure is treated as a connection problem (exit 2 path). return { ok: false, kind: 'connect', message: e instanceof Error ? e.message : String(e) }; } finally { client.close(); }}
// ─── Runner: `shard new` ─────────────────────────────────────────────────────────
const NEW_HELP = 'Usage: shard new --worktree [--name <label>] [--branch <branch>] [--base <ref>]\n' + ' [--integration-target <ref>]\n' + ' shard new --workspace <id>\n' + 'Launch: [--title <t>] [--model <m>] [--provider <p>] [--mode <m>] [--socket <path>]\n' + ' --worktree create a managed worktree workspace from cwd\n' + ' --workspace <id> attach a fresh Agent/Session to an existing active workspace\n' + ' --name <label> workspace label (create only)\n' + ' --branch <branch> attached branch for the new worktree\n' + ' --base <ref> base ref/commit the workspace diverges from\n' + ' --integration-target <ref> integration target ref the workspace merges into\n';
/** Build the `workspace.create` command payload from parsed `new` args. Pure. */export function buildCreateCommand(args: NewArgs, cwd: string): WorkspaceCommandPayload { return { type: 'workspace.create', id: '', version: 1, cwd, ...(args.name !== undefined ? { label: args.name } : undefined), ...(args.branch !== undefined ? { branch: args.branch } : undefined), ...(args.base !== undefined ? { base_ref: args.base } : undefined), ...(args.integrationTarget !== undefined ? { integration_target: args.integrationTarget } : undefined), ...(args.title !== undefined ? { title: args.title } : undefined), ...(args.model !== undefined ? { model: args.model } : undefined), ...(args.provider !== undefined ? { provider: args.provider } : undefined), ...(args.mode !== undefined ? { mode: args.mode } : undefined), };}
/** Build the `workspace.attach` command payload from parsed `new` args. Pure. */export function buildAttachCommand(args: NewArgs): WorkspaceCommandPayload { return { type: 'workspace.attach', id: '', version: 1, workspace_id: args.workspaceId, ...(args.title !== undefined ? { title: args.title } : undefined), ...(args.model !== undefined ? { model: args.model } : undefined), ...(args.provider !== undefined ? { provider: args.provider } : undefined), ...(args.mode !== undefined ? { mode: args.mode } : undefined), };}
/** `shard new` runner. Returns the process exit code. */export async function runNewSub(args: string[], deps: WorktreeCmdDeps = defaultWorktreeCmdDeps()): Promise<number> { let parsed: NewArgs; try { parsed = parseNewArgs(args); } catch (e) { if (e instanceof WorktreeHelpRequested) { deps.stderr.write(NEW_HELP); return EXIT_OK; } errLine(deps, e instanceof Error ? e.message : String(e)); return EXIT_DAEMON_UNAVAILABLE; }
const socket = resolveSocket(deps, parsed.socketPath); if (socket === undefined) { errLine(deps, 'daemon is not running'); return EXIT_DAEMON_UNAVAILABLE; }
const command = parsed.worktree ? buildCreateCommand(parsed, deps.cwd()) : buildAttachCommand(parsed);
const outcome = await sendWorkspaceCommand(deps, socket, command); if (!outcome.ok) { if (outcome.kind === 'connect') { errLine(deps, `daemon is not running: ${outcome.message}`); return EXIT_DAEMON_UNAVAILABLE; } if (outcome.kind === 'invalid') { errLine(deps, outcome.message); return EXIT_DAEMON_UNAVAILABLE; } renderRuntimeStartFailure(deps, outcome.error); return EXIT_DAEMON_REFUSED; }
deps.stdout.write(`${renderCreateAttach(outcome.data as WorkspaceCreateResponse | WorkspaceAttachResponse)}\n`); return EXIT_OK;}
// ─── Runner: `shard worktree list` ──────────────────────────────────────────────
/** Build the `workspace.list` command payload. `--all` omits the cwd filter. Pure. */export function buildListCommand(args: ListArgs, cwd: string): WorkspaceCommandPayload { return { type: 'workspace.list', id: '', version: 1, // list defaults to the cwd repository scope; --all omits the cwd filter entirely. ...(args.all ? {} : { cwd }), // The manager includes retired tombstones by default, so send the CLI's explicit // active-only default rather than relying on daemon omission semantics. include_retired: args.includeRetired, };}
/** `shard worktree list` runner. Returns the process exit code. */export async function runListSub(args: string[], deps: WorktreeCmdDeps = defaultWorktreeCmdDeps()): Promise<number> { let parsed: ListArgs; try { parsed = parseListArgs(args); } catch (e) { if (e instanceof WorktreeHelpRequested) { deps.stderr.write(WORKTREE_LIST_HELP); return EXIT_OK; } errLine(deps, e instanceof Error ? e.message : String(e)); return EXIT_DAEMON_UNAVAILABLE; }
const socket = resolveSocket(deps, parsed.socketPath); if (socket === undefined) { errLine(deps, 'daemon is not running'); return EXIT_DAEMON_UNAVAILABLE; }
const outcome = await sendWorkspaceCommand(deps, socket, buildListCommand(parsed, deps.cwd())); if (!outcome.ok) { if (outcome.kind === 'connect') { errLine(deps, `daemon is not running: ${outcome.message}`); return EXIT_DAEMON_UNAVAILABLE; } if (outcome.kind === 'invalid') { errLine(deps, outcome.message); return EXIT_DAEMON_UNAVAILABLE; } errLine(deps, outcome.error.message); return EXIT_DAEMON_REFUSED; }
deps.stdout.write(`${renderList(outcome.data as WorkspaceListResponse)}\n`); return EXIT_OK;}
const WORKTREE_LIST_HELP = 'Usage: shard worktree list [--all] [--include-retired] [--socket <path>]\n' + ' --all list across all repositories (omit the cwd repository scope)\n' + ' --include-retired include retired tombstones\n';
// ─── Runner: `shard worktree status` ────────────────────────────────────────────
const WORKTREE_STATUS_HELP = 'Usage: shard worktree status <id> [--socket <path>]\n';
/** `shard worktree status <id>` runner. Returns the process exit code. */export async function runStatusSub(args: string[], deps: WorktreeCmdDeps = defaultWorktreeCmdDeps()): Promise<number> { let parsed: StatusArgs; try { parsed = parseStatusArgs(args); } catch (e) { if (e instanceof WorktreeHelpRequested) { deps.stderr.write(WORKTREE_STATUS_HELP); return EXIT_OK; } errLine(deps, e instanceof Error ? e.message : String(e)); return EXIT_DAEMON_UNAVAILABLE; }
const socket = resolveSocket(deps, parsed.socketPath); if (socket === undefined) { errLine(deps, 'daemon is not running'); return EXIT_DAEMON_UNAVAILABLE; }
const outcome = await sendWorkspaceCommand(deps, socket, { type: 'workspace.status', id: '', version: 1, workspace_id: parsed.workspaceId, }); if (!outcome.ok) { if (outcome.kind === 'connect') { errLine(deps, `daemon is not running: ${outcome.message}`); return EXIT_DAEMON_UNAVAILABLE; } if (outcome.kind === 'invalid') { errLine(deps, outcome.message); return EXIT_DAEMON_UNAVAILABLE; } errLine(deps, outcome.error.message); return EXIT_DAEMON_REFUSED; }
deps.stdout.write(`${renderStatus(outcome.data as WorkspaceStatusResponse)}\n`); return EXIT_OK;}
// ─── Runner: `shard worktree retire` (confirmation flow) ─────────────────────────
const WORKTREE_RETIRE_HELP = 'Usage: shard worktree retire <id> [--keep|--delete|--force-delete] [--socket <path>]\n' + ' --keep retire the workspace, keep the branch (default)\n' + ' --delete delete the branch if it is proven merged (else asks for confirmation)\n' + ' --force-delete delete the branch even if it is NOT proven merged\n';
/** Choices offered at an interactive confirmation prompt. */type ConfirmationChoice = 'cancel' | 'keep' | 'confirmed-delete';
/** Build the confirmation prompt text for a typed refusal. Pure. */export function buildConfirmationPrompt(refusal: WorkspaceRetireRefusal): string { return ( `${refusal.reason}\n` + `The branch for workspace ${refusal.workspace_id} could not be proven merged.\n` + `How do you want to proceed?\n` + ` 1) Cancel\n` + ` 2) Keep the branch (retire the workspace only)\n` + ` 3) Delete the branch anyway (confirmed)\n` + `Enter choice [1-3]: ` );}
/** Map a trimmed prompt answer to a confirmation choice. Pure. */export function parseConfirmationChoice(answer: string): ConfirmationChoice | undefined { const a = answer.toLowerCase(); if (a === '1' || a === 'cancel' || a === 'c') return 'cancel'; if (a === '2' || a === 'keep' || a === 'k') return 'keep'; if (a === '3' || a === 'delete' || a === 'confirmed' || a === 'd') return 'confirmed-delete'; return undefined;}
/** Build the actionable noninteractive retry hint for a typed refusal. Pure. */export function buildRetryHint(refusal: WorkspaceRetireRefusal): string { return ( `${refusal.reason}\n` + `Branch deletion was not proven safe. Retry with an explicit disposition:\n` + ` shard worktree retire ${refusal.workspace_id} --keep (retire, keep the branch)\n` + ` shard worktree retire ${refusal.workspace_id} --force-delete (delete the branch anyway)\n` );}
/** Validate + lift a typed `confirmation_required` refusal from a refused response. */function liftRetireRefusal(error: ResponseError): WorkspaceRetireRefusal | undefined { if (error.data === undefined) return undefined; if (!Value.Check(WorkspaceRetireRefusalSchema, error.data)) return undefined; const refusal = error.data as WorkspaceRetireRefusal; if (refusal.kind !== 'confirmation_required') return undefined; return refusal;}
/** Send a `workspace.retire` command with the given wire disposition. */async function sendRetire( deps: WorktreeCmdDeps, socketPath: string, workspaceId: string, wireDisposition: WireDisposition,): Promise<SendOutcome> { return sendWorkspaceCommand(deps, socketPath, { type: 'workspace.retire', id: '', version: 1, workspace_id: workspaceId, branch_disposition: wireDisposition, });}
/** * `shard worktree retire <id>` runner. `--keep`→keep, `--delete`→delete_if_merged, * `--force-delete`→delete_confirmed. When `--delete` returns a typed * `confirmation_required` refusal, an interactive stdin prompts explicitly for * cancel/keep/confirmed-delete and retries; a noninteractive stdin fails with actionable * explicit retry flags and NEVER forces automatically. Returns the process exit code. */export async function runRetireSub(args: string[], deps: WorktreeCmdDeps = defaultWorktreeCmdDeps()): Promise<number> { let parsed: RetireArgs; try { parsed = parseRetireArgs(args); } catch (e) { if (e instanceof WorktreeHelpRequested) { deps.stderr.write(WORKTREE_RETIRE_HELP); return EXIT_OK; } errLine(deps, e instanceof Error ? e.message : String(e)); return EXIT_DAEMON_UNAVAILABLE; }
const socket = resolveSocket(deps, parsed.socketPath); if (socket === undefined) { errLine(deps, 'daemon is not running'); return EXIT_DAEMON_UNAVAILABLE; }
const wireDisposition = toWireDisposition(parsed.disposition); const outcome = await sendRetire(deps, socket, parsed.workspaceId, wireDisposition);
// Success path. if (outcome.ok) { deps.stdout.write(`${renderRetire(outcome.data as WorkspaceRetireResponse)}\n`); return EXIT_OK; }
// Connection problem → unavailable (exit 2). if (outcome.kind === 'connect') { errLine(deps, `daemon is not running: ${outcome.message}`); return EXIT_DAEMON_UNAVAILABLE; } if (outcome.kind === 'invalid') { errLine(deps, outcome.message); return EXIT_DAEMON_UNAVAILABLE; }
// Refused (`success:false`). A `confirmation_required` refusal from `--delete` is the // confirmation flow; any other refusal is a plain error. const refusal = liftRetireRefusal(outcome.error); if (refusal === undefined) { errLine(deps, outcome.error.message); return EXIT_DAEMON_REFUSED; }
// Only the `--delete` (delete_if_merged) disposition triggers confirmation. A // confirmation_required from any other disposition is surfaced as a plain error (the // daemon should not send one, but we never force automatically). if (parsed.disposition !== 'delete') { errLine(deps, outcome.error.message); return EXIT_DAEMON_REFUSED; }
// Interactive: prompt explicitly for cancel/keep/confirmed-delete, then retry. if (deps.isTTY()) { const choice = await confirmRetire(deps, socket, parsed.workspaceId, refusal); return choice; }
// Noninteractive: fail with actionable explicit retry flags; never force automatically. deps.stderr.write(buildRetryHint(refusal)); return EXIT_DAEMON_REFUSED;}
/** * Run the interactive confirmation loop for a `confirmation_required` refusal: prompt * once, map the answer to a disposition, and (for keep/confirmed-delete) retry the retire * command with the new wire disposition. Cancel returns exit 1 without retrying. An * unrecognized answer is re-prompted up to a small bound, then treated as cancel. */async function confirmRetire( deps: WorktreeCmdDeps, socketPath: string, workspaceId: string, refusal: WorkspaceRetireRefusal,): Promise<number> { for (let attempt = 0; attempt < 3; attempt++) { const answer = await deps.prompt.question(buildConfirmationPrompt(refusal)); const choice = parseConfirmationChoice(answer); if (choice === undefined) { deps.stderr.write('shard: invalid choice (enter 1, 2, or 3)\n'); continue; } if (choice === 'cancel') { deps.stderr.write('Cancelled.\n'); return EXIT_DAEMON_REFUSED; } const retryDisposition: WireDisposition = choice === 'keep' ? 'keep' : 'delete_confirmed'; const retry = await sendRetire(deps, socketPath, workspaceId, retryDisposition); if (retry.ok) { deps.stdout.write(`${renderRetire(retry.data as WorkspaceRetireResponse)}\n`); return EXIT_OK; } if (retry.kind === 'connect') { errLine(deps, `daemon is not running: ${retry.message}`); return EXIT_DAEMON_UNAVAILABLE; } if (retry.kind === 'invalid') { errLine(deps, retry.message); return EXIT_DAEMON_UNAVAILABLE; } // A second confirmation_required (unexpected for keep/delete_confirmed) or any other // refusal is surfaced as a plain error — never retried automatically. errLine(deps, retry.error.message); return EXIT_DAEMON_REFUSED; } // Too many invalid answers: treat as cancel. deps.stderr.write('Cancelled (no valid choice).\n'); return EXIT_DAEMON_REFUSED;}
// ─── Runner: `shard worktree` dispatch ───────────────────────────────────────────
const WORKTREE_HELP = 'Usage: shard worktree <list|status|retire> [options]\n' + ' list [--all] [--include-retired] [--socket <path>]\n' + ' status <id> [--socket <path>]\n' + ' retire <id> [--keep|--delete|--force-delete] [--socket <path>]\n';
/** Route `shard worktree <sub> [args]`. Returns the process exit code. */export async function runWorktreeSub(args: string[], deps: WorktreeCmdDeps = defaultWorktreeCmdDeps()): Promise<number> { const [sub, ...rest] = args; if (sub === undefined || sub === '-h' || sub === '--help') { deps.stderr.write(WORKTREE_HELP); return sub === undefined ? EXIT_DAEMON_UNAVAILABLE : EXIT_OK; } if (sub === 'list') return runListSub(rest, deps); if (sub === 'status') return runStatusSub(rest, deps); if (sub === 'retire') return runRetireSub(rest, deps); errLine(deps, `unknown worktree subcommand: ${sub}`); return EXIT_DAEMON_UNAVAILABLE;}