resident

package
v0.4.1-rc.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 22, 2026 License: Apache-2.0 Imports: 38 Imported by: 0

Documentation

Overview

Banking: what an attempt that died on the clock hands to the one that takes over from it.

The incident this file exists for ran for the better part of an hour. A craft job's root leaf implemented four classification algorithms, benchmarked them against RBF-SVM on three datasets, posted a progress row at every step, and at 20:13:51 said "The comparison writeup for all four algorithms is now pulled together into one document". Nine minutes later its first attempt hit its time ceiling. At 20:22:06 the retry began — and it began COLD, with an empty context, in a workspace already holding the writeup, rebuilding from nothing what the journal could have told it in twenty lines.

Nothing was missing except the handover. The graph already knows how to say "here is what the last agent got to, do not do it again": OverrunGoal has composed exactly that for every re-decomposed leaf since the overrun path was built, and its two headers are the whole of the contract. This file makes the same two headers reachable from the OTHER two ways an attempt ends and starts over — the in-place retry, and the requeue at launch after the process carrying the work went away — so a leaf that ran out of clock never loses what it had.

The bank is not a new record. Every line of it is already in the journal (node-anchored progress rows, board notes) or already on disk (the workspace's own files). What was missing was somebody reading them back.

The cooperative half of decomposition: a leaf that found the split rather than failed into it.

Every other way a running job grows begins with something going wrong. The overrun path needs a leaf to spend its whole budget first; the delivery gate needs a reviewer to find the result short; the revision sentinel needs a landed result to contradict the plan. Claim-time division (jit.go) was the first that did not, and it asks its question of a node that has not started — against the plan document and what landed into it, which is everything knowable before the work begins and nothing that is learned by doing it.

This is the case neither of them reaches: the agent is holding the material, has opened it, and can see that what it was handed is four jobs. Until now the only way it could say so was to run out of money, and the graph would then grow from the wreckage of a leaf that had known the answer for twenty minutes. So the worker gets a verb for it, and what it says goes through the same governor, the same expansion call and the same splice the failures use — because a request from a worker is evidence, not authority, and the one thing that must not follow from adding a cheap way to grow a job is a cheap way to grow a job.

A learned workflow is not a second engine. It compiles here into the same admission shape a planned graph produces — steps are leaves, needs are feeds_into edges — so persistence, resume, cost accounting, steering, surgery and the load governor are all inherited rather than reimplemented. Everything this file knows how to plant is an ordinary node; the two shapes craft adds beyond a flat graph (fan-out and repair rounds) are planted as single leaves whose landed results the sentinel expands at runtime.

A provisional craft run is an experiment the user is lent, not one they signed up for. craftmind's three-state evidence rule gives a never-run workflow exactly one run at the decisive bar, and says so out loud — "first time working this way; say 'from scratch' if you'd rather I plan it". The second half of that bargain was never built. When the experiment failed, the job settled failed, the craft went behind the overwhelming bar, and the person's REQUEST died with the experiment: they asked for something, we tried a shortcut we had never tried, the shortcut broke, and the answer to their question was a stack trace.

This file is the other half. A provisional run that fails replans the same ask the ordinary way — compiled and planned, with the shelf never consulted — and says so in one line. The evidence still counts against the craft; that part already worked and is untouched here.

THREE THINGS THIS MUST NOT BECOME.

  1. A second replan authority. It borrows the overrun path's governors whole: the same lineage arithmetic, the same growJob gate, the same round cap and job ceiling and daily rail. A fallback that spent outside the governors would be the 27-round incident with a new name on it.

  2. A loop. The replacement is planned WITHOUT a craft, so its provenance carries no craft reference, so a second failure cannot reach this code at all. The round cap is the belt behind that brace.

  3. A way to hide real news. A PROVEN craft failing is a fact about a way of working the person relies on, and quietly replanning around it would be the system covering for itself. Only the unproven draft gets rescued.

Forging is the other half. Recognition without a writer is a shelf someone else has to stock, and nobody writes a workflow file by hand for a system that is supposed to learn — so the distiller, which already judges what a finished job taught, also judges whether its SHAPE is worth keeping. What it writes lands as an ordinary version in the craft repository: git history is the version history, the commit message is the evidence, and a file the parser refuses never reaches the shelf at all.

Recognition is the half of craft that makes the shelf worth having. A workflow nobody invokes is a file, not a skill: the user asks for a deck in their own words, never by the name of a workflow they have not read, so the request has to find the craft on its own or every version the distiller writes is one nobody asks for again.

The check sits in front of the PLANNER and nowhere else. Head routing still decides what kind of thing an instruction is, the compiler still reads it into a goal, and only then — where a goal would have become a planned graph — does a decisive match compile the craft's subtree instead. That placement is what keeps craft an optimization rather than a gate: everything that is not decisively answered by a stored workflow costs one local BM25 read and then plans exactly as it always did.

The only loop craft has is not a loop in the graph. Fan-out and repair rounds both happen the way the revision sentinel already works: a node lands, its result is read, and the shape that was implicit in the workflow file becomes real nodes spliced into a live job. Nothing about a run lives in this process — every decision here is re-derivable from the store plus the craft repository, which is what makes a craft run resumable after a crash rather than merely restartable.

A failure is the one moment where this system is most tempted to hand a person its own insides. The work stopped, the only thing anybody has is whatever the transport said, and the cheapest thing to do is forward it: node ids, wrapper chains, escaped JSON and all. One real room got exactly that, twice over —

⚑ did not finish — node craft-3799~launch: after 3 node call attempts:
API error (404): {"error":{"message":"No endpoints found that support tool
use. Try disabling \"sh\"...

— which tells the reader nothing they can act on and says four things they were never meant to see. What a person is owed when work dies is small and fixed: WHAT was being attempted, in their own words; that it stopped; WHY, in one plain clause; and what happens next. That is four typed parts, and this file is the composition of them.

The transport is not deleted. It is put below the first line, which is where the room's own disclosure grammar already folds detail — the headline is what a reader sees, the rest is one keystroke away, and nothing has to be believed on faith.

A finding has its own fixed point.

THE DEFECT THIS ANSWERS. happy-dom v4-flash s13 was given 5400 seconds and a gate that was right. Four delivery judgements in a row carried ONE finding — "this work removed checks that existed before it", citing `IntersectionObserver disconnect() Does nothing` and three siblings, the same four names in the same order every time — and each of them bought a repair round. Every round changed files the job was about, so the standstill rule correctly saw motion; every round was handed a differently-worded remainder on the paths that read prose, so nothing there matched either. What stopped the run was arithmetic, `cause: rounds`, forty minutes and $0.135 later, at 9 of 14 hidden checks — where the same task on the previous seed, working the same problem, reached 12.

A round is bought FOR something. The thing it was bought for is the finding the gate raised, and whether it moved is a question about that finding and about nothing else: not about the tree, which a stuck model changes freely, and not about the review's paragraph, which a model rewords for free. So the finding travels with the round that was bought for it, is journaled beside it, and is compared against the next round's — kind and cited names, from the structured record, never from the sentence.

One governor for every way a running job grows.

Growth used to be bounded in as many places as it happened. The overrun path held both caps and enforced them inline; the delivery gate inherited them by calling that path; and the revision sentinel — the mechanism that adds work because a landed result contradicted the plan — spliced straight into the job root with no ceiling, no round counter and no rail check at all. Three paths, two of which were governed by accident and one not at all, and afterwards nothing could tell an overrun replan from a sentinel add without reading intents node by node.

So every execution-time add asks the same question of the same helper, and the answer is journaled against the job it grew. The order of the checks is cheapest first, and it ends with the only one that costs money: is the goal already covered? That question is the reason the criterion exists. Rounds, nodes and dollars all answer "have we done too much"; none of them answers "is there anything left to do", which is why a job could spend three legitimate rounds inventing verification of the round before it and be refused only by arithmetic, long after the money was gone.

Decomposition at claim time: the depth loop, moved out of the build and into the scheduler.

A plan built at t=0 decides every division it will ever make against titles, because at t=0 nothing has run and titles are all there are. The measured consequence was a graph that was the same shape in every run of the battery — two levels, decided before the first leaf started, never revisited — and a node that turned out to hold four workers' worth of work could only be discovered by spending a whole leaf budget failing at it and paying for a replan afterwards.

So the question moves to the one moment it can be answered well: a node is claimed, every piece feeding it has landed and said what it produced, and the same two calls the build would have spent are spent here instead — against what is really there. The node either divides, and its parts run at the same time under it, or it does not, and the worker that is already holding it runs it whole. Refusing is the null hypothesis and it is free: the question that decides costs no call at all (plan.JudgeSplit reads the node), so a job whose every node is atomic pays exactly what it paid before this file existed.

Everything that grows a running job goes through growJob, and this is no exception — it is the fourth caller, and the one whose rounds are counted per node rather than per job, because two siblings that each divide once have divided once each.

Just-in-time re-decomposition: a leaf that ran out of budget mid-work is the planner's clearest evidence that one node held more than one agent's worth. Instead of shipping the partial or failing the job, the remainder is re-planned — informed by what the partial actually produced — and spliced in as deeper structure that consumes the partial and feeds everyone who was waiting. Specialize by addition: the journal keeps the exhausted attempt, the graph grows the finish.

What a round actually moved, weighed against what the job is about.

THE DEFECT THIS ANSWERS. ink s10 was given a 5400-second wall and spent all of it. One lineage — task-2 → x1 → x2 → x3 — exhausted eight times, resumed three, and every round of it was admitted by the growth governor because every round had "produced" something: `debug-grid.ts`, `debug-grid2.ts`, `debug-grid3.tsx`, `debug-grid10.ts`, `debug-grid11.ts`, `debug-yoga.ts`, `debug-yoga2.ts`, `debug-test2.tsx`, `debug-test3.tsx`, `debug-grid-pos.tsx`. A model that is stuck writes scratch files, and a scratch file is a file, so the standstill rule — which was right, and which is the only rule in the governor that asks whether anything was ACHIEVED — saw motion on every round and never once spoke. What stopped the run was the round cap, four rounds and ninety minutes later, with the wall gone, no gate cut, and `settled: false`.

So the reading of "did this round move something" is narrowed to the work:

  • EVERY CHECK FILE COUNTS. A check the run wrote is the one thing a job can produce that is progress on its own terms whatever else happened, and it is what the coverage finding exists to buy. verify.OwnChecks decides what a check is, by the runner's own naming convention and by nothing else.
  • A CHANGED SOURCE COUNTS WHEN THE JOB IS ABOUT IT. The job's focus is what its request names: the paths the request spells that this workspace holds, and the names it uses resolved against the workspace by verify.Locate — the identical reading internal/exec takes to decide how much of a project to verify — plus the adjacency verify.Adjacent's first rank defines: a file named after something in the focus, or sitting in a directory the focus is in. `debug-grid.ts` at a repository root beside `package.json` is neither, and `src/grid.ts` is both.
  • A FILE THE REQUEST NAMES IS NEVER SCRATCH. The spelling comes first and the resolution second, because a resolution is a search and a search can come back without a file the request wrote out in full. See jobFocus.
  • A JOB THAT NAMED NOTHING IS ABOUT EVERYTHING. An empty focus is verify's own "reading of the whole project", and the fail-safe direction here is the same: with nothing to narrow by, every changed source counts and the governor keeps exactly the bounds it had.

NO FILENAME PATTERN APPEARS ANYWHERE IN THIS FILE. `debug-` is a spelling one model happened to choose, and a rule written against it would be one spelling behind forever (FAILSAFE clause 1). What is structural is the relationship between what the round wrote and what the request is about, and that relationship is one verify already computes for its own reasons.

The user is the second event source. A landed result and a person changing their mind mid-flight are the same kind of thing — new information about a plan that is still running — so they reach the same sentinel by the same path. The only differences are that the person speaks with authority, and that the workers already in motion have to be told in their own transcripts.

Package resident reconciles durable thread commands with the active task graph and reports graph outcomes back into their originating sessions.

The retrospective is the loop no single job can close: patterns visible only across the series — a need that keeps recurring, a correction the user keeps making, an approach that consistently works or consistently costs too much. Nothing here names any particular kind of job; the content of what is learned is entirely emergent from what actually happened.

Result-driven revision closes the loop that separates a workflow engine from a problem-solver: plan, execute, observe, replan. When a landed result contradicts what an unstarted node was built to assume, the sentinel edits only that unstarted work — the store's own rules refuse everything else.

Taste is what the user keeps correcting. The loop is deliberately the quietest one in the resident: corrections the distiller already wrote down are aggregated at the settle seam into a candidate rule, a candidate rule annotates one delivery with a single question that never holds anything up, and the answers stand the rule up or let it go. Nothing here calls a model, and nothing here renders — the question is an ordinary structured askback and the receipt is an ordinary learning moment.

Index

Constants

View Source
const (
	// ContinuationPartialHeader introduces what the previous agent had when it
	// stopped — its text and, when it shared any, the lines it posted as it went.
	ContinuationPartialHeader = "What the previous agent produced before stopping (its partial result arrives as a dependency input; build on it):"
	// ContinuationFilesHeader introduces the files already on disk.
	ContinuationFilesHeader = "Files already produced, to reuse rather than recreate:"
	// ContinuationStateHeader introduces the dead leaf's structured findings:
	// the files it touched, the checks it ran, and the last calls it made. It
	// is general for any task — derived from the leaf's own outcome, not from
	// any domain-specific record — so a continuation resumes from what the dead
	// leaf actually did instead of re-reading everything it already diagnosed.
	// Empty when the leaf left no structured record, which is the ordinary
	// case for a generalist that produced only prose.
	ContinuationStateHeader = "" /* 155-byte string literal not displayed */
	// ContinuationTranscriptHeader introduces the dead attempt's own turns as
	// they were recorded: what it said, what it ran, and what came back. It is
	// the last block of the continuation because it is the longest and the most
	// specific — the three above are the summary, this is the working.
	ContinuationTranscriptHeader = "" /* 196-byte string literal not displayed */
)

The two continuation headers, owned here and used by everything that hands unfinished work on: OverrunGoal's replan brief, the retry's dependency input, and the launch requeue's. They are exported so there is exactly one wording of the contract, and so a test can pin the words a retry is actually handed.

View Source
const (
	// BankedTranscriptTurns is how many of the attempt's most recent turns ride
	// into its successor VERBATIM.
	//
	// THE LAST ONES, for the reason [BankedProgressLimit] takes the last progress
	// rows: work of this kind is cumulative, and the state a resuming leaf needs
	// is where the previous one had GOT TO. The head of a run is what an autopsy
	// wants and the store keeps it (store.MaxTranscriptEntries seals from the
	// front); a continuation wants the other end.
	//
	// IT IS NOT THE WHOLE SEED, and treating it as one was the memory half of
	// the ink run of 2026-08-29: twelve turns out of a hundred and thirty-eight
	// is a window on one file's contents, and the attempt's successor re-read
	// the repository because nothing had told it about the other hundred and
	// twenty-six. The outline above it (see [BankedRun]) carries every turn of
	// the run at one line each, which is what makes this bound affordable
	// instead of lossy.
	BankedTranscriptTurns = 12
	// BankedTranscriptBytes bounds the whole block, because a dozen turns of a
	// leaf that ran a test suite is not a dozen short lines.
	//
	// It is store.MaxTranscriptTextBytes × 8 and not a fresh figure: one entry's
	// bound is what this package already accepts as "enough of one step to tell
	// what happened", and this block is a handful of steps. Reached first, it
	// wins over the turn count and the block is trimmed from the FRONT, so what
	// survives is always the end of the work.
	BankedTranscriptBytes = 8 * store.MaxTranscriptTextBytes
)
View Source
const (
	// BankedRunOutlineLead introduces the one-line-per-turn account of the
	// WHOLE run.
	BankedRunOutlineLead = "In outline, every turn that attempt took, oldest first — this is the whole of it, and none of it needs doing again:"
	// BankedRunTailLead introduces the verbatim end of the run.
	BankedRunTailLead = "And the end of it verbatim — what you said, what you ran, and what came back:"
)

The two leads inside the transcript block. They are separate because the two halves answer different questions and a model handed them under one heading reads the outline as a preamble to the tail rather than as the record of thirty turns it will otherwise repeat.

View Source
const (
	// CraftDecisiveScore is how far past the retrieval floor a match has to sit
	// before the resident runs learned know-how instead of planning. The floor
	// is one shared word; a craft's own name counts four times a word in a step
	// brief, so a request that says what the craft is FOR clears this line
	// while one that merely brushes a step does not. The bar also gets safer as
	// the shelf grows: the more workflows there are, the rarer a name term is,
	// and the further a true match sits above it.
	CraftDecisiveScore = 1.5 * craft.MatchFloor
	// CraftOverwhelmingScore is what a craft with no survival record has to
	// clear to be used unasked. A freshly forged workflow is a draft: nothing
	// has run it, so the only evidence it works is that the distiller believed
	// it. Below this line a draft waits to be named — by the user, or by the
	// arrival brief that says it now exists.
	CraftOverwhelmingScore = 4 * craft.MatchFloor
)
View Source
const (
	// FindingUnreadable is the one finding with no names: the project declared
	// a way of checking itself and this run could not read it.
	FindingUnreadable = "unreadable"
	// FindingOwnFailing is checks THIS work wrote that are red.
	FindingOwnFailing = "own-failing"
	// FindingUnexercised is behaviours the request states that no check touches.
	FindingUnexercised = "unexercised"
	// FindingUnasserted is behaviours a check names and no assertion weighs.
	FindingUnasserted = "unasserted"
	// FindingConsumers is definitions this run reshaped that the rest of the
	// project still uses the old way.
	FindingConsumers = "consumers"
	// FindingUnbound is names this run's own sources READ that nothing in the
	// tree binds. It sits beside FindingConsumers because it is the same kind of
	// measurement one question further back — that one is a name whose shape
	// moved, this is a name that is not there at all.
	FindingUnbound = "unbound"
	// FindingMechanical is a file the plan promised and the disk does not hold.
	FindingMechanical = "mechanical"
	// FindingReview is the judge's own finding, named by the spans it cited.
	// Every finding a gate raises that has no list of its own arrives here,
	// including the ones a later wave gives a list to — at which point it gets
	// a case above and stops being one of these.
	FindingReview = "review"
)

The kinds of finding a delivery judgement can raise, in the order they are read off one gate.

The order is SPECIFICITY, and it decides which finding a round is recorded as having been bought for when a gate raises more than one. A measurement of the repository — a behaviour nothing exercises, a check the run wrote and left red, a definition it reshaped under its callers — is more particular than a judge's sentence about the delivery as a whole, and it is the half a repair can be aimed at. The judge's own citations are last because they are the kind every gate has.

View Source
const (
	EvidenceFailing     = "failing-checks"
	EvidenceUnexercised = "unexercised"
	EvidenceUnasserted  = "unasserted"
	EvidenceConsumers   = "consumers"
	EvidenceUnbound     = "unbound"
	EvidenceLost        = "lost-names"
	EvidenceMechanical  = "mechanical-gap"

	// EvidenceFinding is a review's own finding, held in the hand of the round
	// being bought rather than read back off the journal. It is the kind for
	// the findings no reading names — a judge's citation, a suite nobody could
	// read — and it stands for the same reason all the others do: something
	// outside the account being judged says this job is not finished.
	EvidenceFinding = "open-finding"
)

The kinds of standing evidence, as the journal spells them. They are the vocabulary of store.JobGrowth.CoveredDespite and they name READINGS, never judgements: each one is something a mechanism measured on the tree and has not since measured away.

View Source
const (
	GrowOverrun  = "overrun"
	GrowGap      = "gap"
	GrowRevision = "revision"
	GrowRedirect = "redirect"
	GrowJIT      = "jit"
	GrowCoverage = "coverage"

	// GrowResume is a round nobody asked the governor for: a leaf that ran out
	// of room and was claimed again in place, same node id, attempt raised by
	// one. It is journaled because AN OVERRUN ROUND IS A ROUND — see
	// NoteResumedRound — and it is its own word because it is the one row here
	// the round CAP does not count, only the evidence rules do.
	GrowResume = "resume"

	// GrowCooperative is the round a worker asked for rather than earned by
	// failing. It is its own word in the journal because it is the one growth
	// reason that is evidence of the machinery working: every other reason here
	// is a repair, and a battery asking "how often did a leaf divide before it
	// burned a budget instead of after" is asking for exactly this column.
	GrowCooperative = "cooperative"
)

Why a path is asking to grow. The names are the journal's vocabulary and the only thing that made an overrun replan and a sentinel add distinguishable after the fact.

View Source
const (
	CauseRounds  = "rounds"
	CauseCeiling = "ceiling"
	CauseRail    = "rail"
	CauseCovered = "goal-already-covered"

	// CauseStandstill is the round that was refused because the round before it
	// changed nothing in the world, and neither did the work before that.
	CauseStandstill = "standstill"

	// CauseFixedPoint is the round that was refused because it was handed the
	// same remaining work as the round before it: a split whose output is its
	// own input.
	CauseFixedPoint = "fixed-point"

	// CauseFindingStood is the round refused because the finding it would have
	// been bought for has already been bought twice and did not move either
	// time. It is the fixed point of one FINDING rather than of one text.
	CauseFindingStood = "finding-stood"

	// CauseOutOfWall is the round the run does not have time left to finish. It
	// is not a cap and not a count: it is this job's OWN measured pace read
	// against the clock it is actually running under.
	CauseOutOfWall = "out-of-wall"

	// CauseSpendShare is the round refused because growth has already spent more
	// than the requested work itself cost, measured from the moment a gate first
	// found that work done. It is a bound against the bill rather than against a
	// count of rounds, and it exists because a count could not stop a run whose
	// named fix landed at minute eleven from spending the rest of its wall and
	// most of its bill on growth.
	CauseSpendShare = "spend-share"
)

Which governor spoke. Cause is the machine-readable half of the refusal the person reads; a battery asking "did anything ever refuse growth for a reason other than a cap" is asking for exactly this column.

View Source
const (
	RefusedRounds  = "this work has split as many times as splitting helps — handing over what's done"
	RefusedCeiling = "this job has grown as large as jobs are allowed to grow — handing over what's done"
	RefusedCovered = "" /* 126-byte string literal not displayed */

	// The two refusals that read evidence rather than a count. They say what
	// was observed and not what rule fired, because the person reading them is
	// owed the fact — nothing has changed, twice over — and not the machinery.
	RefusedStandstill = "" /* 132-byte string literal not displayed */
	RefusedFixedPoint = "" /* 160-byte string literal not displayed */

	// The refusal that is about one finding rather than about the job. It says
	// what was observed — this exact thing was worked on twice and is still
	// missing — because that is the fact the person is owed, and because it is
	// the sentence that tells them the run stopped repairing rather than
	// stopped caring.
	RefusedFindingStood = "" /* 144-byte string literal not displayed */

	// The refusal that buys the person a verdict. A round the clock will kill
	// halfway spends money to deliver nothing AND costs the run the only thing
	// it was going to end with: a judgement on what it did. So the job stops
	// growing while there is still time to finish and be judged.
	RefusedOutOfWall = "" /* 135-byte string literal not displayed */

	// The refusal that bounds growth against the bill. Once the requested work
	// is done, a round that would take the total past twice what that work cost
	// is refused and the job is handed over: the work the person asked for is
	// finished, and what is left is growth they did not ask for.
	RefusedSpendShare = "the requested work is done and growth has already doubled what it cost — handing over what's done"
)

The refusals in the words a person reads. They are constants because two of them are already load-bearing in tests and in the record: a governor stopping work quietly reads as work finishing, and the difference is the whole point of saying anything at all.

View Source
const (
	// MetaRetrospectiveEvery runs the bounded audit on every fifth reflection.
	MetaRetrospectiveEvery = 5
	// MetaReversalMinSamples keeps tuning inert until an action class has evidence.
	MetaReversalMinSamples = 6
	// MetaReversalEaseBelow makes a proven-safe action class one notch easier.
	MetaReversalEaseBelow = 0.10
	// MetaReversalTightenAbove makes a frequently reversed action class one notch stricter.
	MetaReversalTightenAbove = 0.35
)
View Source
const (
	// OriginalAssignmentHeader introduces the assignment itself, in both
	// wrappers, so the unwrap has one shape to recognise rather than two.
	OriginalAssignmentHeader = "The original assignment:\n"
	// OverrunPreamble is exactly what overrunGoal writes before the assignment.
	// It is a constant because the unwrap matches it EXACTLY: a wrapper found by
	// loose substring matching is a wrapper that will one day be found inside
	// somebody's actual assignment.
	OverrunPreamble = "Finish work a previous agent started. It stopped when its resources ran out, so parts of the assignment may already be complete. Plan only what the assignment still needs — work that is already done must not be redone, and do not add verification, re-verification, or review of existing results unless the assignment itself asks for it.\n\n" + OriginalAssignmentHeader
)

The wrappers a remainder's goal is written in, and the one header they share.

A REMAINDER IS THE SAME PIECE WITH A FINDING, AND ITS SIZE IS THE SIZE OF THE FINDING AND NEVER OF THE GOAL. Both wrappers open by saying what happened and then hand the planner the assignment itself, so the text a round composes is the wrapper plus a brief; and the brief a second round is handed is the FIRST round's composed text, because the node the first round planned carries the whole goal as its brief (plan.Build's undivided shortcut writes Brief: goal). Wrapping that again nests: measured on the canary, a second remainder's goal read "Finish work… The original assignment: Finish work… The original assignment: Implement issue #4031 …" at 28,468 characters with the issue text twice over and the current finding last, and the round's gate call cost 116,674 prompt tokens. So a wrapper is written around the INNERMOST original assignment, which is what originalAssignment recovers, and the finding for this round is added once by the blocks below.

View Source
const (
	RestartModelMarker = "Run this restart on:"
	RestartBoostModel  = "the boost model"
)

RestartModelMarker is the head's reading of the model words on a restart, written out here for the same reason CorrectionMarker is: it is a wire form between two halves of the system and the dependency between them runs one way. RestartBoostModel is what the marker carries when the ask named the boost slot rather than a model.

View Source
const (
	// TastePromotionConfidence is the shrunk standing a candidate must reach
	// before the delivery gate is held to it. Under the store's shared n/(n+8)
	// prior three unanimous confirmations clear it (0.636) and two do not
	// (0.600), so a rule is stood up by a third agreement — never by the pair
	// that merely named it.
	TastePromotionConfidence = 0.63
	// TasteDemotionKeeps is how many times the user has to say the delivery was
	// right as it was before an active rule steps back down. Once is an
	// exception; twice is the rule being wrong about them.
	TasteDemotionKeeps = 2
	// TasteSimilarityFloor is the overlap score below which two corrections are
	// not the same correction: they must share more of their vocabulary than
	// they differ by, in both directions. Below it a pair shares only the
	// grammar every preference line is written in.
	//
	// The bar is stated here and nowhere else. It used to be doubled by a gate
	// inside the scorer that made every score it could return either zero or at
	// least 60, so the number written here decided nothing at all.
	TasteSimilarityFloor = 60
	// TasteNeutralPrior is what a rule with no verdicts is worth. Nobody has
	// agreed or refused yet, so the shrinkage pulls it toward a coin flip.
	TasteNeutralPrior = 0.5
)
View Source
const BankInputTitle = "your own earlier attempt at this same task"

BankInputTitle names the bank where a leaf's brief renders its inputs. It is the second person on purpose: the leaf reading it is the same node, on its next attempt, and telling it otherwise invites it to treat its own output as somebody else's claim to be checked.

View Source
const BankSharedLead = "What it reported as it went, oldest first — this is work that is already done and must not be done again:"

BankSharedLead introduces the shared progress lines inside the partial block.

They sit UNDER the partial header rather than under one of their own, because they are not a different kind of fact: a row saying "the comparison writeup is now pulled together into one document" is the previous agent telling you what it produced, in its own words, at the moment it produced it. A second header would invite the model to read it as commentary about the work instead of as the work.

View Source
const BankedProgressLimit = 16

BankedProgressLimit is how many of an attempt's own lines ride into its successor. The last ones, because progress is cumulative: a row saying the writeup is assembled subsumes the eleven rows about assembling it.

View Source
const CooperativeFindingHeader = "What the agent holding this work found, once it had opened the material. " +
	"It is a finding and not an instruction — weigh it, and divide the assignment as the evidence " +
	"actually supports:"

CooperativeFindingHeader introduces the leaf's own account of the division.

It says who is speaking and what that is worth, because the block below it is the one part of an expansion prompt written by something that had the material open. A planner that reads it as instruction stops planning; a planner that cannot tell it from the assignment reasons about the division as though the person had asked for it.

View Source
const CooperativePreamble = "Divide this assignment into the separate jobs it turned out to hold.\n\n" +
	"An agent was given it, started work, and reported that what it was holding is several " +
	"independent jobs rather than one. It stopped rather than spend the assignment's whole " +
	"budget on the first of them. Nothing has run out and nothing is a remainder: plan the " +
	"division, not a continuation.\n\n" + OriginalAssignmentHeader

CooperativeGoal phrases the division brief.

Its first sentence is the whole difference from OverrunGoal and it is a factual correction rather than a nicer tone: that function opens by telling the planner the work ran out of resources, and a planner told that plans a remainder — which is the wrong shape here, because nothing is left over. The agent stopped on purpose, holding everything, and what is wanted is the division it described.

The request is rendered as what the agent found rather than as a specification to compile. It is the strongest evidence in the prompt — it is the only part written by something that opened the material — and it is still evidence: the parts that actually run are the ones the expansion returns and the acceptance check keeps, so a division that only restates is refused here exactly as it is refused at claim time. Handing the parts over verbatim would make the leaf the planner, and the leaf is the thing being planned. CooperativePreamble is exactly what CooperativeGoal writes before the assignment — the twin of OverrunPreamble, and matched exactly by the same unwrap, so a division asked for on a node a remainder already planned is wrapped once rather than twice. See originalAssignment.

View Source
const CorrectionMarker = "Correcting delivered work:"

CorrectionMarker is the head's mark on a splice that revises the work it targets. It is written here as well as where the head mints it because it is a wire form between two halves of the system — the same reason the head writes the craft-consent option codes out twice — and because the resident cannot import the head: the head already imports the resident for cue extraction, so the dependency runs one way only.

View Source
const CraftFallbackLine = "your learned way didn't survive its first try here — planning it fresh"

CraftFallbackLine is what the person hears. It names what happened in their terms — a way of working, not a workflow file; a first try, not a survival record — and it names what is happening instead, in the present tense, because by the time this is read the fresh plan is already spliced.

View Source
const DefaultBriefAfter = 4 * time.Hour

DefaultBriefAfter is long enough that an ordinary lunch break stays quiet.

View Source
const (
	// DefaultPracticeIdle is deliberately much longer than the reconciler poll:
	// practice is maintenance, never the next thing after a user's splice.
	DefaultPracticeIdle = 20 * time.Minute
)
View Source
const GrowCraftFallback = "craft-fallback"

GrowCraftFallback is why the job grew, in the journal's own vocabulary. A battery asking "did a learned way of working ever cost a round" is asking for exactly this column.

View Source
const JITDepthCeiling = 8

JITDepthCeiling is the arithmetic backstop under the atomicity judgment, and it is deliberately not the policy.

The policy is the judgment: a claimed node divides while a reading of it says it is not yet one worker's job, and stops when that reading says it is. What actually stops a runaway is the pair that cannot be argued with — the per-job node ceiling in growJob, and the shrinkage guard that refuses a division whose parts came back no smaller — and both bind long before this number does. It exists so that a judgment that has gone wrong in a way nobody anticipated still terminates, and it is set well above any depth a real job has reached so that it is never the thing making the decision.

View Source
const (
	// MaxOverrunRounds bounds how many times one lineage may grow. Rounds are
	// sequential by construction — each plans the remainder of the last — so a
	// lineage still growing after three fresh budgets is not too big, it is
	// thrashing, and the honest move is to hand over what exists.
	//
	// It keeps its name because the overrun path is where it was learned and
	// every reader of that path knows it by this name; it governs every growth
	// path now.
	MaxOverrunRounds = 3
)

The two caps that keep growth a repair rather than a lifestyle.

Splitting used to be bounded by dollars alone, and one real run showed what that bound is worth on a cheap model: a leaf that had already finished was replanned 27 rounds deep — each round inventing verification of the round before it — and burned $4.48 of a $20 rail in 22 minutes while the job's actual work sat pending behind it. Dollars bound the damage, not the loop.

View Source
const NoteMark = "⚑ "

NoteMark is the structural marker for a job-board note: written by code, read by code, so a board read can never mistake an anchored ask, receipt or progress post for a worker's shared line. It is a protocol byte, not a phrase the model is asked to produce.

View Source
const OpenFindingsHeader = "" /* 172-byte string literal not displayed */

OpenFindingsHeader introduces the section. It is one wording, exported, and used by every path that hands work on, so a worker meets the same words whether it was spliced by a gap round, an overrun, a split or a retry.

View Source
const ReflexGroup = "reflex"

ReflexGroup is the durable node marker for the no-compiler, no-planner rung. Group is already part of the splice event and rebuilt node view.

View Source
const (
	// ServiceConsentGrace is the bounded hold after a leaf asks to keep an
	// otherwise unconsented process. Silence always lands on the stop default.
	ServiceConsentGrace = 30 * time.Second
)
View Source
const SpecUnchangedNotice = "The criterion this work is judged against has not changed and is given below " +
	"unaltered. Plan against it; do not restate it, extend it, or replace it."

SpecUnchangedNotice is what a spec says about its own criterion when it is carried onto a remainder or onto a replacement attempt.

It is one sentence and it is the whole of the re-target contract in words: the bar did not move because the attempt did. Without it, a planner handed a criterion reads it as material — something to summarise, improve, or expand on — and a criterion that grows every round is a criterion that cannot be met.

View Source
const (

	// VoiceRegister is the register every reply is written in, and it is true
	// of a machine nobody has taught anything yet. It used to ride inside the
	// learned-preference section, which meant a fresh install — the exact
	// moment a person is meeting the product for the first time and has the
	// least vocabulary for it — was the one install that got no anti-jargon
	// instruction at all. The rule that covers every string nobody thought to
	// enumerate cannot be conditional on the user having already complained
	// about something else.
	//
	// The banned list is named rather than gestured at because "jargon" is not
	// a word a model can check a sentence against; these are the words this
	// system uses for itself, and each one has a plain replacement that says
	// the same thing to a person who has never read the source.
	VoiceRegister = `` /* 480-byte string literal not displayed */

)
View Source
const WithdrawnByPlan = "revision: "

WithdrawnByPlan prefixes the reason on a node the job's own second thought dropped, and it is the one thing that tells a step withdrawn from a step lost.

Both end as a cancelled node, and until this had a name every reader downstream had to guess which it was — so a delivery whose plan had correctly dropped a step because another node had already done that work announced itself as "Not all of this landed… much of it is missing", about a job that had in fact landed whole. The prefix is a contract between the pass that withdraws work and the composition that has to describe it, and the reason after it is the reviser's own words about why, which is usually the name of the node that covered it.

View Source
const WorkingDecisionsHeader = "Working decisions, already made — honor them:"

WorkingDecisionsHeader names the block wherever it is rendered. Assumptions were only ever a receipt: the compiler declared "run the test suite before opening the PR" and nothing downstream was ever told. A decision the work is not held to is not a decision, so the same list travels with the goal, into the leaves, and on to the gate that judges what came back.

Variables

View Source
var GrowthGate = env.Get("CODEAF_GROWTH_GATE") != "0"

GrowthGate is the wave's rollback switch. Off, the governor keeps the three free checks — rounds, ceiling, rail — and never asks the paid question, which is today's behaviour plus the revision fix and the journal.

View Source
var RefusalNotPaying = plan.RefusalNotPaying

order sorts children so a child is admitted after the siblings it consumes. The store checks that a declared dependency exists, and a division is a small DAG, so the cheapest correct answer is repeated passes over what is left.

When the capacity fold has measured evidence (see capacity.go), the cheapest-predicted sibling is admitted first — the one whose measured overrun base rate and the planner's own size judgment say is least likely to exceed one worker's envelope — so the runner claims the work most likely to land cheaply before a costlier part. Without evidence the order the expander was handed is returned untouched, which is every non-swarm job and every cold journal: the fifo invariant a measurement could only have perturbed. RefusalNotPaying is the resident-side name for the EV-lookahead's verdict. It is exported here so the expansion caller can journal the reason without importing the plan package's internal constant set.

View Source
var RefusalNotStarved = "no idle slots for its parts"

RefusalNotStarved is the starvation gate's verdict: the node could divide and (with evidence) would pay, but no idle dispatch slot would run its parts, so decomposition buys no wall and pays pure cost.

Functions

func AnnotateDelivery

func AnnotateDelivery(graph *store.Store, node store.Node, delivered string) (store.AgentQuestion, bool, error)

AnnotateDelivery queues at most one quiet taste question against a landing deliverable and reports whether it asked. The delivery never waits on it: the question is queued for the next natural moment, which is the very message the deliverable is announced in, and it expires on its own if nobody answers.

delivered is the text about to be handed over. It has to be passed in because the node is not completed yet at this moment, so node.Summary is still empty — and choosing which preference to ask about from the request alone meant the one quiet question a delivery may carry was regularly asked about the wrong thing, polluting the shelf's evidence with answers to mismatched questions.

func ApplyRevision

func ApplyRevision(graph *store.Store, planGraph *plan.Graph, prefix, jobRoot string, operations []plan.Operation) (int, []string)

ApplyRevision mirrors the sentinel's applied plan-graph operations onto the durable store, governed as an overrun replan is.

It is the compatibility shape: every caller that has nothing to say about why it is growing the job, and no reader to ask whether the job still needs anything, gets the caps and the journal and no paid question.

func ApplyRevisionGoverned

func ApplyRevisionGoverned(ctx context.Context, growth Growth, graph *store.Store, planGraph *plan.Graph, prefix, jobRoot string, operations []plan.Operation) (int, []string)

ApplyRevisionGoverned mirrors the sentinel's applied plan-graph operations onto the durable store: adds splice under the job's root, removals cancel pending nodes, rewires replace dependency edges, retitles amend brief and title. Refusals and store-side rejections are returned as notes rather than failing the batch — a revision is advice, and the store is the law.

The adds now pass the growth governor first, which they never did. This path spliced straight into the job root with no ceiling, no round counter and no rail check, which was invisible while the sentinel was a rare second thought and is the whole story once anything fires it often: a job could be grown without limit by the one mechanism nobody was counting. A refused batch becomes a note, exactly as a store rejection already does — the removals, rewires and retitles in the same batch still apply, because none of them grows anything.

func BankedProgress

func BankedProgress(graph nodeRecord, nodeID string) []string

BankedProgress reads back what a node's earlier attempt said it had reached.

It reads the node's OWN record and nothing else. Both shapes of "where this got to" live there and both are taken: the replaceable progress rows a long worker posts (their Latest line when they carry one, their phase line otherwise) and the board notes a worker shares in its own words. Nothing is matched against a list of phrases — a row either declares itself progress in its fields or carries the note marker, and everything else on a node's record is somebody talking ABOUT the work rather than the work reporting itself.

func BankedRun

func BankedRun(graph transcriptRecord, nodeID string) (string, int)

BankedRun renders the LAST RUN in a node's record as the block a resuming attempt is handed, and says how many turns that run reached.

EMPTY IS AN HONEST ANSWER AND A COMMON ONE. Not every worker records a transcript, and a leaf that died before its first flush recorded nothing. In both the bank simply has one fewer block, which is what it already does with every other field it does not have.

A TOOL CALL WITH NO RESULT IS SAID TO HAVE NO RESULT. That is the shape a partial record takes — the attempt was interrupted between asking and being answered — and it is the one fact about it that must not be smoothed over: a resuming leaf that believed a command had run and returned nothing would skip the command. So the call is rendered with "(interrupted before it answered)" and the leaf can decide to run it again.

IT IS ONE RUN AND NOT THE WHOLE TABLE. A node's record is every attempt any worker ever made under it, appended, and each attempt numbers its own turns from one — so "the last twelve turns" read across the table was not a window on anything. On the ink run of 2026-08-29 the third claim's seed was assembled from turns 79-90 of the attempt before it INTERLEAVED with turns 34-45 of the attempt before that, because both satisfied a turn-number cutoff. A run is found by structure instead: the turn counter only ever goes up inside one attempt, so where it goes backwards a new attempt began.

AND IT CARRIES AN OUTLINE OF THE WHOLE RUN, not only its tail. The tail is where the work got to and the outline is what it decided on the way there, and handing over the second without the first is what an eleven-million-token re-exploration is made of: twelve turns of one file's contents say nothing about the thirty-eight files the attempt had already read and rejected. The outline is one line per turn over every turn of the run — what it said and what it ran — which is affordable precisely because it is one line.

func BankedTranscript

func BankedTranscript(graph transcriptRecord, nodeID string) string

BankedTranscript renders a node's recorded turns as the block a resuming attempt is handed, or "" when this worker left no record.

func BroadcastRedirection

func BroadcastRedirection(graph *store.Store, jobRoot, sessionID, message string) (int, error)

BroadcastRedirection posts the user's words into every running leaf of the job as a node-anchored user message — the same move an amendment makes for one node, made plural. The executor's steering mailbox delivers them before the next turn, so a worker learns the goal moved without being restarted.

sessionID is kept in the signature and deliberately not carried onto the messages: callers name the room the steer came FROM, which is worth having at the call site and is exactly what must not ride into the mailbox copies — see the loop below.

func CancelledRevisionEvent

func CancelledRevisionEvent(node store.Node, partial, reason string, contextTokens int) string

CancelledRevisionEvent is RevisionEvent's third flavor, and the one that had no channel at all until now. A failure tells the sentinel that an assumption died; a redirection tells it the owner changed their mind about the goal. A cancellation says something narrower than either: this particular piece of work is not wanted, and nothing about the goal has changed.

So the licence is narrow to match. The remaining plan may need to stop depending on what was withdrawn — that is a real contradiction, and it is the only one here. What it must never do is treat the cancellation as a failure to repair: adding a node to redo the cancelled work, or to check what it left behind, spends the user's money undoing the decision they just made. The prompt refuses it and this says it again at the event, because the event is what the sentinel reads last.

func CapacityOptions

func CapacityOptions(journal *store.Store, swarm bool, model string, options plan.Options) plan.Options

CapacityOptions folds measured leaf capacity into planner options. Swarm is an argument, rather than a promise left to the caller, so the disabled path returns the input unchanged without even reading the journal. A missing or unreadable history does the same: capacity is evidence, never a prerequisite that can break planning.

The journal cheaply identifies execution model on usage events. It records no workspace identity, so model is the narrowest honest segment; inventing a workspace join would turn process state into supposed historical evidence.

func CompileCraft

func CompileCraft(workflow *craft.Workflow, params map[string]string, provenance store.Provenance) (store.Subtree, error)

CompileCraft turns one loaded workflow into the store's admission shape. The id namespace is derived from the run's provenance so a compile is reproducible; RunCraft uses CompileCraftAs to guarantee a fresh namespace when the same craft is asked for twice.

func CompileCraftAs

func CompileCraftAs(prefix, dir string, workflow *craft.Workflow, params map[string]string, provenance store.Provenance) (store.Subtree, error)

CompileCraftAs is CompileCraft with the caller's id namespace and craft repository directory. dir makes verifier script paths absolute; empty leaves them named relative to the craft repository, which is honest but weaker.

provenance must already carry this workflow's reference: Splice stamps one provenance onto every admitted node, so requiring it here is what makes "every node of a craft run names its version" a compile-time invariant rather than a convention a caller can forget.

func ContractPlaybook

func ContractPlaybook(graph *store.Store) plan.ContractPlaybook

ContractPlaybook builds the optional earned-doctrine lookup used by the contract pass. SearchFacts counts every returned bullet as a real use.

func CooperativeContinuationMessage

func CooperativeContinuationMessage(pieces int) string

CooperativeContinuationMessage is what the record says when a leaf's own request grew the job.

It is not OverrunContinuationMessage, and the difference is the only thing a reader of that record needs: nothing went wrong here. A person opening a node that says work "stopped before finishing" reads a failure, and the whole point of this path is that there was not one.

func CooperativeGoal

func CooperativeGoal(node store.Node, request *executor.SplitRequest, partial string) string

func CraftRef

func CraftRef(workflow *craft.Workflow) string

CraftRef is the durable version identity of one loaded workflow: the name survival stats group by, and the commit that says which draft of it ran.

func CraftSurvivalKey

func CraftSurvivalKey(reference string) string

CraftSurvivalKey is the trait name one craft's record is kept under. Both a version reference (name@commit) and a bare name are legal keys, and they are different records on purpose.

func DecodeSpec

func DecodeSpec(raw json.RawMessage) plan.Spec

DecodeSpec reads a task object back off a node. Anything unreadable is the same answer as anything absent — the empty spec — which every reader handles because an absent spec is what the whole system had until this wave.

func EncodeSpec

func EncodeSpec(spec plan.Spec) json.RawMessage

EncodeSpec renders a task object for the store, which holds it as opaque bytes. An empty spec encodes to nothing at all rather than to "{}": a node with no spec must be indistinguishable from a node admitted before specs existed, or the fallback path is not byte-identical and the rollback is not a rollback.

func ExtractCues

func ExtractCues(text string) []string

ExtractCues turns free text into ordered notebook scopes. Paths lead with their nearest repository parents, tools follow, and general scopes close every query so stable user and environment facts remain available.

func FailureCause

func FailureCause(raw string) string

FailureCause reduces a transport failure to the clause a person can act on.

It is a DECODER, not a cleaner. The only thing it knows how to do is open the envelopes this system actually stamps — a JSON error body, and the sentence inside it — and stop at the innermost thing that carries its own words. Nothing is matched against a list of phrases, nothing is rewritten, and a failure it cannot open comes back exactly as it went in. Inventing a cause would be worse than forwarding a blob: a blob is unreadable, a wrong explanation is believed.

func FindingNoun

func FindingNoun(kind string, count int) string

FindingNoun is what this kind's names ARE, in a person's words. The closing line counts them, and "4 findings" tells a reader nothing that "4 behaviours" does not tell them better.

func FindingWords

func FindingWords(names []string) string

FindingWords says a bounded handful of names as a person reads them.

func GovernorStanding

func GovernorStanding(graph *store.Store, jobRoot string) (string, bool)

GovernorStanding is the run's own account of why it stopped growing, for the one line a person reads at the end.

A RUN MUST NEVER END AT ITS WALL WHILE A GOVERNOR RULE ALREADY KNEW IT HAD STOPPED. The refusal is posted on the work's own record where it happens, and that record is a node somewhere inside a job the person never sees; what they read is the last line, and until this existed the two runs that were refused for a standstill said nothing about it there. FAILSAFE clause 3.

It answers nothing for a job no governor ever refused, and nothing for the refusals that are ordinary arithmetic — a round cap or a node ceiling is a bound being reached, not the run discovering it had stopped working.

func GrowthReasonFrom added in v0.3.0

func GrowthReasonFrom(ctx context.Context) string

GrowthReasonFrom returns the reason the round being planned was bought for — Growth.GrowOverrun for an exhausted leaf, GrowGap for a reviewer's finding, GrowCooperative for a worker's own split — or empty where nobody said.

func GrowthStopped

func GrowthStopped(cause string) (string, bool)

GrowthStopped reports whether a refusal cause is one of the two the governor reaches by READING THE WORLD rather than by counting — the round before this one changed nothing and neither did the work before that, or the remaining work came back word for word the same — and gives the sentence a person reads for it.

ONCE THE HARNESS HAS CONCLUDED NOTHING IS CHANGING, IT STOPS SPENDING ON THAT JOB: no gate on a tree with no diff, no repair round on a tree with no diff, no resume. This is the one place that says which causes mean it, so the leaf that carries the verdict across the seam and the scheduler that acts on it cannot come to different answers about the same word. Every other cause is a cap or a pause and leaves the requeue exactly as it was.

The words are the constants above and are never rewritten here: the stream has already printed this sentence by the time anyone asks, and a second wording of one event is a reader working out whether it is the same event.

func HeadSpeaksFor

func HeadSpeaksFor(kind store.CommandKind) bool

HeadSpeaksFor is the audit, written down: every kind here is journaled by a route that answers the user in its own voice in the same breath — surgery and revision, charters, services, splices — and handover, whose outcome the residency narrates while it waits for it. A kind absent from this list is one nobody has volunteered to answer for, so its receipt becomes the answer. Silence is the failure this list exists to prevent; a kind that grows a spoken reply and is not added here says the same thing twice, which is the cheaper mistake and the one a reader can see.

It is exported because the head reads the same list from the other end. This list is exactly the set of receipts the head has already spoken over, so it is exactly the set whose SETTLEMENT the head is on the hook for — the wake that says what the workforce actually made of the change (internal/head/wake.go).

func IsCorrection

func IsCorrection(instruction string) bool

IsCorrection reports that this splice is a revision of the job it targets rather than new work that merely follows one.

func JobPace

func JobPace(graph *store.Store, jobRoot string) time.Duration

JobPace is how long another round of this job would take, measured on this job, and it is what a run reserves before it stops buying rounds — and what the settlement watch reserves before it forces a verdict. One quantity, one derivation, because a run that stops growing at one estimate and gets judged against another is a run whose two clocks disagree about the same wall.

See PERF.md, "What a round of a job costs".

func JobWorkspace

func JobWorkspace(jobRoot string) string

JobWorkspace is where a job's rounds run, or empty when nothing said.

func LeafState

func LeafState(outcome *executor.Outcome) string

LeafState derives what a dead leaf's worker actually did — the files it touched, the commands it issued, what the finished-tree reading found, and the last calls it made — from the leaf's own outcome. It is general for any task: a worker that owns a verifier contributed its structured account, and every worker contributes the bounded tail of what it did. The principle: a continuation that knows what the dead leaf already found resumes from there instead of re-reading everything it already diagnosed, which is how a one-line fix that exhausted 150k tokens spawned a continuation that spent 137k fresh tokens re-discovering the same diagnosis.

Empty when the leaf left no structured record — no account and no tool calls worth reporting — which is the ordinary case for a generalist that produced only prose. An empty state is simply left out of every composition that uses it.

func LineageBank

func LineageBank(graph *store.Store, lineage, sink string) (string, int)

LineageBank is what a whole job's recorded work hands to the next node spliced under it.

THE RECORDED RUNS ARE A LINEAGE PROPERTY, NOT A NODE'S. BankedRun answers "what did THIS node do", which serves the two paths where the id stays the same — the in-place retry and the requeue after a claim comes back. It cannot serve the path a growing job actually takes: a round splices FRESH IDS (`task-2` → `task-2-x1-n2`), so every child asks its own empty record and starts cold beside a workspace full of its predecessors' work.

The textual run of 2026-08-29 (s9) is the measurement. `task-2` ran to 350 recorded rows over 80 turns and exhausted; thirteen minutes later a gap round spliced five fresh children under it, and `task-2-x1-n2`'s first recorded row is turn 1, "Let me start by examining the existing codebase", followed by `find /app`. The record it needed was in the same store, under the id one character away, and nothing looked.

It is composed newest-first and bounded once, not per node: what a resuming worker most needs is where the job GOT TO, and a bound spent on the oldest attempt is a bound not spent on the newest. The sink is skipped because it is the node being seeded — a brief that quotes the reader back to itself is a brief that has said nothing.

func MeasuredCost

func MeasuredCost(node plan.Node, options plan.Options) (cost float64, ok bool)

MeasuredCost predicts one node's overrun cost from the capacity fold's measured base rate and the planner's own size judgment of the node. It is the ordering signal for claim-time scheduling: a cheaper-predicted node is one the measured history says is less likely to exceed one worker's envelope, so the runner fills the pool with the work most likely to land cheaply while a costlier part is still being divided.

The base rate is the same for every node of one model, so it does not reorder siblings the planner sized equally — those tie, and the caller keeps the order it was handed. The size does the ordering, and only once the fold has measured evidence to back it: a node the planner called oversized is predicted to overrun (it already exceeds one worker), an atomic one carries only the measured residual rate, and a borderline one falls between. ok is false when the fold has no evidence, and the caller must leave the order untouched.

func NoteResumedRound

func NoteResumedRound(graph *store.Store, node store.Node, artifacts []string)

NoteResumedRound journals a round nobody asked the governor for.

AN OVERRUN ROUND IS A ROUND. A leaf that ran out of room and is claimed again in place — same node id, attempt raised by one, the bank of its last attempt handed back to it — has spent a body of work exactly as a spliced repair does. It just does not pass through growJob, because nothing is being added: the node already exists. So the ledger never saw it, the standstill rule never weighed it, and ink s10 got EIGHT exhaustions of one lineage for the price of five journaled rounds and the whole 5400-second wall.

It is journaled as ADMITTED, because it happened, and with the same evidence every other round carries. It is not counted by the round CAP — see growthRound — because the cap bounds how many times a job may be made bigger and this makes it no bigger; what weighs it is the evidence, which is the rule that should have stopped s10 and could not see it.

func NotebookDigest

func NotebookDigest(graph *store.Store, nodeID, brief, goal string, limit int) string

NotebookDigest retrieves the facts relevant to one piece of work and renders the bounded block workers receive with their inputs. A non-empty nodeID attributes the whole injected batch to that node in one event.

func OverrunContinuationMessage

func OverrunContinuationMessage(pieces int) string

OverrunContinuationMessage is the calm user receipt shared by immediate and rail-deferred splitting.

func OverrunGoal

func OverrunGoal(node store.Node, partial string, artifacts []string, gap, state string, records ...string) string

OverrunGoal phrases the replan brief. The partial result is in the goal on purpose — "based on the current result" is the whole point: the planner sees what was actually produced and plans only what remains.

The phrasing is deliberately neutral about how much is left. The first version asserted the work "could not be completed", and handed that premise to a planner that cannot answer "nothing" — so when the partial was in fact complete, the planner obliged the premise by inventing verification of it, and each round of invented verification became the next round's premise. Naming what a reviewer found missing, when a reviewer ran, keeps the replan aimed at the actual gap instead of at whatever sounds like more work. records, when there are any, are the files the finished work left behind that this remainder must READ. They are rendered apart from the artifact list and said to be readable, because "reuse rather than recreate" is an instruction about not repeating work and this is an instruction about where the facts come from — a leaf handed the second under the first's heading reads a path as a thing it already has rather than as a thing it has to open.

func OverrunLineage

func OverrunLineage(nodeID string) (string, int)

OverrunLineage names the lineage a node belongs to and how deep into it the node already is: the id it was split from and its round number, or its own id and zero when it has never been split.

It is exported for the same reason SplitContinuation is: the "-x" arithmetic is the id law and it lives here. A caller that wants to read a whole job's history — every round of it, under one namespace — asks for the base rather than parsing the suffix itself.

func PlanRecordsFromContext

func PlanRecordsFromContext(ctx context.Context) []string

PlanRecordsFromContext returns the readable record of the work this plan is a remainder of. Empty is the ordinary case — a fresh plan is a remainder of nothing — and every pass that reads it renders exactly what it rendered before records existed.

func PlanStoreIDs

func PlanStoreIDs(graph *plan.Graph, prefix string, grown map[int]bool) func(planID int) string

PlanStoreIDs is that law, offered to everything that has to name a store node it did not mint.

It exists because the law had two authors. The splice named the subtree's root with the bare prefix; every later edit of the same subtree spelled every node "<prefix>-n<id>", root included. So a revision that rewired the deliverable's inputs addressed "<prefix>-n<root>" — an id that has never existed in any store — and the store answered "unknown node", which the batch recorded as a note nobody reads while the plan document recorded the edit as applied. The measured shape of that is a job that delivers nothing while the report it was supposed to deliver sits finished on disk.

grown is the set of plan nodes minted after admission; see planShape. Nil is the answer for every caller that is naming the plan as it was admitted.

func ReAdoptServices

func ReAdoptServices(graph *store.Store, sessionID string, runtime ServiceRuntime) error

ReAdoptServices is the startup hook beside orphan release. A stale identity is stopped honestly and never respawned.

func RedirectAudience

func RedirectAudience(graph *store.Store, jobRoot string) (int, error)

RedirectAudience counts who a redirection would reach if it were broadcast now. It exists so the head can say how many workers are about to hear the user's words in the moment the user asks, rather than waiting for the reconciler to say how many did — and it shares the broadcast's own membrane rather than restating it, because two copies of that rule would drift and the receipt would then name a number nobody was told.

func ReleaseWhy

func ReleaseWhy(reason string) string

ReleaseWhy is a release reason with [recordedTail] taken off: what stopped the claim, and nothing about how much of its work survived.

It exists so the headless ↻ line can name the bound that fired WITHOUT repeating the turn count it has already said in its own words. A reason this package did not compose — or one with no such clause — comes back whole, which is the honest answer: the caller asked for the why, and the whole sentence is the why.

func RemainderDigest

func RemainderDigest(gap string) string

RemainderDigest is a piece of remaining work reduced to something two rounds can be compared by.

Case and runs of whitespace are dropped because they are the two ways one sentence is written twice without being a different sentence; nothing else is. This is an EQUALITY test and not a similarity one on purpose: a remainder that came back reworded is a different claim about what is left, and it is the standstill rule beside this one — which reads the tree rather than the text — that catches a loop dressed in fresh words. Empty in, empty out, and an empty digest never matches anything, so a caller with no reviewer finding is never refused on this ground.

func RememberJobWorkspace

func RememberJobWorkspace(graph *store.Store, node store.Node, workspace string)

RememberJobWorkspace records where a job's work happens. Calling it twice with the same answer is free; calling it with a different one replaces the answer, because a job that moved is working in the new place.

func ReplanOverrun

func ReplanOverrun(ctx context.Context, graph *store.Store, node store.Node, partial, gap string, artifacts []string, dailyBudgetUSD float64, planRemainder OverrunPlanFunc) (int, string, error)

ReplanOverrun splices a repair subtree for a leaf whose partial result is about to land. The subtree's entry nodes consume the exhausted node's digest, its sink feeds every consumer that was waiting on the exhausted node and has not started, and the whole thing lives under the same job so workspaces, folding, and narration all treat it as the job's own work. The gap, when non-empty, is what a reviewer found missing from the partial — it aims the replan at the actual remainder. Returns the spliced node count and the repair sink's id. DailyBudgetUSD zero is unlimited; at the rail the durable question is posted and no splice lands.

func ReplanOverrunAs

func ReplanOverrunAs(ctx context.Context, graph *store.Store, node store.Node, partial, gap string, artifacts []string, dailyBudgetUSD float64, growth Growth, planRemainder OverrunPlanFunc) (spliced int, sink string, refused string, err error)

ReplanOverrunAs is the same splice with the growth named for what asked, and it hands back WHICH GOVERNOR SPOKE when one refused the round.

The delivery gate grows a job for a reason this file never had — a reviewer found the result wrong, not the budget short — and it used to inherit this path's governors by borrowing its whole function, which left the journal unable to say afterwards which of the two had spent the round. The reason travels now; everything else is identical.

refused is GrowVerdict.Cause verbatim, and empty when nothing refused — including at the rail, which is a question waiting on a person rather than a refusal. It is RETURNED rather than left in the journal for the caller to read back, because the caller's next three decisions turn on it and a fact re-derived from a row is a fact that can disagree with the row.

func ResumeDeferredOverruns

func ResumeDeferredOverruns(ctx context.Context, graph *store.Store, dailyBudgetUSD float64, planRemainder OverrunPlanFunc) (int, error)

ResumeDeferredOverruns admits journaled repairs after the rail is raised. The splice precedes the resolved event; after a crash, an existing prefix is enough evidence to resolve without planning or admitting a duplicate.

func RetractedBlock

func RetractedBlock(graph *store.Store, limit int) string

RetractedBlock renders what the user has explicitly thrown away, for the prompts that derive new beliefs.

The store has refused to let a derivation lift a human veto since the day RetractedFacts was written, and its own doc comment called this the other half — "the lines a derivation prompt can be shown as already-rejected". That half was never wired. So the distiller re-proposed a vetoed belief every week off the same evidence, the store swallowed it every week, and nobody upstream learned anything. Showing the model what was refused is how the refusal becomes knowledge instead of a wall it keeps walking into.

func RevisionEvent

func RevisionEvent(node store.Node, summary string, artifacts []string, failure string, contextTokens int) string

RevisionEvent phrases what just happened for the sentinel: which node landed, how, what it reported, and what it left on disk. Bounded — the sentinel judges whether a result contradicts the plan, not the result's full content.

The failure arrives as its own words rather than as a boolean. "FAILED" tells the sentinel that the plan's next steps have nothing to consume; "FAILED: the API returns 410 Gone for every v2 endpoint" tells it which assumption died, and that is the entire question it was convened to answer. The artifact list is here for the same reason it is in OverrunGoal: a leaf that says "wrote the notes to api-notes.md" has reported its whole finding in a filename, and a sentinel that cannot see the file at least learns one exists.

contextTokens is the window of the model that will read the event. Zero is unknown and keeps the two literals this function was written with.

func SetGrowthSatisfier

func SetGrowthSatisfier(ask Satisfier)

SetGrowthSatisfier installs the process-wide satisfaction gate. Nil removes it, which is the rollback.

func SetJobCloser

func SetJobCloser(close func(jobRoot, keep, reason string) int)

SetJobCloser installs the one thing that can stop a job's outstanding work. Nil removes it, which is the rollback.

func ShrinkOverrunRate

func ShrinkOverrunRate(local, global float64, samples int) float64

ShrinkOverrunRate applies the journal's shared n/(n+8) empirical-Bayes weight to a local overrun rate. The global population supplies the prior; without local observations it is the only honest estimate.

func SoleWorkNode

func SoleWorkNode(graph *plan.Graph) (int, bool)

SoleWorkNode is the one-node plan document: a job that is one leaf and nothing else, with no synthesis over it. It answers the plan node's id.

It is the reading that tells a claim-time division apart from the one thing it must never divide. A store node carrying the bare prefix is normally the job's deliverable sink — the gathering node, not work — and dividing it would be dividing the answer. When the document holds exactly one node, that same bare prefix is instead the whole of the work, and it is as divisible as any other leaf. Both readings are the same question asked of the document rather than of the id, which carries neither fact.

func SplitContinuation

func SplitContinuation(graph *store.Store, node store.Node) ([]store.Node, bool)

SplitContinuation follows a stamped node into its own split namespace and returns the pieces that carry on from it, oldest round first. It is a read of ids and statuses and nothing else: the namespace is an id-index range, the sink of each round is that round's prefix exactly (SubtreeFromPlan gives the plan root the prefix itself), and a node that is itself a piece only ever continues into rounds above its own.

It lives here because the id law lives here. Anyone who re-derived the "-x" arithmetic at the reading end would own a second copy of it, and the day the counter changes shape the second copy quietly starts answering with the stale half of the job — which is the failure it exists to end.

func SplitContinued

func SplitContinued(summary string) bool

SplitContinued reports that a node's summary is not its last word. A leaf that ran out of budget mid-thought completes with whatever it had said so far, and that sentence is a paragraph cut in half — "the file conflicted, let me clean up and run the test properly" — stamped with the receipt that says the rest was re-planned elsewhere. Read as a result it is a lie of tense: it narrates as present something the graph finished a minute later.

func SplitCooperatively

func SplitCooperatively(ctx context.Context, graph *store.Store, node store.Node,
	request *executor.SplitRequest, partial string, artifacts []string,
	dailyBudgetUSD float64, growth Growth, divide OverrunPlanFunc) (int, string, error)

SplitCooperatively grows a job from a leaf's own division request.

It is deliberately a caller of the overrun splice rather than a second one. What the two paths have in common is everything structural — the round arithmetic under the "-x" namespace, the governor on the way in, the exact ceiling on the way out, the parts consuming the finished node's result, the sink inheriting whoever was waiting on it — and the one thing they do not share is the sentence the planner is handed, which travels as Growth.Goal. Duplicating the rest to change that sentence would be two implementations of the id law, and the id law is the thing in this package that has to be one.

An invalid request is not an error and not a refusal: it is a leaf that said something the growth path cannot act on, and the caller's next move — deliver the partial — is the same move a refused governor leaves it with. Zero spliced says exactly that, in the spelling the overrun caller already reads.

func StandingEvidence

func StandingEvidence(graph *store.Store, jobRoot string) []string

StandingEvidence is what the WORLD still says is wrong with this job, as the kinds that stand.

COVERAGE IS A CLAIM ABOUT THE PLAN; A FINDING IS EVIDENCE FROM THE WORLD. The satisfaction question asks a model whether the acceptance points of a plan are mapped onto work that has landed or is running. That is a reading of the PLAN, and it can be true of a job whose checks are red, whose stated behaviours nothing exercises, whose public names the change deleted, and whose callers were left behind by a definition it reshaped — because none of those is a point on the plan. ink v4-flash s14 refused three rounds as goal-already-covered while its own readings ran 172 checks with 18 red and its own gate held six behaviours nothing exercised; igel s13 refused two while the surface photograph reported eight deleted public names, five times running.

So a claim about the plan may never overrule a measurement of the world. What coverage is still allowed to do is refuse a job the world has nothing standing against — which is the question it was built for.

IT IS READ AT THE JOB AND NOT AT THE LINEAGE THAT ASKED. A repair round is a different lineage from the work it repairs, and the readings sit on the nodes that took them: igel s13's refusal was weighed under `task-2-x1`, whose id namespace does not contain `task-2-x1-n1`, which is where the eight lost names had been journaled ninety seconds earlier. The job has one world.

A read that fails answers nothing standing, which lets coverage speak. That is the direction the caps are under: the round cap, the standstill, the finding fixed point and the wall all still hold whatever this says.

func StripNodeStamp

func StripNodeStamp(nodeID, text string) string

StripNodeStamp removes the executor's own `node <id>: ` stamp from the front of an error.

It is given the id rather than a pattern, which is the whole difference between this and scrubbing: it removes one exact string that this system wrote, and it cannot touch anything a provider said. A node whose real error happened to begin with those bytes is a node whose id is in its own error, which is the stamp.

func SubtreeFromPlan

func SubtreeFromPlan(graph *plan.Graph, prefix string) (store.Subtree, error)

func TasteBlock

func TasteBlock(graph *store.Store) string

TasteBlock renders the rules the gate is actually held to. Only active rules appear: a candidate has not earned the right to fail anyone's work.

func TitleCraftRootFromRequest

func TitleCraftRootFromRequest(subtree *store.Subtree, request string)

TitleCraftRootFromRequest names a craft run from the words that asked for it, for the seams that have no compiler to name it better. It is a no-op when the root already carries a name, so the compiled reading of the ask — which is a person's own words too, read back short — always wins where one exists.

The one thing it will never do is fall back to the workflow's name. A job wearing the name of the machine that ran it is the defect this exists to close; a job with no name at all still shows its brief, which is about the work, and that is the honest degradation.

func UserRevisionEvent

func UserRevisionEvent(message string, flavor RevisionFlavor) string

UserRevisionEvent phrases a revision for the sentinel. The landed-result event describes something that happened; this one describes someone who decides — the sentinel's standing default of "no change" is overridden by the owner of the work, not by evidence. Under urgency the authority is the same and only the licence changes: the remaining plan may lose its tail.

func VoicePrompt

func VoicePrompt(graph *store.Store, prompt string, contextCues ...string) string

VoicePrompt installs the register on every prompt and the learned preferences on top of it when the notebook has any. The register is unconditional on purpose: it is the one instruction that covers strings nobody enumerated, including strings that do not exist yet, and gating it on learned preferences meant a fresh machine spoke the implementation's language until the user complained about something unrelated.

The bytes stay cache-friendly. Whatever this returns begins prompt + "\n\n" + VoiceRegister in both branches, so learning a first voice preference extends the prompt rather than rewriting it.

func VoiceSection

func VoiceSection(graph *store.Store, contextCues ...string) string

VoiceSection assembles the shared speech doctrine with active, user-scoped voice preferences relevant to the current context. SearchFacts is deliberate: rendering a preference is a counted notebook read. No matching preference returns an empty section so existing prompts keep their exact bytes.

func WithFinding

func WithFinding(ctx context.Context, finding Finding) context.Context

WithFinding names the finding a growth about to be asked for is bought to close. The empty finding removes it.

Types

type Bank

type Bank struct {
	// Partial is whatever text the attempt had produced when it stopped. Empty
	// is the ordinary case for a death on the clock, which is exactly why the
	// other two fields exist.
	Partial string
	// Shared is the progress the attempt posted as it went, oldest first.
	Shared []string
	// Artifacts are absolute paths to files that are still on disk.
	Artifacts []string
	// State is the dead leaf's structured findings: files it touched, edits it
	// made, checks it ran and what they found, and the last calls it made.
	// Derived from the leaf's own outcome by LeafState, general for any task.
	// Empty when the leaf left no structured record, which is the ordinary
	// case for a generalist that produced only prose — and an empty state is
	// simply left out of the composition.
	State string
	// Transcript is the dead attempt's OWN TURNS, read back from the record it
	// wrote as it worked (internal/store/transcript.go): the assistant text, the
	// tool calls and the results they returned, in the order they happened.
	//
	// THIS IS THE FIELD THAT MAKES A RESTART A RESUMPTION. The three above are
	// what the attempt CHOSE to announce — a partial result, some progress rows,
	// a structured summary — and a leaf abandoned mid-turn announced almost
	// nothing, because announcing is what a leaf does when it is finishing. Its
	// work is nonetheless all there: seventy-one runs of one test file, on the
	// happy-dom run of 2026-08-28, every one recorded under the node and every
	// one discarded when the claim reaper started the leaf over.
	//
	// It is expected to be PARTIAL. The recorder flushes on a full batch and on
	// every way out of a leaf, a fault included, so what survives is everything
	// up to the last flush — which is exactly what "resume from where it got to"
	// means, and is why nothing here tries to invent the result of a tool call
	// whose answer never arrived. See [BankedRun] for how one is rendered: an
	// outline of every turn the run took, and then its end verbatim.
	Transcript string
}

Bank is what an attempt left behind: the text it had, the lines it shared, and the files it wrote. Every field is optional and an empty one is simply left out of the composition — a bank never invents a handover it does not have.

func (Bank) Continuation

func (b Bank) Continuation() string

Continuation is the bank composed under the continuation headers — the same two OverrunGoal writes, in the same order, with the same words.

func (Bank) Empty

func (b Bank) Empty() bool

Empty reports that there is nothing to hand on, in which case no caller should compose anything: an input announcing an earlier attempt that produced nothing is a sentence that costs tokens and teaches the model that the work has

func (Bank) Input

func (b Bank) Input() executor.Input

Input is the bank as the retry sees it: one more dependency result, rendered by the leaf's own brief under the header that already says results here are work you hold and must not gather again.

The paths ride inside Continuation rather than on Input.Artifacts because the brief renders that field as its own "(files: … — read them if you need the full detail)" line, and a bank that named its files twice would be spending the retry's context to say one thing in two voices.

func (Bank) WithArtifacts

func (b Bank) WithArtifacts(paths ...string) Bank

WithArtifacts returns the bank with more paths merged in, deduplicated and in a stable order.

func (Bank) WithShared

func (b Bank) WithShared(lines ...string) Bank

WithShared returns the bank with more shared lines merged in, oldest first and each said once. It is how the two sources of the same fact join: what a leaf posted in this process, and what the journal remembers of what it posted in a process that is gone.

type BriefActivity

type BriefActivity struct {
	Since         time.Time    `json:"since"`
	Events        []BriefEvent `json:"events"`
	Done          int          `json:"done"`
	Failed        int          `json:"failed"`
	Cancelled     int          `json:"cancelled"`
	Questions     int          `json:"questions"`
	CharterFired  int          `json:"charter_fired"`
	FactsLearned  int          `json:"facts_learned"`
	SkillsLearned int          `json:"skills_learned"`
	CraftsForged  int          `json:"crafts_forged"`
	CostUSD       float64      `json:"cost_usd"`
	// Waiting counts the standing rows: what is stopped on the user right now,
	// as opposed to what happened while they were gone.
	Waiting int `json:"waiting"`
}

BriefActivity is the bounded, factual input to one arrival composition.

type BriefComposeFunc

type BriefComposeFunc func(ctx context.Context, activity BriefActivity) (BriefDraft, error)

BriefComposeFunc makes one arrival message from journal-derived facts.

type BriefDraft

type BriefDraft struct {
	Headline string           `json:"headline"`
	Items    []BriefDraftItem `json:"items"`
}

BriefDraft is one model response: the closed sentence and expanded rows.

type BriefDraftItem

type BriefDraftItem struct {
	Seq  int64  `json:"seq"`
	Body string `json:"body"`
}

BriefDraftItem is the resident voice for one input event, joined by Seq.

type BriefEvent

type BriefEvent struct {
	Seq  int64               `json:"seq"`
	Time time.Time           `json:"time"`
	Kind store.BriefItemKind `json:"kind"`
	Text string              `json:"text"`
	Ref  string              `json:"ref,omitempty"`
}

BriefEvent is one journal fact the composer may turn into a slim fold row. Text is already a truthful fallback; the model's job is voice and compression.

type CancelRethinkFunc

type CancelRethinkFunc func(ctx context.Context, node store.Node, reason string)

CancelRethinkFunc shows one user cancellation to the plan sentinel. It is injected for the same reason the overrun planner is: the live plan document belongs to the process that planned it, and the reconciler owns only the moment at which somebody should look at it again.

type CompileFunc

type CompileFunc func(ctx context.Context, instruction string, graphContext string) (Compiled, error)

CompileFunc turns a verbatim thread instruction into a goal the planner can act on. graphContext is a compact rendering of the active graph.

type Compiled

type Compiled struct {
	Goal        string
	Assumptions []string
	Scale       string

	// Title is the job's rail-sized display name, produced by the compile
	// call itself. Empty falls back to the separate naming pass, which is
	// what every caller without a compiler still gets.
	Title string
	// Contract is the task-scale working method, produced by the same compile
	// call. Empty falls back to the separate contract pass.
	Contract string
	// Parts is the compile call's reading of the ask: the separate requests it
	// contains, in the person's own words. It is evidence handed to the
	// planner, never a layout — see plan.Options.Asked.
	Parts []string
	// Accept is the acceptance checklist: the behaviours the person's REQUEST
	// states, read from the request's own words before any work existed.
	//
	// It rides the compile because the compile is the one pass in the system
	// holding the request VERBATIM. Everything downstream of it holds the
	// compiled goal, which is this program's reading of the ask rather than the
	// ask — and a checklist derived from our own reading is a checklist we wrote
	// for ourselves, which is precisely what the gate may not hold anybody to.
	// See plan.Acceptance and docs/design/gate/ACCEPTANCE.md.
	Accept []plan.Point
	// Constraints are the rules the person's REQUEST states about what the run
	// may or may not DO, in their own words, kept only where the compiler could
	// quote them out of the instruction (head.keepStatedConstraints).
	//
	// It rides beside Accept because the two are read off the same verbatim ask
	// and neither can be recovered downstream — everything past the compile
	// holds the compiled goal, which is this program's reading. They differ in
	// where they land: the checklist goes on the node that DELIVERS, and a
	// constraint goes on every node of the job, because the person said it about
	// the run. See plan.Graph.SetConstraints.
	Constraints []plan.Constraint
	// TrialOf is the retrieved unsettled fact this goal deliberately tests.
	// Zero means the compiled job is ordinary work.
	TrialOf int64

	// BuildsOn names earlier top-level jobs this one continues. Each becomes
	// a feeds_into edge onto the new subtree's entry nodes, so the prior
	// result arrives as an input digest — continuity through the graph, not
	// through a shared workspace.
	BuildsOn []string

	// Question, when set, means the compiler judged one gap too consequential
	// to guess. Nothing is spliced; the question is asked in the thread and
	// the user's reply arrives as an ordinary next message.
	Question string

	// QuestionOptions makes any compiler askback selectable without removing
	// free text. Charter is an inert standing draft until the reconciler records
	// a separate ratification command.
	QuestionOptions []store.QuestionOption
	Charter         *store.CharterSpec
	ServiceIntent   bool

	// WorkModel is the model the user named for this job in their own words.
	// It rides the splice as provenance, so the leaves that run it are pinned
	// to what was asked for rather than to whatever the slot holds later.
	WorkModel string

	// ModelNote is the one calm receipt line about that choice.
	ModelNote string

	// Note is the one calm receipt line the compiler adds about its own
	// answer — that it supplied no reading and the person's words stand as
	// the goal. Empty is the ordinary case.
	Note string
}

Compiled is one instruction after assume-and-declare: the goal to act on, the defaults that were filled (each a revisable receipt), and the compiler's judgement of shape — "lookup", "task", or "project" — which the planner may use to decide how much structure the work deserves.

type ConsolidateFunc

type ConsolidateFunc func(ctx context.Context, scope string, facts []store.Fact, candidate *ScopePair) (Consolidation, error)

ConsolidateFunc rewrites at most one scope's accumulated facts into fewer, better lines and judges at most one emergent scope pair. Each returned line maps itself to its originals through Sources.

type Consolidation

type Consolidation struct {
	Facts      []Learned
	ScopeAlias *ScopeAliasJudgment
}

Consolidation carries the ordinary line rewrite and, when a candidate was offered, the one merge-or-separate taxonomy judgment made in the same call.

type CraftAdvance

type CraftAdvance struct {
	Unrolled int
	Round    int
	Spliced  int
	Receipt  string
	Stopped  string
}

CraftAdvance is what one landed craft node caused. Every field is something that happened; Stopped is the honest reason nothing more was opened.

type CraftCandidate

type CraftCandidate struct {
	Name string
	YAML string
}

CraftCandidate is one workflow file exactly as the distiller wrote it — unparsed, because whether it is a workflow at all is this side's judgment.

type CraftMind

type CraftMind struct {
	// contains filtered or unexported fields
}

CraftMind is craft's thinking half: the shelf it reads and writes, the directory verifier paths resolve against, and the two model seams it borrows — one to read a request's parameters, one to repair a file the parser refused. Nil is the whole disabled state: without a shelf nothing here runs and the resident plans as it always has.

func NewCraftMind

func NewCraftMind(shelf CraftShelf, dir string, fill CraftParamFiller, repair CraftRepairFunc) *CraftMind

NewCraftMind builds the recognizer and forge over one craft repository. dir makes verifier scripts absolute, exactly as the runner's does.

type CraftParamFiller

type CraftParamFiller func(ctx context.Context, instruction string, workflow *craft.Workflow) (map[string]string, error)

CraftParamFiller reads one workflow's declared holes out of the request that matched it. It is a model seam because the values are in the user's prose — "a deck on the Q3 numbers, keep it short" carries a topic and a tone that no pattern would agree on. A filler that cannot answer leaves the map empty and the ordinary planner takes the request.

type CraftRepairFunc

type CraftRepairFunc func(ctx context.Context, candidate CraftCandidate, problem string) (CraftCandidate, error)

CraftRepairFunc hands a refused candidate back to its writer with the parser's own words attached. Errors from craft.Parse and Validate name the step, the field, and the likely intent; this is the reader they were written for.

type CraftRun

type CraftRun struct {
	// Prefix is the run's job root id and id namespace.
	Prefix string
	Nodes  int
	Steps  int
	// Receipt names the craft and its version in the user's own thread.
	Receipt string
}

CraftRun is what admitting one craft run produced.

type CraftRunner

type CraftRunner struct {
	// contains filtered or unexported fields
}

CraftRunner is the craft half of the sentinel: it admits runs and it advances them. It holds no run state — the store and the craft repository hold all of it.

func NewCraftRunner

func NewCraftRunner(graph *store.Store, source CraftSource, dir string) *CraftRunner

NewCraftRunner builds the runner over one store and one craft repository. dir makes verifier scripts absolute; it is the repository the source reads.

func (*CraftRunner) RunCraft

func (c *CraftRunner) RunCraft(name string, params map[string]string, sessionID, intent string) (CraftRun, error)

RunCraft compiles one named workflow and admits it under the spine as ordinary user-origin work. From here on nothing distinguishes it from a planned job except the craft its provenance names.

func (*CraftRunner) Settle

func (c *CraftRunner) Settle(node store.Node, result string, landing float64) (CraftAdvance, error)

Settle advances the run one landed node belongs to. It is called with the result the node is about to complete with, before that completion settles: splicing while the landed node is still open keeps the job's root open too, so nothing downstream can start on a plan that is one splice out of date. Best effort by construction — the sweep re-derives anything this missed.

landing is what this leaf just spent and has not journaled yet. It is the same idiom the daily rail's WithAdditionalSpend is, and it is load-bearing here: the leaf whose landing opens a fan-out is precisely the leaf whose cost the usage table does not have yet, so a money gate that read the table alone would be exactly one leaf behind at the one moment it decides whether to open two dozen more.

func (*CraftRunner) Sweep

func (c *CraftRunner) Sweep(ctx context.Context) (int, error)

Sweep re-derives every craft run's next move from the store alone. It is the resume path: after a crash, a restart, or a Rebuild, the runs that were mid-flight are exactly the landed control nodes whose consequences are not on the graph yet, and nothing else is needed to find them.

func (*CraftRunner) WithClock

func (c *CraftRunner) WithClock(now func() time.Time) *CraftRunner

WithClock replaces the wall clock. Production uses time.Now; the wall-clock bound is otherwise untestable without waiting out a real half hour.

type CraftShelf

type CraftShelf interface {
	Match(request string, k int) []craft.Scored
	Load(name string) (*craft.Workflow, error)
	List() ([]craft.Summary, error)
	History(name string, limit int) ([]craft.Version, error)
	Save(workflow *craft.Workflow, message string) (string, error)
}

CraftShelf is the craft repository as the resident uses it: what can be found, what can be read, what its versions say, and what can be written. *craft.Repo is the only implementation; tests script it.

type CraftSource

type CraftSource interface {
	Load(name string) (*craft.Workflow, error)
}

CraftSource loads one learned workflow by name at the craft repository's current version. The repository is the durable home of workflows; the sentinel re-reads a run's workflow by name@commit rather than caching a copy, so a run that survives a restart is running the same version it started on or it refuses to continue.

type CraftSurvival

type CraftSurvival struct {
	For     int `json:"for"`
	Against int `json:"against"`
	// LastCost is what the most recent clean run of this workflow actually
	// spent, whole-subtree. It rides here rather than in a new query because
	// the outcome write is already standing over the node that just landed and
	// the store already totals a subtree's spend; a receipt that wants to say
	// "last time $0.38" would otherwise be one join away and has never been
	// made. Absent on records written before this field existed, which reads as
	// zero and simply leaves the clause off.
	LastCost float64 `json:"last_cost,omitempty"`
	// Retired is why the person stopped this way of working being reached for,
	// in their own words, and its presence IS the retirement — the recognizer
	// skips any craft whose record carries one.
	//
	// It lives in the survival record rather than in a marker of its own for the
	// reason the record exists at all: this is the one thing the system already
	// knows about a craft by name, it is already read on the recognition path
	// before anything is compiled, and a second key would be a second thing to
	// keep true. Nothing is deleted by a retirement — the workflow file, its
	// versions and its evidence stay exactly where they are, which is what makes
	// this reversible by hand and auditable at all.
	Retired string `json:"retired,omitempty"`
	// RetiredWhen is when that happened, so a page can say how long ago.
	RetiredWhen time.Time `json:"retired_when,omitempty"`
}

CraftSurvival is one craft's record: the runs that settled, and the runs that failed or were cancelled. It rides as the measured value of a trait, which is where this system's second-order facts about itself already live — no new table, and no per-run bookkeeping in the notebook the user reads.

type DistillFunc

type DistillFunc func(ctx context.Context, goal, outcome string, failed bool) ([]Learned, error)

DistillFunc extracts durable memories from one finished or failed job. outcome is the summary on success or the error on failure.

type ExecResult

type ExecResult struct {
	Summary          string
	PromptTokens     int
	CompletionTokens int
	// CachedTokens is the share of PromptTokens the provider billed at the
	// cached rate. The executor has always measured it and the journal now has
	// somewhere to put it; carrying it here is what joins the two, and without
	// it every cache discipline the harness practises stays unfalsifiable from
	// the outside.
	CachedTokens int
	Cost         float64
	// Turns is the same spend with its shape kept: one row per model call,
	// summing to the three totals above. It rides here for the same reason
	// CachedTokens does — the executor has always known it and the journal now
	// has somewhere to put it — and an executor that does not meter turns leaves
	// it empty, which journals nothing rather than journalling a zero.
	Turns []executor.TurnUsage
	// Promote asks the runner to settle this reflex partial and enqueue the
	// same verbatim instruction on the ordinary compiled path atomically.
	Promote         bool
	ServiceRequests []executor.ServiceRequest
	// Model is who actually served the work — the rung a panel picked or an
	// escalation moved to, which is not the model anyone asked for. It rides
	// the spend row because that is the row a receipt already reads.
	Model string
	// SpendBanked says this run banked its own calls as they were billed — one
	// usage row per response, written at the moment the provider answered
	// (cmd/codeaf's leafBanker, provider.WithBilling) — so the three totals
	// above are the REMAINDER and not the whole. On an ordinary banked run they
	// are zero and nothing more is written; they are non-zero when part of the
	// leaf ran on a worker whose calls the adapter never saw, and that part is
	// journaled exactly as it always was.
	//
	// The per-turn shape below is NOT a duplicate and is written either way —
	// it is a different kind of record, one row per turn rather than one per
	// call, and nothing else in the journal carries it. Which is why the zero
	// check above asks this field as well: a fully banked run has nothing left
	// to sum and its turn ledger still has to reach the journal.
	SpendBanked bool

	// HOW THE WORK ENDED, WHICH IS A DIFFERENT FACT FROM WHAT IT PRODUCED.
	//
	// A leaf that ran out of its tokens mid-edit and a leaf that finished
	// reached this seam wearing the same three fields — a summary, some money,
	// some turns — so the scheduler saw err == nil and settled the node done.
	// A judge's "nothing is left" then stood as the whole account of a worker
	// that had been cut off with a red build: measured on 2026-09-01, a leaf
	// stopped at `⏳ ran out of tokens — 33 turns` and was ✓ two seconds later,
	// its summary its own last sentence, and its siblings briefed on truncated
	// work. Nothing that runs after that ✓ can recover the cut work.
	//
	// THE ENDING WORD IS THE WHOLE OF THE ANSWER, and it is one field rather
	// than two. A StopReason is a string whose zero value is the empty string,
	// and [executor.StopReason.OutOfRoom] reads that empty string as false — so
	// a result nobody filled in already settles as an ordinary finish, exactly
	// as it did before any of this existed. Absence is still said out loud.
	//
	// It was once guarded by a second `Stopped` flag asked before this one, and
	// the flag could only ever subtract: one writer set it in the same breath as
	// this field and one reader consulted it, and what it gated was whether a
	// worker's real work is thrown away. A result that arrives carrying an
	// unambiguous "it ran out" and a flag somebody forgot is a node quietly
	// retired over work that was still going — the very defect this seam exists
	// to refuse — so the ending word decides alone.
	//
	// Stop is the executor's own word for the ending — "budget", "turn-cap",
	// "deadline", "done".
	Stop executor.StopReason
	// Meter is what ran out and how far the leaf got, read at land time. It is
	// carried for the record rather than for the decision: the decision is
	// RanOut, and this is what a person and an autopsy are owed about it.
	Meter executor.Meter
	// Continued says something else is already carrying this leaf's remaining
	// work — a spliced continuation, a repair journaled against the daily rail.
	// A leaf that ran out and HAS a successor is finished with; one that ran out
	// with nothing behind it has no account, and the scheduler must not write
	// one for it. See Runner.runOne.
	Continued bool

	// RefusedGrowth is the growth governor's own [GrowVerdict.Cause] — the word
	// "standstill" or "fixed-point" — when the round that would have carried
	// this leaf's remainder was refused because NOTHING IS CHANGING, and it is
	// the empty string when growth was not refused on that ground, which
	// includes every ordinary leaf, every cap, and the daily rail.
	//
	// EMPTY MEANS NO SUCH REFUSAL AND THE VALUE IS THE CAUSE WORD, never a
	// sentence and never a flag: the sentence a person reads is derived from it
	// exactly once, by GrowthStopped, so the stream, the record and the node's
	// ending cannot describe one event three ways.
	//
	// It rides here because the governor's finding was already true and already
	// printed by the time the leaf landed, and the scheduler — the one thing
	// that can stop paying for the job — was the only reader never told. It
	// carried "it ran out" and "nothing is continuing it", both of which were
	// also true of the very first fruitless round, so the queue could not tell
	// the two apart and put a job that had concluded nothing was changing back
	// on it for a third attempt. Stop still answers what stopped the leaf; this
	// answers what the job concluded about carrying on.
	RefusedGrowth string
}

ExecResult is what one execution produced: the summary that flows to dependents, and what producing it cost.

func (ExecResult) RanOut

func (r ExecResult) RanOut() bool

RanOut reports that this leaf STOPPED BECAUSE IT RAN OUT, and that nothing is carrying the rest of its work.

A LEAF THAT RAN OUT HAS NO ACCOUNT. Its work is evidence for the next attempt, never a result: only a leaf that itself reported done, inside its budget, settles a node. Exhaustion is a measured fact and doneness is a claim, and a measured fact is never overturned by an unmeasured claim.

type ExecuteFunc

type ExecuteFunc func(ctx context.Context, node store.Node) (ExecResult, error)

ExecuteFunc runs one claimed node to completion. The runner owns the claim lifecycle around it; the function owns nothing but the work.

type ExpandFunc

type ExpandFunc func(ctx context.Context, node store.Node) (spliced int, expanded bool)

ExpandFunc is asked, after a node has been claimed and before a worker is given it, whether the node is really one worker's job.

It is the one moment the question can be asked well: the claim proves every piece feeding this node has landed, so the division can be decided against what they produced rather than against what they were called. Answering "no" means the hook has already put the parts in the graph and handed the claim back, and the node must not be run — it is structure now, and its parts are ready. Answering "yes" — which is the overwhelmingly common answer and the null hypothesis — means nothing happened and the node runs exactly as it always did.

type Failed

type Failed struct {
	// Ask is what was being attempted, in the words the person used. It is
	// never a node id and never a step brief written by the machine.
	Ask string
	// Cause is one plain clause about why it stopped — the innermost thing that
	// actually refused, in its own words. Empty when nothing said.
	Cause string
	// Next is what happens now: a fallback that is already running, or that
	// nothing is and how to ask again.
	Next string
	// Detail is the transport underneath, kept whole and unedited. It rides
	// below the headline so the room folds it.
	Detail string
}

Failed is a terminal failure in the parts a person is owed. Every field is something that is true; an empty one is something nobody knew, and the composition simply leaves that clause out rather than inventing it.

func FailedNode

func FailedNode(node store.Node, next string) Failed

FailedNode reads one failed node into the parts a person is owed. next is the caller's — only the caller knows whether anything is happening now.

func (Failed) Room

func (f Failed) Room() string

Room composes the row a person reads.

The headline is one sentence built from the parts, in the order a reader needs them: the thing they asked for, that it stopped, why, and what now. The transport follows after a blank line, where every long body on this surface is already folded behind the disclosure mark.

type Finding

type Finding struct {
	Kind  string
	Names []string
}

Finding is one delivery judgement as the thing a repair round is bought to close: what KIND of finding it is, and every name it stands on.

A FINDING'S IDENTITY IS A KIND AND ONE NAME. The set is not the finding; the set is whichever subset of the world one gate happened to weigh, and it rotates. ofetch v4-flash s15 raised four unexercised findings over one request, and the four sets digested to `f3c9d09f`, `8b9bcc0a`, `84152215`, `64a910f1` — four different values — while `Count a circuit failure for body-read/stream-consumption errors` stood in every one of them and was never closed. A rule that compares sets bought four rounds for one behaviour and stopped on the round cap; a rule that compares names stops on the second.

func FindingFrom

func FindingFrom(ctx context.Context) Finding

FindingFrom is that finding, or the empty one where nobody said.

func FindingOf

func FindingOf(gate store.DeliveryGate) Finding

FindingOf reads one delivery judgement as the finding a repair round would be bought to close.

THE MEASUREMENT NAMES ITSELF WHERE IT CAN. store.DeliveryGate.Finding is the verification lane's own word for which measurement raised a gap — `removed-checks`, `regression`, `own-checks-failing`, `removed-public-name` — and where the record carries it, it IS the kind: a reading of the world says what it is, and nothing here gets to guess a better answer from the fields it happened to fill in. The cases below are for the gaps no measurement raised — a model judge reading the request, a coverage mapping — which have no such word and still need an identity, because a round bought for one of those is bought for something just as particular.

A gate that PASSED raises nothing: there is no finding, and a round bought after it is bought for something else. So is a gate whose refusal was overturned — the finding was weighed against the world and lost, and a lost finding is not a standing one.

THE NAMES COME FROM THE STRUCTURED FIELDS AND NOT FROM THE CITATION SAMPLE. A gate's citations are the spans one refusal was built on, bounded and chosen for a sentence a person reads; the lists are the measurement's whole answer. Reading the sample would spend and un-spend names according to which twelve a paragraph happened to quote.

func (Finding) Empty

func (f Finding) Empty() bool

Empty reports that this judgement raised nothing a round could be bought for.

func (Finding) Row

func (f Finding) Row() store.GrowthFinding

Row is the comparable half, for the journal: the kind, and a digest of the whole set. The names travel beside it on the row (store.JobGrowth.BoughtFor) because they are what the per-name rule is actually made of.

type GrowRequest

type GrowRequest struct {
	// JobRoot is the id namespace the job's nodes are minted under: both the
	// ceiling's corpus and the journal's key.
	JobRoot string
	// Node is where a refusal is recorded — the work whose reader needs to know
	// that a governor, and not the work finishing, is why nothing more happens.
	Node store.Node
	// Lineage is the namespace rounds are counted under: a leaf's own split
	// lineage for a replan, the job root for growth that belongs to the job as
	// a whole. Two siblings that each split once are two lineages with one
	// round each, not one lineage with two.
	Lineage string
	Reason  string
	// Adding is the node count about to be spliced. Zero means the caller does
	// not know yet — it has not planned the growth — and the ceiling is then
	// read as "is there room for anything at all".
	Adding int
	// Round is the round this growth would be, when the caller already knows it
	// from its own id arithmetic. Zero derives it from the journal.
	Round int
	// Criterion overrides what the job is judged against. Empty reads it off
	// the job root's own spec, which is where W1 put it.
	Criterion      plan.Done
	DailyBudgetUSD float64
	// Ungated keeps the caps and skips the paid question — Growth.Ungated,
	// carried to the one helper that acts on it.
	Ungated bool
	// Grounded says this round is bought by a REVIEW FINDING THAT NAMES A FILE
	// OF THE RECORD: the delivery gate read the tree it is handing over and
	// said, of a file that is on disk, that it does not do something the
	// request asked for.
	//
	// It is here because two readings of one job may not refuse each other in
	// silence. ofetch s12 is the measured case: the gate refused the delivery
	// over src/circuit-breaker.ts, the first repair round asked to be planned,
	// and the coverage question answered "everything this job is judged on is
	// already covered" — so nothing ran, the run ended partial after 145 calls,
	// and the two answers were never reconciled. The FIRST round after such a
	// finding is not the coverage question's to refuse: the finding IS the
	// evidence that something is not covered, taken from the same world, and it
	// is more specific than a judgement about the job as a whole.
	Grounded bool
	// Quiet keeps the refusal out of the work's record while keeping it in the
	// journal. It is for the one caller whose refusal is not a handover: a
	// claim-time expansion that is refused runs the node whole, immediately, on
	// the worker that is already holding it — so the words every other path
	// needs ("handing over what's done") would describe something that is not
	// happening, on a node the reader is about to watch finish.
	Quiet bool
	// Workspace is where the work this growth reacts to happened, when the
	// caller knows it. Empty reads the seam instead (JobWorkspace), which is
	// where every caller that cannot say gets its answer.
	Workspace string
	// Artifacts is the workspace's own before-and-after reading of the tree:
	// every path the round left behind, relevant or not. Handing the raw list
	// rather than a count is what lets the governor decide what "produced"
	// MEANS instead of taking a caller's word for it — see MeasureRound, and
	// see the ink s10 wall for what a caller's count is worth.
	Artifacts []string
	// Measured says this caller read the world and Produced is its answer.
	//
	// It is a separate field and not a zero test on Produced, because "nobody
	// looked" and "somebody looked and the answer was nothing" are opposite
	// facts that a bare zero spells the same way — and a rule that read them as
	// one would refuse a caller that never measured anything, which is a
	// fail-safe pointing the wrong way. A growth path with no reading of the
	// tree keeps exactly the governors it had.
	Measured bool
	// Produced is how many of those files the JOB IS ABOUT. It is derived here
	// rather than passed in wherever Artifacts are given; a caller that has
	// already narrowed its own reading may set it directly. Meaningless unless
	// Measured.
	Produced int

	// Remainder is the work this round is being bought to finish, as the
	// reviewer named it. It is compared against the last round's for equality
	// and for nothing else.
	Remainder string
	// Finding is the review finding this round is being bought to close, as the
	// record holds it rather than as the review spelled it: a kind and every
	// name it stands on. Empty is every round nobody bought for a finding, and
	// it is never refused on this ground. See [Finding] and [spentNames].
	Finding Finding

	// Rechecking marks a second look at a decision already taken this round —
	// the exact ceiling, once a plan exists and its node count is known. The
	// free checks are re-read; the paid question is not, because it was already
	// asked on the way in and its answer has not changed.
	Rechecking bool
	// contains filtered or unexported fields
}

GrowRequest is one path asking to add work to a running job.

type GrowVerdict

type GrowVerdict struct {
	Allow bool
	Round int
	// Refused is the sentence a person reads, empty when allowed and when the
	// pause is the daily rail — a rail is not a refusal, it is a question
	// already asked in its own words elsewhere.
	Refused string
	Cause   string
	// CoveredDespite is the standing evidence that stopped the coverage
	// question from refusing this round, when it would have. It travels on the
	// verdict so the ADMISSION can journal it: the row that records a round is
	// written after the splice, by a caller holding the request it was decided
	// from, and this is the one fact about the decision that request never had.
	CoveredDespite []string
	// Spent is the names of this round's finding that had already had their two
	// rounds, and it travels for the same reason. The names it was bought for
	// are derived from the finding itself and need no carrying.
	Spent []string
}

GrowVerdict is the governor's answer.

type Growth

type Growth struct {
	Reason string
	Ask    Satisfier
	// Ungated skips the satisfaction question and keeps the caps. It is for the
	// one caller whose growth is not a machine's second thought: a person who
	// has just said what they want more of is not answerable by "the goal is
	// already covered", because they have just redefined the goal.
	Ungated bool
	// Grounded says this growth is bought by a review finding that names a file
	// of the record — GrowRequest.Grounded, carried through the one seam every
	// growing job passes through.
	Grounded bool
	// After is the landed node this growth is a reaction to — the result that
	// convened the revision sentinel, exhausted or failed or merely surprising.
	// The zero node is growth with no such result behind it (a person changing
	// the goal), and it wires no evidence.
	//
	// It travels with the reason because it answers the same kind of question:
	// the reason says why the job grew, and this says what it grew from, which
	// is what an added node has to be able to read. The overrun splice has
	// always had it in hand — it is that path's whole subject — and the
	// revision path used to have nowhere to put it, so its additions were
	// admitted with no edge to the work they were replacing.
	After store.Node

	// Records are files the finished work left behind that the remainder must
	// READ rather than reuse: the text of a change, a measurement, a transcript.
	//
	// They are separate from the artifact list because the two are separate
	// invitations and collapsing them was measured producing a false statement.
	// An artifact is "this exists, do not make it again". A record is "this is
	// what happened, and it is where your account of it has to come from" — and
	// a repair that was handed only artifact NAMES had no way to learn what the
	// work it is finishing actually did, so the pass that wrote its method
	// offered an illustrative root cause instead and the leaf shipped that
	// example verbatim as the real one.
	//
	// Empty is every caller that has one kind of file and not the other, which
	// renders exactly the bytes this path has always rendered.
	Records []string
	// State is the dead leaf's structured findings — files it touched, checks
	// it ran, and its last tool calls — derived from the leaf's own outcome
	// by LeafState. It travels with Records for the same reason: the remainder
	// needs to know what the finished work actually did, not just what files
	// it left. A continuation that knows what the dead leaf already found
	// resumes from there instead of re-reading everything it already diagnosed.
	// Empty is every caller that has no structured outcome, which renders
	// exactly the bytes this path has always rendered.
	State string

	// Goal overrides the brief the splice is planned from. Empty — every caller
	// that existed before the cooperative path — keeps OverrunGoal, which is
	// the only phrasing the splice has ever used.
	//
	// It exists because that phrasing is a claim and not a template: "it stopped
	// when its resources ran out, so parts of the assignment may already be
	// complete" is the first thing the planner reads, and it is false of a leaf
	// that handed its budget back on purpose. A planner told the work ran out
	// plans a remainder; the cooperative path needs it to plan a division, and
	// those are different questions asked of the same call.
	Goal string
}

Growth is what a caller says about itself: why it is growing the job, and — where it has one of its own — the reader that answers whether the job still needs anything. Both are optional; the zero value is an overrun asking the process-wide gate.

type Handover

type Handover struct {
	// Seq and At are the journal's own coordinates for the request. At is what
	// makes the request answerable: a resident only owes an answer to a request
	// made while it was already serving.
	Seq int64
	At  time.Time
	// Reason is the requester's own words, verbatim.
	Reason    string
	SessionID string
}

Handover is one request to take over the resident role.

type HandoverFunc

type HandoverFunc func(request Handover) (accepted bool, reason string)

HandoverFunc is asked to give up the resident role. It answers whether the role will actually be released and says why in the words the requester and the journal both read.

It is called from inside a tick, so it must return promptly: releasing a lease, draining a runner and stopping a head all belong to the goroutine the implementation starts, not to the pass that is still holding the command queue open.

type JITExpander

type JITExpander struct {
	Graph          *store.Store
	DailyBudgetUSD float64
	// FreeSlots reports the pool's idle dispatch slots right now. Nil means
	// "no signal" — the starvation gate is skipped and the gate is exactly
	// as permissive as it was before the field existed.
	FreeSlots func() int
	// ContextTokens is the window of the planning model this expander divides
	// through — the same model the build asked, and not the leaf's. Zero is
	// unknown and falls back to jitDigestBytes, which is what every expansion
	// took before the window was threaded here.
	ContextTokens int
	// Resolve finds the job a claimed node belongs to. Not ok means "this node
	// has no plan" — a one-leaf job, a craft node, a rehydration miss — and is
	// the ordinary answer for most of what a resident claims.
	Resolve func(node store.Node) (JITTarget, bool)
	// Ask overrides the process-wide satisfaction gate. Nil uses it.
	Ask Satisfier
}

JITExpander is the claim-time half of decomposition.

func (JITExpander) Expand

func (e JITExpander) Expand(ctx context.Context, node store.Node) (int, bool)

Expand is the Runner's hook: consulted after a node is claimed and before a worker is given it.

It reports whether the node was turned into structure. When it was, the claim has already been released and the node must not be executed — its children are in the graph, ready, and the next pass dispatches them. When it was not, nothing at all has happened to the node and the caller runs it exactly as it would have.

type JITTarget

type JITTarget struct {
	// Plan is the job's live plan document.
	Plan *plan.Graph
	// Lock guards it. Nil is legal and means the caller has no concurrency to
	// protect against, which is every test and no production surface.
	Lock sync.Locker
	// Prefix is the id namespace the job's store nodes are minted under, so a
	// child of plan node N is "<prefix>-nN" — the same arithmetic the reconciler
	// used at admission, which is what lets the child be looked up and judged
	// again when it is itself claimed.
	Prefix string
	// PlanNode is the claimed node's id inside Plan.
	PlanNode int
	// Client plans the expansion. Nil refuses it — a job whose planning client
	// did not survive a restart runs its nodes whole, which is what it did
	// before this file existed.
	Client plan.Completer
	// Options carries the ceilings the job was planned under.
	Options plan.Options
	// Journal persists the document after it has grown. Nil skips it, at the
	// cost of a restart not seeing the deeper shape.
	Journal func()
}

JITTarget is one job's plan document, and the four facts needed to find one node inside it and put children under that node afterwards.

It is resolved by the caller rather than read from the journal here, because the live document is the one a revision sentinel is also editing: reading a second copy out of the store and writing it back would silently drop whatever the sentinel had just decided.

type JobSketch

type JobSketch struct {
	Origin           store.Origin
	Title            string
	Ask              string
	Outcome          string
	Age              string
	NodeCount        int
	PromptTokens     int
	CompletionTokens int
	Cost             float64
	SurpriseTokens   int
	ExpectedTokens   int
	Surprise         *float64
}

JobSketch is one settled job as the retrospective sees it: what was asked in the user's words, what came back, and how long ago.

func (JobSketch) CostSummary

func (j JobSketch) CostSummary() string

CostSummary renders the structural size and measured spend compactly for the reflector prompt.

type Learned

type Learned struct {
	Scope string
	Kind  store.FactKind
	Body  string
	// Unsettled is the structured pair required by FactUnsettled. Body is a
	// searchable projection and is regenerated from this payload on write.
	Unsettled *store.UnsettledPair
	Replaces  int64
	// Sources names the existing facts a consolidated line derives from,
	// strongest evidence first. It is empty outside consolidation.
	Sources []int64
	// Skill is set only when this memory names a reusable artifact produced by
	// the job. Its fact enters the notebook as a non-retrievable candidate.
	Skill *SkillCandidate
	// Craft is set only when the job's SHAPE looked reusable. It is not a
	// memory at all — it rides here because one distiller call judges both,
	// and it is split off before the notebook ever sees it.
	Craft *CraftCandidate
	// Quarantines names source facts rejected by a repeated bad-outcome pattern.
	// It is honored only by consolidation.
	Quarantines []int64
}

Learned is one distilled memory: what it is about, what kind, one line. Replaces names one existing fact this line supersedes. Quarantines names suspect inputs that consolidation removes from retrieval without replacing; both transitions remain reversible journal events.

type ModelResolveFunc

type ModelResolveFunc func(names []string, boost bool) (string, bool)

ModelResolveFunc answers whether the catalog has the model a restart named. It is a seam rather than a lookup because the catalog is the surface's, and the resident holds no opinion about which provider exists this week. Without it every restart runs on the default and says so.

type NarrateFunc

type NarrateFunc func(ctx context.Context, narration Narration) (string, error)

NarrateFunc turns one Narration into a single casual line for the thread. Returning an empty line skips the update without error.

type Narration

type Narration struct {
	// Goal is the user's verbatim intent for this subtree.
	Goal string
	// Finished are labels of parts landed since the last update, each with a
	// one-line result.
	Finished []string
	// Running are labels of parts in flight, each with elapsed time.
	Running []string
	// Queued is how many parts are admitted but not yet started.
	Queued int
	// Previous are the narrator's own recent lines for this job.
	Previous []string
}

Narration is everything the narrator may speak from, for one job.

type OpenFindings

type OpenFindings struct {
	// Unexercised are the behaviours the request stated that no check in the
	// tree exercises, in the words the request used. store.DeliveryGate.
	Unexercised []string
	// Unasserted are the behaviours a check in the tree NAMES and no assertion
	// WEIGHS, each carrying the observables nothing asserted. store.DeliveryGate.
	Unasserted []string
	// Failing are the named checks the last reading of the project's own tests
	// found red. store.VerificationReading.Sample.
	Failing []string
	// Gap is the last finding the delivery gate recorded against this lineage.
	Gap string
	// Unclosed says a gap the gate raised was never closed — the repair was
	// refused or could not be bought — which is a different fact from a gap
	// that a later round answered.
	Unclosed bool
	// Declined is the sentence a gate wrote INSTEAD OF a judgement: the harness
	// stopped spending on the job before the delivery was ever judged, so the
	// row carries a refusal and no gap. store.DeliveryGate.Refused, on a row
	// whose Unclosed is set.
	//
	// It is a field beside Gap and not a value in it because the two are
	// different news and a brief that ran them together would lie either way: a
	// gap is what a review found missing, this is that nobody looked, and the
	// last gap a review DID find still stands underneath it. Reading the row as
	// silence was the other half of the same lie — a job that produced nothing
	// and was judged by nothing read as a job with nothing outstanding.
	Declined string
	// Unreadable says the last gate passed over a tree whose checks nobody
	// could read, which is not a pass over a checked delivery.
	Unreadable bool
	// Consumers is the changed-definition finding: one line per definition this
	// run reshaped that the rest of the project still uses the old way. It is a
	// reading of the world like Failing and unlike Gap — no suite and no name
	// comparison can make it, because the name is still there.
	// store.DeliveryGate.Consumers.
	Consumers []string
	// Unbound is the unbound-reference finding: one line per name this run's own
	// sources READ that nothing in the tree binds, each carrying the file and
	// line it is read at. It is a reading of the world like Failing and unlike
	// Gap, and it is the one a repair round can act on without running anything.
	// store.DeliveryGate.Unbound.
	Unbound []string
	// Mechanical says the standing gap is the MECHANICAL half's: a file the
	// plan promised and the disk does not hold. It is beside Gap rather than
	// inside it because the two are answered by different evidence — one is a
	// judge's sentence about a delivery, the other is a stat of the filesystem —
	// and nothing that reads a claim about the plan may overrule the second.
	Mechanical bool
}

OpenFindings is everything a job's own record says is still outstanding.

Every field is sourced from a journal row rather than from anybody's summary of one — FAILSAFE.md's second clause, applied to the job's account of itself. An empty value means the record does not say, never that the answer is no.

func ReadOpenFindings

func ReadOpenFindings(graph *store.Store, lineage string) OpenFindings

ReadOpenFindings assembles the findings from one lineage's own journal.

It reads the LINEAGE and not the node, because a repair round is a different node id from the work it repairs — that is the whole shape of the defect in (A) as well — so a reader that asked the node would find a fresh row with nothing on it and conclude the job was short of nothing.

A failure to read is not a failure to work: this is an account of the job and never a part of it, so an unreadable journal answers with nothing and lets the work go on with the brief it would otherwise have had.

func (OpenFindings) Empty

func (f OpenFindings) Empty() bool

Empty reports that the record names nothing outstanding, in which case no composer should write a section: a heading announcing no findings costs tokens and teaches the model that the heading means nothing.

func (OpenFindings) Words

func (f OpenFindings) Words() string

Words renders the fixed section, or nothing when there is nothing to say.

The order is deliberate and it is the order of specificity: a named failing check is a thing to go and run, an unexercised behaviour is a thing to go and write, and the gate's own sentence is the judgement over both. A worker that reads only the first line has read the most actionable one.

type OverrunPlanFunc

type OverrunPlanFunc func(ctx context.Context, goal, prefix string) (store.Subtree, error)

OverrunPlanFunc plans the remaining work of an exhausted leaf into a subtree, with prefix as the id namespace for the new nodes.

func DivideAsRequested

func DivideAsRequested(graph *store.Store, node store.Node, target JITTarget,
	contextTokens int, request *executor.SplitRequest, partial string,
	retain func(sub *plan.Graph, usage plan.Usage, prefix string)) OverrunPlanFunc

DivideAsRequested is the expansion half: the same two calls a claim-time division spends, made against the same document, with the leaf's finding added to what the sub-planner reads.

It is plan.ExpandOne and not a fresh plan.Build, and the difference is the question. Build asks "what work does this goal need"; ExpandOne asks "what are the parts of this node", which is the question a split request raises — and it asks it inside the job's own document, so the parts inherit the settled points, the terrain and the invoice the rest of the job was planned against instead of rebinding them for themselves.

A target the caller could not resolve — a task-scale job with no document, a craft node, a job whose plan did not survive a restart — returns no nodes, which the splice reads as "nothing to add" and the settlement reads as "deliver the partial". That is the same answer those nodes have always given to every question about their own shape.

It takes the splice's goal argument and does not read it, and that is a fact worth stating rather than leaving to be discovered: this divider plans from the job's own plan document, so the prose brief every other OverrunPlanFunc is steered by has nothing to steer here. The leaf's finding reaches the sub-planner through the claim context instead, which is the slot in an expansion prompt that holds results — and CooperativeGoal remains the brief a divider that DOES plan from prose would read, which is what the fallback and every test in this package are.

retain is how the process that owns the plan registry hears about the document this call produced, and what it cost. It is a parameter rather than a field on anything here because which registry a job's plan lives in is the surface's business and this package deliberately does not know — the same division of labour JITTarget.Journal already draws. Nil is legal and costs only a restart's view of the deeper shape, exactly as it does there.

type PlanAnchor

type PlanAnchor struct {
	NodeID     string
	SessionID  string
	CommandSeq int64
}

PlanAnchor is the durable identity a planner can speak against before the subtree itself has landed. CommandSeq is set for a new chat job; replanning an existing job carries only its already-admitted node and session.

func PlanAnchorFromContext

func PlanAnchorFromContext(ctx context.Context) (PlanAnchor, bool)

PlanAnchorFromContext returns the journal anchor for planning progress. It is optional so PlanFunc remains usable outside the resident command loop.

type PlanFunc

type PlanFunc func(ctx context.Context, compiled Compiled) (store.Subtree, error)

PlanFunc turns one compiled goal into an atomic subtree admission.

type Reconciler

type Reconciler struct {
	// contains filtered or unexported fields
}

Reconciler is the replaceable background half of the resident thread. The store remains the source of truth; this type keeps injected planning behavior and a working copy of two durable cursors in memory.

Those cursors are restart-safe because they are journaled, not because they are cheap: the settle lane's place in the event stream and the consolidation clock are both written as lane watermarks (store.LaneSettlement, store.LaneConsolidation). They used to be plain fields primed on the first tick of every process, which meant a job that landed while no reconciler was running was never announced, never distilled and never folded, and every restart bought another belief-rewriting consolidation pass. Anything else held here is a per-tick working set, and losing it costs telemetry only.

func New

func New(graph *store.Store, compile CompileFunc, plan PlanFunc) *Reconciler

New constructs a reconciler. A nil compiler preserves the instruction verbatim with no assumptions. A nil planner admits one task whose stable ID is derived from the command sequence.

func (*Reconciler) AskQuestion

func (r *Reconciler) AskQuestion(question store.AgentQuestion) (store.AgentQuestion, error)

AskQuestion gives resident components one policy-aware entry point. Every urgency is queued first; only blocking questions cross into the thread in the same call.

func (*Reconciler) AttachSession

func (r *Reconciler) AttachSession(sessionID string) error

AttachSession is the resident's session-attach natural moment. It surfaces at most one queued next-natural-moment question and never surfaces a whenever question.

func (*Reconciler) LastWatchPass

func (r *Reconciler) LastWatchPass() WatchPass

LastWatchPass returns the standing-watch decisions made by the latest Tick. It is an ephemeral operation report for bounded callers such as `codeaf wake`; all resulting state transitions remain journaled in the store.

func (*Reconciler) Serve

func (r *Reconciler) Serve(ctx context.Context) error

Serve polls until ctx is cancelled or the store can no longer be read or written. Strategy failures reject their command and do not stop the loop.

func (*Reconciler) SessionClosed

func (r *Reconciler) SessionClosed(sessionID, surface string) error

SessionClosed journals the user's attention leaving this surface.

func (*Reconciler) SessionOpened

func (r *Reconciler) SessionOpened(ctx context.Context, sessionID, surface string, after time.Duration) error

SessionOpened journals an attach edge, then posts at most one folded arrival message for qualifying activity since the previous seen watermark.

func (*Reconciler) SessionOpening

func (r *Reconciler) SessionOpening(sessionID, surface string, after time.Duration) (func(context.Context) error, error)

SessionOpening is SessionOpened split at its one slow seam, for a surface that must not make the user watch it.

The half that runs here is the half whose ordering matters: reading the previous seen watermark and journalling the attach edge, both cheap. The half it hands back is the expensive one — a journal gather, a model round-trip, and the post — and it is already bounded by the window this call fixed, so running it later cannot widen or move what the brief covers. The thread is the delivery channel either way; a brief that arrives a moment after the surface does arrives in exactly the same place.

Nil means there is nothing to say and nothing to wait for.

func (*Reconciler) Tick

func (r *Reconciler) Tick(ctx context.Context) error

Tick drains the current command queue and announces newly settled nodes. Calls are serialized so tests and embedding processes may invoke Tick without racing another Serve loop on the same reconciler.

func (*Reconciler) WatchOnce

func (r *Reconciler) WatchOnce(ctx context.Context) (WatchPass, error)

WatchOnce runs exactly one pass over the charters that were due when the pass began. Interrupted wake phases are resumed from their journaled state.

func (*Reconciler) WithBriefComposer

func (r *Reconciler) WithBriefComposer(compose BriefComposeFunc) *Reconciler

WithBriefComposer installs the resident-only model seam used at session open.

func (*Reconciler) WithCancelRethink

func (r *Reconciler) WithCancelRethink(rethink CancelRethinkFunc) *Reconciler

WithCancelRethink gives cancellation the upward channel failure has had all along. Without it a cancel is exactly what it was before — the work stops and the plan around it carries on as though nothing had been withdrawn.

func (*Reconciler) WithCharterProposals

func (r *Reconciler) WithCharterProposals() *Reconciler

WithCharterProposals lets the resident retrospective surface recurring asks through the explicit ratification door. Non-chat embedding paths stay inert.

func (*Reconciler) WithConsolidator

func (r *Reconciler) WithConsolidator(consolidate ConsolidateFunc) *Reconciler

WithConsolidator installs the notebook's sleep pass and returns the reconciler for chaining. A nil consolidator leaves the notebook untouched.

func (*Reconciler) WithCraftMind

func (r *Reconciler) WithCraftMind(mind *CraftMind) *Reconciler

WithCraftMind installs recognition and forging. Without it the craft repository is still run by name, and still swept — it is simply never reached for on its own.

func (*Reconciler) WithCraftRunner

func (r *Reconciler) WithCraftRunner(craft *CraftRunner) *Reconciler

WithCraftRunner installs the craft sentinel's resume half. The runner advances a craft run as each of its nodes lands; this sweep re-derives the same moves from the store alone, which is what makes a run that died between a completion and its splice pick up exactly where it stopped.

func (*Reconciler) WithDistiller

func (r *Reconciler) WithDistiller(distill DistillFunc) *Reconciler

WithDistiller installs the notebook's writer and returns the reconciler for chaining. A nil distiller (the default) records no facts.

func (*Reconciler) WithHandover

func (r *Reconciler) WithHandover(hand HandoverFunc) *Reconciler

WithHandover installs the seam that lets another window take the resident role while this one is still healthy. Without it — a wake pass, a test, any process with no surface to demote to — a handover request is rejected in words rather than left pending, so the requester learns immediately that it must wait for the heartbeat to go stale instead of waiting forever.

func (*Reconciler) WithHeartbeat

func (r *Reconciler) WithHeartbeat(beat func(time.Time)) *Reconciler

WithHeartbeat installs the liveness stamp the resident lease reads. Holding the role is a claim about doing the work, and the flock alone cannot tell a serving process from a wedged one — so the loop says so on every pass it completes, and a probe that finds the stamp stale may take the role back. Nil (the default) leaves the lease saying nothing, which a probe reads as unknown rather than as dead.

func (*Reconciler) WithModelResolver

func (r *Reconciler) WithModelResolver(resolve ModelResolveFunc) *Reconciler

WithModelResolver installs the surface's catalog-backed reading of the model words a restart carries.

func (*Reconciler) WithModelsInForce

func (r *Reconciler) WithModelsInForce(models func() (plan, work string)) *Reconciler

WithModelsInForce teaches the resident the surface's two model slots, read at splice time: the one that structures and the one that works. Without it a job records nothing about who planned it, which is exactly what every embedding path with no slots to speak of should record.

func (*Reconciler) WithNarrator

func (r *Reconciler) WithNarrator(narrate NarrateFunc) *Reconciler

WithNarrator installs progress narration and returns the reconciler for chaining. A nil narrator (the default) keeps progress out of the thread entirely — the graph lens still shows it live.

func (*Reconciler) WithOneShotErrands

func (r *Reconciler) WithOneShotErrands() *Reconciler

WithOneShotErrands pins this reconciler to the headless errand surface.

The compiler is told the same fact and is the place it should be settled; this is the second rung, for the case where a charter draft arrives anyway — a compiler that is not the head's, a provider that emitted a charter key the prompt never asked for. A draft that reaches a surface with no one at the keyboard is auto-resolved exactly as the caller already chose by typing the verb: once, not standing. The resolution is journaled, and the work then runs, which is the whole point of the errand.

It is also the switch for the surface's other law, which is about words rather than time: the submitted ask is the goal, kept byte for byte, and a question the compiler wanted to ask is answered here rather than returned. See keepTheAskVerbatim and assumeAndDeclare.

func (*Reconciler) WithOverrunPlanner

func (r *Reconciler) WithOverrunPlanner(dailyBudgetUSD float64, plan OverrunPlanFunc) *Reconciler

WithOverrunPlanner installs restart-safe resumption for repairs deferred at the daily rail. Zero budget keeps the planner unlimited.

func (*Reconciler) WithPracticeLoop

func (r *Reconciler) WithPracticeLoop(dailyBudgetUSD float64, idleFor time.Duration) *Reconciler

WithPracticeLoop enables curiosity-driven maintenance. A zero dollar carve- out disables it. The daily budget is split across the charter's two-firing cap; the global daily rail remains an additional admission boundary.

func (*Reconciler) WithRedirector

func (r *Reconciler) WithRedirector(redirect RedirectFunc) *Reconciler

WithRedirector registers the plan-revision half of user-driven redirection. Without it the words still reach every running worker as steering.

func (*Reconciler) WithReflector

func (r *Reconciler) WithReflector(reflect ReflectFunc) *Reconciler

WithReflector enables the periodic retrospective.

func (*Reconciler) WithResidentSince

func (r *Reconciler) WithResidentSince(at time.Time) *Reconciler

WithResidentSince tells the reconciler when this process took the role. A handover journaled before that moment was addressed to whoever was serving then, and answering it would make a freshly promoted resident stand straight back down — the loop that would otherwise pass the role around a ring of windows forever.

func (*Reconciler) WithStandingWatch

func (r *Reconciler) WithStandingWatch(standing StandingWatch) *Reconciler

WithStandingWatch enables the one-time unattended-presence offer after the first charter ratification. Nil preserves embedding paths with no host timer.

func (*Reconciler) WithTerritoryDigester

func (r *Reconciler) WithTerritoryDigester(digest TerritoryDigestFunc) *Reconciler

WithTerritoryDigester enables territory maintenance during a retrospective. It is separate from WithReflector so non-chat and headless paths stay inert.

func (*Reconciler) WithTitler

func (r *Reconciler) WithTitler(title TitleFunc) *Reconciler

WithTitler sets the display-title compressor. Nil stays valid: nodes fall back to the first line of their brief everywhere titles are shown.

func (*Reconciler) WithWatchEngine

func (r *Reconciler) WithWatchEngine(dailyBudgetUSD float64, sentinel SentinelFunc) *Reconciler

WithWatchEngine enables standing work in this reconciler. Nil keeps the existing resident and headless paths inert.

type RedirectFunc

type RedirectFunc func(ctx context.Context, job store.Node, message string, flavor RevisionFlavor) (Redirection, error)

RedirectFunc revises one job's remaining plan in light of the user's own words. It is injected rather than built here because the live plan graph belongs to the process that planned it; the reconciler owns everything that follows — the cancels, the broadcast, and the receipt.

type Redirection

type Redirection struct {
	Added   int
	Dropped int
	Amended int
	Notes   []string
	// RunningRemovals names store nodes the revision wanted removed while a
	// worker is inside them. Started work is frozen, so removal degrades to a
	// cancel request, gated by what it would throw away.
	RunningRemovals []string
}

Redirection is what one user-driven revision pass actually did, in the terms the receipt speaks: counts, the store's refusals, and the running leaves the sentinel wanted gone — which the store will not simply delete.

type ReflectFunc

type ReflectFunc func(ctx context.Context, jobs []JobSketch) ([]Learned, error)

ReflectFunc looks across recent jobs for what only the series reveals and returns it as notebook memories. An empty return is the common, correct answer.

type RevisionFlavor

type RevisionFlavor string

RevisionFlavor is why the user spoke: to change what the work is, or to change how long they are willing to wait for it. Both reach the same sentinel by the same path; only the event they carry differs.

const (
	RevisionRedirect RevisionFlavor = "redirect"
	RevisionExpedite RevisionFlavor = "expedite"
)

type RoundChange

type RoundChange struct {
	// Relevant is what the round changed that the job is about: check files,
	// and sources inside the focus.
	Relevant []string
	// Scratch is the rest — files the round wrote that are outside everything
	// the request named. They are journaled rather than dropped: "this round
	// wrote fourteen files and moved none of them" is a recognisable failure
	// and the names are what make it recognisable.
	Scratch []string
	// Measured says somebody could look. It is false where there is no
	// workspace to read the round against, which reads as "nobody counted" and
	// leaves every governor exactly as it was.
	Measured bool
}

RoundChange is one round's work as the world holds it, split by whether the job is about it.

func MeasureRound

func MeasureRound(graph *store.Store, jobRoot, workspace string, artifacts []string) RoundChange

MeasureRound reads what one round left behind against what its job is about.

artifacts is the workspace's own before-and-after reading of the tree — never a worker's account of itself (FAILSAFE clause 2) — and workspace is the directory that reading was taken in. An empty workspace is a caller that cannot say where the work happened, and it answers "nobody looked".

func (RoundChange) Moved

func (c RoundChange) Moved() bool

Moved reports that the round changed something the job is about.

type Runner

type Runner struct {
	// contains filtered or unexported fields
}

Runner drains ready nodes from the durable graph and executes them. It is the store-side counterpart of the one-shot scheduler: any process may run one, claims make ownership a compare-and-swap, and a crashed runner leaves nothing worse than claimed nodes another Release can recover.

func NewRunner

func NewRunner(graph *store.Store, execute ExecuteFunc, owner string, workers int) *Runner

NewRunner builds a runner executing at most workers nodes concurrently.

func (*Runner) CloseOut

func (r *Runner) CloseOut(jobRoot, keep, reason string) int

CloseOut stops a job's outstanding work so that what has landed can be judged, and answers how many nodes it stopped.

A GATE ALWAYS PRECEDES THE WALL. A job whose growth has just been refused with the wall nearer than one measured round has had this run's last decision about it taken; what it must not do next is keep claiming leaves the clock will kill mid-flight, because a job still moving when the clock stops never settles, no verdict on it is ever cut, and the person is handed a partial with nothing judged. ofetch v4-flash s13 ended exactly there: two refusals inside the last ninety seconds, thirteen pending leaves, a pending job root, and not one delivery judgement in 5407 seconds.

The job root itself is never touched. It is the node that carries the whole remainder and it is where the gate fires, so what this does is clear the way to it: every part of the job that has not started is retired, every part this process is behind is asked to stop and cancelled, and the root then has nothing left to wait for. A part claimed by a worker in another process is asked and left — the claim reaper is what finishes those, and taking a claim from a live worker is the one thing this may not do.

keep is the node whose landing is asking. Stopping it would release the very claim it is in the middle of settling, and the row would go back on the queue to be claimed again — a close-out that reopens the job it closed.

func (*Runner) Drain

func (r *Runner) Drain()

Drain stops the dispatch loop without cancelling the work already in flight, and Serve returns nil once the running leaves have landed.

A handover is why it exists. The process giving up the resident role must stop claiming new leaves the instant it lets go of the lease, or two runners race for the same queue; but it must not take its running leaves down with it, because the store owns their claims and a leaf killed mid-turn is work paid for and thrown away. Cancelling the context does both at once, which is exactly the thing that must not happen here.

func (*Runner) FreeSlots

func (r *Runner) FreeSlots() int

FreeSlots reports how many dispatch slots are unheld right now. The claim-time expander consults it before multiplying nodes: with every slot held, decomposition buys no parallelism and pays pure cost, which is the split-waste this field exists to refuse.

func (*Runner) RaiseStaleAge

func (r *Runner) RaiseStaleAge(deadline time.Duration)

RaiseStaleAge lifts the reaper's window so it stays above a leaf whose own deadline has just been decided, and never lowers it.

It exists because the window is a CONSTANT and the deadline is not. A leaf's deadline scales with the budget it was granted (cmd/codeaf's leafDeadline: a minute per fifty thousand tokens above the floor), so a well-fed leaf is entitled to run for longer than the reaper's default window — and the reaper would then take a node away from a worker that was still working, which is the one thing a backstop must never do. The surface that decides a deadline is the only party that knows it, so it says so here.

MONOTONIC, AND ON PURPOSE. Several leaves of different sizes run at once and the sweep is one query over the whole store, so the window has to clear the widest deadline in flight rather than the newest. It is never lowered again: the cost of a window left wide is a dead claim noticed later, and the cost of one narrowed under a live leaf is the leaf.

It is called from the leaf-building goroutine and read by the dispatch loop, which is why it is guarded.

func (*Runner) Serve

func (r *Runner) Serve(ctx context.Context) error

Serve polls for ready work until ctx ends, then waits for in-flight nodes to land. Landing is bounded by each execution's own respect for ctx.

A pass is not free: it asks the store for deferred overruns, for the ready set, and for whether the user is idle, three times a second even on a machine with nothing to do. So a pass that dispatched nothing records the journal watermark it started from, and the ticker skips while that watermark stands still — the same proof the head already sleeps on. The watermark is read before the pass and only kept afterwards: anything journaled while the pass was reading sits above the recorded mark, so the next tick looks again rather than sleeping through it. Nothing about latency changes — nudge() still fires the instant a landing opens the ready set, and it never consults the gate.

func (*Runner) Tick

func (r *Runner) Tick(ctx context.Context) (int, error)

Tick claims as many ready nodes as free slots allow and dispatches them. It returns how many nodes were dispatched; store errors stop the runner, execution errors do not — they land on the node as a recorded failure.

func (*Runner) Wait

func (r *Runner) Wait()

Wait blocks until every dispatched node has landed. Tests use it to make Tick deterministic.

func (*Runner) WithCraftRunner

func (r *Runner) WithCraftRunner(craft *CraftRunner) *Runner

WithCraftRunner installs the craft sentinel. Nil (the default) leaves every leaf ordinary; craft provenance is what selects a node into it, so a runner with one installed behaves identically on work that is not a craft run.

func (*Runner) WithDailyBudgetUSD

func (r *Runner) WithDailyBudgetUSD(amount float64) *Runner

WithDailyBudgetUSD installs the policy rail checked immediately before each claim. Zero is unlimited and preserves the old scheduling path.

func (*Runner) WithExpand

func (r *Runner) WithExpand(expand ExpandFunc) *Runner

WithExpand installs the claim-time division. Nil (the default) is today's behaviour: every claimed node goes to a worker whole.

func (*Runner) WithGovernor

func (r *Runner) WithGovernor(governor *executor.Governor) *Runner

WithGovernor replaces the shared host gate. Production uses the process-wide one so every runner in this process reads the same machine.

func (*Runner) WithServiceConsentGrace

func (r *Runner) WithServiceConsentGrace(grace time.Duration) *Runner

WithServiceConsentGrace is primarily a deterministic test seam; production uses the named bounded default above.

func (*Runner) WithStaleAge

func (r *Runner) WithStaleAge(age time.Duration) *Runner

WithStaleAge sets how long a claim may sit SILENT before the tick reaper returns the node to pending. Callers that know their longest possible leaf deadline set it just above it; the default (staleClaimAge) covers jobs with no deadline to compare against.

type Satisfier

type Satisfier interface {
	Satisfied(ctx context.Context, criterion plan.Done, landed []plan.Landed, inflight []plan.Spec) (plan.Satisfaction, error)
}

Satisfier answers the positive stopping question. It is an interface rather than a direct call into the plan package because the graph layer must not need a provider client to be tested, and because a build with no client at all — every test in this package — must behave exactly as it did before the gate existed.

func SatisfierFor

func SatisfierFor(client plan.Completer, contextTokens int) Satisfier

SatisfierFor binds a planning client, and the window that client reads through, to the seam. Zero tokens is unknown and clips the gate's tables exactly where they were clipped before any of this existed.

The window is bound once with the client rather than read per call, because it decides how much of the landed table each row carries and that table is this call's cache prefix: a number that moved between two asks about the same job would move the prefix with it.

The call's usage is dropped rather than threaded back: it is one small call against a refused round's full replan plus the leaf that round would have spawned, and the paths that grow a job mid-run have no accounting slot to return it through. What it costs is visible where every other plan call's cost is, under the job's own spend node.

type SatisfierFunc

type SatisfierFunc func(ctx context.Context, criterion plan.Done, landed []plan.Landed, inflight []plan.Spec) (plan.Satisfaction, error)

SatisfierFunc adapts a plain function to the seam.

func (SatisfierFunc) Satisfied

func (f SatisfierFunc) Satisfied(ctx context.Context, criterion plan.Done, landed []plan.Landed, inflight []plan.Spec) (plan.Satisfaction, error)

Satisfied calls the function.

type ScopeAliasJudgment

type ScopeAliasJudgment struct {
	Merge     bool   `json:"merge"`
	Canonical string `json:"canonical"`
}

ScopeAliasJudgment is the consolidator's one taxonomy decision. Canonical is empty for keep-separate and one member of the candidate pair for merge.

type ScopePair

type ScopePair struct {
	First  string
	Second string
}

ScopePair is one cheap taxonomy candidate offered to consolidation. Both names have the same gardenable prefix and are still canonical shelves.

type SentinelFunc

type SentinelFunc func(ctx context.Context, prompt SentinelPrompt) (SentinelVerdict, error)

SentinelFunc makes exactly one cheap model call for a reserved wake.

type SentinelPrompt

type SentinelPrompt struct {
	CharterID    string
	Invariant    string
	SentinelHint string
	Watch        store.WatchSpec
	Evidence     string
	// Previous is what this sentinel decided at its last few wakes and what
	// became of each decision, newest first. For a poll charter the evidence is
	// the constant condition string, so without this the call is byte-identical
	// every wake — a firing the user has already declined is judged the same
	// way again an hour later, and again, forever.
	Previous []string
	// Voice is the learned speech contract, assembled here rather than at the
	// surface because the notebook belongs to the resident. The sentinel's line
	// is read by the user, so it is subject to the same learned preferences as
	// anything else that speaks; an empty notebook leaves it empty and the
	// prompt byte-identical.
	Voice string
}

SentinelPrompt is the complete bounded judgment made at one durable wake.

type SentinelVerdict

type SentinelVerdict struct {
	Yes  bool
	Line string
}

SentinelVerdict is deliberately tiny: yes/no plus the one-line reason the charter journal keeps.

type ServiceRuntime

type ServiceRuntime interface {
	IdentityMatches(pid int, startedAt time.Time) (bool, error)
	Healthy(context.Context, store.Service) error
	Start(store.Service) (pid int, startedAt time.Time, err error)
	Stop(pid int, startedAt time.Time) error
}

ServiceRuntime is the fakeable platform membrane for health, process identity, detached restart, and group stop.

type ServiceSupervisor

type ServiceSupervisor struct {
	// contains filtered or unexported fields
}

ServiceSupervisor owns journaled services. It creates no goroutines: Tick, Stop, and Restart finish their bounded process work synchronously.

func NewServiceSupervisor

func NewServiceSupervisor(graph *store.Store) *ServiceSupervisor

func (*ServiceSupervisor) Restart

func (supervisor *ServiceSupervisor) Restart(id string) error

func (*ServiceSupervisor) SetAutoRestart

func (supervisor *ServiceSupervisor) SetAutoRestart(id string, enabled bool) error

func (*ServiceSupervisor) Stop

func (supervisor *ServiceSupervisor) Stop(id, reason string) error

func (*ServiceSupervisor) Tick

func (supervisor *ServiceSupervisor) Tick(ctx context.Context) error

func (*ServiceSupervisor) WithRuntime

func (supervisor *ServiceSupervisor) WithRuntime(runtime ServiceRuntime) *ServiceSupervisor

type Shortfall

type Shortfall struct {
	Unexercised int
	Red         int
	// Lost is how many public names the newest symbol-level reading says the
	// finished tree no longer spells. It is the check roster's sibling and it
	// belongs here for the same reason: a round that put back eight deleted
	// public attributes moved the work whatever the check-level row said, and
	// on igel s11 the check-level row said the tree had got BETTER on the run
	// that deleted them. store.SurfaceReading is the reading; nothing here
	// re-derives it.
	Lost int
	// Standing is the review finding that is still open, as a digest. Empty is
	// a job with nothing standing against it.
	Standing string
}

Shortfall is the job's own account of what it is still short of, as counts a later round can be weighed against.

MOVING A FILE IS NOT THE ONLY WAY TO MOVE THE WORK. A round that closed a regression, brought a stated behaviour under a check, or answered a standing review finding has made progress even where the focus gained nothing — so the evidence the governor reads is the union of the two, and a rule that read only the tree would refuse the round after the one that finally started working.

It is counts and a digest rather than the findings themselves because every comparison made of it is a FALL: fewer unexercised behaviours, fewer red checks, a finding that stood and now does not. A shortfall REWORDED is not a shortfall closed, which is the distinction the remainder digest already draws one rule along.

func ReadShortfall

func ReadShortfall(graph *store.Store, lineage string) Shortfall

ReadShortfall reads it off one lineage's own journal, through the same account of the record every brief is composed from.

type SkillCandidate

type SkillCandidate struct {
	Artifact string
}

SkillCandidate names the artifact directory a job proved useful. It remains a belief until recurrence and an executable self-test promote it.

type StandingWatch

type StandingWatch interface {
	Install(ctx context.Context) error
	// Uninstall is the reverse gear. A consent the product accepts and cannot
	// give back is not consent, and the timer repairs itself against a manual
	// `launchctl unload` every five minutes, so the only honest off-switch is
	// one the resident itself performs after journalling the decision.
	Uninstall(ctx context.Context) error
	Status() (watchdog.Status, error)
}

StandingWatch is the small consequence-facing seam the resident needs. watchdog.Manager implements it; tests inject an in-memory recorder.

type TasteStanding

type TasteStanding struct {
	Scope string
	// For counts the corrections behind the rule plus every "this is what I
	// meant"; Against counts every "keep it this way".
	For     int
	Against int
	// KeepsSince counts only the refusals that landed after the rule's current
	// standing was recorded, which is what a demotion may act on.
	KeepsSince int
	// Confidence is For/(For+Against) shrunk toward the neutral prior by the
	// same n/(n+8) rule every other sensor in the store is judged by.
	Confidence float64
}

TasteStanding is one shelf's evidence, derived rather than stored: the corrections that still say the rule, the answers that agreed, and the answers that did not. Rebuild replays the facts and the questions; this recomputes.

func TasteStandingOf

func TasteStandingOf(graph *store.Store, rule store.Fact) (TasteStanding, error)

TasteStandingOf projects one rule's evidence. The rule's own line is never its own evidence, and a superseded standing's verdicts still count — they belong to the shelf, not to the row that happened to hold it.

type TerritoryDigestFunc

type TerritoryDigestFunc func(ctx context.Context, title string, jobs []TerritoryDigestJob, voice string) (string, error)

TerritoryDigestFunc writes the one model-authored map for a territory. Clustering, naming, membership, and hierarchy are all deterministic Go.

The voice contract arrives as an argument rather than being fetched by the writer, because the notebook belongs to the resident and this is the only surface that speaks without a store handle of its own. Empty on an empty notebook, which keeps the prompt byte-identical to what it was before any preference was learned.

type TerritoryDigestJob

type TerritoryDigestJob struct {
	ID       string
	Title    string
	Ask      string
	Outcome  string
	Pointers []string
}

TerritoryDigestJob is the bounded evidence supplied for one member of a territory digest. Pointers retain the route to its durable artifacts.

type TitleFunc

type TitleFunc func(ctx context.Context, goal string) (string, error)

TitleFunc compresses one goal into a few display words. It is a chat-surface nicety: headless runs never construct a reconciler, so they never pay for it.

type WatchPass

type WatchPass struct {
	Examined  int
	Woken     int
	Checked   int
	Fired     int
	Proposed  int
	No        int
	Errors    int
	Quota     int
	Expired   int
	RailWaits int
}

WatchPass reports what one reconciler or `codeaf wake` pass decided.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL