spec-flow 如何減少 AI 編碼時的頻繁打斷
Stop Letting AI Interrupt You Every Ten Minutes
作者在 dockit 中建立本地協調器 spec-flow,先集中釐清規格,再把執行階段設為預設不打斷,完成五項功能時連續自動執行五個半小時。系統以 13 個狀態的有限狀態機、隔離的子智能體上下文及具來源依據的決策紀錄管理執行,遇上無先例或範圍變更則暫停並交由作者處理。作者指出,此流程依賴前期嚴謹討論,不適合零散日常維護,也不能解決多智能體自主協商。
In my previous post, I drew a distant boundary—peer-to-peer scheduling protocols among autonomous agents are still sitting on the drafting table. Coming back down to earth, in the daily reality of a single primary agent orchestrating sub-agents, a far more immediate and exhausting problem stands in my way: how do I stop it from knocking on my door every ten minutes while writing code?
When coding with AI, what truly drains your energy is never the few dozen seconds spent waiting for tokens to stream; it is the confirmation prompts popping up at random. Picture yourself diving deep down a complex call chain, painstakingly erecting a fragile mental scaffolding of logic, when a polite question suddenly appears in the corner of your screen: "Should we use Option A or Option B here?" Even if you spend just ten seconds typing a two-word reply, by the time your eyes return to the editor, that scaffolding has collapsed. Climbing back up the ladder to where you were easily takes fifteen or twenty minutes. Get interrupted a dozen times a day, and your contiguous blocks of focus are shredded into confetti.
Human thought relies on momentum. Reading unfamiliar code requires constructing a map in your head; weighing two designs requires laying out constraints one by one. AI operates on the exact opposite principle—its execution is inherently fragmented. It can pause at every step to wait for you, and the cost of asking a question is practically zero. Left unconstrained, it will politely interrupt you at every microscopic ambiguity.
That is why I built spec-flow, a local orchestrator inside dockit (https://github.com/13813385093/dockit). The goal was never to make the model magically smarter or teach it to "ask less," but to lock the permission to interrupt behind deterministic engineering rules.
I. Caging the Interruptions: Three Hours Up Front, Five and a Half Hours Unbroken
Consider the timestamps from an actual run a few days ago:
At 16:04 on November 21, I kicked off a spec-flow run, entering the issue discussion phase. By 19:07, the objectives, definitions, and delivery sequence for five tightly coupled features were locked down, and the discussion closed. By 00:42 the next morning, implementation, cross-review, and branch merges for all five features were complete.
For those first three hours, I never left my chair, going toe-to-toe with the AI. It surfaced ambiguities and edge cases in the specs item by item; I queried the local database, made the calls, and pressed for details. From 7:07 PM until 12:42 AM—five and a half straight hours of automated execution—it did not pop up to bother me once.
This is by no means some fantasy of "eight hours of unattended autonomy." Human involvement did not vanish into thin air; it was forcefully compressed and shifted into the three hours before a single line of production code was written. Interruptions transformed from torture into something entirely acceptable because permissions were partitioned: the discussion phase exists to be interrupted; the execution phase forbids interruption by default. When those questions arrive inside a block of time I have already set aside for architectural decisions, they fuel deep thinking. Scattered across five and a half hours of coding, they are a catastrophe.
To understand what those three hours were actually guarding against, a bit of context on the task is necessary. I am building a purely local memory store for a coding agent—zero external services, built entirely on local files and embedded storage. During a coding session, every tool call, return payload, and human message is persisted chronologically as an event stream. When the next session spins up, the system must accurately retrieve historical context, or fold and compress older entries when the context window approaches its budget ceiling.
This round required shipping five sequential capabilities: pairing tool calls with their return results, slicing continuous event streams into discrete "work units," tagging those units, recalling historical units verbatim on demand, and folding old units under a budget. It is an interlocking pipeline—if an upstream data definition drifts by an inch, all four downstream features have to be torn down and rebuilt.
During that three-hour tug-of-war, the AI fired off dozens of granular questions. Three seemingly minor definitions stood out—had I not inspected the live database and settled them before starting, execution would inevitably have ground to a halt:
The yardstick for length. Budget folding requires defining how to measure the "length" of a piece of content. The initial draft naturally defaulted to token counts. Rather than guessing, I had the agent sample distributions directly from our historical database. The numbers told a different story: the vast majority of recorded tokens came from underlying cache read overhead, leaving the ratio of character count to token count hovering around 0.08—bearing almost no correlation to actual text volume. Using that metric for compression budgets would be like tailoring a suit with a ruler unrelated to the length of the cloth. We tore it up on the spot: everything switched to character counts, and all downstream budget modules were updated in sync. Discovering that mid-coding would have meant building two features, hitting a wall, stopping to ask, rewriting implementations and unit tests, and burning half a day.
Slicing boundaries for a "work unit." The original design doc defined a "turn" cleanly: one tool call immediately followed by its return result. On paper, flawless. Diving into the real event stream revealed that 59.8% of tool calls had asynchronous background events—task state transitions, progress logs—interleaved between the call and its return. Slicing by literal adjacency would have yielded exactly zero valid units from real data. We replaced static adjacency with a dynamic time window: everything from the initiation of a tool call until all corresponding results return is swept into that single unit. Re-running the new rule against historical data carved out over a hundred thousand work units, averaging 2.3 events each. A discrepancy like this never triggers a compiler error or fails a unit test; it silently warps the upper-level index until integration testing ends in total ruin.
Unit IDs and rebuild consistency. Every work unit carries a hash ID computed from session_id + start_offset, while the memory store allows full rebuilds after event deletions or rule adjustments. The trap was subtle: after a rebuild, the end offset for a given start offset might shift, yet the hash ID remained identical. Downstream consumers holding an old ID wouldn't get an error—they would silently read altered content. So we added a hard rule during discussion: any reference to a unit ID must persist the fingerprint of the slicing rules active at that moment. Reads enforce fingerprint validation; a mismatch invalidates the reference immediately, with silent fallback strictly prohibited.
II. The Silent Ledger: State Machines and "Circuit-Breaking on Zero Evidence"
When the discussion phase closes, decisions cannot simply remain floating in conversation history—once a thread grows long enough, context gets compressed. Every consensus must be structurally persisted into plain specification files: those three hours distilled into 6 core resolutions, each bound explicitly to its target spec documents, alongside a frozen delivery checklist dictating build order. Meanwhile, every decision rationale and dispute during execution is maintained in tabular form inside a local ledger.
Once execution begins, the primary session steps back into a PM (Project Manager) role, dispatching two sub-agents with strictly isolated contexts: tech for implementation, and reviewer for black-box verification. There is no room for casual chatter between them—only cold, rigid communication boundaries:
When tech encounters an ambiguity in the specs while coding, it is forbidden from pausing to ping me; it must log the question into the reconciliation table. When reviewer spots a flaw, it can only write it into the review report. The PM then sweeps the reconciliation list—checking the specs first. Wherever black-and-white precedent exists, the PM logs a proxy decision and closes the item. Yet one red line remains inviolable: every proxy decision must carry hard provenance—citing a specific resolution ID, a verbatim quote from the discussion log, or a section of the spec. In uncharted territory not covered by the ledger, the PM is strictly forbidden from guessing via LLM "common sense"; it must immediately suspend the pipeline and escalate to me. Furthermore, any change to scope or acceptance criteria—no matter how trivial—triggers a mandatory escalation.
Across those five and a half hours, pushing through all five features, 86 reconciliation items were closed and 65 PM proxy decisions were recorded in the ledger. The number of times the pipeline actually had to escalate and interrupt me due to missing precedent was zero.
Of course, specifications are hardly static truths carved in stone. While scaffolding the second feature, tech cross-referenced the specs and caught three resolutions contradicting one another on edge details: one mandated measuring length by raw payload, another by extracted body text, and a third required UTF-16 code units while banning SQLite's native length(). Instead of quietly picking one and moving on, tech logged the collision in the reconciliation table. The PM checked the timeline, ruled in favor of the latest amendment, and marked the earliest resolution as DEPRECATED in the spec. This mechanism does not guarantee flawless specs out of the gate, but it guarantees that whenever an agent hits a contradiction during execution, there is a place to register it, a role to adjudicate it, and an audit trail left behind. Any given issue is decided once across the entire pipeline; every downstream step simply looks up the verdict.
Running uninterrupted for five and a half hours did not rely on a generational leap in model intelligence, but on two layers of almost stubbornly mechanical engineering constraints:
The first is a deterministic finite state machine. Inside spec-flow, a directed graph of 13 states governs execution, writing runtime state live to run.json. At any node, an agent has no need to recall the grand narrative of the project; its world is restricted to the card view rendered for the current state—the immediate objective, readable files, writable directories, exit criteria, and legal outbound transitions. The instant a run initializes, the state machine definition freezes as a snapshot inside the run directory. Halfway through this run, I upgraded the underlying toolchain twice, yet the in-flight pipeline marched steadily to completion against its frozen manifest copy.
The second is strict context isolation. The PM inherits the full memory of the discussion phase, giving it the grounding to adjudicate ambiguities. tech receives only the specs, interface skeletons, and the ledger digest for its current state, focusing purely on code. reviewer is completely blind to all prior discussions and implementation steps, performing cold black-box comparisons solely against the final code and specs. Over five cycles, reviewer surfaced 39 findings and bounced 21 items back to tech for rework. Almost all of them were fatal flaws where unit tests passed green while real concurrency or failure modes would crash—read-only query anomalies during version upgrade windows, lost data segments on unexpected process restarts, and build failures from cross-package circular imports. By the end, the codebase grew by over 14,000 net lines, more than 4,000 of which were tests. On an acceptance state card, "I'm done coding" never counts as a passing condition; the state machine refuses to advance without verifiable test and review artifacts.
In truth, the eight underlying capability skills were already working in the previous version. All I added this time was a lightweight local orchestrator doing something almost tedious in its simplicity: encoding "who gets dispatched, which files are visible, and where the checkpoints sit" into a finite state machine and plain-text ledgers.
III. Boundaries and Solitude
As usual, let me lay out the boundaries of this approach clearly so no one mistakes it for a silver bullet:
It solves nothing regarding autonomous multi-agent negotiation—the peer-to-peer communication, permission whitelists, and communication quotas from my previous post have nothing to do with this. spec-flow remains a strict master-worker hierarchy; spawning and reclaiming sub-agents still relies on native harness capabilities, while I simply use a state machine to keep them on deterministic rails. Nor is it meant for piecemeal daily maintenance. Fixing an isolated bug, triaging a production outage, or untangling a half-written messy branch through a heavy 13-state workflow is a pure waste of life—direct conversation is far faster.
More importantly, automated proxy adjudication still carries blind spots. "Escalate on zero evidence" prevents the PM from hallucinating in a vacuum, but if a ledger entry is ambiguously worded and the PM confidently cites a flawed interpretation to make a call, downstream steps will not automatically sound an alarm—unless, as happened earlier, it collides head-on with another rule. Ultimately, the smoothness of those five and a half hours depends entirely on the rigor of the three-hour discussion preceding them. If you get lazy during discussion and wave a hand saying, "You figure it out," the next five and a half hours quickly degenerate into the AI making architectural decisions on your behalf—and unwinding that afterward is an expensive mess.
At 12:42 AM, the final merge log scrolled past the terminal, and the cooling fans gradually spun down. Outside the window, the night was deep; inside, only the faint glow of the monitor remained. Once the coordination workflow clicked into place, what the AI actually saved me wasn't the time spent typing several thousand lines of code—it was handing back control over my own uninterrupted blocks of thought, letting me experience once again, in the quiet of the night, that long-lost, unbroken flow of mind.
來源:DEV Community · dev.to