@flow-state-dev/workspace
Classes
HeldWorkMismatchError
The run's held work disagrees with its record, or this host cannot use it.
Not a WorkspaceRefusedError: a refusal will not clear on a retry, while a mismatch waits for a person to decide. Nothing held is changed when this is thrown.
Extends
Error
Constructors
Constructor
new HeldWorkMismatchError(field, message): HeldWorkMismatchError;
Parameters
field
message
string
Returns
Overrides
Error.constructor
Properties
cause?
cause?: unknown;
Inherited from
Error.cause
field
readonly field: HeldWorkMismatchField;
message
message: string;
Inherited from
Error.message
name
name: string;
Inherited from
Error.name
stack?
stack?: string;
Inherited from
Error.stack
PlaceUnreadableError
The place could not be listed, so the flush decided nothing.
The one failure a flush can reject with that a caller may safely swallow: nothing was read, nothing was written, and the run's files are still where the run left them. Every other rejection — a collection read, a write, a delete — means the opposite, that work did not reach the store, and a caller catching both alike reports success for a run whose files went nowhere.
Thrown only by flush, and only for Place.list.
Extends
Error
Constructors
Constructor
new PlaceUnreadableError(message, options?): PlaceUnreadableError;
Parameters
message
string
options?
cause?
unknown
Returns
Overrides
Error.constructor
Properties
cause?
cause?: unknown;
Inherited from
Error.cause
message
message: string;
Inherited from
Error.message
name
name: string;
Inherited from
Error.name
stack?
stack?: string;
Inherited from
Error.stack
WorkspaceRefusedError
The host would not provision this run, and says why — before any agent was paid for. Nothing was created, and an existing checkout was left exactly as it was.
reason is stable: "invalid-remote", "remote-not-allowed",
"remote-unreadable", "base-diverged" (a repository on this machine
whose base and its upstream each have commits the other lacks),
"checkout-moved" (the run's checkout is off the run's branch and is
mid-way through a merge, rebase or similar, or the run's branch is checked
out in another worktree), or
whatever reason a run source refused with. A caller should fail the run
with it rather than retry: none of these clears by itself, and the message
says what clears it. base-diverged clears once someone pulls or rebases,
or pushes, there; checkout-moved once someone does what its message names
in the checkout.
Extends
Error
Constructors
Constructor
new WorkspaceRefusedError(reason, message): WorkspaceRefusedError;
Parameters
reason
string
message
string
Returns
Overrides
Error.constructor
Properties
cause?
cause?: unknown;
Inherited from
Error.cause
message
message: string;
Inherited from
Error.message
name
name: string;
Inherited from
Error.name
reason
readonly reason: string;
stack?
stack?: string;
Inherited from
Error.stack
Interfaces
AcquireOptions
How one acquisition waits. All optional.
Properties
now?
now?: () => number;
The clock. Injectable so a wait's arithmetic can be tested.
Returns
number
owner?
owner?: string;
Who holds it, written into the lock file for a person reading it.
signal?
signal?: AbortSignal;
Stop waiting when this aborts. Checked before the first create and woken by the sleep itself, so a cancelled waiter neither takes the lock nor waits out a poll interval. Interrupting the wait is safe: nothing has been made yet.
what?
what?: string;
What the lock guards, for the error a waiter gives up with. Defaults to the lock's path.
BranchPullRequestsContext
What the check reads off a block's context.
Properties
request?
readonly request?: object;
identity
readonly identity: object;
identity.id
readonly id: string;
resources?
readonly resources?: unknown;
response?
readonly response?: unknown;
The request's response: the check waits for its in-turn recorder's writes before writing.
CheckoutCommandResult
What one command did.
Properties
command
command: string;
The command, as it was written.
durationMs
durationMs: number;
How long it ran, in milliseconds. 0 when skipped.
exitCode
exitCode: number | null;
Its exit code; null when it was stopped or never ran.
skipped
skipped: boolean;
The wall clock had run out before its turn, so it never ran.
tail
tail: string;
The end of its standard output and standard error, together, colour codes removed.
timedOut
timedOut: boolean;
The wall clock ran out while it ran, and it was stopped.
ClaimRegistry
Methods
claim()
claim(key, holder): symbol;
Claim key for holder.
Returns the CURRENT holder either way: holder itself when the claim is
granted or already held, somebody else when it is refused. Returning the
holder rather than a boolean is what lets a refusal name who is writing
instead of only that somebody is.
Parameters
key
string
holder
symbol
Returns
symbol
heldBy()
heldBy(key): symbol | undefined;
Who holds key, if anyone. For assertions and diagnostics.
Parameters
key
string
Returns
symbol | undefined
releaseAll()
releaseAll(holder): void;
Drop every claim holder holds.
Parameters
holder
symbol
Returns
void
ExistingPullRequest
The pull request already open from a run's branch, as existingPullRequest finds it.
Properties
branch
readonly branch: string;
The branch it is open from: the run's own, or the one its checkout is on (see LandTarget.baseCommit).
number
readonly number: number;
url
readonly url: string;
The pull request's web link.
FilesRunSource
The run has no repository: its working directory is the kept files, hydrated before the run and saved back after.
Properties
files
files: RunFiles;
kind
kind: "files";
projectId
projectId: string;
The key prefix of this run's files in files.collection.
FlushReport
Everything one flush decided.
Properties
conflicts
conflicts: readonly object[];
The conflicted subset, so a caller need not filter to find the bad news.
contested
contested: readonly object[];
Paths another live projection is writing. See the contested outcome.
outcomes
outcomes: readonly FlushOutcome[];
Every path the flush reached, in the order it reached them.
HeldWork
One hold: what checkpoint wrote, for the caller to record.
Properties
base
base: string;
The commit the run's branch was cut at.
bytes
bytes: number;
The pack's size in bytes.
head
head: string;
The branch's commit when the hold ran.
key
key: string;
The store key of the pack.
sha256
sha256: string;
The pack's sha256, hex.
skipped
skipped: SkippedPath[];
Paths left out of the snapshot.
snapshot
snapshot: string;
The snapshot commit: the working tree, on top of head. Content-addressed.
unchanged
unchanged: boolean;
true when the snapshot equals the one the caller passed in: nothing was
written, and the record should not change.
HeldWorkStore
Where held work goes: one object per key, put, read, deleted and listed.
The operator wires one on the host. fileHeldWorkStore is the shipped default; an adapter over S3, R2 or Vercel Blob is a few lines.
Two rules every implementation keeps:
putis atomic. A reader sees the whole object or none of it, never a partly written one. A machine that dies mid-hold must leave the run's last good pack readable, and the record still names that one.- Deleting a missing key does nothing. It resolves.
Methods
delete()
delete(key): Promise<void>;
Remove key. Resolves when it is already gone.
Parameters
key
string
Returns
Promise<void>
get()
get(key): Promise<Uint8Array<ArrayBufferLike> | undefined>;
The bytes under key, or undefined when there are none.
Parameters
key
string
Returns
Promise<Uint8Array<ArrayBufferLike> | undefined>
list()
list(prefix): Promise<string[]>;
Every key under prefix, keys only.
Parameters
prefix
string
Returns
Promise<string[]>
put()
put(key, bytes): Promise<void>;
Store bytes under key, replacing anything there. Atomic.
Parameters
key
string
bytes
Uint8Array
Returns
Promise<void>
HostPlace
What a projection needs from wherever it puts files. Three operations, and
deliberately not a Sandbox: the projection never executes a command,
so a place that cannot run one is a first-class place rather than a
degraded one.
list is the operation that decides whether a flush may proceed at all, so
its failure mode is load-bearing: an unreadable place must throw, never
return an empty list. A flush that reads "no files" from a broken place
and believes it would delete the collection's entire contents — which is
precisely how the machinery this replaces lost data.
Extends
Properties
root
readonly root: string;
The absolute directory every projected path is resolved against.
Methods
list()
list(prefixes): Promise<readonly string[]>;
Every path the place currently holds under any of prefixes.
Throws if the place cannot be read. Returning [] asserts the place is
readable and empty, which a flush acts on by deleting.
Parameters
prefixes
readonly string[]
Returns
Promise<readonly string[]>
Inherited from
read()
read(path): Promise<string | null>;
The content at path, or null if the place does not hold it.
Parameters
path
string
Returns
Promise<string | null>
Inherited from
write()
write(path, content): Promise<void>;
Put content at path, creating any intermediate structure.
Parameters
path
string
content
string
Returns
Promise<void>
Inherited from
IgnoredDirectory
A directory inside the checkout that git must never commit — somewhere the caller writes files of its own, such as a question a run asks.
Provisioning refuses a checkout whose repository tracks a guarded file there
or does not ignore the directory, before any worker runs. Refused rather than
fixed: the rule belongs in the repository's own .gitignore, which is the
operator's file.
Properties
dir
dir: string;
The directory, relative to the checkout, /-separated.
guards?
guards?: (gitPath) => boolean;
Which tracked paths under dir (as git ls-files prints them) are the
caller's files. A tracked sibling the caller never writes is harmless.
Omitted: every tracked path under dir.
Parameters
gitPath
string
Returns
boolean
rule
rule: string;
The .gitignore line that satisfies the check, named in the refusal.
why
why: string;
One sentence saying what the caller writes there, for the refusal.
LandTarget
The run whose work lands: its checkout and branch, and the ref it was cut from.
Properties
baseCommit?
readonly baseCommit?: string | null;
The commit the run's branch was cut at. When the run's branch is gone
(the run renamed it, or moved its work to a branch of its own), the
branch the checkout has checked out is landed instead, but only when it
holds commits over this one, no pull request open from it is someone
else's (see ownPullRequests), and, with none of the run's open
from it, the remote doesn't have it yet. A merge takes it only when the
run's branch was renamed to it in the run's checkout, and refuses it
moved-branch otherwise. Absent: a gone branch is refused.
baseRef?
readonly baseRef?: string | null;
The ref the run's branch was cut from, as its place recorded it. Absent
or "HEAD": the branch the repository's own checkout is on now.
branch
readonly branch: string;
The run's branch.
cwd
readonly cwd: string;
The run's checkout.
ownPullRequests?
readonly ownPullRequests?: readonly string[] | null;
The pull requests known to be the run's own, by pullRequestKey. Read
only when the run's branch is gone and the branch its checkout is on is
pushed instead: a pull request open from that branch that isn't one of
these may be someone else's, so nothing is pushed and the landing is
refused foreign-pull-request. Absent: none is.
ListedWorktree
One worktree a host holds, as WorkspaceHost.list reports it.
Properties
branch
branch: string | null;
The branch checked out; null for a detached HEAD.
cwd
cwd: string;
The worktree's directory.
dir
dir: string;
The place's directory.
dirty
dirty: boolean | null;
Whether it holds uncommitted or untracked changes; null when its directory is gone.
head
head: string | null;
The commit checked out; null when git could not say.
place
place: readonly string[];
The place's segments under the root, as a PlaceRequest names them.
repository
repository: string;
The repository it is a worktree of: a clone under the root, or a listed repository.
LocalRepoWorkspaceHostOptions
Options for localRepoWorkspaceHost.
Extends
Pick<LocalWorkspaceHostOptions,"root"|"setup"|"pullRequestRepo"|"provisionTimeoutMs"|"now">
Properties
baseRef?
baseRef?: string;
The ref a new branch is cut from. Absent, the repository's HEAD.
now?
now?: () => number;
The clock the provision budget is measured on. For tests.
Returns
number
Inherited from
provisionTimeoutMs?
provisionTimeoutMs?: number;
How long one whole provision may take, every git command in it included, in milliseconds. Defaults to ten minutes. A caller that holds a lock across provisioning reads it as the longest provisioning can hold it.
Inherited from
LocalWorkspaceHostOptions.provisionTimeoutMs
pullRequestRepo?
pullRequestRepo?: (url) => string | undefined;
The GitHub repository (host/owner/name) a listed repository's pinned
remote URL names, for land's pull request. Default: read from a
GitHub-shaped URL (https://github.com/owner/name.git,
[email protected]:owner/name.git); undefined offers no pull request.
Parameters
url
string
Returns
string | undefined
Inherited from
LocalWorkspaceHostOptions.pullRequestRepo
repo
repo: string;
The repository every run is cut from. Resolved to an absolute path here, because the host reads only an absolute path as a repository on this machine; a relative one would be judged a remote and refused.
root
root: string;
The host directory every clone and place lives under.
Inherited from
LocalWorkspaceHostOptions.root
setup?
setup?: WorkspaceSetup;
A command run in each repository checkout this host makes, before it is
handed over: { command: ["pnpm", "install", "--frozen-lockfile", "--prefer-offline"] }, say. Absent by default, and then nothing runs.
It runs once per fresh checkout, and again on the next provision until it
exits 0. It is the last step of the provision and draws from its one
budget, so raise provisionTimeoutMs to cover it. A failure doesn't fail
the provision: the checkout is handed over with place.setup saying what
went wrong. A place with no repository runs nothing. See ./setup.
Inherited from
LocalWorkspaceHostOptions.setup
LocalWorkspaceHostOptions
Properties
heldWork?
heldWork?: HeldWorkStore;
Where a run's held work goes. Absent by default, and then holding is off:
checkpoint returns null and starts no process, and provision does
what it always did, except that it rejects a recorded hold it cannot use
(HeldWorkMismatchError, field: "disabled").
With a store, a repository run cut from a remote whose source names a
heldPrefix is held at each checkpoint, and rebuilt from it by
provision on any host sharing the store.
localRepositories?
localRepositories?: readonly string[];
Repositories on this machine that runs are cut from directly, as their
absolute paths. A source answering one of these paths as its repo gets a
worktree of that repository itself: no clone, and the run's branch kept
in it. When the source names no kept files, the place's directory is the
checkout; when it names them, the worktree is the place's checkout/ and
the files are in project/ beside it.
A NEW branch whose base tracks an upstream is cut from the newer of the
two, after fetching that one upstream branch into its tracking ref; a
base and upstream that have each moved are refused as base-diverged,
and a fetch that fails or is skipped starts the run from the local base,
with a warning. Listing a path admits fetching its own upstream:
remotes.allow isn't asked, though the URL is still judged for shape
before git sees it. Each listed path's remote URLs and branch upstreams
are pinned in <root>/.fetch-pins/ the first time a host start sees
them, and kept across restarts; a remote whose URL has changed since (a
run shares the repository's config) is not fetched, with a warning that
names the pin file to delete to accept the change, and the fetch obeys
no program-running setting in the repository's own config.
A run in a listed repository acts with the operator's own trust: it can move the repository's branches and refs as they can. Keep a run that must not do that in a separate clone, not in this list.
Any other bare path is still refused. Listing a path is the operator's
allowance, judged before any git process, the same as remotes.allow.
now?
now?: () => number;
The clock the provision budget is measured on. For tests.
Returns
number
provisionTimeoutMs?
provisionTimeoutMs?: number;
How long one whole provision may take, every git command in it included, in milliseconds. Defaults to ten minutes. A caller that holds a lock across provisioning reads it as the longest provisioning can hold it.
pullRequestRepo?
pullRequestRepo?: (url) => string | undefined;
The GitHub repository (host/owner/name) a listed repository's pinned
remote URL names, for land's pull request. Default: read from a
GitHub-shaped URL (https://github.com/owner/name.git,
[email protected]:owner/name.git); undefined offers no pull request.
Parameters
url
string
Returns
string | undefined
remotes
remotes: object;
The remotes this host may reach. allow lists hosts, reached over
https or ssh, and may include "file" to permit file:// remotes.
pass names more variables of the host's environment that its remote
calls (fetch, push, ls-remote, gh) may see, beyond the GitHub, ssh,
TLS and proxy ones they always get: the ones a credential helper reads,
such as AWS_ACCESS_KEY_ID for CodeCommit's. Names only; no local git
call, setup command or check ever sees them.
allow
allow: readonly string[];
pass?
pass?: readonly string[];
root
root: string;
The host directory every clone and place lives under.
setup?
setup?: WorkspaceSetup;
A command run in each repository checkout this host makes, before it is
handed over: { command: ["pnpm", "install", "--frozen-lockfile", "--prefer-offline"] }, say. Absent by default, and then nothing runs.
It runs once per fresh checkout, and again on the next provision until it
exits 0. It is the last step of the provision and draws from its one
budget, so raise provisionTimeoutMs to cover it. A failure doesn't fail
the provision: the checkout is handed over with place.setup saying what
went wrong. A place with no repository runs nothing. See ./setup.
source
source: RunSource;
Where each run's files come from. Kept on the host for its callers to ask.
LockBounds
How a lock is waited on and judged.
Properties
heartbeatMs?
heartbeatMs?: number;
How often a holder refreshes its lock, well under staleAfterMs. Absent:
never, and staleAfterMs has to outlast the longest legitimate hold.
pollMs
pollMs: number;
How often to re-check a held lock.
staleAfterMs
staleAfterMs: number;
A lock not refreshed for this long belongs to a holder that is gone.
waitMs
waitMs: number;
How long to wait for a live holder before failing.
LockLease
A held lock. Hand it to releaseLock on every exit.
path and token are plain values, so a holder can write them down (a
run's own state, say) and release from there; the token is what tells this
acquisition's lock from an identical-looking one a replacement made.
Properties
path
path: string;
The lock file.
timer?
timer?: number;
Stops the refresh, when there is one.
token
token: string;
Written into the lock file; unique to this acquisition.
MemoryPlace
What a projection needs from wherever it puts files. Three operations, and
deliberately not a Sandbox: the projection never executes a command,
so a place that cannot run one is a first-class place rather than a
degraded one.
list is the operation that decides whether a flush may proceed at all, so
its failure mode is load-bearing: an unreadable place must throw, never
return an empty list. A flush that reads "no files" from a broken place
and believes it would delete the collection's entire contents — which is
precisely how the machinery this replaces lost data.
Extends
Methods
breakListing()
breakListing(reason?): void;
Make every subsequent list throw.
The failure a flush must survive without deleting anything, and the one
a place that returned [] on error would hide.
Parameters
reason?
string
Returns
void
list()
list(prefixes): Promise<readonly string[]>;
Every path the place currently holds under any of prefixes.
Throws if the place cannot be read. Returning [] asserts the place is
readable and empty, which a flush acts on by deleting.
Parameters
prefixes
readonly string[]
Returns
Promise<readonly string[]>
Inherited from
read()
read(path): Promise<string | null>;
The content at path, or null if the place does not hold it.
Parameters
path
string
Returns
Promise<string | null>
Inherited from
remove()
remove(path): void;
Remove a path, the way a run deleting a file would.
Parameters
path
string
Returns
void
snapshot()
snapshot(): Record<string, string>;
Everything the place holds, for assertions.
Returns
Record<string, string>
write()
write(path, content): Promise<void>;
Put content at path, creating any intermediate structure.
Parameters
path
string
content
string
Returns
Promise<void>
Inherited from
MergeTarget
What a host's repository is judged against, as mergeTarget reads it.
Properties
commit
readonly commit: string | null;
The commit the git half judges against: the tip of the default branch as
a source no run can write reports it. null when there is none, and the
git half proves nothing.
defaultRef
readonly defaultRef: string;
The default branch that commit is the tip of, for a person (origin/main), or why there is none.
github
readonly github: string | null;
The GitHub repository (host/owner/name) its pinned remote names; null when it names none.
Mount
One collection, projected at one prefix inside the place.
Properties
collection
collection: ResourceCollectionRef<ProjectedEntryState>;
The durable side.
collectionId
collectionId: string;
What this mount's collection IS, durably — the same string for two runs addressing the same rows, a different one for two that only spell their paths alike.
Arbitration is per durable row, and the path cannot name one.
artifacts/report.md is a naming convention, so two sessions writing it
are writing two rows and neither contests the other; one collection
mounted under two prefixes is one row under two paths and both writers
must see each other. Neither case comes out right from a path.
Required rather than defaulted, because every default is wrong for one of those two: omit the scope and unrelated tenants refuse each other's writes, use the collection object and two runs in one session stop arbitrating at all. Derive it from the collection's scope, the resolved id for that scope, and its pattern.
entryState?
entryState?: (key) => ProjectedEntryExtra;
Extra state to stamp on an entry this projection commits, keyed by the entry's own key.
The projection sets path, hash, and updatedAt because it needs them
to do its job, and those values win. Anything else an application shows
about a file — a title, an author — is the application's to add.
Parameters
key
string
Returns
prefix
prefix: string;
Where this collection's entries appear in the place, e.g. "artifacts".
Derived from the collection's pattern by the caller rather than
configured here — discoverMounts in the bash tool already computes it
the same way.
scope?
scope?: string;
Narrow the mount to one key prefix of its collection: "a" addresses the
keys under a/… and nothing else.
Inside the place the scope does not appear — the collection's a/notes.md
sits at <prefix>/notes.md — so the agent sees one owner's files as if
they were the whole collection. Every list, read, write and delete the
projection makes through this mount is keyed under the scope, and the
listing is filtered by the collection itself rather than after the fact:
a mount that listed every key and dropped the rest would still have read
every owner's rows.
A key prefix, not a path: no leading or trailing /, no empty, . or
.. segment. Omit it and the mount addresses the whole collection, as
before.
writable
writable: boolean;
Whether a flush may write back. A read-only mount is hydrated and then left alone — its paths are skipped, never reported as orphans.
MovedBack
A checkout found off its run's branch and moved back onto it.
how says what moved:
"fast-forward": the checkout's commit contained the run's branch, which was moved up to it. No file moved."re-pointed": the run's branch was already at the checkout's commit. No file moved."switched": the checkout's commit lacked some of the run's branch, and it had no uncommitted changes, so the run's branch was checked out as it stands. Files moved; everything the run made is onfrom, or onkeptfor a detached HEAD.
Properties
commit
commit: string;
The commit the run's branch points at now.
from
from: string | null;
The branch the checkout was found on; null for a detached HEAD. Left where it is.
how
how: "fast-forward" | "re-pointed" | "switched";
kept?
kept?: string;
A branch the host made so a detached HEAD's commits are not orphaned:
<run's branch>-detached-<commit>, with -2, -3… when that name is
taken. Only on "switched".
OffBranch
A checkout handed back off its run's branch, as it was found.
Properties
message
message: string;
Why it was left there and what moves it back, in a sentence for a person or a run.
on
on: string | null;
The branch the checkout is on; null for a detached HEAD.
Place
What a projection needs from wherever it puts files. Three operations, and
deliberately not a Sandbox: the projection never executes a command,
so a place that cannot run one is a first-class place rather than a
degraded one.
list is the operation that decides whether a flush may proceed at all, so
its failure mode is load-bearing: an unreadable place must throw, never
return an empty list. A flush that reads "no files" from a broken place
and believes it would delete the collection's entire contents — which is
precisely how the machinery this replaces lost data.
Extended by
Methods
list()
list(prefixes): Promise<readonly string[]>;
Every path the place currently holds under any of prefixes.
Throws if the place cannot be read. Returning [] asserts the place is
readable and empty, which a flush acts on by deleting.
Parameters
prefixes
readonly string[]
Returns
Promise<readonly string[]>
read()
read(path): Promise<string | null>;
The content at path, or null if the place does not hold it.
Parameters
path
string
Returns
Promise<string | null>
write()
write(path, content): Promise<void>;
Put content at path, creating any intermediate structure.
Parameters
path
string
content
string
Returns
Promise<void>
PlaceRequest
Which place a run gets, named by its caller.
Properties
branch?
branch?: string;
The run's own branch. Required for a repository run.
existing?
existing?: boolean;
branch is an existing branch to work on, never one to cut: a pull
request's head, say. The run commits to it as it stands, and the source's
baseRef is not read. A branch the repository lacks is made from the
remote's branch of that name, freshly fetched (in a listed repository,
from origin's pinned URL, and set to track it); with no copy anywhere
the provision is refused, no-such-branch. The place's repo.baseCommit
is the tip it was checked out at.
ignored?
ignored?: IgnoredDirectory;
A directory inside the checkout that the repository must keep out of git. A checkout whose repository tracks the caller's files there, or does not ignore the directory, is refused before it is handed over, and one this call made is removed again.
For a run with no repository, the same directory inside workspace/ is
left out of the kept files: save never writes it to the collection.
onSetup?
onSetup?: () => void | Promise<void>;
Told just before the host's setup command starts in this place's checkout
(LocalWorkspaceHostOptions.setup), so the caller can say the run is
waiting on it. Awaited. Never called when nothing runs.
Returns
void | Promise<void>
place
place: readonly string[];
The place's directory under the root, one segment per level — typically
whatever identifies the run, outermost first. Each segment is a plain
name: no separators, nothing starting with ..
progress?
progress?: (state) => void | Promise<void>;
Told when the recorded place is not live here (lost), and when the
host starts rebuilding it from held work (restoring), so the caller
can record each before it happens. Awaited.
Parameters
state
"lost" | "restoring"
Returns
void | Promise<void>
recorded?
recorded?: RecordedPlace;
What the run's record says about the place, from an earlier provision. Omitted on a first provision, and on a record written before held work existed: the place is provisioned as it always was.
worktrees?
worktrees?: WorktreeRecording;
Write the worktree's row in the user's list (./worktrees): marked
provisioning before the worktree is made and ready with its path,
branch and base after. A repository run only. Absent: no row is written.
PreviewBoot
How to boot one app on the merged tree, and tell that it loaded.
{port} (a free loopback port) and {scratch} (an empty directory the
build removes afterwards, for a store the boot may write) are replaced in
the command's words and in env's values. The command runs with no shell,
from the base environment plus env: no credential the host holds.
Properties
command
command: readonly [string, string];
The program and its arguments.
cwd?
cwd?: string;
Where it runs, relative to the checkout. Default: the checkout.
env?
env?: Record<string, string>;
Variables to set for it.
id
id: string;
The app, as the output names it.
loaded
loaded: string;
The path on http://127.0.0.1:{port} whose answer, a 2xx, says the app loaded.
timeoutMs?
timeoutMs?: number;
How long it may take to load, in milliseconds.
PreviewLeftOut
One branch left out of the preview.
Properties
branch
branch: string;
reason
reason: PreviewLeftOutReason;
tip
tip: string | null;
Its tip when it was judged; null for a branch that no longer exists.
PreviewOptions
Options for buildPreview and previewStatus.
Properties
baseRef?
baseRef?: string;
The branch the preview is cut from, as the host fetches it. Default main.
boots?
boots?:
| readonly PreviewBoot[]
| ((checkout) => Promise<readonly PreviewBoot[]>);
Gate 2: the apps to boot on the merged tree. None: the build says it was not boot-checked. A function is called once the primary holds the base, so a declaration that lives in the repository is read as the base has it, never as a branch the last preview merged left it; when it throws, the build says the boots could not be read.
checks?
checks?: readonly string[];
Gate 1: the commands each branch's checks run, in order. None: every branch passes.
checksTimeoutMs?
checksTimeoutMs?: number;
Gate 1's wall clock for one branch.
holder?
holder?: string;
Who builds, written into the lock for a second caller to read.
host
host: Pick<WorkspaceHost, "list" | "baseTip">;
The host whose worktrees are in flight (list) and whose fetch gives the base (baseTip; a host without one builds nothing: base-unreadable). primary must be a repository it lists.
merged?
merged?: (branch) => Promise<boolean>;
Whether a branch's work has merged into the base. Merged branches are not in flight.
Parameters
branch
string
Returns
Promise<boolean>
optIn?
optIn?: readonly string[];
Branches that change a lockfile and come in anyway: the person says the app is stopped, and installs after.
primary
primary: string;
The repository's primary checkout, where the preview lives.
recorded?
recorded?: (branch, tip) => Promise<boolean | undefined>;
A check result recorded elsewhere (a run's record) for this branch at exactly this tip; undefined when there is none.
Parameters
branch
string
tip
string
Returns
Promise<boolean | undefined>
user
user: string;
Whose preview: the branch is preview/<user>.
PreviewReport
What buildPreview built.
Properties
base
base: string;
The base commit, as fetched for this build.
branch
branch: string;
preview/<user>.
head
head: string;
Where the preview is now.
installOwed
installOwed: string[];
Opted-in branches that change a lockfile: install, then restart the app.
keptPrevious
keptPrevious:
| {
app: string;
why: string;
}
| null;
The base itself doesn't boot: the preview was put back where it was, and no branch is blamed.
landed
landed: string[];
Listed or in a worktree, but merged into the base already, so not in flight.
leftOut
leftOut: PreviewLeftOut[];
Left out, each with why.
listed
listed: string[];
The branch the primary was on when the build began, now in preview.branch so it stays in flight with no checkout on it.
merged
merged: object[];
In the preview, in merge order, each at the tip merged.
branch
branch: string;
tip
tip: string;
notBootChecked
notBootChecked: string | null;
Why the merged tree was not boot-checked; null when it was.
notFullyShown
notFullyShown: object[];
Branches whose worktree holds uncommitted work or is mid-rebase: only their commits show.
branch
branch: string;
cwd
cwd: string;
why
why: string;
PreviewStatus
What previewStatus reads, without building.
Properties
branch
branch: string;
handled
handled: boolean;
The preview moved since the last build (a hand merge or commit).
lastBuild
lastBuild:
| {
at: number;
base: string;
head: string;
merged: object[];
}
| null;
The last build, as it recorded itself; null when there has been none.
moved
moved: string[];
Branches the last build merged whose tip has moved since.
on
on: boolean;
The primary is on the preview now.
unseen
unseen: string[];
Branches in flight now that the last build neither merged nor left out.
Projection
A live projection over one place.
Methods
flush()
flush(): Promise<FlushReport>;
Reconcile the place back into the collections.
Resolves with everything it decided. Rejects only if the place cannot be
read — see Place.list.
Returns
Promise<FlushReport>
hydrate()
hydrate(): Promise<void>;
Lay every mounted collection's entries into the place, recording a baseline for each.
Returns
Promise<void>
ownedPaths()
ownedPaths(): readonly string[];
The paths this projection currently owns. Exposed for the consumers that have to answer "is another run holding this?" without reaching inside.
Returns
readonly string[]
put()
put(path, content): Promise<FlushOutcome | undefined>;
Commit one path the caller has already written, through the same three-way check a flush applies.
For a consumer whose write channel bypasses the place — a tool call that
writes one named file and already knows which — a full flush is both
wasteful and wrong. Wasteful because it walks everything to learn one
thing; wrong because a projection holding no baseline would report every
pre-existing file in the place as new. put narrows the decision to the
one path, and advances the baseline so the next flush reads the write as
ours rather than as somebody else's.
Resolves undefined only when the path is genuinely nothing to decide —
a collection's own metadata. A read-only mount used to resolve undefined
too, which the tools read as success and relayed to the model as a saved
file; it comes back as a readonly outcome instead.
Parameters
path
string
content
string
Returns
Promise<FlushOutcome | undefined>
ProjectionOptions
Properties
claims?
claims?: ClaimRegistry;
Where this projection arbitrates writes against other live projections.
Defaults to a process-wide registry, which is what makes two projections nobody wired together still arbitrate. Pass your own to scope arbitration to a subset — a test, or one tenant's runs.
mounts
mounts: readonly Mount[];
place
place: Place;
ProjectionSession
One projection's open-and-close.
Properties
projection
readonly projection: Projection;
The projection itself, for put and anything beyond hydrate and flush.
Methods
flush()
flush(): Promise<SettledFlush>;
Reconcile the place back into its collections.
Resolves readable: false when, and only when, the place could not be
listed: the projection decided nothing, so nothing was deleted, and the
run's files are still where it left them. Every other failure (a
collection read, write or delete) rejects, because a run reported as
finished while its files never reached the store is a silent loss.
Returns
Promise<SettledFlush>
hydrate()
hydrate(): Promise<void>;
Lay every mount's entries into the place.
Returns
Promise<void>
PullRequestHead
A pull request's head, as pullRequestHead resolves it.
Properties
branch
readonly branch: string;
The branch the pull request's work is on, in the same repository.
commit
readonly commit: string | null;
The commit at its head when asked.
merged
readonly merged: boolean;
Whether it was merged.
state
readonly state: "open" | "closed" | null;
GitHub's state when asked: open or closed; null when it named none.
url
readonly url: string | null;
PullRequestHeadOptions
Options for pullRequestHead.
Properties
cwd
readonly cwd: string;
A checkout of the repository the pull request is in; gh resolves the repository from its remote.
gh?
readonly gh?: string;
The gh to run. Default "gh" on PATH.
number
readonly number: number;
The pull request's number.
timeoutMs?
readonly timeoutMs?: number;
The wall clock for the one gh call. Default BRANCH_PULL_REQUESTS_TIMEOUT_MS.
PullRequestRead
One pull request, as readPullRequest read it.
Properties
baseRepository
readonly baseRepository: string | null;
owner/name of the repository it merges into.
branch
readonly branch: string | null;
The branch its work is on.
commit
readonly commit: string | null;
The commit at its head when asked.
headRepository
readonly headRepository: string | null;
owner/name of the repository its head is in; another repository's for a fork's. null once that repository is gone.
merged
readonly merged: boolean;
Whether it was merged.
number
readonly number: number;
state
readonly state: "open" | "closed";
GitHub's own state: open or closed. A merged pull request is closed, with merged set.
title
readonly title: string | null;
url
readonly url: string | null;
ReadPullRequestOptions
Options for readPullRequest.
Properties
cwd
readonly cwd: string;
Where gh runs. Without repository, a checkout of the repository
the pull request is in: gh resolves the repository from its remote.
gh?
readonly gh?: string;
The gh to run. Default "gh" on PATH.
host?
readonly host?: string;
The forge's host (github.com, or a GitHub Enterprise host), passed to gh as --hostname. Absent, gh picks its own default.
number
readonly number: number;
The pull request's number.
repository?
readonly repository?: string;
owner/name, when known: asked directly, with no remote to resolve.
timeoutMs?
readonly timeoutMs?: number;
The wall clock for the one gh call. Default BRANCH_PULL_REQUESTS_TIMEOUT_MS.
RecordBranchPullRequestsOptions
Options for recordBranchPullRequests.
Properties
branches?
readonly branches?: readonly string[];
More branches to check beside the checkout's current one: the branch the
host made for the session, which an agent may have left with
git checkout -b.
cwd
readonly cwd: string;
The checkout whose current branch is checked.
gh?
readonly gh?: string;
The gh to run. Default "gh" on PATH.
openedSince?
readonly openedSince?: number;
Only pull requests GitHub says were created at or after this time (epoch ms) are written; older ones on the branch are left out. Pass the start of the turn or run the check follows. Unset, every pull request on the branches is written.
requestId?
readonly requestId?: string | null;
The request the rows are stamped with when new. Default: the context's.
timeoutMs?
readonly timeoutMs?: number;
The whole check's wall clock, shared by every command it runs. Its own budget, never the turn's abort signal.
worktree?
readonly worktree?: object;
The worktree's row in the user's list (./worktrees): what is found is
added to its pullRequests too. startedOn is the pull request the
session started on (start: { pullRequest }): opened before any turn, it
is added to the row whatever openedSince says, though not to the
session's record.
collection
readonly collection: WorktreeCollection;
key
readonly key: string;
startedOn?
readonly startedOn?: number;
RecordedHold
The hold a run record names, handed back to provision.
Properties
base
base: string;
head
head: string;
key
key: string;
parked?
parked?: boolean;
The pack parked the run, and the owner has answered. The next provision
starts from the base and lays the snapshot out in held/.
sha256
sha256: string;
snapshot
snapshot: string;
RecordedPlace
What a run's record says about its place. Every field may be absent.
Properties
baseRef?
baseRef?: string | null;
The branch the run was cut from, for a hold on a place provisioned before holding was on.
branch?
branch?: string | null;
The run's branch. A rebuild refuses another (field: "branch").
held?
held?: RecordedHold | null;
The run's last hold, as checkpoint returned it.
host?
host?: string | null;
The host the place was last ready on. See WorkspaceHost.hostId.
remote?
remote?: string | null;
The remote the run was cut from. A rebuild refuses another (field: "remote").
RemovedWorktree
What WorkspaceHost.remove removed.
Properties
branch
branch: string | null;
The branch the worktree was on; null for a detached HEAD.
branchDeleted
branchDeleted: boolean;
Whether the branch was deleted.
cwd
cwd: string;
RemoveMergedOptions
Options for removeMergedWorktrees.
Properties
dryRun?
readonly dryRun?: boolean;
Judge and report, removing nothing.
exclude?
readonly exclude?: readonly string[];
Directories never taken, with every worktree they sit in: the caller's own working directory, say.
gh?
readonly gh?: string;
The gh to ask GitHub through. Default "gh" on PATH.
prove?
readonly prove?: (options) => Promise<MergedProof>;
The proof each worktree is judged by. Default workMerged; a goal's control swaps it.
Parameters
options
Returns
Promise<MergedProof>
timeoutMs?
readonly timeoutMs?: number;
The wall clock for each git and gh call.
RemoveMergedReport
What removeMergedWorktrees did.
Properties
githubUnread
readonly githubUnread: number;
How many kept worktrees GitHub was not asked about, whose answer might have proven them.
judgedAgainst
readonly judgedAgainst: readonly (object & MergeTarget)[];
Each repository the host listed, and what its worktrees were judged against.
worktrees
readonly worktrees: readonly SweptWorktree[];
RemoveOptions
Options for WorkspaceHost.remove.
Properties
deleteBranch?
deleteBranch?: boolean;
Delete the branch the worktree is on, too.
force?
force?: boolean;
Delete the branch even when it holds the only copy of some commits. Ignored without deleteBranch.
worktrees?
worktrees?: WorktreeCollection;
The user's worktree rows: a removal marks the worktree's row removed.
RepoRunSource
The run cuts a fresh branch of a git repository.
With projectId and files, the kept files are laid down in project/
beside the checkout and saved back; without them, the run gets the
checkout alone.
Properties
baseRef?
baseRef?: string;
The branch on the remote to cut from. Omitted: the remote's default branch, read fresh each time a new branch is cut.
files?
files?: RunFiles;
The collection of kept files. Required together with projectId.
heldPrefix?
heldPrefix?: string;
Where this run's held work goes in the host's held-work store: a key
prefix, /-separated. Opaque to the host, like projectId. Without it,
nothing is held for the run, even on a host with a held-work store.
kind
kind: "repo";
projectId?
projectId?: string;
The key prefix of the kept files. Required together with files.
repo
repo: string;
The remote, as you would pass it to git clone. Checked against the host's allowlist.
RunCheckoutCommandsOptions
Options for runCheckoutCommands.
Properties
commands
commands: readonly string[];
The commands, in order.
cwd
cwd: string;
The checkout the commands run in.
env?
env?: Record<string, string>;
Variables to set for the commands. They never inherit the host's whole
environment, only WORKSPACE_BASE_PASS: a command the run can rewrite
(a package script) gains no secret the host didn't name here.
signal?
signal?: AbortSignal;
Stops the commands early: the running one is stopped with its group and reported as timed out, and any after it are skipped, as when the wall clock runs out.
timeoutMs
timeoutMs: number;
The wall clock for all of them together, in milliseconds.
RunFiles
Where the files kept beside a run live: one collection, addressed under the
answer's projectId.
Carried on the answer rather than configured on the host, because a collection ref is bound to the context that resolved it — the host is built once at boot, with no context to resolve one from.
Properties
collection
collection: ResourceCollectionRef<ProjectedEntryState>;
The collection that holds the kept files, keyed <projectId>/<path>.
collectionId
collectionId: string;
What the collection IS, durably. Write arbitration keys on it — see
Mount.collectionId.
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.
RunSourceRefusal
The source will not give this run any files, and says why.
Not an error: an answer. A host handed one refuses to provision, naming the reason, before anything is created.
Properties
kind
kind: "refused";
message
message: string;
What a person reading the run's failure should be told.
reason
reason: string;
A stable, machine-readable reason, e.g. "not-a-member".
RunToEndResult
How a runToEnd process ended.
Properties
exitCode
exitCode: number | null;
The exit code, or null when a signal ended it.
output
output: string;
Standard output and standard error together, in arrival order: the last keepChars of it.
timedOut
timedOut: boolean;
The wall clock ran out and the process group was stopped.
ScopePrincipal
Who a run is, as far as scoping is concerned.
Properties
orgId?
orgId?: string;
From a verified principal, not the request body. Absent when there is none.
requestId
requestId: string;
This request's id. The narrowest scope there is.
requestIncarnation?
requestIncarnation?: string;
Which request holds requestId: ctx.request.incarnation, stamped once
when the request is first recorded. An id can be reused once its record
is deleted; this cannot. Absent only on a context the engine did not
build.
sessionId
sessionId: string;
tenantId?
tenantId?: string;
The framework's tenant boundary. Absent in a single-tenant app.
userId?
userId?: string;
From a verified principal, not the request body. Absent when anonymous.
SessionRepositorySourceOptions
What sessionRepositorySource reads from.
Properties
check?
check?: (repository) => Promise<RepositoryCheckResult>;
The host's check of an unlisted repository (WorkspaceHost.checkRepository). Absent: any is used as named.
Parameters
repository
string
Returns
Promise<RepositoryCheckResult>
field
field: string;
The session field that names the repository: a key of the session's server-written state.
repositories
repositories: readonly string[];
The repositories a run works in a worktree of, by their real paths: the host's localRepositories.
SkippedPath
A path a hold left out, and why.
Properties
path
path: string;
why
why: "over-cap" | "submodule";
over-cap: larger than the size cap. submodule: a submodule or nested repository.
SourceReadCut
A result the caps cut short: how many more there were.
Properties
by
by: "bytes" | "paths" | "lines" | "matches" | "limit";
Which cap cut it.
left
left: number;
What was left out, in the result's own unit: paths, lines or matches.
SweptWorktree
One worktree as removeMergedWorktrees judged it.
Properties
code
readonly code:
| UnmergedCode
| "proven"
| "excluded"
| "detached"
| "primary-checkout"
| "uncommitted-work"
| string & object;
What decided it: an UnmergedCode, a refusal of remove's, or why it was never a candidate.
outcome
readonly outcome: "failed" | "removed" | "would-remove" | "kept";
failed: proven merged, and the removal failed for a reason other than one of remove's refusals.
proof?
readonly proof?: MergedProof;
The proof, for a worktree that was judged.
reason
readonly reason: string;
A sentence for a person: the pull request or merge commit that proved it, or why it was kept.
worktree
readonly worktree: ListedWorktree;
WorkMergedOptions
Options for workMerged.
Properties
branch
readonly branch: string;
The local branch whose work is judged.
cutPoint?
readonly cutPoint?: string | null;
Where the branch was cut, when the caller knows it (a worktree row's
baseCommit). Absent: the commit the branch's first reflog entry
created it at. Neither: unproven.
defaultRef?
readonly defaultRef?: string | null;
The default branch's tip the git half judges against: a commit from a
source no run can write (mergeTarget's commit), not a ref in a
git directory every worktree shares, which a run can move onto a merge
of its own making. null or absent: the git half is skipped, and only
GitHub can prove a merge.
github?
readonly github?:
| {
gh?: string;
pass?: readonly string[];
repository: string;
}
| null;
The GitHub repository to ask, as host/owner/name (gh's --repo),
with the gh to ask it through. null or absent: GitHub is not asked.
Union Members
Type Literal
{
gh?: string;
pass?: readonly string[];
repository: string;
}
gh?
readonly gh?: string;
The gh to run. Default "gh" on PATH.
pass?
readonly pass?: readonly string[];
The environment names gh may see. Default HOST_REMOTE_PASS.
repository
readonly repository: string;
null
repository
readonly repository: string;
Any directory of the repository: a checkout of it, or its git directory.
timeoutMs?
readonly timeoutMs?: number;
The wall clock for each git and gh call. Default BRANCH_PULL_REQUESTS_TIMEOUT_MS.
WorkspaceHost
Provision, save and release the places runs work in.
Properties
provisionTimeoutMs
readonly provisionTimeoutMs: number;
The budget one provision is held to. See LocalWorkspaceHostOptions.provisionTimeoutMs.
root
readonly root: string;
The host directory.
source
readonly source: RunSource;
The run source the host was built with. Ask it, then hand its answer to provision.
Methods
attach()?
attach?(target, options): Promise<string | null>;
Record that by (a session or run) works in the place's worktree beside
its owner (start: { worktreeOf }): added to the row's attached, once.
The row's key, or null when the place has no row (made before rows were
written, or with none asked for). Optional, as remove is.
Parameters
target
place
readonly string[]
options
by
{
id: string;
kind: "session" | "run";
}
by.id
string
by.kind
"session" | "run"
worktrees
Returns
Promise<string | null>
baseTip()?
baseTip?(target): Promise<string | undefined>;
The commit the run's base branch is at now, fetched from the remote the
host pinned: what a pull request from the run's branch would be diffed
against, so a review can leave out the base's commits a run merged in.
Only a commit this fetch brought, by the rules a new branch's fetch
follows (fetchUpstream), into the checkout's own object store: never a
local branch or tracking ref, which the run shares and could point at its
own work. undefined for a checkout not in a listed repository, a base
named only as HEAD (or none), whose branch is whichever the repository
is on when asked, a base with no pinned upstream, and a fetch that fails.
Never rejects. Optional,
as remove is.
Parameters
target
Pick<LandTarget, "cwd" | "baseRef">
Returns
Promise<string | undefined>
checkpoint()
checkpoint(place, recorded?): Promise<HeldWork | null>;
Hold the place's work: snapshot its working tree on top of its head, pack
every object from its base to that snapshot, and put the pack under a
new key. Writes no ref, never touches the checkout's own index, and never
contacts the remote.
null unless holding applies to the place. When the snapshot equals
recorded's, nothing is written and the result says unchanged.
Record the result after this resolves, then dropHeld the key it replaced.
Parameters
place
recorded?
| Pick<HeldWork, "snapshot" | "sha256" | "bytes">
| null
Returns
Promise<HeldWork | null>
checkRepository()?
checkRepository?(repository, options?): Promise<RepositoryCheckResult>;
Whether a run on repository would get a checkout here, asked before any
run, with nothing made. Checks the remote allow-list; for a listed
repository or file:// remote, that the folder is a git repository with a
commit whose tree ignores ignored (the same ignoredProblem a provision
runs). An allowed network remote answers usable without being reached.
Never rejects for an unusable repository; the answer says why. Optional.
Parameters
repository
string
options?
ignored?
Returns
Promise<RepositoryCheckResult>
dropHeld()
dropHeld(place, key): Promise<void>;
Delete one held pack of this place. Refuses a key outside the place's prefix; resolves when the key is already gone.
Parameters
place
key
string
Returns
Promise<void>
existingPullRequest()?
existingPullRequest?(target): Promise<ExistingPullRequest | null>;
The pull request already open from the branch land would land, asked
before the review is: a run whose work goes onto it is never offered a
second one, or a local merge. null where landWays offers no
pull-request, and where there is none. Rejects when it can't be told
(git or GitHub can't be read), so the caller can say so.
Parameters
target
Returns
Promise<ExistingPullRequest | null>
holds()
holds(answer): boolean;
Whether holding applies to a run with this answer. false on a host with no held-work store.
Parameters
answer
Returns
boolean
hostId()
hostId(): string;
This host's identity: kept in <root>/.host-id, so hosts sharing a root
share it. Record it as the place's host.
Returns
string
land()?
land?(target, request): Promise<Landed>;
Land a run's accepted branch (./land): push it to the repository's
pinned remote and open a pull request through the host's gh, or merge
it into the base branch where the person has it checked out. Only for a
run in a repository listed in localRepositories; the run's branch and
checkout are never changed, whatever fails. Optional, as remove is.
Rejects with a WorkspaceRefusedError saying what happened: a checkout
not in a listed repository is land-unsupported, and the rest are
landRun's.
Parameters
target
request
Returns
Promise<Landed>
landWays()?
landWays?(target): Promise<("pull-request" | "merge")[]>;
The ways land can land this run here, asked before the review is: none
for a checkout land would refuse as land-unsupported, merge for a
worktree of a listed repository, and pull-request too when its base has
a pinned remote that names a GitHub repository. Never rejects.
Parameters
target
Returns
Promise<("pull-request" | "merge")[]>
list()?
list?(): Promise<readonly ListedWorktree[]>;
Every worktree this host holds: each one git knows, in a clone under the
root or a listed repository, whose directory is strictly inside the root.
A directory git does not know is not listed. Optional, as remove is.
Returns
Promise<readonly ListedWorktree[]>
locate()
locate(answer, request): object;
Where provision would put a place for this answer, without making
anything: its directory, and where the worker runs. For a caller that
has to name the working directory (in a prompt, say) before provisioning.
Parameters
answer
request
Pick<PlaceRequest, "place">
Returns
object
cwd
cwd: string;
dir
dir: string;
provision()
provision(answer, request): Promise<WorkspacePlace>;
Make (or hand back) the place for one run.
Rejects with a WorkspaceRefusedError for a refused source or remote,
before any git process or directory exists. Rejects with a
HeldWorkMismatchError when the recorded held work disagrees with the
record or this host cannot use it, with nothing held changed.
Parameters
answer
request
Returns
Promise<WorkspacePlace>
readSource()?
readSource?(answer, request): Promise<SourceReadResult>;
Read the files answer names, without a run: list paths by a glob, read
one file's lines, or search the files. Optional: a host without it offers
no reads, and a caller that needs them refuses it when it is built.
Nothing is made but the shared clone, and nothing is written. A
repository is read at one commit of the remote's default branch, never
a run's own branch; a checkout listed in localRepositories at the base
a new run there would be cut from; kept files from their collection.
Every result is held to SOURCE_READ_LIMITS and says when it was cut.
Rejects with a WorkspaceRefusedError for a refused answer, a remote the
host may not reach, or a path that is not a repository path.
Parameters
answer
request
Returns
Promise<SourceReadResult>
recordCheckout()?
recordCheckout?(target, options): Promise<CheckoutSnapshot | null>;
Read the place's worktree at a turn's end and write it to its row: the
branch HEAD is on and the commits past the row's baseCommit (null
when there is no base or git can't count), with the time, in one write.
A directory that is gone marks the row lost. by, when attached, has
its own last-turn time set. Answers what it read, so a caller that reports
the branch or count uses this one read; null for a place with no row.
Optional, as remove is.
Parameters
target
place
readonly string[]
options
by?
{
id: string;
kind: "session" | "run";
}
by.id
string
by.kind
"session" | "run"
worktrees
Returns
Promise<CheckoutSnapshot | null>
release()
release(place): Promise<void>;
Let the place go. The directory is kept; the live link to its kept files is dropped, so a later provision rebuilds them from the collection. Does nothing for a place provisioned again since.
Parameters
place
Returns
Promise<void>
remove()?
remove?(target, options?): Promise<RemovedWorktree>;
Remove one place's worktree, and with deleteBranch its branch: the
removal path, which every cleanup calls. Never loses work:
- refused,
uncommitted-work, while the worktree holds uncommitted or untracked changes (ignored files go with it); - refused,
place-busy, while a provision of the place holds its lock; - refused,
in-use, while a run holds the worktree in use (occupyWorktree); - with
deleteBranch, refused,unique-commits, while the branch holds commits no other branch or remote-tracking ref holds, unlessforce.
A refusal removes nothing. Kept files and held work are left alone: the collection and the held-work store are their record. Rejects for a target that names no worktree this host lists.
Parameters
target
options?
Returns
Promise<RemovedWorktree>
reserve()?
reserve?(answer, request): Promise<boolean>;
Reserve a place's and branch's names for one run, holder: true when
they are now that run's, false when another run holds them, the place's
directory exists, or the repository the answer names (a listed one, or the
host's clone of its remote) has the branch. Asked before a NEW run takes a
name, so it never inherits another run's tree or branch. The reservation
is atomic and names its holder, so two runs asking for one name at once
get one true between them, and the same run asking again gets true.
Contacts no remote. Optional, as remove is: a host without it gives a run
its derived name as it is.
Parameters
answer
request
branch
string
holder
string
place
readonly string[]
Returns
Promise<boolean>
restore()
restore(place): Promise<void>;
Does nothing: provision rebuilds a lost place from held work.
Parameters
place
Returns
Promise<void>
save()
save(place): Promise<FlushReport>;
Flush the place's kept files back to their collection. A conflict is an outcome in the report, never an overwrite. A place with no kept files reports nothing. Refuses a place provisioned again since: its kept files are the newer provision's to save.
Parameters
place
Returns
Promise<FlushReport>
WorkspacePlace
A provisioned place. Hand it back to save, checkpoint, restore and release.
Properties
cwd
cwd: string;
Where the worker runs: checkout/ for a repository, workspace/ otherwise.
dir
dir: string;
The place's directory.
filesDir?
filesDir?: string;
The directory synced with the kept files, when the run has any.
heldDir?
heldDir?: string;
Where a held snapshot was laid out beside the checkout, after its owner answered a mismatch. Absent when it could not be read.
holder?
holder?: string;
Which provision of the place this is, when it has kept files. A place
provisioned again hands its kept files to the newer provision, so save
refuses an older one and release leaves the newer one's link alone.
holding?
holding?: object;
Present only when holding applies to this place: the host has a held-work
store, the source named a heldPrefix, and the branch came from a remote.
base
base: string;
The commit holds pack from.
host
host: string;
The host that provisioned it.
keyPrefix
keyPrefix: string;
Every key this place's holds use starts with it.
kind
kind: "repo" | "files";
Which kind of source made it.
origin?
origin?: PlaceOrigin;
Where a repository place came from.
repo?
repo?: object;
What the checkout is, for a repository run. Record remote and baseRef on the run.
baseCommit?
baseCommit?: string;
The commit it was cut at. Only when created.
baseRef?
baseRef?: string;
The ref the run's branch was cut from, as asked ("HEAD" when none was
named). Only when created.
branch
branch: string;
branchCut?
branchCut?: boolean;
Whether this call cut the branch itself, not only made a new checkout of a branch that already existed (after a removal that kept the branch). Absent on places made before it existed.
clone
clone: string;
The repository this checkout is a worktree of: the shared clone, or the local repository itself. Log it so an operator can find it.
created
created: boolean;
Whether this call made the checkout: it cut the branch, or checked out a
branch that already existed into a new tree (a rebuild from held work
included). false for a checkout handed back.
movedBack?
movedBack?: MovedBack;
Present when the checkout was handed back off the run's branch and moved
back onto it (see MovedBack). Tell the run, which may still think it is
on the branch it switched to.
offBranch?
offBranch?: OffBranch;
Present when the checkout was handed back off the run's branch and left
there, because moving it would move uncommitted changes (see
OffBranch). Tell the run; a caller that must only run on the run's
branch refuses with its message.
remote
remote: string;
The remote as the source gave it.
setup?
setup?: PlaceSetup;
What the host's setup command came to, when this provision ran it
(LocalWorkspaceHostOptions.setup). Absent when nothing ran: no setup
configured, or a checkout already set up.
worktree?
worktree?: string;
The key of the worktree's row, when the provision was given worktrees.
WorkspaceSetup
A command a host runs in each checkout it makes. See LocalWorkspaceHostOptions.setup.
Properties
command
command: readonly [string, string];
The program and its arguments, run in the checkout without a shell.
env?
env?: Record<string, string>;
Variables to set for the command. It never inherits the host's whole
environment, only WORKSPACE_BASE_PASS (PATH, HOME, locale, proxy
and CA settings): a variable it needs, a registry token say, is named
here.
WorktreeRecording
What a caller hands the host so a provision writes the worktree's row.
Properties
collection
readonly collection: WorktreeCollection;
The user's rows, off the request's ctx.resources.
label?
readonly label?: string;
What the name's slug is made from: a task's or session's title.
name?
readonly name?: string;
The name, when the caller already named the worktree: a board run whose
branch and folder carry its name, so the resource reads the same.
Absent: worktreeName makes one from label.
owner
readonly owner: object;
The session or run the worktree is made for.
id
id: string;
kind
kind: "session" | "run";
Type Aliases
BranchPullRequestsResult
type BranchPullRequestsResult =
| {
branches: readonly string[];
pullRequests: readonly PullRequestRef[];
status: "recorded";
}
| {
reason: string;
status: "unavailable";
};
How a recordBranchPullRequests call ended.
CheckoutSnapshot
type CheckoutSnapshot =
| {
at: number;
branch: string | null;
commits: number | null;
present: true;
}
| {
at: number;
present: false;
};
What the turn-end read found in the worktree.
ClaimHolder
type ClaimHolder = symbol;
A holder of claims — one in-flight operation, identified by nothing but itself.
FlushOutcome
type FlushOutcome =
| {
kind: "unchanged";
path: string;
}
| {
kind: "created";
path: string;
}
| {
kind: "written";
path: string;
}
| {
kind: "converged";
path: string;
}
| {
kind: "deleted";
path: string;
}
| {
kind: "orphan";
path: string;
}
| {
kind: "readonly";
path: string;
prefix: string;
}
| {
kind: "contested";
path: string;
}
| {
base: string | null;
kind: "conflict";
ours: string | null;
path: string;
theirs: string | null;
};
What a flush decided about one path.
A conflict is not an error. It is an outcome of a flush that succeeded: everything uncontested still landed, and the contested path was left exactly as both writers left it, with the three hashes needed to say why.
Union Members
Type Literal
{
kind: "unchanged";
path: string;
}
Local content matches the baseline — the run never touched it.
Type Literal
{
kind: "created";
path: string;
}
We hold no baseline and the collection holds nothing: a clean create.
Type Literal
{
kind: "written";
path: string;
}
The collection still holds what we last put there: a clean write.
Type Literal
{
kind: "converged";
path: string;
}
The collection already holds exactly what we would have written. Nothing
is written, and the baseline still advances — see Projection.flush.
Type Literal
{
kind: "deleted";
path: string;
}
We held a baseline, the place no longer holds the path, nobody else touched it.
Type Literal
{
kind: "orphan";
path: string;
}
A write landed under no writable mount. Reported rather than guessed into a default collection, and never silently dropped.
Comes from put, where the caller names a path the projection then finds
no home for — which is how the tools that write one file at a time reach
it. A flush sees this only for a path inside a mount prefix that
nothing owns: it lists the place BY prefix, so a file the run dropped
outside every prefix is never walked and never reported. If you need those
seen, the place has to be listed wider than the mounts.
Type Literal
{
kind: "readonly";
path: string;
prefix: string;
}
The path is under a read-only mount, so nothing was saved and nothing ever will be.
Only put produces this, because only put was handed one path and
asked to persist it; a flush keeps no baseline on a read-only mount and so
cannot tell an edit from what it laid down itself.
Unlike contested and conflict it never clears on a retry, and a caller
relaying it should say so rather than inviting the write again.
Type Literal
{
kind: "contested";
path: string;
}
Another live projection is writing this path, so this one did not.
Distinct from conflict, and the difference is who the other writer is.
A conflict is somebody who already wrote — the evidence is in the
collection, and three hashes describe it. A contested path is somebody
writing now: there is nothing to compare yet, only a claim held
elsewhere. Merging the two would report "the collection changed" about a
collection that has not.
Type Literal
{
base: string | null;
kind: "conflict";
ours: string | null;
path: string;
theirs: string | null;
}
Two writers, and we cannot tell which is wanted. ours: null is the
delete half — the path left the place while somebody else changed it.
base
base: string | null;
What we last committed, or null if we never laid this path down.
kind
kind: "conflict";
ours
ours: string | null;
What the place holds now, or null if the path was deleted.
path
path: string;
theirs
theirs: string | null;
What the collection holds now, or null if it holds nothing.
GrepDialect
type GrepDialect = "extended-regex" | "javascript-regex" | "literal";
The regular expression dialect a grep used.
HeldWorkMismatchField
type HeldWorkMismatchField =
| "scope"
| "pack"
| "base"
| "head"
| "snapshot"
| "tree"
| "branch"
| "remote"
| "disabled";
What a held-work mismatch names.
Landed
type Landed =
| {
base: string;
baseGone?: string;
branch: string;
existing?: boolean;
kind: "pull-request";
number: number;
remote: string;
url: string;
}
| {
branch: string;
checkout: string;
commit: string;
from: string;
kind: "merge";
};
Where a run's work landed.
Union Members
Type Literal
{
base: string;
baseGone?: string;
branch: string;
existing?: boolean;
kind: "pull-request";
number: number;
remote: string;
url: string;
}
base
readonly base: string;
The branch the pull request asks to merge into, on the remote.
baseGone?
readonly baseGone?: string;
The base the run's work was cut from, when the remote no longer has
that branch (its pull request merged and the branch was deleted), so
the pull request asks to merge into the remote's default branch,
base, instead. Absent when it went into the run's own base.
branch
readonly branch: string;
The branch pushed: the run's own, or the one its checkout is on when
the run moved its work off it (see LandTarget.baseCommit).
existing?
readonly existing?: boolean;
true when the pull request was already open from the branch: the
branch was pushed to it and no pull request was opened. Absent on a
landing that opened one.
kind
readonly kind: "pull-request";
number
readonly number: number;
remote
readonly remote: string;
The remote pushed to, with any credential removed.
url
readonly url: string;
The pull request's web link.
Type Literal
{
branch: string;
checkout: string;
commit: string;
from: string;
kind: "merge";
}
branch
readonly branch: string;
The branch merged into: the base, in the person's checkout.
checkout
readonly checkout: string;
The checkout the base branch is checked out in, where the merge ran.
commit
readonly commit: string;
The commit that branch is at after the merge.
from
readonly from: string;
The run's branch, merged: its own, or the one its checkout is on (see LandTarget.baseCommit).
kind
readonly kind: "merge";
LandRequest
type LandRequest =
| {
body: string;
gh?: string;
kind: "pull-request";
onlyExisting?: boolean;
timeoutMs?: number;
title: string;
}
| {
kind: "merge";
timeoutMs?: number;
};
How a run's accepted work lands.
Union Members
Type Literal
{
body: string;
gh?: string;
kind: "pull-request";
onlyExisting?: boolean;
timeoutMs?: number;
title: string;
}
body
readonly body: string;
The pull request's description.
gh?
readonly gh?: string;
The gh to run. Default "gh" on PATH.
kind
readonly kind: "pull-request";
onlyExisting?
readonly onlyExisting?: boolean;
Land only on a pull request already open from the branch into its
base: when none is (it was closed or merged since it was found), or
GitHub can't say, nothing is pushed and none is opened, and the
landing is refused pull-request-gone or pull-request-failed.
timeoutMs?
readonly timeoutMs?: number;
The whole landing's wall clock. Default two minutes.
title
readonly title: string;
The pull request's title.
Type Literal
{
kind: "merge";
timeoutMs?: number;
}
kind
readonly kind: "merge";
timeoutMs?
readonly timeoutMs?: number;
The whole landing's wall clock. Default two minutes.
MergedProof
type MergedProof =
| {
by: "pull-request";
merged: true;
number: number;
url: string | null;
}
| {
by: "merge-commit";
commit: string;
merged: true;
}
| {
code: UnmergedCode;
githubUnread: boolean;
merged: false;
reason: string;
};
What workMerged answered.
Union Members
Type Literal
{
by: "pull-request";
merged: true;
number: number;
url: string | null;
}
Type Literal
{
by: "merge-commit";
commit: string;
merged: true;
}
Type Literal
{
code: UnmergedCode;
githubUnread: boolean;
merged: false;
reason: string;
}
code
readonly code: UnmergedCode;
githubUnread
readonly githubUnread: boolean;
GitHub was not asked (none named, or the read failed), and its answer might have proven the merge.
merged
readonly merged: false;
reason
readonly reason: string;
PlaceOrigin
type PlaceOrigin = "new" | "live" | "held" | "base";
Where a repository place came from. new: cut for the first time. live:
on this host already, handed back as it was. held: rebuilt from held
work. base: recorded elsewhere with nothing held, so cut again from the
base.
PlaceSetup
type PlaceSetup =
| {
status: "done";
}
| {
status: "failed";
tail: string;
};
What one setup run came to. On WorkspacePlace.setup when the provision ran it.
Union Members
Type Literal
{
status: "done";
}
Type Literal
{
status: "failed";
tail: string;
}
status
status: "failed";
tail
tail: string;
The last lines the command wrote, and how it ended, for a person to read.
PreviewLeftOutReason
type PreviewLeftOutReason =
| {
commits: string[];
kind: "preview-commits";
}
| {
files: string[];
kind: "install-owed";
}
| {
failed: string[];
kind: "checks-red";
}
| {
kind: "unchecked";
why: string;
}
| {
after: string[];
files: string[];
kind: "conflict";
}
| {
kind: "merge-failed";
why: string;
}
| {
after: string[];
app: string;
kind: "boot";
why: string;
}
| {
kind: "missing";
};
Why a branch was left out of the preview.
ProjectedEntryExtra
type ProjectedEntryExtra = Record<string, JsonValue> & object;
Fields a mount may add when the projection commits an entry.
path, hash, and updatedAt belong to the projection. A function that
returns them does not type-check, and a value that arrives anyway is
ignored: the projection's own values are what the collection stores.
Type Declaration
hash?
hash?: never;
path?
path?: never;
updatedAt?
updatedAt?: never;
ProjectedEntryState
type ProjectedEntryState = object;
The state a projected file carries in its collection. File content lives in the entry's content, not here.
A type alias, not an interface, so it satisfies the JsonObject index
signature a ResourceCollectionRef requires.
Indexable
[key: string]: string
Properties
hash
hash: string;
Content hash, for diffing at flush.
path
path: string;
Path relative to the mount, e.g. "src/index.ts".
updatedAt
updatedAt: string;
ISO timestamp of the last sync.
RemoveTarget
type RemoveTarget =
| {
place: readonly string[];
}
| {
cwd: string;
};
Which worktree WorkspaceHost.remove removes: by its place, or by its directory.
RepositoryCheckResult
type RepositoryCheckResult =
| {
how: "worktree" | "clone";
usable: true;
}
| {
problem: string;
usable: false;
};
What WorkspaceHost.checkRepository answers. how says where a run's
checkout would be: a worktree of a repository the host lists, or a clone
under the host's root. problem is a sentence for a person, naming the fix,
and never repeats a credential.
RunSource
type RunSource = (ctx) =>
| RunSourceAnswer
| Promise<RunSourceAnswer>;
Resolve a run's source from its block context.
Handed the context and nothing else, so it can only answer from what the context reaches — stored, server-written data — and never from a row's input, its metadata, or anything a model wrote.
Parameters
ctx
BlockContext
Returns
| RunSourceAnswer
| Promise<RunSourceAnswer>
RunSourceAnswer
type RunSourceAnswer =
| RepoRunSource
| FilesRunSource
| RunSourceRefusal;
Everything a run source can answer.
ScopeName
type ScopeName = "request" | "session" | "user" | "org";
A scope, spelled the way core spells it.
SettledFlush
type SettledFlush =
| {
outcomes: readonly FlushOutcome[];
readable: true;
}
| {
error: PlaceUnreadableError;
readable: false;
};
What a flush settled to: what it decided, or that the place could not be read.
SourceReadAt
type SourceReadAt =
| {
ageMs: number | null;
branch: string;
commit: string;
fetchedAt: string | null;
kind: "repo";
}
| {
kind: "files";
};
Which version of the files a read saw.
Union Members
Type Literal
{
ageMs: number | null;
branch: string;
commit: string;
fetchedAt: string | null;
kind: "repo";
}
ageMs
ageMs: number | null;
How long ago that was, in milliseconds; null when fetchedAt is.
branch
branch: string;
The branch it was resolved from: the remote's default branch, or a mapped checkout's base.
commit
commit: string;
The commit every part of this read came from.
fetchedAt
fetchedAt: string | null;
When the shared clone was last fetched, as an ISO time; null for a checkout on this machine.
kind
kind: "repo";
Type Literal
{
kind: "files";
}
SourceReadRequest
type SourceReadRequest =
| {
kind: "glob";
limit?: number | null;
pattern?: string | null;
}
| {
endLine?: number | null;
kind: "read";
path: string;
startLine?: number | null;
}
| {
kind: "grep";
maxResults?: number | null;
pattern: string;
prefix?: string | null;
};
What one read asks for. Every path is a repository path: /-separated, no leading /, no . or .. segment.
Union Members
Type Literal
{
kind: "glob";
limit?: number | null;
pattern?: string | null;
}
kind
kind: "glob";
limit?
limit?: number | null;
At most this many paths, and never more than the cap.
pattern?
pattern?: string | null;
A glob matched against each path (src/**, **/*.ts). Omitted or null: every path.
Type Literal
{
endLine?: number | null;
kind: "read";
path: string;
startLine?: number | null;
}
endLine?
endLine?: number | null;
The last line to return. Omitted: the end of the file, within the caps.
kind
kind: "read";
path
path: string;
The file to read.
startLine?
startLine?: number | null;
The first line to return, counting from 1. Omitted: 1.
Type Literal
{
kind: "grep";
maxResults?: number | null;
pattern: string;
prefix?: string | null;
}
kind
kind: "grep";
maxResults?
maxResults?: number | null;
At most this many matches, and never more than the cap.
pattern
pattern: string;
A regular expression, or a literal when it doesn't compile. The result names which.
prefix?
prefix?: string | null;
Only files at or under this path.
SourceReadResult
type SourceReadResult =
| {
at: SourceReadAt;
cut: SourceReadCut | null;
kind: "glob";
paths: string[];
}
| {
at: SourceReadAt;
content: string;
cut: SourceReadCut | null;
endLine: number;
kind: "read";
path: string;
startLine: number;
status: "ok";
totalLines: number;
}
| {
at: SourceReadAt;
bytes?: number;
kind: "read";
path: string;
status: "missing" | "directory" | "binary" | "too-large";
}
| {
at: SourceReadAt;
binary: "skipped";
cut: SourceReadCut | null;
dialect: GrepDialect;
kind: "grep";
matches: object[];
};
What one read answers.
Union Members
Type Literal
{
at: SourceReadAt;
cut: SourceReadCut | null;
kind: "glob";
paths: string[];
}
Type Literal
{
at: SourceReadAt;
content: string;
cut: SourceReadCut | null;
endLine: number;
kind: "read";
path: string;
startLine: number;
status: "ok";
totalLines: number;
}
at
at: SourceReadAt;
content
content: string;
The lines returned, startLine to endLine, joined with \n.
cut
cut: SourceReadCut | null;
endLine
endLine: number;
kind
kind: "read";
path
path: string;
startLine
startLine: number;
status
status: "ok";
totalLines
totalLines: number;
The lines in the whole file.
Type Literal
{
at: SourceReadAt;
bytes?: number;
kind: "read";
path: string;
status: "missing" | "directory" | "binary" | "too-large";
}
at
at: SourceReadAt;
bytes?
bytes?: number;
The file's size, for binary and too-large.
kind
kind: "read";
path
path: string;
status
status: "missing" | "directory" | "binary" | "too-large";
missing: no file there. directory: a directory, not a file. binary: refused, not text. too-large: past what a read loads.
Type Literal
{
at: SourceReadAt;
binary: "skipped";
cut: SourceReadCut | null;
dialect: GrepDialect;
kind: "grep";
matches: object[];
}
at
at: SourceReadAt;
binary
binary: "skipped";
Binary files are never searched.
cut
cut: SourceReadCut | null;
dialect
dialect: GrepDialect;
kind
kind: "grep";
matches
matches: object[];
UnmergedCode
type UnmergedCode =
| "branch-gone"
| "no-cut-point"
| "no-own-commit"
| "open-pull-request"
| "past-merged-head"
| "fast-forward"
| "not-merged";
Why workMerged kept a branch: each case its own code, with a sentence for a person.
WorktreeAttached
type WorktreeAttached = z.infer<typeof worktreeAttachedSchema>;
One entry of a row's attached.
WorktreeCollection
type WorktreeCollection = ResourceCollectionRef<WorktreeResourceState>;
The collection as a block reads it off ctx.resources.
WorktreeOwner
type WorktreeOwner = z.infer<typeof worktreeOwnerSchema>;
Who owns a worktree.
WorktreePullRequest
type WorktreePullRequest = z.infer<typeof worktreePullRequestSchema>;
A pull request on a worktree's branch.
WorktreeResourceState
type WorktreeResourceState = z.infer<typeof worktreeResourceStateSchema>;
The state of one resource of worktreesCollection: one worktree.
WorktreeStatus
type WorktreeStatus = z.infer<typeof worktreeStatusSchema>;
Where a worktree is in its life: being made, ready, removed by its owner, or gone from disk.
Variables
BRANCH_PULL_REQUESTS_TIMEOUT_MS
const BRANCH_PULL_REQUESTS_TIMEOUT_MS: 30000 = 30000;
How long the whole check may take, by default: every command it runs shares this one deadline.
CHECK_OUTPUT_TAIL_CHARS
const CHECK_OUTPUT_TAIL_CHARS: 4000 = 4000;
The most of a command's output a result keeps: its last characters.
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.
sharedClaimRegistry
const sharedClaimRegistry: ClaimRegistry;
The registry projections share when none is supplied.
Module-level, so two projections built anywhere in one process arbitrate against each other without being introduced. That is the point: the runs this protects against are the ones nobody wired together.
sleep
const sleep: (ms, signal?) => Promise<void>;
Wait ms, or until signal aborts, whichever is first. Resolves either
way; the caller checks the signal. An already-aborted signal returns at
once, since abort never replays for a listener armed after it fired.
Parameters
ms
number
signal?
AbortSignal
Returns
Promise<void>
SOURCE_READ_FRESH_MS
const SOURCE_READ_FRESH_MS: 60000 = 60000;
How long a fetch of a shared clone serves reads before the next read fetches again. A model reads in bursts, so a minute bounds staleness without a fetch per call.
SOURCE_READ_LIMITS
const SOURCE_READ_LIMITS: object;
The caps every read is held to. Each result says when it was cut, and by how much.
Type Declaration
bytes
readonly bytes: number;
Bytes one read returns, counted in UTF-8.
lines
readonly lines: 2000;
Lines one read returns.
matches
readonly matches: 200;
Matches one grep returns.
paths
readonly paths: 500;
Paths one glob returns.
snippet
readonly snippet: 200;
Characters of one grep match's line.
worktreeAttachedSchema
const worktreeAttachedSchema: z.ZodEffects<z.ZodObject<{
id: z.ZodString;
kind: z.ZodEnum<["session", "run"]>;
lastTurnAt: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
}, "strip", z.ZodTypeAny, {
id: string;
kind: "run" | "session";
lastTurnAt: number | null;
}, {
id: string;
kind: "run" | "session";
lastTurnAt?: number | null;
}>, {
id: string;
kind: "run" | "session";
lastTurnAt: number | null;
}, unknown>;
A session or run working in a worktree beside its owner, and when its last turn there ended. A bare string, which no released row holds, reads as a session never yet read at a turn's end.
worktreeOwnerSchema
const worktreeOwnerSchema: z.ZodObject<{
id: z.ZodString;
kind: z.ZodEnum<["session", "run"]>;
}, "strip", z.ZodTypeAny, {
id: string;
kind: "run" | "session";
}, {
id: string;
kind: "run" | "session";
}>;
Who owns a worktree: the session or the board run it was made for.
worktreePullRequestSchema
const worktreePullRequestSchema: z.ZodObject<{
number: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
state: z.ZodDefault<z.ZodNullable<z.ZodString>>;
title: z.ZodDefault<z.ZodNullable<z.ZodString>>;
url: z.ZodString;
}, "strip", z.ZodTypeAny, {
number: number | null;
state: string | null;
title: string | null;
url: string;
}, {
number?: number | null;
state?: string | null;
title?: string | null;
url: string;
}>;
A pull request on a worktree's branch, as last seen. The session's observed-pull-requests rows are the full record.
worktreeResourceStateSchema
const worktreeResourceStateSchema: z.ZodObject<{
attached: z.ZodDefault<z.ZodArray<z.ZodEffects<z.ZodObject<{
id: z.ZodString;
kind: z.ZodEnum<["session", "run"]>;
lastTurnAt: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
}, "strip", z.ZodTypeAny, {
id: string;
kind: "run" | "session";
lastTurnAt: number | null;
}, {
id: string;
kind: "run" | "session";
lastTurnAt?: number | null;
}>, {
id: string;
kind: "run" | "session";
lastTurnAt: number | null;
}, unknown>, "many">>;
baseCommit: z.ZodDefault<z.ZodNullable<z.ZodString>>;
branch: z.ZodDefault<z.ZodNullable<z.ZodString>>;
commits: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
key: z.ZodDefault<z.ZodNullable<z.ZodString>>;
lastTurnAt: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
name: z.ZodDefault<z.ZodNullable<z.ZodString>>;
owner: z.ZodDefault<z.ZodNullable<z.ZodObject<{
id: z.ZodString;
kind: z.ZodEnum<["session", "run"]>;
}, "strip", z.ZodTypeAny, {
id: string;
kind: "run" | "session";
}, {
id: string;
kind: "run" | "session";
}>>>;
path: z.ZodDefault<z.ZodNullable<z.ZodString>>;
pullRequests: z.ZodDefault<z.ZodArray<z.ZodObject<{
number: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
state: z.ZodDefault<z.ZodNullable<z.ZodString>>;
title: z.ZodDefault<z.ZodNullable<z.ZodString>>;
url: z.ZodString;
}, "strip", z.ZodTypeAny, {
number: number | null;
state: string | null;
title: string | null;
url: string;
}, {
number?: number | null;
state?: string | null;
title?: string | null;
url: string;
}>, "many">>;
repo: z.ZodDefault<z.ZodNullable<z.ZodString>>;
state: z.ZodDefault<z.ZodNullable<z.ZodEnum<["provisioning", "ready", "removed", "lost"]>>>;
}, "strip", z.ZodTypeAny, {
attached: object[];
baseCommit: string | null;
branch: string | null;
commits: number | null;
key: string | null;
lastTurnAt: number | null;
name: string | null;
owner: | {
id: string;
kind: "run" | "session";
}
| null;
path: string | null;
pullRequests: object[];
repo: string | null;
state: "lost" | "provisioning" | "ready" | "removed" | null;
}, {
attached?: unknown[];
baseCommit?: string | null;
branch?: string | null;
commits?: number | null;
key?: string | null;
lastTurnAt?: number | null;
name?: string | null;
owner?: | {
id: string;
kind: "run" | "session";
}
| null;
path?: string | null;
pullRequests?: object[];
repo?: string | null;
state?: "lost" | "provisioning" | "ready" | "removed" | null;
}>;
One worktree. Every field is nullable or defaulted, so a row written by an older or newer shape still parses.
WORKTREES
const WORKTREES: "worktrees";
Accessor key AND storage prefix for the worktree rows.
worktreesCollection
const worktreesCollection: object & ResourceCollectionConfig & object;
The user's worktree rows.
User-scoped and shared across flows, so a board run's worktree and
a session's are in one list. Lazy: a writer upserts by exact key and never
lists. llmReadable, so an agent reads the list with core's resource tools;
live, so an open page sees a row change mid-turn. No client write, and no
model write.
Type Declaration
client
readonly client: object;
client.expose
readonly expose: readonly ["key", "name", "path", "branch", "repo", "baseCommit", "owner", "attached", "state", "commits", "lastTurnAt", "pullRequests"];
client.live
readonly live: true;
client.state
readonly state: object;
client.state.read
readonly read: true;
llmReadable
readonly llmReadable: true;
pattern
readonly pattern: "worktrees/**";
prefetchMode
readonly prefetchMode: "lazy";
scope
readonly scope: "user";
stateSchema
readonly stateSchema: z.ZodObject<{
attached: z.ZodDefault<z.ZodArray<z.ZodEffects<z.ZodObject<{
id: z.ZodString;
kind: z.ZodEnum<[..., ...]>;
lastTurnAt: z.ZodDefault<z.ZodNullable<...>>;
}, "strip", z.ZodTypeAny, {
id: string;
kind: "run" | "session";
lastTurnAt: number | null;
}, {
id: string;
kind: "run" | "session";
lastTurnAt?: number | null;
}>, {
id: string;
kind: "run" | "session";
lastTurnAt: number | null;
}, unknown>, "many">>;
baseCommit: z.ZodDefault<z.ZodNullable<z.ZodString>>;
branch: z.ZodDefault<z.ZodNullable<z.ZodString>>;
commits: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
key: z.ZodDefault<z.ZodNullable<z.ZodString>>;
lastTurnAt: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
name: z.ZodDefault<z.ZodNullable<z.ZodString>>;
owner: z.ZodDefault<z.ZodNullable<z.ZodObject<{
id: z.ZodString;
kind: z.ZodEnum<["session", "run"]>;
}, "strip", z.ZodTypeAny, {
id: string;
kind: "run" | "session";
}, {
id: string;
kind: "run" | "session";
}>>>;
path: z.ZodDefault<z.ZodNullable<z.ZodString>>;
pullRequests: z.ZodDefault<z.ZodArray<z.ZodObject<{
number: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
state: z.ZodDefault<z.ZodNullable<z.ZodString>>;
title: z.ZodDefault<z.ZodNullable<z.ZodString>>;
url: z.ZodString;
}, "strip", z.ZodTypeAny, {
number: number | null;
state: string | null;
title: string | null;
url: string;
}, {
number?: number | null;
state?: string | null;
title?: string | null;
url: string;
}>, "many">>;
repo: z.ZodDefault<z.ZodNullable<z.ZodString>>;
state: z.ZodDefault<z.ZodNullable<z.ZodEnum<["provisioning", "ready", "removed", "lost"]>>>;
}, "strip", z.ZodTypeAny, {
attached: object[];
baseCommit: string | null;
branch: string | null;
commits: number | null;
key: string | null;
lastTurnAt: number | null;
name: string | null;
owner: | {
id: string;
kind: "run" | "session";
}
| null;
path: string | null;
pullRequests: object[];
repo: string | null;
state: "lost" | "provisioning" | "ready" | "removed" | null;
}, {
attached?: unknown[];
baseCommit?: string | null;
branch?: string | null;
commits?: number | null;
key?: string | null;
lastTurnAt?: number | null;
name?: string | null;
owner?: | {
id: string;
kind: "run" | "session";
}
| null;
path?: string | null;
pullRequests?: object[];
repo?: string | null;
state?: "lost" | "provisioning" | "ready" | "removed" | null;
}>;
__brand
readonly __brand: "ResourceCollection";
ClientType
ClientType: Pick<{
attached: object[];
baseCommit: string | null;
branch: string | null;
commits: number | null;
key: string | null;
lastTurnAt: number | null;
name: string | null;
owner: | {
id: string;
kind: "run" | "session";
}
| null;
path: string | null;
pullRequests: object[];
repo: string | null;
state: "lost" | "provisioning" | "ready" | "removed" | null;
},
| "attached"
| "baseCommit"
| "branch"
| "commits"
| "key"
| "lastTurnAt"
| "name"
| "owner"
| "path"
| "pullRequests"
| "repo"
| "state">;
StateType
StateType: object;
StateType.attached
attached: object[];
StateType.baseCommit
baseCommit: string | null;
StateType.branch
branch: string | null;
StateType.commits
commits: number | null;
StateType.key
key: string | null;
StateType.lastTurnAt
lastTurnAt: number | null;
StateType.name
name: string | null;
StateType.owner
owner:
| {
id: string;
kind: "run" | "session";
}
| null;
StateType.path
path: string | null;
StateType.pullRequests
pullRequests: object[];
StateType.repo
repo: string | null;
StateType.state
state: "lost" | "provisioning" | "ready" | "removed" | null;
worktreeStatusSchema
const worktreeStatusSchema: z.ZodEnum<["provisioning", "ready", "removed", "lost"]>;
Where a worktree is in its life.
Functions
acquireLock()
function acquireLock(
path,
bounds?,
options?
): Promise<LockLease>;
Wait for, and take, the lock at path.
Parameters
path
string
bounds?
options?
Returns
Promise<LockLease>
buildPreview()
function buildPreview(options): Promise<PreviewReport>;
Build or rebuild the preview, and report what is in it and what was left out.
Parameters
options
Returns
Promise<PreviewReport>
Throws
WorkspaceRefusedError preview-busy (another build holds the lock),
checkout-busy (the primary is mid-merge or mid-rebase), base-unreadable,
switch-stopped, preview-own-commits (the preview holds a commit no build
made and no listed branch has) or reset-stopped (the base changed a file
the person is editing). Each leaves the primary as it was.
checkCommandsFrom()
function checkCommandsFrom(value, setting): string[] | undefined;
The checks a setting names, ;-separated (pnpm typecheck; pnpm test):
each command trimmed, blanks dropped, and each checked with
checkoutCommandProblem. Commands run with no shell, so a ; can only
separate two of them. For a host reading its checks from the environment.
Parameters
value
string | undefined
The setting's value, as read.
setting
string
The setting's name, which a refusal starts with.
Returns
string[] | undefined
The commands, or undefined when the value names none.
Throws
${setting}: <problem> for the first command that can't be a check.
checkedOutBranch()
function checkedOutBranch(cwd): Promise<string | null>;
The branch checked out in the worktree at cwd, or null when HEAD is detached or git can't say.
Parameters
cwd
string
Returns
Promise<string | null>
checkoutCommandPassed()
function checkoutCommandPassed(result): boolean;
Whether a command passed: it ran, and exited 0.
Parameters
result
Returns
boolean
checkoutCommandProblem()
function checkoutCommandProblem(command): string | undefined;
Why command can't be a check, or undefined when it can.
Refused: an empty line, an unclosed quote, and anything a shell would read
as more than one program (&&, ||, |, ;, &, <, >, $(…),
backticks), quoted or not. Commands run with no shell, so such a line would
not do what it says.
Parameters
command
string
Returns
string | undefined
claimKey()
function claimKey(collectionId, entryKey): string;
The key one durable entry is claimed under.
Length-framed rather than joined on a delimiter, because a raw join is not
injective: (collection "a", key "b/c") and (collection "a/b", key "c")
spell one string, and a collision here hands one writer another's claim.
Parameters
collectionId
string
entryKey
string
Returns
string
collectionIdFor()
function collectionIdFor(collection, principal): string;
What a collection IS, durably — the value Mount.collectionId wants.
Scope, the instance of that scope, and the pattern. Two runs addressing the same rows get the same string; two that only spell their paths alike get different ones.
Close to the engine's storage key, not equal to it. The engine also
folds per-resource flow isolation into where a user- or org-scoped resource
lands, and that rule is the engine's — reproducing it here would be a second
copy of something this package does not own. So two flows that isolate the
same user's resources from each other share an id here while their rows are
separate, and one of them can be told contested over a row it does not
share. That direction is the safe one: a refusal is reported and retryable,
a missed claim is a silent overwrite. Making it exact needs the storage key
itself, which means a public accessor on the collection ref.
Parameters
collection
pattern
string
scope
principal
Returns
string
createClaimRegistry()
function createClaimRegistry(): ClaimRegistry;
Returns
createHostPlace()
function createHostPlace(root): HostPlace;
Parameters
root
string
Returns
createMemoryPlace()
function createMemoryPlace(initial?): MemoryPlace;
Parameters
initial?
Record<string, string>
Returns
createProjection()
function createProjection(__namedParameters): Projection;
Build a projection over mounts and place.
Holds no I/O of its own beyond what the place and the collections provide, which is what lets the whole of §10's behaviour set run against an in-memory place with no sandbox, no harness and no model.
Parameters
__namedParameters
Returns
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
fileHeldWorkStore()
function fileHeldWorkStore(options): HeldWorkStore;
A HeldWorkStore over a folder: each key is a file under dir.
A put writes a temporary file beside the target and renames it into place,
so a reader never sees a partial pack. For hosts on different machines, put
dir on storage they share.
Parameters
options
dir
string
Returns
frameComponents()
function frameComponents(parts): string;
Join components into one string no other component list can spell.
Length-framed, because a raw join on a delimiter is not injective: with a
: join, (tenant "a:b", id "d") and (tenant "a", id "b:d") are one
string. An absent component gets its own shape rather than a sentinel value,
because every sentinel is also a legal id — - is a tenant id the engine
accepts, so spelling "no tenant" as - puts it on the same key as the
tenant actually named -.
Parameters
parts
readonly (string | undefined)[]
Returns
string
hashContent()
function hashContent(content): string;
A hex SHA-256 of content. The only comparison the projection makes.
Parameters
content
string
Returns
string
identityFromCommonDir()
function identityFromCommonDir(dir, commonDir): string | undefined;
Turn a git rev-parse --git-common-dir answer, asked in dir, into the
identity two directories are compared by: the real path of the common dir,
or undefined when it does not resolve.
The common dir is the one directory every worktree of a repository shares,
so it identifies the repository rather than the checkout. Resolved with
realpath, not lexically: git answers .git for both a repository and a
symlink to it, and a lexical resolve would call those two repositories.
Parameters
dir
string
commonDir
string
Returns
string | undefined
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
listedRepository()
function listedRepository(repository, repositories): string | undefined;
repository as one of repositories, by its real path, when it is one: a
path or a file:// remote of a folder the host lists. undefined for any
other, a network remote or a folder not on this machine included.
Parameters
repository
string
repositories
readonly string[]
Returns
string | undefined
localRepoWorkspaceHost()
function localRepoWorkspaceHost(options): WorkspaceHost;
A workspace host whose every run is a worktree of repo.
Parameters
options
Returns
Example
const workspace = localRepoWorkspaceHost({ root: "/srv/runs", repo: "/srv/app", baseRef: "main" });
localWorkspaceHost()
function localWorkspaceHost(options): WorkspaceHost;
Build a workspace host over a directory on this machine.
Parameters
options
Returns
mergeTarget()
function mergeTarget(
root,
repository,
options?
): Promise<MergeTarget>;
What repository, one a host on root cuts worktrees from, is judged
against.
Never a ref in the repository: every run's worktree shares its git
directory, and a run can move refs/remotes/origin/main onto a merge it
made of another worktree's tip. A host's clone: the tip its last fetch
stamped beside it, in the host's root, and no GitHub repository (a clone
keeps no pinned remote). A listed repository: its pinned remote (origin,
or the only one) and the GitHub repository that remote's URL names; the
default branch's tip as GitHub reports it, else as the pinned URL does
(ls-remote from an empty repository of its own, so the repository's
config is never read). A tip this repository hasn't fetched, or a remote
that doesn't answer, is no commit. Nothing is fetched.
Parameters
root
string
repository
string
options?
gh?
string
timeoutMs?
number
Returns
Promise<MergeTarget>
occupyWorktree()
function occupyWorktree(cwd, options?): Promise<LockLease>;
Hold the worktree at cwd in use until the lease is released
(releaseLock). Waits while another holder has it. The lease refreshes
itself, so another run takes one left by a dead process a minute later;
remove never treats it as stale, so that file is deleted by hand.
Parameters
cwd
string
options?
owner?
string
signal?
AbortSignal
Returns
Promise<LockLease>
parseCheckoutCommand()
function parseCheckoutCommand(command):
| {
words: [string, ...string[]];
}
| {
problem: string;
};
A command's words, checked once: the refusals of checkoutCommandProblem and the split of splitCheckoutCommand together.
Parameters
command
string
Returns
| {
words: [string, ...string[]];
}
| {
problem: string;
}
The words (the program first), or why the line can't be a command.
previewStatus()
function previewStatus(options): Promise<PreviewStatus>;
What the last build recorded, against the branches as they are now. Reads only: no fetch, no lock.
Parameters
options
Returns
Promise<PreviewStatus>
principalFromContext()
function principalFromContext(ctx): ScopePrincipal;
Read the principal off a block's execution context.
The one place that knows which context fields carry it. session.identity.id
and request.identity.id come off the request body; userId, orgId and
tenantId come from a verified principal, which is what makes them safe to
key a shared scope on. request.incarnation is the engine's, read
from the request's stored record. It is optional here only so a hand-built
context without one still resolves, to a key of its own.
Parameters
ctx
request
{
identity: {
id: string;
};
incarnation?: string;
}
request.identity
{
id: string;
}
request.identity.id
string
request.incarnation?
string
session
{
identity: {
id: string;
orgId?: string;
tenantId?: string;
userId?: string;
};
}
session.identity
{
id: string;
orgId?: string;
tenantId?: string;
userId?: string;
}
session.identity.id
string
session.identity.orgId?
string
session.identity.tenantId?
string
session.identity.userId?
string
Returns
privateTempRoot()
function privateTempRoot(name, purpose): Promise<string>;
<tmpdir>/<name>-<uid>, made if missing, checked private to this user.
On a platform with no uid (Windows), <tmpdir>/<name>, unchecked: its temp
folder is already per-user.
Parameters
name
string
purpose
string
What the folder holds, for the refusal: "the short links deep working directories reach Cursor through".
Returns
Promise<string>
Throws
When the folder exists and is not a directory this user owns that only it can enter.
projectionSession()
function projectionSession(options): ProjectionSession;
Open a projection over options.place and options.mounts.
Parameters
options
Returns
Example
const session = projectionSession({ place: createHostPlace(root), mounts });
await session.hydrate();
// ... the run works in `root` ...
const settled = await session.flush();
if (!settled.readable) report(settled.error.message);
pullRequestHead()
function pullRequestHead(options): Promise<PullRequestHead>;
The branch a pull request's work is on, asked of GitHub through the host's
gh (the call readPullRequest makes), so a run can work on it
(PlaceRequest.existing) and its commits land where the pull request sees
them once pushed.
Unlike the turn-end check, this one throws: the run cannot start without
an answer. Refused, pull-request-unreadable, when gh can't say, and
pull-request-from-fork when the head is in another repository, whose
branch is not on this one's remote.
Parameters
options
Returns
Promise<PullRequestHead>
readableSegment()
function readableSegment(id): string;
An id with everything but [A-Za-z0-9_-] replaced by -: readable, never
unique. A run name or folder takes it as a label beside a digest, never alone.
Parameters
id
string
Returns
string
readPullRequest()
function readPullRequest(options): Promise<PullRequestRead>;
One pull request, asked of GitHub through the host's gh
(repos/<owner>/<repo>/pulls/<n>): its state, whether it merged, and its
head. A fork's pull request reads like any other.
Throws pull-request-unreadable when gh can't say: missing, signed out,
timed out, or an answer that names no state. The caller decides what an
unreadable pull request means.
Parameters
options
Returns
Promise<PullRequestRead>
recordBranchPullRequests()
function recordBranchPullRequests(ctx, options): Promise<BranchPullRequestsResult>;
Find the pull requests on a checkout's branches and write the ones the session's record lacks.
The branches are the checkout's current one (unless it is detached) and
options.branches. Each is asked of GitHub's REST API through gh api,
in the repository gh resolves from the checkout's remote, open or closed,
all at once. Before writing, it waits for the request's in-turn recorder to
finish its writes, so a pull request seen in a create call keeps
source: "tool".
const result = await recordBranchPullRequests(ctx, { cwd: worktree, branches: [sessionBranch] });
if (result.status === "unavailable") ctx.emit.status(`Pull requests on the branch were not checked: ${result.reason}`);
Parameters
ctx
options
RecordBranchPullRequestsOptions
Returns
Promise<BranchPullRequestsResult>
redactRemote()
function redactRemote(remote): string;
The remote as a person may be shown it: any userinfo removed, so a refusal that names the remote never prints a credential.
The userinfo runs to the LAST @ before the path, as a URL parser reads
it — a credential may itself hold an @, and stopping at the first one
would print the rest of it.
Parameters
remote
string
Returns
string
refreshLock()
function refreshLock(lease): void;
Mark a held lock live now, for a holder that refreshes it as its own work goes rather than on a timer. Touches nothing that isn't this acquisition's (a lock released, or taken over since), and never throws.
Parameters
lease
Pick<LockLease, "path" | "token">
Returns
void
releaseLock()
function releaseLock(lease): void;
Release a lock this acquisition holds. Never removes another taker's. Idempotent.
Parameters
lease
Returns
void
remoteDefaultBranch()
function remoteDefaultBranch(
root,
repository,
options?
): Promise<string | undefined>;
The base a host cuts runs from, rather than whatever the repository has
checked out (a preview/<user> branch merging every run in flight, say):
the pinned remote's default branch, as the remote names it now, spelled
<remote>/<branch>, so the host fetches it fresh before each cut and never
reads a tracking ref a run can move. refs/remotes/origin/HEAD is not read:
any worktree can repoint or delete it.
undefined when the repository pins no single remote (origin, or the only
one): there is nothing to fetch, and the host keeps cutting from HEAD.
Parameters
root
string
repository
string
options?
timeoutMs?
number
Returns
Promise<string | undefined>
Throws
When the repository pins a remote that doesn't name its default
branch: starting on HEAD then would cut from whatever is checked out.
removeMergedWorktrees()
function removeMergedWorktrees(host, options?): Promise<RemoveMergedReport>;
Remove every worktree host lists whose work has merged (workMerged),
through host.remove, keeping each branch. Every other worktree is kept and
named with its reason; a refusal of remove's (uncommitted work, a run in
it, a provision of it) keeps that one and the sweep goes on. Never takes a
detached HEAD, a repository's own checkout, or a worktree an exclude
directory is in.
const report = await removeMergedWorktrees(host, { dryRun: true, exclude: [process.cwd()] });
for (const swept of report.worktrees) console.log(swept.outcome, swept.worktree.cwd, swept.reason);
Parameters
host
options?
Returns
Promise<RemoveMergedReport>
repositoryIdentity()
function repositoryIdentity(dir): string | undefined;
The repository dir belongs to, as identityFromCommonDir names it, or undefined.
Parameters
dir
string
Returns
string | undefined
resolvesToCommit()
function resolvesToCommit(repo, ref): boolean;
true when ref resolves to a commit in the repository at repo.
Parameters
repo
string
ref
string
Returns
boolean
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;
}>
runCheckoutCommands()
function runCheckoutCommands(options): Promise<CheckoutCommandResult[]>;
Run commands in cwd, in order, and report each.
Never throws for a command that fails, can't start or is refused: each is
a result. A refused command (see checkoutCommandProblem) is not
started and reports exit code null with the reason as its tail.
Parameters
options
Returns
Promise<CheckoutCommandResult[]>
runToEnd()
function runToEnd(
file,
args,
options
): Promise<RunToEndResult>;
Run file with args to its end, whatever its exit code, keeping the end
of what it wrote.
Unlike run, a non-zero exit resolves: the caller's question is what
happened, not whether it worked. The process gets a group of its own, so
the wall clock stops what it started too (a test runner's workers), not
only the process named. Its environment is run's: the allowlist,
never this process's whole one. A file that cannot be started at all resolves as
exit code 127, with the reason as its output. An aborted signal stops
the group as the wall clock does, and reports it as timed out.
Parameters
file
string
args
string[]
options
cwd
string
env?
Record<string, string>
gitCredentials?
boolean
keepChars
number
pass?
readonly string[]
signal?
AbortSignal
timeoutMs
number
Returns
Promise<RunToEndResult>
scopeComponents()
function scopeComponents(scope, principal): (string | undefined)[];
The components that name ONE instance of scope, in order.
request and session are namespaced by tenant because their ids arrive on
the request body: two tenants naming the same session must not meet.
request also carries the request's incarnation, because a request id names
one request only while its record exists. Once retention (or anything else)
deletes the record, the id is free for a new request, from the same user or
another, while state keyed on it (a run workspace directory) stays behind.
The incarnation is what makes the new request a new instance. An absent one
is its own component, never equal to any token. Anything else that keys on
a request and outlives it must key on this list, not on the id alone.
user
and org are not, because they are keyed on an identity the framework
verified, and those scopes are shared across tenants by design — a tenant
segment would split the sharing they exist to provide.
A user or org scope with no such identity falls back to the session,
tenant included. That is a narrowing, never a widening: it can only give a
run less reach than it asked for.
Parameters
scope
principal
Returns
(string | undefined)[]
scopeFolder()
function scopeFolder(
root,
scope,
principal
): string;
The folder one instance of scope keeps its files in, under root.
root/.fsdev/workspaces/<scope>/<segments>, one segment per component of
scopeComponents, so the folder splits exactly where the scope does:
by tenant for a request or session, never for a user or org. Every segment
is encoded, so no id, however hostile, names a folder outside root.
Parameters
root
string
scope
principal
Returns
string
Example
scopeFolder(process.cwd(), "session", principalFromContext(ctx))
segmentDigest()
function segmentDigest(text): string;
12 hex of SHA-256 over bytes that mean text and nothing else: the digest
in a scope-folder segment and in a bash MOAT run name.
UTF-8 alone is not that: it cannot carry a lone surrogate, and Node writes
each one as U+FFFD's bytes, so "\ud800", "\udfff" and "\ufffd" were
one digest and so one directory and one MOAT container.
Valid Unicode still hashes as UTF-8, so every existing directory and run
name keeps its name and nothing moves. Anything else hashes as 0xFF then
its UTF-16LE code units, which keeps every code unit. 0xFF never occurs in
UTF-8, so the two kinds of input cannot spell each other's bytes.
Parameters
text
string
Returns
string
sessionRepositorySource()
function sessionRepositorySource(options): RunSource;
The run source that answers the repository the run's session works in. A
session naming none is refused (no-repository); an unlisted repository
check finds unusable is refused with its problem (repository-unusable).
Parameters
options
SessionRepositorySourceOptions
Returns
setupCommandFrom()
function setupCommandFrom(value, setting): WorkspaceSetup | undefined;
The setup command a setting names (pnpm install --frozen-lockfile): one
command, trimmed and checked with parseCheckoutCommand, as a
workspace host's setup takes it. It runs with no shell. For a host reading
its setup from the environment, beside checkCommandsFrom.
Parameters
value
string | undefined
The setting's value, as read.
setting
string
The setting's name, which a refusal starts with.
Returns
WorkspaceSetup | undefined
The setup, or undefined when the value is unset or blank.
Throws
${setting}: <problem> when the line can't be one command.
splitCheckoutCommand()
function splitCheckoutCommand(command): string | string[];
Split a command into its words, or answer why it can't be one.
Parameters
command
string
Returns
string | string[]
The words (the program first), or a sentence naming what was refused.
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
tryAcquireLock()
function tryAcquireLock(
path,
bounds?,
options?
): LockLease | undefined;
Take the lock at path if it is free now, or undefined when a live holder
has it. Never waits: for a caller that does something else when the lock is
held, such as a read serving what it already has instead of fetching.
A lock left by a holder that died counts as free, judged by the same stale rule a waiting acquire uses, so a crash can't keep a try failing for ever. The lease refreshes itself as an acquired one does; release it the same way.
Parameters
path
string
bounds?
options?
Pick<AcquireOptions, "now" | "owner">
Returns
LockLease | undefined
unscopedCollectionId()
function unscopedCollectionId(collection): string;
The identity for a door that has no principal to scope by.
createBashTool returns plain tools rather than blocks, so it never sees an
execution context — which is also why it refuses a scope. With no scope
instance to name, two tool sets built over the same pattern share an id and
therefore arbitrate.
That over-arbitrates: two sets over unrelated collections with one pattern refuse each other. It is the deliberate direction. The alternative — a unique id per factory call — makes two sets holding refs to the SAME rows invisible to each other, and a missed claim is a silent overwrite where a false one is a reported refusal.
Parameters
collection
pattern
string
scope
Returns
string
workMerged()
function workMerged(options): Promise<MergedProof>;
Whether branch's work has merged, by the three gates in this file's
header. Never throws: what can't be read is unproven, with the reason.
const proof = await workMerged({ repository, branch: "feat/export", defaultRef: "refs/remotes/origin/main", github: { repository: "github.com/acme/app" } });
if (proof.merged) console.log(proof.by === "pull-request" ? `PR #${proof.number}` : `merge ${proof.commit}`);
Parameters
options
Returns
Promise<MergedProof>
worktreeKey()
function worktreeKey(hostId, place): string;
A row's key: the host's id, then the place's segments, each escaped. The
host derives it from a place, so no caller looks a key up. Injective: no
escaped segment holds a /.
Parameters
hostId
string
place
readonly string[]
Returns
string
worktreeLockPath()
function worktreeLockPath(cwd): string;
Where the in-use lock of the worktree at cwd lives: beside it, never inside.
Parameters
cwd
string
Returns
string
worktreeName()
function worktreeName(
key,
label,
place
): string;
A row's name: a slug of label (or the last place segment), then 6 hex of the key's hash.
Parameters
key
string
label
string | undefined
place
readonly string[]
Returns
string