diff --git a/CHANGELOG.md b/CHANGELOG.md index 4469d5e8..d30de343 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ grouped by area, with links to the docs for the details. ### Added +- **Work.** `coding.sh handoff --work ` 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 ` 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/`) 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/`) 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 ` 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/`, 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) diff --git a/docs/guides/evals.md b/docs/guides/evals.md index bdc2073b..85f85f07 100644 --- a/docs/guides/evals.md +++ b/docs/guides/evals.md @@ -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 ` 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 ` prints a chronological `Timeline` section for multi-session work items +(`timeline` in `--json`) and suggests `coding.sh handoff --work ` on multi-session high-risk +items (or `coding.sh handoff ` on single-session high-risk items). ### Live session steering diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 188f4204..84a99a97 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -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 | @@ -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 [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 ` | | Aggregate every session of a work item (work id, prefix, or member session id) into a multi-day handoff brief. | +| `--since ` | `30d` | With --work: look the work item up among sessions started at or after this time. | | `-o, --out ` | | Write the handoff Markdown (or JSON with --json) to FILE and print its path. | -| `--max-dead-ends ` | `8` | Maximum unresolved failed approaches listed under Do Not Repeat. | +| `--max-dead-ends ` | | Maximum unresolved failed approaches listed under Do Not Repeat (default: 8 for a session, 10 for --work) | +| `--max-sessions ` | `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 <id>, 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` diff --git a/packages/coding.sh/src/cli/commands/handoff.ts b/packages/coding.sh/src/cli/commands/handoff.ts index 0c2f944e..c4b262d9 100644 --- a/packages/coding.sh/src/cli/commands/handoff.ts +++ b/packages/coding.sh/src/cli/commands/handoff.ts @@ -1,19 +1,51 @@ -// coding.sh handoff : deterministic $0 context-reset brief for a fresh session. +// coding.sh handoff | coding.sh handoff --work : +// 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 ` so multi-day work items are found cleanly. */ +export const WORK_HANDOFF_SINCE = "30d"; export async function run(c: CommandContext): Promise { 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 or --work , not both", { reason: "invalid_argument" }); + } + if (!sessionRef && !workRef) { + throw new UsageError( + `Missing or --work . Usage: ${out.command("coding.sh handoff ")} or ${out.command("coding.sh handoff --work ")}`, + { 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" }); @@ -21,19 +53,79 @@ export async function run(c: CommandContext): Promise { 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(); + 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 = { ...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 = { ...packet }; Object.assign(doc, pendingField(backlog)); diff --git a/packages/coding.sh/src/cli/commands/work.ts b/packages/coding.sh/src/cli/commands/work.ts index 5852b841..c4893ff3 100644 --- a/packages/coding.sh/src/cli/commands/work.ts +++ b/packages/coding.sh/src/cli/commands/work.ts @@ -2,9 +2,11 @@ // coding.sh work show|ack|snooze : 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"; @@ -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; @@ -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()); @@ -441,6 +453,22 @@ async function show(c: CommandContext): Promise { 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 ` 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(); + 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), @@ -456,6 +484,8 @@ async function show(c: CommandContext): Promise { 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), }); @@ -514,9 +544,36 @@ async function show(c: CommandContext): Promise { 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; }); } diff --git a/packages/coding.sh/src/cli/registry.ts b/packages/coding.sh/src/cli/registry.ts index e11e74b5..81dc8e7e 100644 --- a/packages/coding.sh/src/cli/registry.ts +++ b/packages/coding.sh/src/cli/registry.ts @@ -536,18 +536,26 @@ export const COMMANDS: CommandSpec[] = [ { name: "handoff", group: "Explore", - summary: "Build a deterministic $0 context-reset handoff brief for starting a fresh session", - args: [{ name: "session", desc: "Session id, a unique prefix of one (4+ characters, like a git short hash), the x_ alias coding.sh prints for one, or 'latest'", required: true }], + summary: "Build a deterministic $0 context-reset handoff brief for a session or multi-day work item", + args: [{ name: "session", desc: "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)" }], flags: [ + { name: "work", short: "w", type: "string", value: "", desc: "Aggregate every session of a work item (work id, prefix, or member session id) into a multi-day handoff brief" }, + { ...SINCE, desc: "With --work: look the work item up among sessions started at or after this time", default: "30d" }, { name: "out", short: "o", type: "string", value: "", desc: "Write the handoff Markdown (or JSON with --json) to FILE and print its path" }, - { name: "max-dead-ends", type: "number", value: "", desc: "Maximum unresolved failed approaches listed under Do Not Repeat", default: "8" }, + { name: "max-dead-ends", type: "number", value: "", desc: "Maximum unresolved failed approaches listed under Do Not Repeat (default: 8 for a session, 10 for --work)" }, + { name: "max-sessions", type: "number", value: "", desc: "With --work: maximum newest sessions shown in the timeline (original goal is preserved)", default: "20" }, FRESH, ], - examples: ["coding.sh handoff latest", "coding.sh handoff 9f1c2e --out handoff.md", "coding.sh handoff latest --max-dead-ends 5 --json"], + examples: [ + "coding.sh handoff latest", + "coding.sh handoff --work w3f9a1c --out handoff.md", + "coding.sh handoff 9f1c2e --max-dead-ends 5 --json", + ], notes: [ "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 , 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.", PENDING_NOTE, ], load: () => import("./commands/handoff.ts"), diff --git a/packages/coding.sh/src/core/handoff.ts b/packages/coding.sh/src/core/handoff.ts index 730b5e6a..4b1ee671 100644 --- a/packages/coding.sh/src/core/handoff.ts +++ b/packages/coding.sh/src/core/handoff.ts @@ -1,7 +1,8 @@ -// Deterministic $0 context-reset handoff packet for a single session. -// Summarizes original goal, verified progress, unresolved dead ends, supervision -// risk and formal-verification status with full secret redaction and no LLM call. -import type { AgentEvent, ProofLang, Session } from "../schema/index.ts"; +// Deterministic $0 context-reset handoff packets for a single session or a multi-day +// work item. Summarizes original goal, direction pivots, verified progress, unresolved +// dead ends, supervision risk, multi-day timeline, and formal-verification status with +// full secret redaction and no LLM call. +import type { AgentEvent, ProofLang, Session, SupervisionRisk } from "../schema/index.ts"; import { isFileEditTool, isShellCall } from "../adapters/_shared/tools.ts"; import { isoMs } from "./dates.ts"; import { failureState, foldFailure } from "./failures.ts"; @@ -10,13 +11,21 @@ import { buildProofReport, type ProofTamperFinding, type ProofVerdict } from "./ import { createRedactor, type Redactor } from "./redact.ts"; import { byTime, commandOf, isRealPrompt, isVerifyCommand } from "./sessions.ts"; import { normalizeTracePath, shellCommand, shellWrites } from "./shell-diff.ts"; +import type { WorkItem } from "./work.ts"; export const DEFAULT_MAX_DEAD_ENDS = 8; +export const DEFAULT_MAX_WORK_DEAD_ENDS = 10; +export const DEFAULT_MAX_WORK_SESSIONS = 20; export const DEFAULT_MAX_FILES = 40; const DEFAULT_MAX_CHECKS = 12; const GOAL_MAX = 1500; +const TITLE_MAX = 120; const CMD_MAX = 200; const ERROR_MAX = 180; +const DAY_MS = 86_400_000; +/** Short acknowledgements skipped when looking for a meaningful direction pivot across sessions. */ +const TRIVIAL_ACK = /^(?:ok|okay|yes|yep|yeah|y|lgtm|thanks|thank you|thx|continue|go ahead|sounds good|proceed|do it|ship it)[.!?\s]*$/i; +const RISK_RANK: Record = { medium: 1, high: 2 }; /** Additional mechanical verification commands beyond sessions.ts VERIFY_COMMAND. */ const EXTRA_VERIFY = /\b(?:go\s+(?:build|vet)|biome\s+(?:check|lint)|flake8|pylint|black\s+--check|prettier\s+--check|cargo\s+fmt\s+--check)\b/i; @@ -91,6 +100,86 @@ export interface HandoffOptions { redact?: Redactor; } +export type EventsBySession = ReadonlyMap | Readonly>; + +export type WorkHandoffItem = Pick & + Partial>; + +export interface WorkTimelineEntry { + sessionId: string; + shortId?: string; + agent: string; + startedAt: string; + endedAt?: string; + day: string; + title: string; + turns: number; + compactions: number; + verificationChecks: number; + unverifiedTailEdits: number; + risk?: SupervisionRisk; + proofVerdict?: Exclude; + deadEnds: number; + summary: string; +} + +export interface WorkTimeline { + firstStartedAt?: string; + lastEndedAt?: string; + spanDays: number; + totalSessions: number; + omittedSessions?: number; + entries: WorkTimelineEntry[]; +} + +export interface WorkTimelineOptions { + maxSessions?: number; + shortId?: (id: string) => string; + redact?: Redactor; +} + +export interface WorkContextResets { + compactions: number; + sessionHandoffs: number; + total: number; +} + +export interface WorkHandoffRisk extends HandoffRisk { + sessionHandoffs?: number; + contextResets?: number; +} + +export interface WorkHandoffProof extends HandoffProof { + oscillatingChecks?: number; +} + +export interface WorkHandoffPacket { + workId: string; + title?: string; + repo?: string; + branch?: string; + agents: string[]; + firstStartedAt?: string; + lastEndedAt?: string; + spanDays: number; + totalSessions: number; + omittedSessions?: number; + goal?: string; + latestDirection?: string; + timeline: WorkTimelineEntry[]; + progress: HandoffProgress; + deadEnds: HandoffDeadEnd[]; + risk?: WorkHandoffRisk; + contextResets: WorkContextResets; + proof?: WorkHandoffProof; + markdown: string; +} + +export interface WorkHandoffOptions extends HandoffOptions { + maxSessions?: number; + shortId?: (id: string) => string; +} + interface OpenCall { tool: string; actionKey?: string; @@ -124,7 +213,7 @@ function clip(text: string, max: number): string { } function formatTs(ts: number): string { - return isoMs(ts) ?? new Date(ts).toISOString(); + return isoMs(ts) ?? "-"; } function isVerifyCmd(cmd: string | undefined): boolean { @@ -401,27 +490,37 @@ export function formatHandoffMarkdown(packet: Omit | return lines.join("\n"); } -/** - * Builds a deterministic, fully redacted context-reset handoff packet for a session. - * Pure: performs no disk, git, or network I/O and makes no LLM calls. - */ -export function buildHandoff( - session: Pick, - events: readonly AgentEvent[], - opts: HandoffOptions = {}, -): HandoffPacket { - const maxDeadEnds = opts.maxDeadEnds ?? DEFAULT_MAX_DEAD_ENDS; - const maxFiles = opts.maxFiles ?? DEFAULT_MAX_FILES; - const redactor = opts.redact ?? createRedactor(); - const redact = (s: string) => redactor.string(s); - - const sorted = byTime([...events]); - const baseCwd = session.repo?.root ?? session.cwd; +interface TraceAccumulator { + filesSet: Set; + passingByKey: Map; + deadEndsByKey: Map; + editsSinceCheck: number; + checksRun: number; + compactionsSeen: number; +} - const filesSet = new Set(); - const passingByKey = new Map(); - const deadEndsByKey = new Map(); +function createAccumulator(): TraceAccumulator { + return { + filesSet: new Set(), + passingByKey: new Map(), + deadEndsByKey: new Map(), + editsSinceCheck: 0, + checksRun: 0, + compactionsSeen: 0, + }; +} +/** + * Folds one chronologically sorted session's events into `acc`. + * Per-session call-tracking maps stay local so toolUseIds never collide across sessions, + * while files, passing checks, dead ends and tail edits accumulate across sessions. + */ +function foldSessionEvents( + sorted: readonly AgentEvent[], + baseCwd: string | undefined, + redact: (s: string) => string, + acc: TraceAccumulator, +): void { const fState = failureState(); const openCalls = new Map(); const seenStartIds = new Set(); @@ -431,13 +530,11 @@ export function buildHandoff( const currentFailed = new Map>(); const preCompactFailed = new Map>(); - let editsSinceCheck = 0; - const markResolved = (scope: string, key: string | undefined): void => { if (!key) return; currentFailed.get(scope)?.delete(key); preCompactFailed.get(scope)?.delete(key); - const existing = deadEndsByKey.get(key); + const existing = acc.deadEndsByKey.get(key); if (existing) existing.resolved = true; }; @@ -450,10 +547,10 @@ export function buildHandoff( scopeSet(currentFailed, scope).add(key); const errTail = extractErrorTail(e.payload, redact); - const existing = deadEndsByKey.get(key); + const existing = acc.deadEndsByKey.get(key); if (existing) { existing.count++; - existing.lastTs = e.ts; + existing.lastTs = Math.max(existing.lastTs, e.ts); existing.resolved = false; if (repeatedAfterCompact) existing.postCompactionRepeat = true; if (errTail) existing.error = errTail; @@ -467,7 +564,7 @@ export function buildHandoff( resolved: false, }; if (errTail) entry.error = errTail; - deadEndsByKey.set(key, entry); + acc.deadEndsByKey.set(key, entry); } }; @@ -477,6 +574,7 @@ export function buildHandoff( const cwd = baseCwd ?? e.cwd; if (e.kind === "context.compact") { + acc.compactionsSeen++; const cur = currentFailed.get(scope); if (cur?.size) { const pre = scopeSet(preCompactFailed, scope); @@ -490,15 +588,15 @@ export function buildHandoff( const raw = str(p.path); if (!raw) continue; const rel = normalizeTracePath(raw, cwd); - if (rel) filesSet.add(rel); + if (rel) acc.filesSet.add(rel); const moved = str(p.movedTo); if (moved) { const movedRel = normalizeTracePath(moved, cwd); - if (movedRel) filesSet.add(movedRel); + if (movedRel) acc.filesSet.add(movedRel); } const id = str(p.toolUseId); if (id) fileChangeIds.add(id); - editsSinceCheck++; + acc.editsSinceCheck++; continue; } @@ -506,7 +604,8 @@ export function buildHandoff( const id = str(p.toolUseId); if (id && countedTestIds.has(id)) continue; if (id) countedTestIds.add(id); - editsSinceCheck = 0; + acc.editsSinceCheck = 0; + acc.checksRun++; const failed = num(p.failed) ?? 0; if (failed === 0) { const runner = str(p.runner); @@ -515,7 +614,7 @@ export function buildHandoff( ? passed !== undefined ? `${runner} (${passed} passed)` : runner : passed !== undefined ? `tests (${passed} passed)` : "tests"; const key = `test:${(runner ?? "tests").toLowerCase()}`; - passingByKey.set(key, { + acc.passingByKey.set(key, { command: clip(redact(label), CMD_MAX), at: formatTs(e.ts), outcome: "passed", @@ -539,7 +638,7 @@ export function buildHandoff( if (cmd) { for (const w of shellWrites(cmd)) { const target = normalizeTracePath(w.renamedTo ?? w.path, cwd); - if (target) filesSet.add(target); + if (target) acc.filesSet.add(target); } } const call = classifyCall(e, cwd); @@ -563,9 +662,9 @@ export function buildHandoff( const rawPath = editPathOf(p.input); if (rawPath) { const rel = normalizeTracePath(rawPath, cwd); - if (rel) filesSet.add(rel); + if (rel) acc.filesSet.add(rel); } - if (!(id && fileChangeIds.has(id))) editsSinceCheck++; + if (!(id && fileChangeIds.has(id))) acc.editsSinceCheck++; markResolved(scope, call.actionKey); } else if (!failure || failure.cls === "real") { recordDeadEnd(scope, call, e); @@ -576,10 +675,11 @@ export function buildHandoff( if (call.proof) { const outcome = checkOutcome(call.proof, p); if (outcome === "green" && !call.proof.bypass) { - editsSinceCheck = 0; + acc.editsSinceCheck = 0; + acc.checksRun++; if (id) countedTestIds.add(id); if (call.actionKey) { - passingByKey.set(call.actionKey, { + acc.passingByKey.set(call.actionKey, { command: clip(redact(call.display), CMD_MAX), at: formatTs(e.ts), outcome: "passed", @@ -589,8 +689,9 @@ export function buildHandoff( markResolved(scope, call.actionKey); } } else if (outcome === "red" || p.ok === false) { - editsSinceCheck = 0; - if (call.actionKey) passingByKey.delete(call.actionKey); + acc.editsSinceCheck = 0; + acc.checksRun++; + if (call.actionKey) acc.passingByKey.delete(call.actionKey); if (!failure || failure.cls === "real") recordDeadEnd(scope, call, e); } continue; @@ -598,11 +699,12 @@ export function buildHandoff( if (call.verify) { if (p.interrupted === true || failure?.cls === "interrupted") continue; - editsSinceCheck = 0; + acc.editsSinceCheck = 0; + acc.checksRun++; if (p.ok !== false) { if (id) countedTestIds.add(id); if (call.actionKey) { - passingByKey.set(call.actionKey, { + acc.passingByKey.set(call.actionKey, { command: clip(redact(call.display), CMD_MAX), at: formatTs(e.ts), outcome: "passed", @@ -612,7 +714,7 @@ export function buildHandoff( markResolved(scope, call.actionKey); } } else if (!failure || failure.cls === "real") { - if (call.actionKey) passingByKey.delete(call.actionKey); + if (call.actionKey) acc.passingByKey.delete(call.actionKey); recordDeadEnd(scope, call, e); } continue; @@ -624,20 +726,10 @@ export function buildHandoff( recordDeadEnd(scope, call, e); } } +} - const filesChanged = [...new Set([...filesSet].map(redact))].sort().slice(0, maxFiles); - const passingChecks: HandoffCheck[] = [...passingByKey.values()] - .sort((a, b) => a.ts - b.ts) - .slice(-DEFAULT_MAX_CHECKS) - .map(({ command, at, outcome, kind }) => ({ command, at, outcome, kind })); - - const progress: HandoffProgress = { filesChanged, passingChecks }; - const tailEdits = session.stats.verification !== undefined - ? session.stats.verification.unverifiedTailEdits - : editsSinceCheck > 0 ? editsSinceCheck : undefined; - if (tailEdits !== undefined && tailEdits > 0) progress.unverifiedTailEdits = tailEdits; - - const deadEnds: HandoffDeadEnd[] = [...deadEndsByKey.values()] +function finalizeDeadEnds(deadEndsByKey: ReadonlyMap, maxDeadEnds: number): HandoffDeadEnd[] { + return [...deadEndsByKey.values()] .filter((d) => !d.resolved) .sort((a, b) => Number(b.postCompactionRepeat) - Number(a.postCompactionRepeat) || b.count - a.count || b.lastTs - a.lastTs) .slice(0, maxDeadEnds) @@ -651,6 +743,45 @@ export function buildHandoff( if (d.postCompactionRepeat) item.postCompactionRepeat = true; return item; }); +} + +function finalizePassingChecks(passingByKey: ReadonlyMap): HandoffCheck[] { + return [...passingByKey.values()] + .sort((a, b) => a.ts - b.ts) + .slice(-DEFAULT_MAX_CHECKS) + .map(({ command, at, outcome, kind }) => ({ command, at, outcome, kind })); +} + +/** + * Builds a deterministic, fully redacted context-reset handoff packet for a session. + * Pure: performs no disk, git, or network I/O and makes no LLM calls. + */ +export function buildHandoff( + session: Pick, + events: readonly AgentEvent[], + opts: HandoffOptions = {}, +): HandoffPacket { + const maxDeadEnds = opts.maxDeadEnds ?? DEFAULT_MAX_DEAD_ENDS; + const maxFiles = opts.maxFiles ?? DEFAULT_MAX_FILES; + const redactor = opts.redact ?? createRedactor(); + const redact = (s: string) => redactor.string(s); + + const sorted = byTime([...events]); + const baseCwd = session.repo?.root ?? session.cwd; + + const acc = createAccumulator(); + foldSessionEvents(sorted, baseCwd, redact, acc); + + const filesChanged = [...new Set([...acc.filesSet].map(redact))].sort().slice(0, maxFiles); + const passingChecks = finalizePassingChecks(acc.passingByKey); + + const progress: HandoffProgress = { filesChanged, passingChecks }; + const tailEdits = session.stats.verification !== undefined + ? session.stats.verification.unverifiedTailEdits + : acc.editsSinceCheck > 0 ? acc.editsSinceCheck : undefined; + if (tailEdits !== undefined && tailEdits > 0) progress.unverifiedTailEdits = tailEdits; + + const deadEnds = finalizeDeadEnds(acc.deadEndsByKey, maxDeadEnds); const base: Omit = { sessionId: session.id, @@ -676,3 +807,633 @@ export function buildHandoff( const markdown = redact(formatHandoffMarkdown(base)); return { ...base, markdown }; } + +// ------------------------------------------------------------ multi-day work timeline & handoff + +function eventsFor(eventsBySession: EventsBySession | undefined, sessionId: string): readonly AgentEvent[] { + if (!eventsBySession) return []; + if (eventsBySession instanceof Map) return eventsBySession.get(sessionId) ?? []; + const rec = eventsBySession as Readonly>; + return rec[sessionId] ?? []; +} + +function isOrganicSession(s: Session): boolean { + return !s.parent?.subagentId && !s.id.includes(":sub:"); +} + +function orderWorkSessions(item: Pick, sessions: readonly Session[]): Session[] { + const byId = new Map(sessions.map((s) => [s.id, s])); + const picked: Session[] = []; + const seen = new Set(); + for (const id of item.sessionIds) { + if (seen.has(id)) continue; + const s = byId.get(id); + if (s) { + seen.add(id); + picked.push(s); + } + } + const base = picked.length > 0 ? picked : [...sessions]; + return base.sort((a, b) => a.startedAt - b.startedAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); +} + +function dayOf(ts: number): string { + const iso = isoMs(ts); + return iso ? iso.slice(0, 10) : "-"; +} + +function spanDaysBetween(firstTs: number, lastTs: number): number { + const firstDay = Date.parse(`${dayOf(firstTs)}T00:00:00.000Z`); + const lastDay = Date.parse(`${dayOf(Math.max(firstTs, lastTs))}T00:00:00.000Z`); + if (!Number.isFinite(firstDay) || !Number.isFinite(lastDay)) return 1; + return Math.max(1, Math.floor((lastDay - firstDay) / DAY_MS) + 1); +} + +function inferProofVerdictFromStats(s: Session): Exclude | undefined { + const p = s.stats.verification?.proof; + if (!p) return undefined; + if (s.flags.includes("test-tamper")) return "tampered"; + if ((p.escapeRemaining ?? 0) > 0 || p.passed === 0 || p.failed > 0) return "incomplete"; + return "verified"; +} + +function firstLine(text: string | undefined): string | undefined { + if (!text) return undefined; + const line = text.split(/\r?\n/).find((l) => l.trim()); + return line?.trim(); +} + +function summarizeTimelineEntry( + s: Session, + acc: TraceAccumulator, + compactions: number, + verificationChecks: number, + unverifiedTailEdits: number, + deadEndCount: number, + risk: SupervisionRisk | undefined, + proofVerdict: Exclude | undefined, + redact: (s: string) => string, +): string { + const parts: string[] = []; + const filesCount = acc.filesSet.size > 0 ? acc.filesSet.size : (s.stats.filesChanged ?? 0); + if (filesCount > 0) parts.push(`${filesCount} ${filesCount === 1 ? "file" : "files"}`); + + const v = s.stats.verification; + if (v && v.checks > 0) { + parts.push(`${v.passed}/${v.checks} ${v.checks === 1 ? "check" : "checks"} passed`); + } else if (verificationChecks > 0) { + const passed = acc.passingByKey.size; + parts.push(passed > 0 ? `${passed}/${verificationChecks} ${verificationChecks === 1 ? "check" : "checks"} passed` : `${verificationChecks} ${verificationChecks === 1 ? "check" : "checks"}`); + } + + if (compactions > 0) parts.push(`${compactions} ${compactions === 1 ? "compaction" : "compactions"}`); + if (risk) parts.push(`risk:${risk}`); + if (proofVerdict) parts.push(`proof:${proofVerdict}`); + if (deadEndCount > 0) parts.push(`${deadEndCount} dead ${deadEndCount === 1 ? "end" : "ends"}`); + if (unverifiedTailEdits > 0) parts.push(`${unverifiedTailEdits} unverified tail ${unverifiedTailEdits === 1 ? "edit" : "edits"}`); + + if (!parts.length) { + const turns = s.stats.turns ?? 0; + parts.push(turns > 0 ? `${turns} ${turns === 1 ? "turn" : "turns"}` : "no changes recorded"); + } + return clip(redact(parts.join(", ")), ERROR_MAX); +} + +function buildTimelineEntry( + s: Session, + sortedEvents: readonly AgentEvent[], + redact: (s: string) => string, + shortId?: (id: string) => string, +): WorkTimelineEntry { + const acc = createAccumulator(); + if (sortedEvents.length > 0) { + foldSessionEvents(sortedEvents, s.repo?.root ?? s.cwd, redact, acc); + } + const compactions = Math.max(s.stats.contextHygiene?.compactions ?? 0, acc.compactionsSeen); + const verificationChecks = s.stats.verification?.checks ?? (acc.checksRun > 0 ? acc.checksRun : (s.stats.testsPassed ?? 0) + (s.stats.testsFailed ?? 0)); + const unverifiedTailEdits = s.stats.verification?.unverifiedTailEdits ?? (sortedEvents.length > 0 ? acc.editsSinceCheck : 0); + const unresolvedDeadEnds = [...acc.deadEndsByKey.values()].filter((d) => !d.resolved).length; + const deadEnds = sortedEvents.length > 0 ? unresolvedDeadEnds : (s.stats.contextHygiene?.deadEndStreak ? 1 : 0); + const risk = s.stats.contextHygiene?.supervisionRisk; + + let proofVerdict: Exclude | undefined; + if (sortedEvents.length > 0) { + const proof = buildProofSummary(s, sortedEvents, redact); + proofVerdict = proof?.verdict; + } + proofVerdict ??= inferProofVerdictFromStats(s); + + const goalLine = sortedEvents.length > 0 ? firstLine(extractGoal(s, sortedEvents, redact)) : undefined; + const rawTitle = s.title?.trim() || goalLine || "(untitled)"; + const title = clip(redact(rawTitle).replace(/\s+/g, " ").trim(), TITLE_MAX); + const summary = summarizeTimelineEntry(s, acc, compactions, verificationChecks, unverifiedTailEdits, deadEnds, risk, proofVerdict, redact); + + const entry: WorkTimelineEntry = { + sessionId: s.id, + agent: s.agent, + startedAt: formatTs(s.startedAt), + day: dayOf(s.startedAt), + title, + turns: s.stats.turns ?? 0, + compactions, + verificationChecks, + unverifiedTailEdits, + deadEnds, + summary, + }; + const sid = shortId?.(s.id); + if (sid) entry.shortId = sid; + const endedAt = isoMs(s.endedAt); + if (endedAt) entry.endedAt = endedAt; + if (risk) entry.risk = risk; + if (proofVerdict) entry.proofVerdict = proofVerdict; + return entry; +} + +/** + * Builds a chronological multi-day continuity timeline for a work item. + * Orders sessions by `startedAt` ascending, computes multi-day span across ALL member + * sessions, and caps `entries` to the newest `maxSessions` (default 20). + */ +export function buildWorkTimeline( + item: Pick, + sessions: readonly Session[], + eventsBySession?: EventsBySession, + opts: WorkTimelineOptions = {}, +): WorkTimeline { + const maxSessions = opts.maxSessions ?? DEFAULT_MAX_WORK_SESSIONS; + const redactor = opts.redact ?? createRedactor(); + const redact = (s: string) => redactor.string(s); + + const ordered = orderWorkSessions(item, sessions); + if (!ordered.length) { + return { spanDays: 0, totalSessions: 0, entries: [] }; + } + + let lastTs = ordered[0]!.startedAt; + const sortedById = new Map(); + for (const s of ordered) { + const evs = byTime([...eventsFor(eventsBySession, s.id)]); + sortedById.set(s.id, evs); + const evLast = evs.length ? evs[evs.length - 1]!.ts : s.startedAt; + const candidate = Math.max(s.startedAt, s.endedAt ?? s.startedAt, evLast); + if (candidate > lastTs) lastTs = candidate; + } + + const firstTs = ordered[0]!.startedAt; + const shown = ordered.length > maxSessions ? ordered.slice(-maxSessions) : ordered; + const entries = shown.map((s) => buildTimelineEntry(s, sortedById.get(s.id) ?? [], redact, opts.shortId)); + + const firstStartedAt = isoMs(firstTs); + const lastEndedAt = isoMs(lastTs); + const out: WorkTimeline = { + spanDays: spanDaysBetween(firstTs, lastTs), + totalSessions: ordered.length, + entries, + }; + if (firstStartedAt) out.firstStartedAt = firstStartedAt; + if (lastEndedAt) out.lastEndedAt = lastEndedAt; + if (ordered.length > shown.length) out.omittedSessions = ordered.length - shown.length; + return out; +} + +function normalizePromptCompare(text: string): string { + return text + .toLowerCase() + .replace(/\s+/g, " ") + .replace(/[.!?\s]+$/g, "") + .trim(); +} + +interface PromptPick { + eventId?: string; + text: string; +} + +function extractWorkGoals( + item: WorkHandoffItem, + ordered: readonly Session[], + sortedById: ReadonlyMap, + redact: (s: string) => string, +): { goal?: string; latestDirection?: string } { + const organic = ordered.filter(isOrganicSession); + const searchOrder = organic.length > 0 ? [organic, ordered] : [ordered]; + + let first: PromptPick | undefined; + for (const pool of searchOrder) { + for (const s of pool) { + for (const e of sortedById.get(s.id) ?? []) { + if (!isRealPrompt(e) || e.payload.from === "agent") continue; + const text = str(e.payload.text); + if (!text) continue; + const task = extractTaskPrompt(text); + if (task) { + first = { eventId: e.id, text: task }; + break; + } + } + if (first) break; + } + if (first) break; + } + if (!first) { + for (const s of ordered) { + for (const e of sortedById.get(s.id) ?? []) { + if (!isRealPrompt(e)) continue; + const text = str(e.payload.text); + if (!text) continue; + const task = extractTaskPrompt(text); + if (task) { + first = { eventId: e.id, text: task }; + break; + } + } + if (first) break; + } + } + if (!first) { + const fallbackTitle = item.title?.trim() || ordered.find((s) => s.title?.trim())?.title?.trim(); + if (fallbackTitle) first = { text: fallbackTitle }; + } + + let latest: PromptPick | undefined; + for (const pool of searchOrder) { + for (let i = pool.length - 1; i >= 0; i--) { + const s = pool[i]!; + const evs = sortedById.get(s.id) ?? []; + for (let j = evs.length - 1; j >= 0; j--) { + const e = evs[j]!; + if (!isRealPrompt(e) || e.payload.from === "agent") continue; + const text = str(e.payload.text); + if (!text) continue; + const task = extractTaskPrompt(text); + if (!task || TRIVIAL_ACK.test(task)) continue; + latest = { eventId: e.id, text: task }; + break; + } + if (latest) break; + } + if (latest) break; + } + + const goal = first ? clip(redact(first.text), GOAL_MAX) : undefined; + let latestDirection: string | undefined; + if (latest && first) { + const sameEvent = first.eventId !== undefined && first.eventId === latest.eventId; + const sameText = normalizePromptCompare(first.text) === normalizePromptCompare(latest.text); + if (!sameEvent && !sameText) { + latestDirection = clip(redact(latest.text), GOAL_MAX); + } + } + return { goal, latestDirection }; +} + +function namespaceEventsForProof(ordered: readonly Session[], sortedById: ReadonlyMap): AgentEvent[] { + const merged: AgentEvent[] = []; + for (const s of ordered) { + for (const e of sortedById.get(s.id) ?? []) { + const tid = str(e.payload?.toolUseId); + if (tid) { + merged.push({ ...e, payload: { ...e.payload, toolUseId: `${s.id}\u0000${tid}` } }); + } else { + merged.push(e); + } + } + } + return byTime(merged); +} + +function buildWorkProofRollup( + item: WorkHandoffItem, + ordered: readonly Session[], + sortedById: ReadonlyMap, + redact: (s: string) => string, +): WorkHandoffProof | undefined { + const merged = namespaceEventsForProof(ordered, sortedById); + const firstWithRepo = ordered.find((s) => s.repo?.root) ?? ordered[0]; + const proofTarget: Pick = { + id: item.id, + cwd: item.cwd ?? firstWithRepo?.cwd, + repo: item.repo ? { root: item.repo, head: firstWithRepo?.repo?.head ?? "", branch: item.branch } : firstWithRepo?.repo, + }; + const oscillating = ordered.reduce((sum, s) => sum + (s.stats.verification?.proof?.oscillatingChecks ?? 0), 0) || (item.proof?.oscillatingChecks ?? 0); + + const fromEvents = merged.length > 0 ? buildProofSummary(proofTarget, merged, redact) : undefined; + if (fromEvents) { + const out: WorkHandoffProof = { ...fromEvents }; + if (oscillating > 0) out.oscillatingChecks = oscillating; + return out; + } + + // Fallback when only aggregated stats exist (e.g. stats-only work items). + const langs = new Set(item.proof?.langs ?? []); + let hasStatsProof = !!item.proof; + let escapesRemaining = 0; + let passed = 0; + let failed = 0; + let tampered = false; + for (const s of ordered) { + const p = s.stats.verification?.proof; + if (!p) continue; + hasStatsProof = true; + for (const l of p.langs) langs.add(l); + escapesRemaining += p.escapeRemaining ?? 0; + passed += p.passed; + failed += p.failed; + if (s.flags.includes("test-tamper")) tampered = true; + } + if (!hasStatsProof) return undefined; + if (escapesRemaining === 0 && item.proof?.escapeRemaining) escapesRemaining = item.proof.escapeRemaining; + if (passed === 0 && failed === 0 && item.proof) { + passed = item.proof.passed; + failed = item.proof.failed; + } + const verdict: Exclude = tampered ? "tampered" : escapesRemaining > 0 || passed === 0 || failed > 0 ? "incomplete" : "verified"; + const out: WorkHandoffProof = { + verdict, + langs: [...langs].sort(), + specUntouched: !tampered, + escapesRemaining, + escapeKinds: [], + tamperFindings: [], + verifyHints: [], + }; + if (oscillating > 0) out.oscillatingChecks = oscillating; + return out; +} + +function buildWorkRiskRollup( + item: WorkHandoffItem, + ordered: readonly Session[], + contextResets: WorkContextResets, +): WorkHandoffRisk | undefined { + let level: SupervisionRisk | undefined = item.supervisionRisk; + const reasons = new Set(item.riskReasons ?? []); + let postCompactionFailedRepeats = 0; + let deadEndStreak = 0; + for (const s of ordered) { + const ch = s.stats.contextHygiene; + if (!ch) continue; + if (ch.supervisionRisk && (!level || RISK_RANK[ch.supervisionRisk] > RISK_RANK[level])) { + level = ch.supervisionRisk; + } + for (const r of ch.riskReasons ?? []) if (r) reasons.add(r); + postCompactionFailedRepeats += ch.postCompactionFailedRepeats ?? 0; + if ((ch.deadEndStreak ?? 0) > deadEndStreak) deadEndStreak = ch.deadEndStreak!; + } + if (!level) return undefined; + const risk: WorkHandoffRisk = { + level, + reasons: [...reasons].sort(), + }; + if (contextResets.compactions > 0) risk.compactions = contextResets.compactions; + if (contextResets.sessionHandoffs > 0) risk.sessionHandoffs = contextResets.sessionHandoffs; + if (contextResets.total > 0) risk.contextResets = contextResets.total; + if (postCompactionFailedRepeats > 0) risk.postCompactionFailedRepeats = postCompactionFailedRepeats; + if (deadEndStreak > 0) risk.deadEndStreak = deadEndStreak; + return risk; +} + +function cell(text: string, max = 80): string { + return clip(text.replace(/[\r\n]+/g, " ").replace(/\|/g, "/").replace(/\s+/g, " ").trim(), max); +} + +/** Formats a multi-day WorkHandoffPacket into a copy-paste-ready Markdown brief for a fresh session. */ +export function formatWorkHandoffMarkdown(packet: Omit | WorkHandoffPacket): string { + const titlePart = packet.title ? ` — ${packet.title}` : ""; + const lines: string[] = [ + "# Work Handoff", + "", + "Continue this work item in a fresh session. Keep the verified progress below and avoid repeating failed approaches.", + "", + `- **Work:** \`${packet.workId}\`${titlePart}`, + ]; + + if (packet.repo) { + const branchPart = packet.branch ? ` (\`${packet.branch}\`)` : ""; + lines.push(`- **Repo:** \`${packet.repo}\`${branchPart}`); + } else if (packet.branch) { + lines.push(`- **Branch:** \`${packet.branch}\``); + } + + const sessWord = packet.totalSessions === 1 ? "session" : "sessions"; + const dayWord = packet.spanDays === 1 ? "day" : "days"; + const rangePart = + packet.firstStartedAt && packet.lastEndedAt + ? packet.firstStartedAt.slice(0, 10) === packet.lastEndedAt.slice(0, 10) + ? ` (${packet.firstStartedAt.slice(0, 10)})` + : ` (${packet.firstStartedAt.slice(0, 10)} to ${packet.lastEndedAt.slice(0, 10)})` + : ""; + lines.push(`- **Span:** ${packet.totalSessions} ${sessWord} across ${packet.spanDays} ${dayWord}${rangePart}`); + + if (packet.agents.length) { + lines.push(`- **Agents:** ${packet.agents.join(", ")}`); + } + + const cr = packet.contextResets; + const compWord = cr.compactions === 1 ? "compaction" : "compactions"; + const hoWord = cr.sessionHandoffs === 1 ? "session handoff" : "session handoffs"; + lines.push(`- **Context resets:** ${cr.total} (${cr.compactions} ${compWord}, ${cr.sessionHandoffs} ${hoWord})`); + + if (packet.risk) { + const reasonText = packet.risk.reasons.length ? ` (${packet.risk.reasons.join(", ")})` : ""; + lines.push(`- **Supervision risk:** \`${packet.risk.level}\`${reasonText}`); + } + + lines.push("", "## Goal", ""); + if (packet.goal && packet.latestDirection) { + lines.push(`**Original goal:** ${packet.goal}`); + lines.push(""); + lines.push(`**Latest direction:** ${packet.latestDirection}`); + } else { + lines.push(packet.goal ?? "(no user prompt recorded)"); + } + + lines.push("", "## Multi-Day Timeline", ""); + if (packet.timeline.length) { + if (packet.omittedSessions && packet.omittedSessions > 0) { + lines.push( + `_Showing newest ${packet.timeline.length} of ${packet.totalSessions} sessions (${packet.omittedSessions} older omitted; original goal preserved from the first session)._`, + "", + ); + } + lines.push("| Date | Session | Agent | Checks | Compactions | Status | Summary |"); + lines.push("| --- | --- | --- | --- | --- | --- | --- |"); + for (const e of packet.timeline) { + const idLabel = `\`${e.shortId ?? e.sessionId}\``; + const flags: string[] = []; + if (e.risk) flags.push(`risk:${e.risk}`); + if (e.proofVerdict) flags.push(`proof:${e.proofVerdict}`); + const status = flags.length ? flags.join(", ") : "ok"; + lines.push( + `| ${e.day} | ${idLabel} | ${cell(e.agent, 24)} | ${e.verificationChecks} | ${e.compactions} | ${status} | ${cell(e.summary, 90)} |`, + ); + } + } else { + lines.push("No sessions recorded."); + } + + lines.push("", "## Files Changed", ""); + if (packet.progress.filesChanged.length) { + for (const f of packet.progress.filesChanged) lines.push(`- \`${f}\``); + } else { + lines.push("None recorded."); + } + if (packet.progress.unverifiedTailEdits && packet.progress.unverifiedTailEdits > 0) { + const n = packet.progress.unverifiedTailEdits; + lines.push("", `- **Unverified tail edits:** ${n} edit${n === 1 ? "" : "s"} after the last check`); + } + + lines.push("", "## Passing Checks", ""); + if (packet.progress.passingChecks.length) { + for (const c of packet.progress.passingChecks) { + lines.push(`- \`${c.command}\` (${c.outcome} at ${c.at})`); + } + } else { + lines.push("None recorded."); + } + + if (packet.proof) { + lines.push("", "## Formal Proofs", ""); + const langText = packet.proof.langs.length ? ` (${packet.proof.langs.join(", ")})` : ""; + lines.push(`- **Verdict:** \`${packet.proof.verdict}\`${langText}`); + lines.push(`- **Spec files:** ${packet.proof.specUntouched ? "untouched" : "modified"}`); + const kindText = packet.proof.escapeKinds.length ? ` (${packet.proof.escapeKinds.join(", ")})` : ""; + lines.push(`- **Remaining escapes:** ${packet.proof.escapesRemaining}${kindText}`); + if (packet.proof.oscillatingChecks) { + lines.push(`- **Oscillating checks:** ${packet.proof.oscillatingChecks}`); + } + if (packet.proof.tamperFindings.length) { + lines.push("- **Tamper findings:**"); + for (const f of packet.proof.tamperFindings) { + const where = f.file ? `\`${f.file}\`: ` : ""; + lines.push(` - [${f.kind}] ${where}${f.detail}`); + } + } + if (packet.proof.verifyHints.length) { + lines.push("- **Verify hints:**"); + for (const h of packet.proof.verifyHints) lines.push(` - \`${h}\``); + } + } + + if (packet.deadEnds.length) { + lines.push("", "## Do Not Repeat", ""); + for (const d of packet.deadEnds) { + const tags: string[] = [`failed ${d.count}x`]; + if (d.postCompactionRepeat) tags.push("repeated after compaction"); + const errPart = d.error ? `: ${d.error}` : ""; + lines.push(`- \`${d.command}\` (${tags.join(", ")})${errPart}`); + } + } + + lines.push("", "## Next Step", ""); + lines.push("1. Inspect `git status` and `git diff` for the changed files before editing."); + if (packet.latestDirection) { + lines.push("2. Follow the latest direction above while staying consistent with the original goal."); + } else if (packet.deadEnds.length) { + lines.push("2. Avoid the failed approaches listed under Do Not Repeat and try a different strategy."); + } else { + lines.push("2. Continue from the verified state above and keep changes scoped to the goal."); + } + if (packet.proof && (packet.proof.escapesRemaining > 0 || packet.proof.verdict !== "verified")) { + lines.push("3. Eliminate remaining proof escapes without weakening specs, then run the verify hints above."); + } else if (packet.deadEnds.length && packet.latestDirection) { + lines.push("3. Avoid the failed approaches listed under Do Not Repeat and run verification checks after each edit."); + } else { + lines.push("3. Run verification checks after each focused edit."); + } + + return lines.join("\n"); +} + +/** + * Builds a deterministic, fully redacted cross-session multi-day handoff packet for a work item. + * Pure: performs no disk, git, or network I/O and makes no LLM calls. + */ +export function buildWorkHandoff( + item: WorkHandoffItem, + sessions: readonly Session[], + eventsBySession: EventsBySession = new Map(), + opts: WorkHandoffOptions = {}, +): WorkHandoffPacket { + const maxDeadEnds = opts.maxDeadEnds ?? DEFAULT_MAX_WORK_DEAD_ENDS; + const maxFiles = opts.maxFiles ?? DEFAULT_MAX_FILES; + const maxSessions = opts.maxSessions ?? DEFAULT_MAX_WORK_SESSIONS; + const redactor = opts.redact ?? createRedactor(); + const redact = (s: string) => redactor.string(s); + + const ordered = orderWorkSessions(item, sessions); + const sortedById = new Map(); + const acc = createAccumulator(); + + let totalCompactions = 0; + for (const s of ordered) { + const sorted = byTime([...eventsFor(eventsBySession, s.id)]); + sortedById.set(s.id, sorted); + const beforeCompactions = acc.compactionsSeen; + foldSessionEvents(sorted, item.repo ?? s.repo?.root ?? item.cwd ?? s.cwd, redact, acc); + const seenInSession = acc.compactionsSeen - beforeCompactions; + totalCompactions += Math.max(s.stats.contextHygiene?.compactions ?? 0, seenInSession); + } + + const timeline = buildWorkTimeline(item, ordered, sortedById, { maxSessions, shortId: opts.shortId, redact: redactor }); + const { goal, latestDirection } = extractWorkGoals(item, ordered, sortedById, redact); + + const filesChanged = [...new Set([...acc.filesSet].map(redact))].sort().slice(0, maxFiles); + const passingChecks = finalizePassingChecks(acc.passingByKey); + const progress: HandoffProgress = { filesChanged, passingChecks }; + const newest = ordered[ordered.length - 1]; + const tailEdits = + acc.editsSinceCheck > 0 + ? acc.editsSinceCheck + : sortedById.get(newest?.id ?? "")?.length + ? undefined + : newest?.stats.verification?.unverifiedTailEdits; + if (tailEdits !== undefined && tailEdits > 0) progress.unverifiedTailEdits = tailEdits; + + const deadEnds = finalizeDeadEnds(acc.deadEndsByKey, maxDeadEnds); + + const sessionHandoffs = Math.max(0, ordered.length - 1); + const contextResets: WorkContextResets = { + compactions: totalCompactions, + sessionHandoffs, + total: totalCompactions + sessionHandoffs, + }; + + const agents = [...new Set([...(item.agents ?? []), ...ordered.map((s) => s.agent)])]; + const base: Omit = { + workId: item.id, + agents, + spanDays: timeline.spanDays, + totalSessions: timeline.totalSessions, + timeline: timeline.entries, + progress, + deadEnds, + contextResets, + }; + + if (timeline.firstStartedAt) base.firstStartedAt = timeline.firstStartedAt; + if (timeline.lastEndedAt) base.lastEndedAt = timeline.lastEndedAt; + if (timeline.omittedSessions !== undefined) base.omittedSessions = timeline.omittedSessions; + + const rawTitle = item.title?.trim() || ordered.find((s) => s.title?.trim())?.title?.trim(); + if (rawTitle) base.title = clip(redact(rawTitle), TITLE_MAX); + + const repoPath = item.repo ?? ordered.find((s) => s.repo?.root)?.repo?.root ?? item.cwd ?? ordered.find((s) => s.cwd)?.cwd; + if (repoPath) base.repo = redact(repoPath); + + const branch = item.branch ?? [...ordered].reverse().find((s) => s.repo?.branch)?.repo?.branch; + if (branch) base.branch = redact(branch); + + if (goal) base.goal = goal; + if (latestDirection) base.latestDirection = latestDirection; + + const risk = buildWorkRiskRollup(item, ordered, contextResets); + if (risk) base.risk = risk; + + const proof = buildWorkProofRollup(item, ordered, sortedById, redact); + if (proof) base.proof = proof; + + const markdown = redact(formatWorkHandoffMarkdown(base)); + return { ...base, markdown }; +} diff --git a/packages/coding.sh/src/viewer/work.ts b/packages/coding.sh/src/viewer/work.ts index 27284c42..ff1a74b8 100644 --- a/packages/coding.sh/src/viewer/work.ts +++ b/packages/coding.sh/src/viewer/work.ts @@ -7,7 +7,9 @@ import { bucketsFlag, kindsFlag, mainFilesChanged, risksFlag, stagesFlag } from import { parsePlace } from "../mcp/data.ts"; import { dateMs, isoMs } from "../core/dates.ts"; import type { IndexStore } from "../core/types.ts"; -import type { Session } from "../schema/index.ts"; +import type { AgentEvent, Session } from "../schema/index.ts"; +import { buildWorkTimeline, DEFAULT_MAX_WORK_SESSIONS, type WorkTimeline } from "../core/handoff.ts"; +import { createRedactor } from "../core/redact.ts"; import { shortener } from "../core/session-ref.ts"; import { indexAge, indexAgeField, indexAgeText, staleIndexText, type IndexAge } from "../core/ingest-health.ts"; import { addAck, readOverlay, snoozeItem, writeOverlay, type WorkOverlay } from "../core/work-overlay.ts"; @@ -228,11 +230,24 @@ export async function workShow(index: IndexStore, src: WorkSource, id: string, q const now = judgedAt(src, clock, age); const overlay = readOverlay(src.overlay); // The window and the judgment as the list's: from the last ingest while the index is old. - const { item, items, sessions } = await findItem(index, src, id, q, now, { filtered: true, judged: now, shortId: await shortener(index), overlay }); + const shortId = await shortener(index); + const { item, items, sessions } = await findItem(index, src, id, q, now, { filtered: true, judged: now, shortId, overlay }); const byId = new Map(sessions.map((s) => [s.id, s])); // Before workItemJson: when it reads every session, workFiles sets the item's file count and review reason. const files = await workFiles(index, item, sessions, now); const children = item.sessionIds.filter((sid) => sid !== item.primaryId).map((sid) => byId.get(sid)).filter((s): s is Session => !!s); + let timeline: WorkTimeline | undefined; + if (item.sessionIds.length > 1) { + const memberSessions = item.sessionIds + .map((sid) => byId.get(sid)) + .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(); + for (const s of memberSessions.slice(-DEFAULT_MAX_WORK_SESSIONS)) { + eventsBySession.set(s.id, await index.listEvents(s.id)); + } + timeline = buildWorkTimeline(item, memberSessions, eventsBySession, { shortId, redact: createRedactor() }); + } const doc: Record = { ...workItemJson(item), now: new Date(now).toISOString(), @@ -246,6 +261,8 @@ export async function workShow(index: IndexStore, src: WorkSource, id: string, q if (s.stats.waiting) row.waiting = s.stats.waiting.kind; return row; }), + spanDays: timeline ? timeline.spanDays : undefined, + timeline: timeline ? timeline.entries : undefined, }; if (item.supersededBy) { // The newer item ended with no failure, so it is often hidden, or outside the filters. diff --git a/packages/coding.sh/test/cli/work-handoff.test.ts b/packages/coding.sh/test/cli/work-handoff.test.ts new file mode 100644 index 00000000..b9cdb86f --- /dev/null +++ b/packages/coding.sh/test/cli/work-handoff.test.ts @@ -0,0 +1,269 @@ +// `coding.sh handoff --work ` and multi-session `coding.sh work show ` timeline +// through the CLI in a throwaway HOME and repo. +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, before, describe, it } from "node:test"; +import type { WorkHandoffPacket, WorkTimelineEntry } from "../../src/core/handoff.ts"; +import { buildSession } from "../../src/core/sessions.ts"; +import { workItemId } from "../../src/core/work.ts"; +import type { AgentEvent } from "../../src/schema/index.ts"; +import { CLI } from "../_cli.ts"; + +const DAY = 86_400_000; +const diff = (path: string, ...lines: string[]) => `--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n${lines.join("\n")}\n`; + +let root = ""; +let home = ""; +let repo = ""; +let env: NodeJS.ProcessEnv = {}; +let workId = ""; +let singleHighId = ""; +const SECRET_KEY = ["sk-ant-api03-", "Z".repeat(40)].join(""); + +function cli(...args: string[]) { + const r = spawnSync(process.execPath, ["--no-warnings", CLI, ...args], { cwd: repo, env, encoding: "utf8", timeout: 120_000 }); + return { status: r.status, stdout: r.stdout, stderr: r.stderr }; +} + +function makeEvents( + sessionId: string, + startTs: number, + agent: string, + steps: [AgentEvent["kind"], Record][], +): AgentEvent[] { + let ts = startTs; + return steps.map(([kind, payload], i) => { + ts += 1000; + return { + id: `${sessionId}-${i}`, + v: 0, + sessionId, + ts, + agent, + cwd: repo, + repo: { root: repo, branch: "feat/multiday-handoff", head: "bf255bb5" }, + kind, + payload, + }; + }); +} + +before(async () => { + root = realpathSync(mkdtempSync(join(tmpdir(), "csh-cli-work-handoff-"))); + home = join(root, "home"); + repo = join(root, "repo"); + mkdirSync(home); + mkdirSync(repo, { recursive: true }); + env = { + PATH: process.env.PATH, + HOME: home, + USERPROFILE: home, + CODING_SH_HOME: join(home, ".coding.sh"), + XDG_CONFIG_HOME: join(home, ".config"), + XDG_DATA_HOME: join(home, ".local", "share"), + NO_COLOR: "1", + CODING_SH_NO_UPDATE_CHECK: "1", + CODING_SH_NO_AUTO_INGEST: "1", + }; + + // Place 3 sessions across 3 distinct UTC calendar days within the last 5 days so both + // `work show` (default 7d) and `handoff --work` (default 30d) resolve the work item. + const nowDayMidnight = Math.floor(Date.now() / DAY) * DAY; + const day1 = nowDayMidnight - 3 * DAY + 10 * 3600_000; + const day2 = nowDayMidnight - 2 * DAY + 14 * 3600_000; + const day3 = nowDayMidnight - 1 * DAY + 9 * 3600_000; + + const { openContext } = await import("../../src/core/context.ts"); + const ctx = await openContext({ env, cwd: repo }); + try { + const ev1 = makeEvents("wday-1111", day1, "claude-code", [ + ["session.start", {}], + ["user.message", { text: `Implement token rotation without printing ${SECRET_KEY}.` }], + ["file.change", { path: "src/tokens.ts", op: "modify", diff: diff("src/tokens.ts", "-const v = 1;", "+const v = 2;") }], + ["tool.start", { tool: "Bash", toolUseId: "c1", input: { command: "npm test" } }], + ["tool.end", { tool: "Bash", toolUseId: "c1", ok: true, output: "ok" }], + ["tool.start", { tool: "Bash", toolUseId: "d1", input: { command: "node scripts/bad-step.mjs" } }], + ["tool.end", { tool: "Bash", toolUseId: "d1", ok: false, output: "Error: bad step day 1" }], + ["session.end", {}], + ]); + const s1 = buildSession(ev1); + await ctx.index.upsertSession(s1); + await ctx.index.putEvents(ev1); + + const ev2 = makeEvents("wday-2222", day2, "claude-code", [ + ["session.start", {}], + ["user.message", { text: "Pivot: prove rotation safety in Proof/Rotate.lean without sorry." }], + ["file.change", { path: "Proof/Rotate.lean", op: "modify", diff: diff("Proof/Rotate.lean", " theorem rot : True := by", "- trivial", "+ sorry") }], + ["context.compact", { trigger: "auto", tokensBefore: 150_000 }], + ["tool.start", { tool: "Bash", toolUseId: "d2", input: { command: "node scripts/bad-step.mjs" } }], + ["tool.end", { tool: "Bash", toolUseId: "d2", ok: false, output: "Error: bad step day 2" }], + ["tool.start", { tool: "Bash", toolUseId: "p1", input: { command: "lake env lean Proof/Rotate.lean" } }], + ["tool.end", { tool: "Bash", toolUseId: "p1", ok: false, output: "Proof/Rotate.lean:2:2: error: unsolved goals" }], + ["tool.start", { tool: "Bash", toolUseId: "p2", input: { command: "lake env lean Proof/Rotate.lean" } }], + ["tool.end", { tool: "Bash", toolUseId: "p2", ok: false, output: "Proof/Rotate.lean:3:2: error: unsolved goals" }], + ["tool.start", { tool: "Bash", toolUseId: "p3", input: { command: "lake env lean Proof/Rotate.lean" } }], + ["tool.end", { tool: "Bash", toolUseId: "p3", ok: false, output: "Proof/Rotate.lean:4:2: error: unsolved goals" }], + ["tool.start", { tool: "Bash", toolUseId: "p4", input: { command: "lake env lean Proof/Rotate.lean" } }], + ["tool.end", { tool: "Bash", toolUseId: "p4", ok: false, output: "Proof/Rotate.lean:5:2: error: unsolved goals" }], + ["tool.start", { tool: "Bash", toolUseId: "p5", input: { command: "lake env lean Proof/Rotate.lean" } }], + ["tool.end", { tool: "Bash", toolUseId: "p5", ok: false, output: "Proof/Rotate.lean:6:2: error: unsolved goals" }], + ["session.end", {}], + ]); + const s2 = buildSession(ev2); + s2.parent = { sessionId: "wday-1111", type: "fork" }; + await ctx.index.upsertSession(s2); + await ctx.index.putEvents(ev2); + + const ev3 = makeEvents("wday-3333", day3, "codex", [ + ["session.start", {}], + ["user.message", { text: "Finish src/rotate-cli.ts and keep npm test green." }], + ["file.change", { path: "src/rotate-cli.ts", op: "modify", diff: diff("src/rotate-cli.ts", "+export const cli = true;") }], + ["tool.start", { tool: "Bash", toolUseId: "c3", input: { command: "npm test" } }], + ["tool.end", { tool: "Bash", toolUseId: "c3", ok: true, output: "ok" }], + ["session.end", {}], + ]); + const s3 = buildSession(ev3); + s3.parent = { sessionId: "wday-2222", type: "provider-switch" }; + await ctx.index.upsertSession(s3); + await ctx.index.putEvents(ev3); + + workId = workItemId("wday-1111"); + + // Also seed a single-session high-risk work item to verify single-session behavior stays intact. + const evSingle = makeEvents("solo-high-9999", day3 + 3600_000, "claude-code", [ + ["session.start", {}], + ["user.message", { text: "Fix solo proof." }], + ["file.change", { path: "Proof/Solo.lean", op: "modify", diff: diff("Proof/Solo.lean", " theorem solo : True := by", "- trivial", "+ sorry") }], + ["tool.start", { tool: "Bash", toolUseId: "s1", input: { command: "lake env lean Proof/Solo.lean" } }], + ["tool.end", { tool: "Bash", toolUseId: "s1", ok: false, output: "Proof/Solo.lean:2:2: error: unsolved goals" }], + ["tool.start", { tool: "Bash", toolUseId: "s2", input: { command: "lake env lean Proof/Solo.lean" } }], + ["tool.end", { tool: "Bash", toolUseId: "s2", ok: false, output: "Proof/Solo.lean:3:2: error: unsolved goals" }], + ["tool.start", { tool: "Bash", toolUseId: "s3", input: { command: "lake env lean Proof/Solo.lean" } }], + ["tool.end", { tool: "Bash", toolUseId: "s3", ok: false, output: "Proof/Solo.lean:4:2: error: unsolved goals" }], + ["tool.start", { tool: "Bash", toolUseId: "s4", input: { command: "lake env lean Proof/Solo.lean" } }], + ["tool.end", { tool: "Bash", toolUseId: "s4", ok: false, output: "Proof/Solo.lean:5:2: error: unsolved goals" }], + ["tool.start", { tool: "Bash", toolUseId: "s5", input: { command: "lake env lean Proof/Solo.lean" } }], + ["tool.end", { tool: "Bash", toolUseId: "s5", ok: false, output: "Proof/Solo.lean:6:2: error: unsolved goals" }], + ["session.end", {}], + ]); + const solo = buildSession(evSingle); + await ctx.index.upsertSession(solo); + await ctx.index.putEvents(evSingle); + singleHighId = workItemId("solo-high-9999"); + } finally { + await ctx.close(); + } +}); + +after(() => { + if (root) rmSync(root, { recursive: true, force: true }); +}); + +describe("coding.sh handoff --work and work show timeline", () => { + it("builds a multi-day Markdown brief via --work and unique prefix with secret redaction", () => { + const res = cli("handoff", "--work", workId.slice(0, 5)); + assert.equal(res.status, 0, res.stdout + res.stderr); + assert.match(res.stdout, /^# Work Handoff\n/); + assert.match(res.stdout, /3 sessions across 3 days/); + assert.match(res.stdout, /\*\*Original goal:\*\*/); + assert.match(res.stdout, /\*\*Latest direction:\*\*/); + assert.match(res.stdout, /## Multi-Day Timeline/); + assert.match(res.stdout, /## Files Changed/); + assert.match(res.stdout, /src\/tokens\.ts/); + assert.match(res.stdout, /Proof\/Rotate\.lean/); + assert.match(res.stdout, /src\/rotate-cli\.ts/); + assert.match(res.stdout, /## Passing Checks/); + assert.match(res.stdout, /## Formal Proofs/); + assert.match(res.stdout, /## Do Not Repeat/); + assert.match(res.stdout, /## Next Step/); + assert.ok(!res.stdout.includes(SECRET_KEY), "secret redacted from stdout"); + assert.match(res.stderr, new RegExp(`Work handoff brief for ${workId} \\(3 sessions, 3 days`)); + }); + + it("supports --json, --max-dead-ends, --max-sessions, and --out for --work", () => { + const rJson = cli("handoff", "--work", workId, "--max-dead-ends", "1", "--max-sessions", "2", "--json"); + assert.equal(rJson.status, 0, rJson.stdout + rJson.stderr); + const doc = JSON.parse(rJson.stdout) as WorkHandoffPacket; + assert.equal(doc.workId, workId); + assert.equal(doc.spanDays, 3); + assert.equal(doc.totalSessions, 3); + assert.equal(doc.omittedSessions, 1); + assert.equal(doc.timeline.length, 2); + assert.equal(doc.deadEnds.length, 1); + assert.equal(doc.deadEnds[0]!.command, "lake env lean Proof/Rotate.lean"); + assert.equal(doc.proof?.verdict, "incomplete"); + assert.equal(doc.proof?.escapesRemaining, 1); + assert.equal(doc.risk?.level, "high"); + assert.deepEqual(doc.contextResets, { compactions: 1, sessionHandoffs: 2, total: 3 }); + assert.ok(doc.goal?.startsWith("Implement token rotation")); + assert.equal(doc.latestDirection, "Finish src/rotate-cli.ts and keep npm test green."); + assert.ok(!JSON.stringify(doc).includes(SECRET_KEY)); + + const mdPath = join(root, "out", "work-handoff.md"); + const rOut = cli("handoff", "--work", workId, "--out", mdPath); + assert.equal(rOut.status, 0, rOut.stdout + rOut.stderr); + assert.equal(rOut.stdout.trim(), mdPath); + assert.match(rOut.stderr, /Wrote work handoff brief/); + const written = readFileSync(mdPath, "utf8"); + assert.match(written, /^# Work Handoff\n/); + assert.ok(!written.includes(SECRET_KEY)); + }); + + it("validates mutually exclusive and --work arguments and reports unknown work ids", () => { + const neither = cli("handoff"); + assert.equal(neither.status, 2); + assert.match(neither.stderr, /Missing or --work /); + + const both = cli("handoff", "wday-1111", "--work", workId); + assert.equal(both.status, 2); + assert.match(both.stderr, /Pass either or --work , not both/); + + const emptyWork = cli("handoff", "--work", ""); + assert.equal(emptyWork.status, 2); + assert.match(emptyWork.stderr, /--work needs a work item id/); + + const badMaxSessions = cli("handoff", "--work", workId, "--max-sessions", "0"); + assert.equal(badMaxSessions.status, 2); + assert.match(badMaxSessions.stderr, /--max-sessions must be a whole number from 1/); + + const missing = cli("handoff", "--work", "w000000"); + assert.equal(missing.status, 1); + assert.match(missing.stderr, /Can't find work item "w000000"/); + }); + + it("surfaces Timeline in work show (text and --json) and suggests handoff --work for multi-session high-risk items", () => { + const showText = cli("work", "show", workId); + assert.equal(showText.status, 0, showText.stdout + showText.stderr); + assert.match(showText.stdout, /Timeline +3 sessions across 3 days/); + assert.match(showText.stdout, /wday-1111|wday-1/); + assert.match(showText.stdout, /risk:high/); + assert.match(showText.stdout, /proof:incomplete/); + assert.match(showText.stderr, new RegExp(`(?:coding\\.sh|codingsh) handoff --work ${workId}`)); + + const showJson = cli("work", "show", workId, "--json"); + assert.equal(showJson.status, 0, showJson.stdout + showJson.stderr); + const parsed = JSON.parse(showJson.stdout) as { id: string; spanDays?: number; timeline?: WorkTimelineEntry[] }; + assert.equal(parsed.id, workId); + assert.equal(parsed.spanDays, 3); + assert.equal(parsed.timeline?.length, 3); + assert.deepEqual( + parsed.timeline?.map((e) => e.sessionId), + ["wday-1111", "wday-2222", "wday-3333"], + ); + + // Single-session high-risk item omits timeline and keeps single-session handoff hint. + const soloJson = cli("work", "show", singleHighId, "--json"); + assert.equal(soloJson.status, 0, soloJson.stdout + soloJson.stderr); + const soloParsed = JSON.parse(soloJson.stdout) as { id: string; timeline?: WorkTimelineEntry[] }; + assert.equal(soloParsed.timeline, undefined); + + const soloText = cli("work", "show", singleHighId); + assert.equal(soloText.status, 0, soloText.stdout + soloText.stderr); + assert.doesNotMatch(soloText.stdout, /\bTimeline\b/); + assert.doesNotMatch(soloText.stderr, /handoff --work/); + assert.match(soloText.stderr, /(?:coding\.sh|codingsh) handoff solo/); + }); +}); diff --git a/packages/coding.sh/test/core/work-handoff.test.ts b/packages/coding.sh/test/core/work-handoff.test.ts new file mode 100644 index 00000000..aceab326 --- /dev/null +++ b/packages/coding.sh/test/core/work-handoff.test.ts @@ -0,0 +1,311 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { + buildWorkHandoff, + buildWorkTimeline, + formatWorkHandoffMarkdown, +} from "../../src/core/handoff.ts"; +import { buildSession } from "../../src/core/sessions.ts"; +import { buildWorkQueue, workItemId } from "../../src/core/work.ts"; +import type { AgentEvent, RepoState, Session } from "../../src/schema/index.ts"; + +const DAY = 86_400_000; +const DAY1 = Date.UTC(2026, 9, 20, 10, 0, 0); +const DAY2 = DAY1 + DAY + 4 * 3600_000; +const DAY3 = DAY1 + 2 * DAY - 3600_000; +const CWD = "/work/demo"; +const REPO: RepoState = { root: CWD, branch: "feat/key-rotation", head: "3b5f1f08" }; + +type Step = [AgentEvent["kind"], Record, { durationMs?: number; tsOffsetMs?: number }?]; + +const diff = (path: string, ...lines: string[]) => `--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n${lines.join("\n")}\n`; + +function makeSession( + id: string, + startTs: number, + steps: Step[], + opts: { agent?: string; parentSessionId?: string; parentType?: string } = {}, +): { session: Session; events: AgentEvent[] } { + let ts = startTs; + const agent = opts.agent ?? "claude-code"; + const events: AgentEvent[] = steps.map(([kind, payload, extra], i) => { + ts += extra?.tsOffsetMs ?? 1000; + const ev: AgentEvent = { + id: `${id}-${i}`, + v: 0, + sessionId: id, + ts, + agent, + cwd: CWD, + repo: REPO, + kind, + payload, + }; + if (extra?.durationMs !== undefined) ev.durationMs = extra.durationMs; + return ev; + }); + const session = buildSession(events); + if (opts.parentSessionId) { + session.parent = { sessionId: opts.parentSessionId }; + if (opts.parentType) session.parent.type = opts.parentType; + } + return { session, events }; +} + +describe("buildWorkHandoff and buildWorkTimeline", () => { + it("stitches a 3-day work item with direction pivot, deduplicated dead ends, proof rollup, and secret redaction", () => { + const apiKey = ["sk-ant-api03-", "A".repeat(40)].join(""); + const ghToken = ["ghp_", "B".repeat(36)].join(""); + const dbPass = "TopSecret42"; + + // Day 1: initial goal, first edit, passing check, dead-end script failure. + const d1 = makeSession("s-day1", DAY1, [ + ["session.start", {}], + ["user.message", { text: `Implement JWT auth refresh middleware without logging ${apiKey}.` }], + ["file.change", { path: `${CWD}/src/auth.ts`, op: "modify", diff: diff("src/auth.ts", "-const ttl = 10;", "+const ttl = 60;") }], + ["tool.start", { tool: "Bash", toolUseId: "t1", input: { command: "npm test" } }], + ["tool.end", { tool: "Bash", toolUseId: "t1", ok: true, output: "10 passing" }], + ["tool.start", { tool: "Bash", toolUseId: "t2", input: { command: `curl -H "Authorization: Bearer ${ghToken}" https://api.example.com/migrate` } }], + ["tool.end", { tool: "Bash", toolUseId: "t2", ok: false, exitCode: 1, output: `Error: connection refused for postgres://admin:${dbPass}@db.example.com:5432/app` }], + ["session.end", {}], + ]); + + // Day 2: direction pivot, compaction, repeated dead-end, Lean proof sorry + oscillating failures -> high risk. + const d2 = makeSession( + "s-day2", + DAY2, + [ + ["session.start", {}], + ["user.message", { text: "Pivot to Ed25519 signing keys and prove rotation invariant in Proof/KeyRotate.lean without sorry." }], + ["file.change", { path: "src/auth.ts", op: "modify", diff: diff("src/auth.ts", "-const alg = 'HS256';", "+const alg = 'Ed25519';") }], + ["file.change", { path: "Proof/KeyRotate.lean", op: "modify", diff: diff("Proof/KeyRotate.lean", " theorem rotate_ok (k : Nat) : k = k := by", "- rfl", "+ sorry") }], + ["context.compact", { trigger: "auto", tokensBefore: 160_000 }], + ["tool.start", { tool: "Bash", toolUseId: "t2", input: { command: `curl -H "Authorization: Bearer ${ghToken}" https://api.example.com/migrate` } }], + ["tool.end", { tool: "Bash", toolUseId: "t2", ok: false, exitCode: 1, output: `Error: connection refused for postgres://admin:${dbPass}@db.example.com:5432/app` }], + ["tool.start", { tool: "Bash", toolUseId: "p1", input: { command: "lake env lean Proof/KeyRotate.lean" } }], + ["tool.end", { tool: "Bash", toolUseId: "p1", ok: false, output: "Proof/KeyRotate.lean:2:2: error: unsolved goals" }], + ["tool.start", { tool: "Bash", toolUseId: "p2", input: { command: "lake env lean Proof/KeyRotate.lean" } }], + ["tool.end", { tool: "Bash", toolUseId: "p2", ok: false, output: "Proof/KeyRotate.lean:3:2: error: unsolved goals" }], + ["tool.start", { tool: "Bash", toolUseId: "p3", input: { command: "lake env lean Proof/KeyRotate.lean" } }], + ["tool.end", { tool: "Bash", toolUseId: "p3", ok: false, output: "Proof/KeyRotate.lean:4:2: error: unsolved goals" }], + ["tool.start", { tool: "Bash", toolUseId: "p4", input: { command: "lake env lean Proof/KeyRotate.lean" } }], + ["tool.end", { tool: "Bash", toolUseId: "p4", ok: false, output: "Proof/KeyRotate.lean:5:2: error: unsolved goals" }], + ["tool.start", { tool: "Bash", toolUseId: "p5", input: { command: "lake env lean Proof/KeyRotate.lean" } }], + ["tool.end", { tool: "Bash", toolUseId: "p5", ok: false, output: "Proof/KeyRotate.lean:6:2: error: unsolved goals" }], + ["session.end", {}], + ], + { agent: "claude-code", parentSessionId: "s-day1", parentType: "fork" }, + ); + + // Day 3: partial fix on another agent, keeps tests green, trivial ack prompt so Day 2 pivot stays latest direction. + const d3 = makeSession( + "s-day3", + DAY3, + [ + ["session.start", {}], + ["user.message", { text: "continue" }], + ["file.change", { path: "src/keys.ts", op: "modify", diff: diff("src/keys.ts", "+export const algo = 'Ed25519';") }], + ["tool.start", { tool: "Bash", toolUseId: "t1", input: { command: "npm test" } }], + ["tool.end", { tool: "Bash", toolUseId: "t1", ok: true, output: "12 passing" }], + ["session.end", {}], + ], + { agent: "codex", parentSessionId: "s-day2", parentType: "provider-switch" }, + ); + + // Pass sessions intentionally out of order to verify chronological sorting. + const sessions = [d3.session, d1.session, d2.session]; + const queue = buildWorkQueue(sessions, { all: true, now: DAY3 + 60_000 }); + assert.equal(queue.items.length, 1); + const item = queue.items[0]!; + assert.equal(item.id, workItemId("s-day1")); + + const eventsBySession = new Map([ + [d1.session.id, d1.events], + [d2.session.id, d2.events], + [d3.session.id, d3.events], + ]); + + const packet = buildWorkHandoff(item, sessions, eventsBySession, { + shortId: (id) => id.slice(0, 6), + }); + + assert.equal(packet.workId, item.id); + assert.equal(packet.repo, CWD); + assert.equal(packet.branch, "feat/key-rotation"); + assert.deepEqual(packet.agents, ["claude-code", "codex"]); + assert.equal(packet.spanDays, 3); + assert.equal(packet.totalSessions, 3); + assert.equal(packet.omittedSessions, undefined); + assert.equal(packet.firstStartedAt?.slice(0, 10), "2026-10-20"); + assert.equal(packet.lastEndedAt?.slice(0, 10), "2026-10-22"); + + // Original goal from Day 1 + latest meaningful direction pivot from Day 2. + assert.ok(packet.goal?.startsWith("Implement JWT auth refresh middleware")); + assert.equal( + packet.latestDirection, + "Pivot to Ed25519 signing keys and prove rotation invariant in Proof/KeyRotate.lean without sorry.", + ); + + // Chronological timeline across 3 days. + assert.equal(packet.timeline.length, 3); + assert.deepEqual( + packet.timeline.map((e) => [e.sessionId, e.day, e.agent]), + [ + ["s-day1", "2026-10-20", "claude-code"], + ["s-day2", "2026-10-21", "claude-code"], + ["s-day3", "2026-10-22", "codex"], + ], + ); + assert.equal(packet.timeline[0]!.shortId, "s-day1"); + assert.equal(packet.timeline[1]!.compactions, 1); + assert.equal(packet.timeline[1]!.risk, "high"); + assert.equal(packet.timeline[1]!.proofVerdict, "incomplete"); + assert.equal(packet.timeline[0]!.risk, undefined); + assert.equal(packet.timeline[0]!.proofVerdict, undefined); + + // Deduplicated union of files and latest passing check. + assert.deepEqual(packet.progress.filesChanged, ["Proof/KeyRotate.lean", "src/auth.ts", "src/keys.ts"]); + assert.equal(packet.progress.passingChecks.length, 1); + assert.equal(packet.progress.passingChecks[0]!.command, "npm test"); + assert.equal(packet.progress.passingChecks[0]!.at.slice(0, 10), "2026-10-22"); + + // Deduplicated dead-ends across Day 1 and Day 2. + assert.equal(packet.deadEnds.length, 2); + assert.equal(packet.deadEnds[0]!.command, "lake env lean Proof/KeyRotate.lean"); + assert.equal(packet.deadEnds[0]!.count, 5); + assert.equal(packet.deadEnds[1]!.count, 2); + assert.match(packet.deadEnds[1]!.error ?? "", /connection refused/); + + // Formal-proof rollup. + assert.ok(packet.proof); + assert.equal(packet.proof.verdict, "incomplete"); + assert.deepEqual(packet.proof.langs, ["lean"]); + assert.equal(packet.proof.specUntouched, true); + assert.equal(packet.proof.escapesRemaining, 1); + assert.deepEqual(packet.proof.escapeKinds, ["sorry"]); + assert.ok((packet.proof.oscillatingChecks ?? 0) > 0); + + // Supervision risk and context-reset rollup. + assert.equal(packet.risk?.level, "high"); + assert.ok(packet.risk?.reasons.includes("tactic-oscillation")); + assert.deepEqual(packet.contextResets, { compactions: 1, sessionHandoffs: 2, total: 3 }); + + // Secret redaction everywhere. + const serialized = JSON.stringify(packet); + assert.ok(!serialized.includes(apiKey), "anthropic key redacted"); + assert.ok(!serialized.includes(ghToken), "github token redacted"); + assert.ok(!serialized.includes(dbPass), "db password redacted"); + + // Markdown sections. + assert.equal(formatWorkHandoffMarkdown(packet), packet.markdown); + assert.match(packet.markdown, /^# Work Handoff\n/); + assert.match(packet.markdown, /## Goal/); + assert.match(packet.markdown, /\*\*Original goal:\*\*/); + assert.match(packet.markdown, /\*\*Latest direction:\*\*/); + assert.match(packet.markdown, /## Multi-Day Timeline/); + assert.match(packet.markdown, /## Files Changed/); + assert.match(packet.markdown, /## Passing Checks/); + assert.match(packet.markdown, /## Formal Proofs/); + assert.match(packet.markdown, /## Do Not Repeat/); + assert.match(packet.markdown, /## Next Step/); + }); + + it("caps timeline sessions via maxSessions while preserving original goal and resolves cross-day proof escapes", () => { + const d1 = makeSession("s-1", DAY1, [ + ["session.start", {}], + ["user.message", { text: "Prove add_zero in Proof/Nat.lean." }], + ["file.change", { path: "Proof/Nat.lean", op: "modify", diff: diff("Proof/Nat.lean", " theorem add_zero (n : Nat) : n + 0 = n := by", "- rfl", "+ sorry") }], + ["tool.start", { tool: "Bash", toolUseId: "p1", input: { command: "lake env lean Proof/Nat.lean" } }], + ["tool.end", { tool: "Bash", toolUseId: "p1", ok: false, output: "Proof/Nat.lean:2:2: error: unsolved goals" }], + ["session.end", {}], + ]); + + const d2 = makeSession( + "s-2", + DAY2, + [ + ["session.start", {}], + ["user.message", { text: "Add helper lemma." }], + ["file.change", { path: "Proof/Helper.lean", op: "modify", diff: diff("Proof/Helper.lean", "+theorem h : True := trivial") }], + ["session.end", {}], + ], + { parentSessionId: "s-1", parentType: "fork" }, + ); + + const d3 = makeSession( + "s-3", + DAY3, + [ + ["session.start", {}], + ["user.message", { text: "Remove sorry from Proof/Nat.lean and verify." }], + ["file.change", { path: "Proof/Nat.lean", op: "modify", diff: diff("Proof/Nat.lean", " theorem add_zero (n : Nat) : n + 0 = n := by", "- sorry", "+ rfl") }], + ["tool.start", { tool: "Bash", toolUseId: "p2", input: { command: "lake env lean Proof/Nat.lean" } }], + ["tool.end", { tool: "Bash", toolUseId: "p2", ok: true, output: "" }], + ["session.end", {}], + ], + { parentSessionId: "s-2", parentType: "fork" }, + ); + + const sessions = [d1.session, d2.session, d3.session]; + const eventsBySession = { [d1.session.id]: d1.events, [d2.session.id]: d2.events, [d3.session.id]: d3.events }; + const item = { id: workItemId("s-1"), sessionIds: ["s-1", "s-2", "s-3"] }; + + const tl = buildWorkTimeline(item, sessions, eventsBySession, { maxSessions: 2 }); + assert.equal(tl.totalSessions, 3); + assert.equal(tl.omittedSessions, 1); + assert.equal(tl.spanDays, 3); + assert.deepEqual(tl.entries.map((e) => e.sessionId), ["s-2", "s-3"]); + + const packet = buildWorkHandoff(item, sessions, eventsBySession, { maxSessions: 2 }); + assert.equal(packet.goal, "Prove add_zero in Proof/Nat.lean."); + assert.equal(packet.latestDirection, "Remove sorry from Proof/Nat.lean and verify."); + assert.equal(packet.timeline.length, 2); + assert.equal(packet.omittedSessions, 1); + assert.equal(packet.proof?.verdict, "verified"); + assert.equal(packet.proof?.escapesRemaining, 0); + assert.deepEqual(packet.deadEnds, []); + assert.equal(packet.progress.passingChecks.length, 1); + assert.equal(packet.progress.passingChecks[0]!.command, "lake env lean Proof/Nat.lean"); + assert.match(packet.markdown, /1 older omitted; original goal preserved/); + assert.doesNotMatch(packet.markdown, /## Do Not Repeat/); + }); + + it("omits latestDirection, proof, risk, and Do Not Repeat for a clean work item without pivots", () => { + const s1 = makeSession("clean-1", DAY1, [ + ["session.start", {}], + ["user.message", { text: "Add sum helper test." }], + ["file.change", { path: "src/sum.ts", op: "modify", diff: diff("src/sum.ts", "+export const sum = (a: number, b: number) => a + b;") }], + ["tool.start", { tool: "Bash", toolUseId: "c1", input: { command: "npm test" } }], + ["tool.end", { tool: "Bash", toolUseId: "c1", ok: true, output: "ok" }], + ["session.end", {}], + ]); + const s2 = makeSession( + "clean-2", + DAY1 + 3600_000, + [ + ["session.start", {}], + ["user.message", { text: "Add sum helper test." }], + ["session.end", {}], + ], + { parentSessionId: "clean-1", parentType: "fork" }, + ); + + const packet = buildWorkHandoff( + { id: workItemId("clean-1"), sessionIds: ["clean-1", "clean-2"] }, + [s1.session, s2.session], + new Map([ + [s1.session.id, s1.events], + [s2.session.id, s2.events], + ]), + ); + + assert.equal(packet.spanDays, 1); + assert.equal(packet.latestDirection, undefined); + assert.equal(packet.proof, undefined); + assert.equal(packet.risk, undefined); + assert.deepEqual(packet.deadEnds, []); + assert.doesNotMatch(packet.markdown, /\*\*Latest direction:\*\*/); + assert.doesNotMatch(packet.markdown, /## Formal Proofs/); + assert.doesNotMatch(packet.markdown, /## Do Not Repeat/); + }); +});