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
55 changes: 55 additions & 0 deletions .agents/skills/ask-matt/PHASE-BOUNDARIES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Phase boundaries

A **phase** is a chunk of work inside a session — the grilling, the implementation, the QA. The definition is fuzzy on purpose: a phase ends when you think *"ok, we're done with that"*.

The **phase boundary** is the gap between two phases, and it is the only place this decision belongs. Mid-phase there is no decision to make — continue, or split the work that's left into subagents. Compacting mid-phase makes the agent lose the thread.

## The five options

| Option | What it does |
| ------------ | --------------------------------------------------------------- |
| **Continue** | Stay in the session. No context switch at all. |
| **`/clear`** | Empty the context window and start from nothing. |
| **`/handoff`** | Write a portable markdown file and seed a session anywhere with it. |
| **Subagent** | Send the task to its own context window and get a report back. |
| **`/compact`** | Compress this context and seed a fresh session with the summary. |

## The tree

Work top to bottom at the boundary. The first **yes** wins.

**1. Can you continue in this session?** Two things make the answer yes: the next phase needs this phase as a **primary source**, or you have enough [smart zone](https://www.aihero.dev/ai-coding-dictionary/smart-zone) left (~150k tokens) for the next phase to fit. Grilling → implementation is the standard yes: the implementation wants the reasoning verbatim, not a summary of it. Continue costs nothing and loses nothing, so rule it out before anything else.

**2. Is the context irrelevant to what comes next?** Is everything in this session — the exploration, the decisions, the dead ends — disposable? If so, **`/clear`**. It is the cheapest move on the board: it takes no time and hands back the whole window. `/clear` also isn't terminal — the old session stays resumable.

The cost of getting this wrong is one-way. Clear a *relevant* context and you lose the **why** behind what you built, and no amount of reading the diff back gets it returned.

**3. Do you need to hand off?** `/handoff` is narrow. You need it only when you are:

- swapping to a **new harness** (Claude → Codex),
- moving to a **new directory** or repo,
- sending the work to a **colleague**,
- or forking a side task you found **mid-phase** without derailing what you're doing.

That list is the whole clause. What `/handoff` buys is **portability** — a file that travels. If nothing is travelling, you don't need it.

**4. Can the task be done AFK?** Is it scoped tightly enough to run with you away from the keyboard, no steering? Then send it to a **subagent** and leave this session untouched. Automated review is the standard case: the agent reads the diff and reports, and you aren't needed while it does.

**5. Otherwise, `/compact`.** Relevant context, same harness, same directory, and you need to stay in the loop — this is where the tree lands, and it lands here often. Pass it an instruction (`/compact we're going to QA this area`) so the summary keeps what the next phase needs.

`/compact` is the **default, not the first reach**. It sits at the bottom because the four questions above it are all cheaper or more precise. The failure mode when people start here is a fresh session that is confidently wrong about a decision the summary flattened.

## Primary and secondary sources

Every move except **Continue** turns a **primary source** into a **secondary source** — the session as it happened, replaced by a summary of it. The trade is always the same shape:

| Source | Information | Noise | Room to move |
| --------------------------------- | ----------- | ----- | ------------ |
| Primary (Continue) | Full | Lots | Little |
| Secondary (`/compact`, `/handoff`) | Lossy | Less | Lots |

This is why question 1 comes first. You only pay the lossiness when staying costs more than it saves.

## These are judgement calls

The questions are not objective — each has taste in it, and the same boundary can go two ways on two days. The value is in asking them **in order**, at the boundary rather than in the middle of the work.
20 changes: 17 additions & 3 deletions app/api/sync/projects/route.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { asProjectRepository } from "@/lib/local-capture/types";
import { requireSyncAccess } from "@/lib/sync/access";
import { getThreadRepository } from "@/lib/sync/repository";

Expand All @@ -12,14 +13,19 @@ export async function GET(request: Request) {
return Response.json({ projects });
}

/** Create a Project by name; filing the same name twice returns the same one. */
/**
* Create a Project by name; filing the same name twice returns the same one.
* An optional `repository` (`owner/repo`) names where spec Threads routed to
* this Project draft their issues (ADR 0018); passing it for an existing
* name sets it, `null` clears it, omitting it keeps what the Project has.
*/
export async function POST(request: Request) {
const access = await requireSyncAccess(request);
if ("error" in access) return access.error;

let body: { name?: string };
let body: { name?: string; repository?: string | null };
try {
body = (await request.json()) as { name?: string };
body = (await request.json()) as typeof body;
} catch {
return Response.json({ error: "invalid_json" }, { status: 400 });
}
Expand All @@ -30,11 +36,19 @@ export async function POST(request: Request) {
if (name.length > 60) {
return Response.json({ error: "name_too_long" }, { status: 400 });
}
let repository: string | null | undefined = undefined;
if (body.repository !== undefined) {
repository = body.repository === null ? null : asProjectRepository(body.repository);
if (body.repository !== null && !repository) {
return Response.json({ error: "repository_invalid" }, { status: 400 });
}
}

try {
const project = await getThreadRepository().createProject(
access.userId,
name,
repository === undefined ? undefined : { repository },
);
return Response.json({ project });
} catch (error) {
Expand Down
44 changes: 44 additions & 0 deletions app/api/sync/review/route.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { getEnrichmentRepository } from "@/lib/enrichment/repository";
import {
asResearchVerdict,
asThreadKind,
asThreadRoute,
verdictImpliedByRoute,
} from "@/lib/local-capture/types";
import { orphanSpecHandoff, settleSpecHandoff } from "@/lib/spec/handoff";
import { getIssueDrafter } from "@/lib/spec/issue-drafter";
import { requireSyncAccess } from "@/lib/sync/access";
import { getThreadRepository } from "@/lib/sync/repository";

Expand Down Expand Up @@ -69,6 +72,46 @@ export async function POST(request: Request) {
if (!thread) {
return Response.json({ error: "thread_not_found" }, { status: 404 });
}

// The handoff runs after the filing write, never instead of it: the
// Route is already committed, so nothing the handoff does — not even
// an unexpected throw — may turn this response into an error
// (ADR 0018). Un-routing a drafted spec leaves the issue and notes the
// orphan; routing back to spec reuses it and never drafts twice.
let specHandoff = thread.specHandoff ?? null;
try {
if (route === "spec") {
specHandoff = await settleSpecHandoff({
userId: access.userId,
thread,
threads: repository,
reports: getEnrichmentRepository(),
drafter: getIssueDrafter(),
});
} else if (route !== undefined) {
specHandoff = await orphanSpecHandoff({
userId: access.userId,
thread,
threads: repository,
});
}
} catch (error) {
// A throw that escaped the settle logic (the record write itself,
// the project lookup). An orphan that failed leaves the prior
// record standing; a settle that failed answers as a failed draft.
if (route === "spec") {
specHandoff = {
status: "failed",
repository: null,
issueUrl: null,
issueNumber: null,
reason: error instanceof Error ? error.message : "handoff_failed",
at: new Date().toISOString(),
orphanedAt: null,
};
}
}

return Response.json({
threadId: thread.id,
reviewedAt: thread.reviewedAt ?? null,
Expand All @@ -77,6 +120,7 @@ export async function POST(request: Request) {
projectName: thread.projectName ?? null,
researchVerdict: thread.researchVerdict ?? null,
route: thread.route ?? null,
specHandoff,
});
} catch (error) {
const reason = error instanceof Error ? error.message : "review_failed";
Expand Down
28 changes: 28 additions & 0 deletions components/thread-filing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ export function ThreadFiling({
// otherwise the Enrichment's proposal — defaulted from Kind until a
// ROUTE: header exists.
const proposedRoute = thread.route ?? routeForKind(thread.kind);
const handoff = thread.specHandoff ?? null;

return (
<div className="thread-filing" data-testid="thread-filing">
Expand All @@ -102,6 +103,33 @@ export function ThreadFiling({
? `Routed to ${ROUTE_LABELS[thread.route]}`
: "Where does this go?"}
</p>
{/* The spec handoff's receipt (ADR 0018): the drafted issue with its
repo named, or plainly why the handoff is not live. */}
{handoff?.status === "drafted" && handoff.issueUrl ? (
<p className="thread-filing-handoff" data-testid="spec-handoff-note">
<a href={handoff.issueUrl} target="_blank" rel="noreferrer">
Issue drafted in {handoff.repository}
</a>
{handoff.orphanedAt
? " — re-routed since; the issue remains."
: null}
</p>
) : null}
{thread.route === "spec" && handoff?.status === "skipped" ? (
<p className="thread-filing-handoff" data-testid="spec-handoff-note">
{handoff.reason === "no_credential"
? "Spec recorded — the repo handoff is not wired up yet, so no issue was drafted."
: thread.projectId
? "Spec recorded — this Project has no repository, so the handoff is not live."
: "Spec recorded — no Project with a repository is attached, so the handoff is not live."}
</p>
) : null}
{thread.route === "spec" && handoff?.status === "failed" ? (
<p className="thread-filing-handoff" data-testid="spec-handoff-note">
The issue draft failed ({handoff.reason ?? "unknown"}). Routing to
Spec again retries it.
</p>
) : null}
<div className="thread-filing-routes">
{THREAD_ROUTES.map((route) => (
<button
Expand Down
56 changes: 56 additions & 0 deletions docs/adr/0018-spec-routing-drafts-a-repo-issue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Spec routing drafts one issue per Thread, and the record of it lives on the Thread

Routing a Thread to Spec is the first gesture that writes outside the
system: a ticket-shaped issue drafted in the Project's repository, title
from the Thread, body from the Enrichment's idea-shaped report. An
external write cannot be retried casually or deleted quietly, so three
questions are settled here before any seam ships.

**Idempotency.** One Thread earns at most one drafted issue, ever. The
guard is a handoff record stored on the Thread itself (`spec_handoff`):
once it says `drafted`, every later spec routing — a re-route, a retry, a
second device replaying the same gesture — returns that record instead of
drafting again. The stable key is derived from the Thread id
(`spec:<threadId>`) and travels in the issue body, so the GitHub drafter
can search for it before creating — that closes the crash window where
the issue landed but the record write did not. The alternative, keying on
the filing request or timestamp, was rejected because the same Thread
routed from the deck and from a desk row is one intent, not two. `skipped`
and `failed` records are deliberately *not* guards: they exist so the next
attempt can succeed once the Project has a repository or the outage ends.

**Failure visibility.** A draft that does not land is recorded on the
Thread as `failed` with its reason, returned in the filing response, and
shown where the Route was settled — never swallowed, and never allowed to
fail the filing itself: the Route and Reviewed still commit, because the
walker's decision is real even when GitHub is down. Routing to Spec when
the Project has no repository is not a failure but a `skipped` record: the
Route is kept, no external write happens, and the Thread says plainly that
the handoff is not live. The rejected alternative — refusing the spec
Route until a repository exists — would make an external service's
configuration a gate on the walker's own filing.

**Undo.** Un-routing reverses only what lives inside the system. If an
issue was already drafted, it stays in the repository — we never delete or
close external writes, because by then a coding agent may own it — and the
handoff record notes it was orphaned (`orphanedAt`), keeping the link so
the receipt can still name what exists. Routing back to Spec clears the
orphan note and reuses the same issue; it never drafts a second one.

**Batching.** There is none: each settle gesture drafts its own issue
right then, matching the desk's no-commit-gate posture (ADR 0017) — the
receipts screen is a reading of what already happened, never a queue
waiting to flush. The rejected alternative, collecting a Day's spec
routings into one batched write, would reintroduce exactly the gate the
prototype cut.

Accepted costs, recorded so nobody rediscovers them: an orphaned issue in
a repo is the walker's to close by hand; a Thread whose title or report
improves after drafting does not update the issue (the draft is a
handoff, not a mirror); and until a server-side GitHub credential is
provisioned, spec routing settles as `skipped` with its own reason
(`no_credential`) — recorded, said plainly on the Thread, and retried by
a later routing once the token exists. A fabricated success was rejected
outright: `drafted` is the permanent guard, so pretending would silently
block the real issue forever. The in-memory drafter exists for tests
only, never as a production fallback.
8 changes: 8 additions & 0 deletions lib/desk/file-thread.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,14 @@ export async function fileThread(
filing.route === undefined
? undefined
: (asThreadRoute(result.route) ?? filing.route ?? null),
// The server settles what spec routing did outside the system — adopt
// its record whenever a route was part of this filing and the server
// actually answered with the field (ADR 0018); an older server's
// silence must not clear a record we already hold.
specHandoff:
filing.route === undefined || result.specHandoff === undefined
? undefined
: (result.specHandoff ?? null),
});
return true;
}
4 changes: 4 additions & 0 deletions lib/local-capture/transitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,10 @@ export function fileThreadTransition(
filing.route === undefined
? (thread.route ?? null)
: filing.route,
specHandoff:
filing.specHandoff === undefined
? (thread.specHandoff ?? null)
: filing.specHandoff,
}
: thread,
);
Expand Down
62 changes: 62 additions & 0 deletions lib/local-capture/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,63 @@ export function verdictImpliedByRoute(
return undefined;
}

/**
* What happened when this Thread was routed to Spec (ADR 0018). One record
* per Thread, overwritten as attempts settle: `drafted` is the permanent
* guard — an issue exists and is never drafted twice — while `skipped`
* (Project has no repository) and `failed` (the draft did not land) are
* visible states the next spec routing may retry past.
*/
export type SpecHandoffStatus = "drafted" | "skipped" | "failed";

export type SpecHandoff = {
status: SpecHandoffStatus;
/** The `owner/repo` the draft targeted; null when the Project had none. */
repository: string | null;
issueUrl: string | null;
issueNumber: number | null;
/** Why the handoff is not live — set on skipped and failed records. */
reason: string | null;
at: string;
/**
* Set when the walker re-routed away after the issue was drafted: the
* issue stays in the repository (never delete external writes), and this
* marks that the Route no longer points at it.
*/
orphanedAt?: string | null;
};

/**
* Narrow a stored value to a handoff record. Server-written JSON, so only
* the status is checked — an unknown status reads as no record at all.
*/
export function asSpecHandoff(value: unknown): SpecHandoff | null {
if (!value || typeof value !== "object") return null;
const record = value as SpecHandoff;
return record.status === "drafted" ||
record.status === "skipped" ||
record.status === "failed"
? record
: null;
}

/**
* A Project's repository is a plain `owner/repo` — enough to address the
* issue drafter without carrying a whole URL through the seams. Dot-only
* segments are refused: `owner/..` splices into an API path as traversal.
*/
export function asProjectRepository(value: unknown): string | null {
if (typeof value !== "string") return null;
const trimmed = value.trim();
const segments = trimmed.split("/");
const wellFormed =
segments.length === 2 &&
segments.every(
(segment) => /^[A-Za-z0-9_.-]+$/.test(segment) && !/^\.+$/.test(segment),
);
return wellFormed ? trimmed : null;
}

export type LocalThread = {
id: string;
title: string;
Expand All @@ -169,6 +226,8 @@ export type LocalThread = {
researchVerdict?: ResearchVerdict | null;
/** Where the walker routed this Thread; absent/null = not yet settled. */
route?: ThreadRoute | null;
/** What spec routing did outside the system; absent/null = nothing yet. */
specHandoff?: SpecHandoff | null;
};

export type CaptureSyncStatus =
Expand Down Expand Up @@ -325,6 +384,8 @@ export type CaptureStore = {
researchVerdict?: ResearchVerdict | null;
/** Omitted keeps the current route; null clears it. */
route?: ThreadRoute | null;
/** Omitted keeps the current handoff record; null clears it. */
specHandoff?: SpecHandoff | null;
}): Promise<void>;
markSyncing(ids: string[]): Promise<void>;
restoreSavedLocally(ids: string[]): Promise<void>;
Expand Down Expand Up @@ -372,6 +433,7 @@ export type CaptureStore = {
projectName?: string | null;
researchVerdict?: ResearchVerdict | null;
route?: ThreadRoute | null;
specHandoff?: SpecHandoff | null;
captures: Array<{
id: string;
text: string;
Expand Down
Loading
Loading