Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ grouped by area, with links to the docs for the details.

### Added

- **Work.** `coding.sh handoff --work <id>` builds a deterministic $0, secret-redacted multi-day handoff brief across every session in a work item, with direction pivots, timeline, changed files, passing checks, deduplicated dead ends, proof rollup, and context resets. `work show <id>` adds a `Timeline` (`timeline` in `--json`) and suggests `handoff --work` on multi-session high-risk items. ([docs](https://github.com/jackulau/coding.sh/blob/main/docs/guides/evals.md#resetting-context-with-a-handoff-brief))
- **Viewer.** At-risk sessions (`#/s/<id>`) show a collapsible Live Steer card (expanded on `intervene`, collapsed on `nudge`) with prioritized directives, a copyable `suggestedSteer` prompt, and a `coding.sh handoff` hint on context resets; blocked, failed, or at-risk work items (`#/w/<id>`) show the same advice for their cause session, while healthy items make zero `/steer` requests. [Evals](https://github.com/jackulau/coding.sh/blob/main/docs/guides/evals.md#live-session-steering)
- **Steer.** `coding.sh steer <session>` and `GET /api/sessions/{id}/steer` read live verification, proof loop, context hygiene, tamper and wait telemetry to return `continue`, `nudge` or `intervene` with prioritized directives and a paste-ready steer prompt (`--prompt`, `--strict`, `--fresh`, `--json`). [Evals](https://github.com/jackulau/coding.sh/blob/main/docs/guides/evals.md#live-session-steering)
- **Viewer.** `GET /api/sessions/{id}/proof` returns a trace-only formal-verification integrity report with checker milestones for `ui` and `serve`. On `#/s/<id>`, the header adds a verification and context hygiene strip when relevant, and proof sessions show a collapsible Proof Review card with verdict, spec status, escapes, tamper findings, jumpable milestones, and copyable audit hints. [API reference](https://github.com/jackulau/coding.sh/blob/main/docs/reference/api.md#get-apisessionsidproof)
Expand Down
11 changes: 10 additions & 1 deletion docs/guides/evals.md
Original file line number Diff line number Diff line change
Expand Up @@ -3151,12 +3151,21 @@ model call.
```sh
coding.sh handoff latest > handoff.md
coding.sh handoff 9f1c2e --out handoff.md --max-dead-ends 5
coding.sh handoff --work w3f9a1c --out handoff.md
coding.sh handoff latest --json
```

The brief keeps the original goal, changed files, passing checks, unresolved failed approaches under
Do Not Repeat, supervision risk signals when medium or high, and formal-proof status when present.
`coding.sh work show` suggests `coding.sh handoff` on high-risk items.

For multi-day work spanning several sessions, `coding.sh handoff --work <id>` stitches every session
in that work item chronologically (`--since 30d` by default, `--max-sessions 20`). It preserves the
original goal, notes any latest direction pivot, unions changed files, deduplicates Do Not Repeat
dead ends, and rolls up proof status and context resets.

`coding.sh work show <id>` prints a chronological `Timeline` section for multi-session work items
(`timeline` in `--json`) and suggests `coding.sh handoff --work <id>` on multi-session high-risk
items (or `coding.sh handoff <session>` on single-session high-risk items).

### Live session steering

Expand Down
20 changes: 12 additions & 8 deletions docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ Every command accepts these.
| [`sessions`](#codingsh-sessions) | Explore | List captured sessions |
| [`views`](#codingsh-views) | Explore | Save a --where query under a name, for sessions --view, the MCP server and the viewer |
| [`proof`](#codingsh-proof) | Explore | Review a session's formal-verification integrity (escapes, checks, spec changes) |
| [`handoff`](#codingsh-handoff) | Explore | Build a deterministic $0 context-reset handoff brief for starting a fresh session |
| [`handoff`](#codingsh-handoff) | Explore | Build a deterministic $0 context-reset handoff brief for a session or multi-day work item |
| [`steer`](#codingsh-steer) | Explore | Advise whether to continue, nudge or intervene in a session, with a paste-ready steer |
| [`show`](#codingsh-show) | Explore | Show a session timeline with subagents and latency |
| [`tree`](#codingsh-tree) | Explore | Show a session and its subagents, or a whole run, as one tree, with rolled-up totals |
Expand Down Expand Up @@ -685,31 +685,35 @@ coding.sh proof latest --strict --json

## `coding.sh handoff`

Build a deterministic $0 context-reset handoff brief for starting a fresh session.
Build a deterministic $0 context-reset handoff brief for a session or multi-day work item.

```text
coding.sh handoff <SESSION> [options]
coding.sh handoff [session] [options]
```

| Argument | Required | Description |
|---|---|---|
| `session` | yes | Session id, a unique prefix of one (4+ characters, like a git short hash), the x_ alias coding.sh prints for one, or 'latest'. |
| `session` | no | Session id, a unique prefix of one (4+ characters, like a git short hash), the x_ alias coding.sh prints for one, or 'latest' (omit when using --work) |

| Option | Default | Description |
|---|---|---|
| `-w, --work <ID>` | | Aggregate every session of a work item (work id, prefix, or member session id) into a multi-day handoff brief. |
| `--since <WHEN>` | `30d` | With --work: look the work item up among sessions started at or after this time. |
| `-o, --out <FILE>` | | Write the handoff Markdown (or JSON with --json) to FILE and print its path. |
| `--max-dead-ends <N>` | `8` | Maximum unresolved failed approaches listed under Do Not Repeat. |
| `--max-dead-ends <N>` | | Maximum unresolved failed approaches listed under Do Not Repeat (default: 8 for a session, 10 for --work) |
| `--max-sessions <N>` | `20` | With --work: maximum newest sessions shown in the timeline (original goal is preserved) |
| `--fresh` | | Wait for every pending capture to be ingested (default: answer after 1.5 s) |

```sh
coding.sh handoff latest
coding.sh handoff 9f1c2e --out handoff.md
coding.sh handoff latest --max-dead-ends 5 --json
coding.sh handoff --work w3f9a1c --out handoff.md
coding.sh handoff 9f1c2e --max-dead-ends 5 --json
```

- Deterministic and $0: runs locally over stored events with secret redaction and makes no model call.
- Prints copy-paste-ready Markdown on stdout and status notes on stderr, so `coding.sh handoff latest > handoff.md` writes a clean brief.
- Includes the original goal, changed files, passing checks, unresolved failed approaches under Do Not Repeat, supervision risk signals when medium or high, and formal-verification status when the session has proof activity.
- Includes the original goal, changed files, passing checks, unresolved failed approaches under Do Not Repeat, supervision risk signals when medium or high, and formal-verification status when proof activity exists.
- With --work &lt;id&gt;, stitches every session of the work item chronologically into a multi-day timeline with direction pivots, union of changed files, deduplicated Do Not Repeat dead ends, proof rollup, and context-reset counts.
- With --json, an answer given before every capture was indexed carries "pending": {"files": N, "indexing": true\|false} (files still to ingest; indexing: an ingest is still running). The field is absent once all are indexed.

## `coding.sh steer`
Expand Down
112 changes: 102 additions & 10 deletions packages/coding.sh/src/cli/commands/handoff.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,131 @@
// coding.sh handoff <session>: deterministic $0 context-reset brief for a fresh session.
// coding.sh handoff <session> | coding.sh handoff --work <id>:
// Deterministic $0 context-reset brief for a single session or a multi-day work item.
// Prints copy-paste-ready Markdown on stdout (or structured JSON with --json), with status
// notes on stderr. --out writes the brief or JSON to a file cleanly.
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { buildHandoff, DEFAULT_MAX_DEAD_ENDS } from "../../core/handoff.ts";
import type { AgentEvent, Session } from "../../schema/index.ts";
import {
buildHandoff,
buildWorkHandoff,
DEFAULT_MAX_DEAD_ENDS,
DEFAULT_MAX_WORK_DEAD_ENDS,
DEFAULT_MAX_WORK_SESSIONS,
} from "../../core/handoff.ts";
import { indexAge } from "../../core/ingest-health.ts";
import { createRedactor } from "../../core/redact.ts";
import { positiveInt, UsageError } from "../args.ts";
import { readOverlay } from "../../core/work-overlay.ts";
import { parseSinceWhen, positiveInt, UsageError } from "../args.ts";
import { autoIngest, notFoundWithBacklog, pendingField, readIngest, resolveSession, str, withContext } from "../common.ts";
import { plural } from "../output.ts";
import type { CommandContext } from "../types.ts";
import { findWorkItem } from "./work.ts";

/** Default window for `handoff --work <id>` so multi-day work items are found cleanly. */
export const WORK_HANDOFF_SINCE = "30d";

export async function run(c: CommandContext): Promise<number> {
const { out } = c;
const ref = c.positionals[0]!;
const maxDeadEnds = positiveInt(c.flags["max-dead-ends"], "max-dead-ends") ?? DEFAULT_MAX_DEAD_ENDS;
const sessionRef = c.positionals[0]?.trim();
const workFlagRaw = c.flags.work;
const workRef = str(workFlagRaw)?.trim();
if (workFlagRaw !== undefined && !workRef) {
throw new UsageError("--work needs a work item id, e.g. --work w3f9a1c", { reason: "missing_argument" });
}
if (sessionRef && workRef) {
throw new UsageError("Pass either <session> or --work <id>, not both", { reason: "invalid_argument" });
}
if (!sessionRef && !workRef) {
throw new UsageError(
`Missing <session> or --work <id>. Usage: ${out.command("coding.sh handoff <session>")} or ${out.command("coding.sh handoff --work <id>")}`,
{ reason: "missing_argument" },
);
}

const maxDeadEnds = positiveInt(c.flags["max-dead-ends"], "max-dead-ends");
const maxSessions = positiveInt(c.flags["max-sessions"], "max-sessions") ?? DEFAULT_MAX_WORK_SESSIONS;
const sinceText = str(c.flags.since) ?? WORK_HANDOFF_SINCE;
const sinceMs = workRef || c.flags.since !== undefined ? parseSinceWhen(sinceText).ms : undefined;
const outFile = str(c.flags.out)?.trim();
if (c.flags.out !== undefined && !outFile) {
throw new UsageError("--out needs a file path, e.g. --out handoff.md", { reason: "missing_argument" });
}

return withContext(c, async (ctx) => {
const backlog = await autoIngest(ctx, readIngest(c));
const redactor = createRedactor({
redact: [...new Set(["secrets", ...ctx.config.capture.redact])],
patterns: ctx.config.capture.redactPatterns,
});

if (workRef) {
const age = ctx.storeOverridden ? undefined : indexAge(ctx.paths.root);
const stale = age?.stale ? age : undefined;
const overlay = readOverlay(ctx.paths.work);
let found;
try {
found = await findWorkItem(ctx, workRef, { since: sinceMs!, sinceText }, overlay, stale?.at);
} catch (err) {
throw notFoundWithBacklog(err, backlog);
}

const byId = new Map(found.sessions.map((s) => [s.id, s]));
const memberSessions: Session[] = [];
for (const id of found.item.sessionIds) {
const s = byId.get(id) ?? (await ctx.index.getSession(id));
if (s) memberSessions.push(s);
}
const eventsBySession = new Map<string, AgentEvent[]>();
for (const s of memberSessions) {
eventsBySession.set(s.id, await ctx.index.listEvents(s.id));
}

const packet = buildWorkHandoff(found.item, memberSessions, eventsBySession, {
maxDeadEnds: maxDeadEnds ?? DEFAULT_MAX_WORK_DEAD_ENDS,
maxSessions,
shortId: found.shortId,
redact: redactor,
});
const doc: Record<string, unknown> = { ...packet };
Object.assign(doc, pendingField(backlog));
const summaryNote = `${plural(packet.totalSessions, "session")}, ${plural(packet.spanDays, "day")}, ${plural(packet.progress.filesChanged.length, "file")}, ${plural(packet.deadEnds.length, "dead end")}`;

if (outFile) {
const outPath = resolve(c.cwd, outFile);
mkdirSync(dirname(outPath), { recursive: true });
if (out.json) {
writeFileSync(outPath, `${JSON.stringify(doc, null, 2)}\n`, "utf8");
out.data({ ...doc, path: outPath });
return 0;
}
writeFileSync(outPath, `${packet.markdown}\n`, "utf8");
out.print(outPath);
out.note(`Wrote work handoff brief for ${packet.workId} (${summaryNote})`);
return 0;
}

if (out.json) {
out.data(doc);
return 0;
}

out.print(packet.markdown);
out.note(`Work handoff brief for ${packet.workId} (${summaryNote})`);
return 0;
}

let session;
try {
session = await resolveSession(ctx, ref);
session = await resolveSession(ctx, sessionRef!);
} catch (err) {
throw notFoundWithBacklog(err, backlog);
}

const events = await ctx.index.listEvents(session.id);
const redactor = createRedactor({
redact: [...new Set(["secrets", ...ctx.config.capture.redact])],
patterns: ctx.config.capture.redactPatterns,
const packet = buildHandoff(session, events, {
maxDeadEnds: maxDeadEnds ?? DEFAULT_MAX_DEAD_ENDS,
redact: redactor,
});
const packet = buildHandoff(session, events, { maxDeadEnds, redact: redactor });
const doc: Record<string, unknown> = { ...packet };
Object.assign(doc, pendingField(backlog));

Expand Down
67 changes: 62 additions & 5 deletions packages/coding.sh/src/cli/commands/work.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
// coding.sh work show|ack|snooze <id>: what needs you across every agent's sessions
// (core/work.ts), with acks and snoozes in work.json (core/work-overlay.ts).
import { parsePlace, type Place } from "../../mcp/data.ts";
import type { PullRequestRef, Session } from "../../schema/index.ts";
import type { AgentEvent, PullRequestRef, Session } from "../../schema/index.ts";
import type { Context } from "../../core/context.ts";
import { dateMs, isoMs } from "../../core/dates.ts";
import { buildWorkTimeline, DEFAULT_MAX_WORK_SESSIONS, type WorkTimeline } from "../../core/handoff.ts";
import { createRedactor } from "../../core/redact.ts";
import type { IndexStore } from "../../core/types.ts";
import { indexAge, staleIndexText, type IndexAge } from "../../core/ingest-health.ts";
import { addAck, readOverlay, snoozeItem, writeOverlay, type WorkOverlay } from "../../core/work-overlay.ts";
Expand Down Expand Up @@ -389,9 +391,14 @@ export async function matchItem(ctx: Context, ref: string, since: number, overla
return item && { item, sessions, shortId };
}

/** matchItem in the window of --since. Unknown: exit 1; an ambiguous prefix lists its candidates. */
async function findItem(c: CommandContext, ctx: Context, ref: string, overlay: WorkOverlay, now?: number): Promise<{ item: WorkItem; sessions: Session[]; shortId: (id: string) => string }> {
const w = windowOf(c, now);
/** matchItem in `w`. Unknown: exit 1; an ambiguous prefix lists its candidates. */
export async function findWorkItem(
ctx: Context,
ref: string,
w: Window,
overlay: WorkOverlay,
now?: number,
): Promise<{ item: WorkItem; sessions: Session[]; shortId: (id: string) => string }> {
const found = await matchItem(ctx, ref, w.since, overlay, now, (r) =>
resolveSession(ctx, r).catch((e: unknown) => {
if (e instanceof CliError && e.reason === "not_found") return undefined;
Expand All @@ -407,6 +414,11 @@ async function findItem(c: CommandContext, ctx: Context, ref: string, overlay: W
return found;
}

/** matchItem in the window of --since. Unknown: exit 1; an ambiguous prefix lists its candidates. */
async function findItem(c: CommandContext, ctx: Context, ref: string, overlay: WorkOverlay, now?: number): Promise<{ item: WorkItem; sessions: Session[]; shortId: (id: string) => string }> {
return findWorkItem(ctx, ref, windowOf(c, now), overlay, now);
}

/** A prefix several items' ids share, worded as the CLI words an ambiguous session id prefix (resolveSession), newest first. */
function ambiguousItemError(ref: string, { ambiguous: shown, more }: { ambiguous: WorkItem[]; more: boolean }, w: Window): CliError {
const lines = shown.map((i) => ` ${i.id} ${i.agent} ${ago(i.startedAt)} ${oneLine(i.title ?? "", 50)}`.trimEnd());
Expand Down Expand Up @@ -441,6 +453,22 @@ async function show(c: CommandContext): Promise<number> {
const agents = itemWorkflowAgents(item, sessions, stale?.at ?? Date.now());
// filesChanged covers every session of the item; the main session's own count is what `show <sessionId>` reports.
const own = mainFilesChanged(item, byId);
let timeline: WorkTimeline | undefined;
if (item.sessionIds.length > 1) {
const memberSessions = item.sessionIds
.map((id) => byId.get(id))
.filter((s): s is Session => !!s)
.sort((a, b) => a.startedAt - b.startedAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
const eventsBySession = new Map<string, AgentEvent[]>();
for (const s of memberSessions.slice(-DEFAULT_MAX_WORK_SESSIONS)) {
eventsBySession.set(s.id, await ctx.index.listEvents(s.id));
}
const redactor = createRedactor({
redact: [...new Set(["secrets", ...ctx.config.capture.redact])],
patterns: ctx.config.capture.redactPatterns,
});
timeline = buildWorkTimeline(item, memberSessions, eventsBySession, { shortId, redact: redactor });
}
if (out.json) {
out.data({
...workItemJson(item),
Expand All @@ -456,6 +484,8 @@ async function show(c: CommandContext): Promise<number> {
if (s.stats.waiting) row.waiting = s.stats.waiting.kind;
return row;
}),
spanDays: timeline ? timeline.spanDays : undefined,
timeline: timeline ? timeline.entries : undefined,
...staleIndexField(stale),
...pendingField(backlog),
});
Expand Down Expand Up @@ -514,9 +544,36 @@ async function show(c: CommandContext): Promise<number> {
for (const s of children.slice(0, 10)) out.print(` ${shortId(s.id)} ${s.agent} ${oneLine(s.title, 50)}`);
if (children.length > 10) out.print(out.style(` and ${children.length - 10} more: ${out.command(`coding.sh tree ${shortId(item.primaryId)}`)}`, "faint"));
}
if (timeline && timeline.entries.length > 0) {
const firstDay = timeline.firstStartedAt?.slice(0, 10);
const lastDay = timeline.lastEndedAt?.slice(0, 10);
const span =
timeline.spanDays > 1 && firstDay && lastDay
? `${plural(timeline.totalSessions, "session")} across ${plural(timeline.spanDays, "day")} (${firstDay} to ${lastDay})`
: firstDay
? `${plural(timeline.totalSessions, "session")} on ${firstDay}`
: plural(timeline.totalSessions, "session");
out.row("Timeline", span, "none", true);
if (timeline.omittedSessions) {
out.print(out.style(` (${plural(timeline.omittedSessions, "older session")} omitted)`, "faint"));
}
for (const e of timeline.entries) {
const meta: string[] = [plural(e.verificationChecks, "check")];
if (e.compactions > 0) meta.push(plural(e.compactions, "compaction"));
if (e.risk) meta.push(`risk:${e.risk}`);
if (e.proofVerdict) meta.push(`proof:${e.proofVerdict}`);
if (e.deadEnds > 0) meta.push(plural(e.deadEnds, "dead end"));
out.print(` ${e.day} ${e.shortId ?? e.sessionId} ${e.agent} ${meta.join(", ")} ${oneLine(e.title, 48)}`);
}
}
out.row("Next", nextText(item.next), "none", true);
if (item.proof) out.next("Review proof integrity", `coding.sh proof ${shortId(item.primaryId)}`);
if (item.supervisionRisk === "high") out.next("Reset context with a clean handoff brief", `coding.sh handoff ${shortId(item.primaryId)}`);
if (item.supervisionRisk === "high") {
const handoffCmd = item.sessionIds.length > 1
? `coding.sh handoff --work ${item.id}`
: `coding.sh handoff ${shortId(item.cause?.sessionId ?? item.primaryId)}`;
out.next("Reset context with a clean handoff brief", handoffCmd);
}
return 0;
});
}
Expand Down
Loading
Loading