@flow-state-dev/harness-manager/checkout
Interfaces
CheckoutLease
A held checkout. Release it on every exit from the attempt that took it.
Properties
lockPath
lockPath: string;
The lock file this acquisition created.
token
token: string;
A token written INTO that lock file, unique to this acquisition. A value, so the lease can live in the run's own state and be released from there, and what stops a displaced holder from releasing its replacement's lock.
RunLocation
Everything that makes one run's state distinct from another's.
One object rather than four positional strings, deliberately. Every field here is an isolation boundary, and adjacent string parameters are exactly the shape that lets a transposed call compile and silently resolve the wrong tree — which is the failure this type exists to make impossible.
Properties
branchPrefix?
branchPrefix?: string;
What the run's branch starts with (branchFor): the app's own, such
as teammates/, else DEFAULT_BRANCH_PREFIX. A run found from its
record keeps the prefix its branch was cut with. Not part of the run's
identity: two runs that differ only here are the same run.
bump?
bump?: number;
Which free spelling of the name the run took (freeRunLocation):
absent for the first, 1 for -2, and so on. Read back from the record.
epic
epic: string;
The board's own discriminator — one epic's collection identity.
D-4 partitions the board by it because the board is a claim pool. It has to
reach here too: runs/** is one collection EVERY epic writes, so without it
two epics driving the same issue-phase resolve one run topic, one checkout
and one branch. That is obligation B across boards — two live attempts, one
tree — and partitioning the topic while leaving the path shared would fix
the report and keep the overwrite.
issue
issue: string;
nested?
nested?: true;
Derive the place and branch in the long shape every run had before runs were named: the principal, board and issue-phase as nested segments, with full digests. Only for a run whose record already names that branch (locationFor decides), so a run under way keeps its tree. Implied by orgless. Never set it for a new run: its ref can pass GitHub's 255-byte limit, and the push is refused.
orgless?
orgless?: true;
Derive the place and branch without the organization, as they were derived before it was part of them. Only for a run whose record already names that branch (locationFor decides), so a run under way when the derivation changed keeps its tree, its commits and its uncommitted work. Never set it for a new run: it is the shape in which two organizations share one checkout.
phase
phase: string;
principal
principal: RunPrincipal;
slug?
slug?: string;
The name's slug exactly as the run's record names it, so a run found again keeps it whatever its title says now. Set by locationFor.
title?
title?: string;
The task's title as filed, which the run's name is a slug of (runName). A run found from its record takes its name from the branch the record names, so a retitle never moves a tree.
trackerIssue?
trackerIssue?: string;
The tracker issue the run's task names, on a board read from the claim, where issue is the row's own id. It leads the branch's leaf so the branch says what it is for; the checkout path and run topic never read it, so a record is found where it always was. locationFor leaves it off for a run whose record names the branch without it.
RunOptions
Properties
cwd
cwd: string;
env?
env?: Record<string, string>;
Variables to set on the child. It never inherits this process's whole
environment: it starts from WORKSPACE_BASE_PASS and pass (see
./child-env), and these are set over them, unfiltered: a credential
named here reaches the child whatever pass says.
gitCredentials?
gitCredentials?: boolean;
Pass the host's GIT_CONFIG_KEY_<n> pairs that can carry a credential
(http.*, credential.*, url.*, remote.*). Set only on the host's remote calls,
beside HOST_REMOTE_PASS; without it those pairs are dropped.
input?
input?: string | Uint8Array<ArrayBufferLike>;
Written to the process's standard input, which is then closed.
maxBuffer?
maxBuffer?: number;
onLine?
onLine?: (line) => void;
Each line of standard output, as it arrives, without its \n. Given,
the output is handed over line by line and never buffered, so
maxBuffer does not apply and the result's stdout is empty.
Parameters
line
string
Returns
void
pass?
pass?: readonly string[];
Names the child may see from this process's environment beyond
WORKSPACE_BASE_PASS: HOST_GIT_PASS for the host's own git,
HOST_REMOTE_PASS for its remote calls. Nothing else of the host's is
passed.
signal?
signal?: AbortSignal;
Cancellation, where interrupting is safe. Never passed on a call that
makes a worktree: a worktree add killed halfway leaves a tree the next
provision has to disentangle. A listing that writes nothing has no such
problem.
timeoutMs
timeoutMs: number;
The wall clock, in milliseconds. execFile sends SIGTERM when it
elapses and the promise rejects, so the caller sees a failure rather than
a hang.
RunPrincipal
Who a run belongs to. Every field comes from the request's resolved identity, never from anything a caller supplies in a body.
Properties
orgId
orgId: string;
The organization the request was admitted under: the verified one, never a caller-supplied value. One person works in several organizations, and the filesystem and git do not partition by organization the way the run record does, so without it two of their runs on one host share a tree.
tenantId?
tenantId?: string;
The tenant, on a multi-tenant deployment.
userId
userId: string;
The authenticated user.
Variables
CHECKOUT_CLEANUP_TIMEOUT_MS
const CHECKOUT_CLEANUP_TIMEOUT_MS: 60000 = 60000;
Undoing a checkout a provision just made and is refusing: worktree prune
and branch -D, local bookkeeping that takes milliseconds.
Its own budget rather than the provision's, because the case it exists for is that budget running out. A caller holding a lock across provisioning has to count it in the longest it can hold that lock.
GIT_TIMEOUT_MS
const GIT_TIMEOUT_MS: 600000 = 600000;
Git that talks to a remote. Minutes rather than seconds, because a first fetch of a large repository is genuinely slow.
NETWORK_CALL_TIMEOUT_MS
const NETWORK_CALL_TIMEOUT_MS: 60000 = 60000;
How long a call that answers over the network may take.
Bounds the phase's own hooks (the prompt builder, the completion check) and
any listing a host's phase makes with gh: generous for a slow API, far
short of a coding run's own deadline, so the verdict is never the thing that
hangs. harnessDrainBudgetMs reserves it twice.
Every child process this package's callers start goes through
@flow-state-dev/workspace's run; this is the one wait of their own that
the manager sizes.
Functions
acquireCheckout()
function acquireCheckout(
checkoutPath,
owner,
bounds,
now?,
signal?
): Promise<CheckoutLease>;
Take exclusive ownership of a checkout for the whole attempt — waiting for it, not failing on it (obligation B).
- Two live attempts never share a tree. A lapsed lease does not stop the attempt that held it, and two coding agents in one checkout corrupt the artifact the run exists to produce.
- Resolving contention never consumes a retry. Every throw out of this
worker spends one, so ordinary contention waits and only exceeding
waitMsthrows — a wedged process, correctly charged.
Held across provisioning AND the run, which is why it is not the workspace
host's own lock (that one is held only while provisioning). Built on the
same lock file mechanism (acquireLock in @flow-state-dev/workspace):
atomic create, a stale steal that re-checks the file it judged, a token
release. No timer refreshes it: the run's events do (refreshCheckout), and
staleAfterMs outlasts the longest a live holder goes between them.
The lock sits BESIDE the checkout, so git worktree add never meets a
non-empty directory. A cancelled signal stops the wait at once.
Parameters
checkoutPath
string
owner
string
bounds
now?
() => number
signal?
AbortSignal
Returns
Promise<CheckoutLease>
assertSafeSegment()
function assertSafeSegment(label, value): string;
@flow-state-dev/harness-manager/checkout — how a run gets a directory.
A separate entry point because these are not the supported contract.
harnessManager({ harness }) plus the construction guards is what this
package promises and versions. Everything here is git-worktree-specific:
provisionCheckout cuts a worktree (through @flow-state-dev/workspace's
host, which runs the git), acquireCheckout takes a lock file beside the
tree, and the path grammar assumes both. A second checkout
strategy — a fresh clone per run, a projected workspace — would put them
behind a seam, and a host that built on them would move with it.
It is a subpath rather than a comment on the main barrel because semver binds
what index.ts exports regardless of what a file header says. Splitting the
entry point is what makes the two halves actually different.
The consumer in this repository and its goal checks import from here. If you are a host, you probably want the main entry.
Parameters
label
string
value
string
Returns
string
branchFor()
function branchFor(location): string;
This issue-phase's branch, for this principal: <prefix><name>
(RunLocation.branchPrefix, runName), or the long shape,
under conductor/, for a run recorded on it.
Carries the principal (in the name's hex) for the same reason the path does, and it is the half that is easier to miss: two users could be given separate directories and still share a branch, at which point one user's commits land on the other's branch and a pull request opened by either can satisfy the other's completion check. Separate trees pushing one ref is not isolation.
Parameters
location
Returns
string
canonicalSegment()
function canonicalSegment(value): string;
The canonical form of an owned segment — the fold, without the grammar check.
Both validators above return this, so anything comparing against a derived
identity has to apply the same fold or the two quietly disagree. It is a
function rather than a .toLowerCase() at each site for the usual reason:
a rule in a function gets imported, a rule at a call site gets copied — and
this one was already spelled out twice here before a third caller needed it.
Separate from the validators because a caller-supplied FILTER is not an identity. A filter that could never be a valid segment simply matches nothing, and throwing on it would turn a query into an error.
Parameters
value
string
Returns
string
checkoutPathFor()
function checkoutPathFor(root, location): string;
This run's checkout directory.
A pure function of the durable task, the authenticated identity, and the epic whose board filed it.
Parameters
root
string
location
Returns
string
encodeSegment()
function encodeSegment(value): string;
Encode an identifier into one path segment. Encode, never validate.
The framework's user and tenant ids are unrestricted strings — auth0|abc
and [email protected] are ordinary values, and neither matches a filesystem
grammar. Validating them would fail every attempt during workspace derivation
and burn the retry budget on a configuration mismatch the run cannot fix.
Worse, a grammar is a rule someone else's identifier space never agreed to,
and enforcing it is a list that is never finished: separators, .., trailing
dots (Windows strips them, so acme and acme. are one directory), reserved
device names, case folding. Encoding removes the list — the output is
injective, so two distinct ids can never share a directory, and its alphabet
contains nothing any filesystem treats specially.
A SHA-256 digest in hex, behind a literal h: h[0-9a-f]{64}, which cannot
spell a reserved device name, cannot end in a dot, and cannot contain a
separator or the identity frame.
A digest and not a reversible encoding, because the output has to be
bounded. Hex of the input doubles it, so a 128-character id — an ordinary
length for an opaque subject claim — produced a 257-character component.
Measured: a filesystem name is refused at 256, and ENAMETOOLONG arrives
from worktree add, which is to say after the row is claimed. Every retry
would then be spent on a length no retry can change. A fixed 65 characters
cannot do that.
The cost is honest: the path no longer says which user it belongs to. What it keeps is the property the derivation actually needs — distinct ids give distinct components — since a SHA-256 collision is not a failure mode this system will meet.
The prefix is load-bearing, not decoration. A bare digest of an empty id
is still a digest, but the prefix keeps the alphabet closed under h[0-9a-f]
for every input including the empty one, and it is what a reader recognises
as "this segment is derived, not typed".
The issue and phase segments stay validated. Those identifiers are ours, the grammar is one we set, and rejecting a malformed issue key is a real signal rather than an imposition.
Parameters
value
string
Returns
string
freeRunLocation()
function freeRunLocation(location, reserve): Promise<RunLocation>;
The location a NEW run takes: its derived name, or the first bumped one
(-2, -3, …) that reserve holds for this run. A host's reservation is
atomic, so two runs whose names collide while neither has a checkout yet
still get different names, and it names its holder, so a crash before the
run records its branch takes the same name again. Ask it only for a run
whose record names no branch; a recorded run is found with locationFor.
Parameters
location
reserve
(candidate) => Promise<boolean>
Returns
Promise<RunLocation>
harnessTaskId()
function harnessTaskId(issue, phase): string;
This issue-phase's board task id — stable, so seed is idempotent.
Built from the same validated segments the checkout path and branch are, for the same reason: the value lands in the ledger's key space, and a separator or a traversal there is the identical class of problem it would be in a path.
Parameters
issue
string
phase
string
Returns
string
isStrictlyInside()
function isStrictlyInside(candidate, root): boolean;
Is candidate a strict descendant of root? Compared by path segments,
so a Windows separator and a root of / both work, and the root itself is
not inside itself — a clear aimed at the root would take every checkout.
Parameters
candidate
string
root
string
Returns
boolean
joinIdentity()
function joinIdentity(...parts): string;
Join identity components into one string, injectively.
Every component reaching here is already frame-free — an owned one by
grammar, an opaque one by encoding — so the join is reversible and two
distinct component tuples can never collide. Use this for every derived
identity. A literal prefix is an ordinary component: it must be frame-free
too, which is why conductor-tasks is spelled with a single dash.
Parameters
parts
...string[]
Returns
string
locationFor()
function locationFor(location, recordedBranch): RunLocation;
The location a run works at, given the branch its run record already names.
A run first opened before the organization was part of the derivation has that older branch on its record, and keeps it: deriving afresh would cut a new tree from the base and leave the run's work behind. Every other run, a new one included, derives with the organization.
Reading the record here is safe as an isolation matter because the record is user-scoped, which the framework keeps per user AND organization: another organization's run never reads this one's record, so it never inherits the older place through it.
Parameters
location
Omit<RunLocation, "orgless" | "nested" | "bump" | "slug">
recordedBranch
string | null | undefined
Returns
provisionCheckout()
function provisionCheckout(
host,
answer,
location
): Promise<Checkout>;
Give this issue-phase a checkout from host, or hand back the one the last
attempt left.
Provisioned through the workspace host (@flow-state-dev/workspace), which
runs every git command: idempotent, never resets, forces or discards work,
one budget for the whole operation (the host's provisionTimeoutMs), and a
checkout whose branch was deleted or that was cut from another repository is
refused rather than recreated. A checkout a run switched to another branch is
moved back onto the run's branch, keeping what the run made on the other, so
the attempt commits where the prompt says. One left there with uncommitted
changes is refused (checkout-moved): those changes are the run's to commit,
stash or discard. For a host built by localRepoWorkspaceHost, the checkout
is exactly checkoutPathFor's path under the host's root and the
branch lives in its repository.
Parameters
host
WorkspaceHost
answer
RunSourceAnswer
location
Returns
Promise<Checkout>
releaseCheckout()
function releaseCheckout(lease): void;
Release a checkout lease — the one place a lock this process took is removed, called from every exit. Never unlinks a lock that is not this acquisition's. Synchronous and idempotent.
Parameters
lease
CheckoutLease | undefined
Returns
void
run()
function run(
file,
args,
options
): Promise<{
stderr: string;
stdout: string;
}>;
Run file with args, resolving with its output or rejecting on a non-zero exit.
Parameters
file
string
args
string[]
options
Returns
Promise<{
stderr: string;
stdout: string;
}>
runIdentityKey()
function runIdentityKey(location): string;
The whole digest a run's name hash is cut from: the same for every attempt of
one run and different for any other run, however its name comes out. What a
host's reserve records as a name's holder, so two runs whose 6 hex collide
still tell each other apart.
Parameters
location
Returns
string
runName()
function runName(location): string;
A run's name: a slug of the task's title (or of its issue-phase, when the
title has none), led by the tracker issue when the task names one, then 6 hex of its identity, then -<n> when it was bumped.
The branch is <prefix><name> and the folder is <root>/<name>, so
refs/heads/<prefix><name> is at most 81 bytes however deep the run's
identity is.
Parameters
location
Returns
string
sameSegment()
function sameSegment(a, b): boolean;
Do two spellings name the same owned segment?
The comparison, not the fold, is what call sites keep getting wrong.
canonicalSegment existed and the sites that needed it still wrote
a !== b — because applying the fold is a step somebody has to remember,
and remembering is what fails. So the comparison itself is the exported
thing, and there is no correct-looking way to write it by hand.
The cost of a raw comparison is not cosmetic. Identity derivation folds, so
implement and IMPLEMENT are ONE task, one checkout and one branch — but a
guard comparing raw strings calls them different. The two disagree only after
a row has been claimed, so the row is charged an attempt for a mismatch its
own identity says does not exist, once per wake, until the budget is gone.
Parameters
a
string
b
string
Returns
boolean
tenantSegment()
function tenantSegment(tenantId): string;
One tenant, as one identity component. Presence is tagged, never defaulted.
t0 for an untenanted request, t1<digest> for a tenanted one — so an
absent tenant and a tenant named like whatever placeholder someone picks
can never produce the same component.
This exists as a shared function because collapsing absence into a value is a
bug that was fixed here and then reintroduced one file away: the board's
identity used ?? "single-tenant", which made a real tenant called
single-tenant indistinguishable from no tenant at all. Same user id, same
user-scoped board, each able to claim the other's rows — while THIS function
kept them in different checkouts, so a task could execute and report against
a tree that was not its own.
Absent and "single-tenant" are different facts. The type carries that
(string | undefined), and every derivation reads it through here.
Parameters
tenantId
string | undefined
Returns
string
worktreeNameFor()
function worktreeNameFor(location): string | undefined;
The name a run's worktree carries in the worktrees resource: the run's own
name, so the entry, the branch and the folder read alike. undefined for a
run on the long shape, whose entry keeps the name the host gives it.
Parameters
location
Returns
string | undefined