harness

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: Apache-2.0 Imports: 58 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package harness runs workers: one agent process per task, in the task's own worktree, followed and recorded in the store as it goes. A provider (Claude, a fake for tests) knows how to start its agent and read what it says; the harness does the rest the same way for all of them.

Index

Constants

View Source
const (
	DefaultDiskTrim = 30 * GB
	DefaultDiskFull = 10 * GB
)

The disk thresholds djinn up uses unless told otherwise (--disk-trim-gb, --disk-full-gb).

View Source
const (
	// StallSilence is how long a running worker may say nothing, with its CPU idle, before it is stalled.
	StallSilence = 10 * time.Minute
	// StallAfterTurn is StallSilence after the worker's turn ended (its last event its result): it may wait for the
	// background work it started, a monitor or a subagent, which said nothing for up to 25 minutes on this machine.
	StallAfterTurn = 30 * time.Minute
)

The thresholds of a stall, from the history of this machine's tasks (W188, 7 to 17/10/2026: 330 817 gaps between two events of a running worker). 118 gaps passed 5 minutes, 64 passed 10, 47 passed 15. Every gap past 5 minutes whose worker used 5% of a core or more on average was a command at work (tests, builds, benches: 13% to 944%); the idle ones (1% to 3% on average, at most 12% in a reading) were the API outage of 16/10 (W44, W55, W67: 23 minutes, ended by the agent's own "cut off mid-stream"), workers the Lamplighter woke (W3), and workers that waited for their background work after their turn's result (W31, W33, W47: 10 to 25 minutes).

View Source
const (
	DefaultInvestigationMinutes   = 25
	DefaultInvestigationBudgetUSD = 10.0
)

Defaults of an investigation, from the studies and mockups of the wish that asked for it (W213, 17/10/2026): twelve of them ran 9 to 40 minutes, 16 at the median, 11 of 12 under 25; they cost 3 to 12 dollars, 6.4 at the median, 11 of 12 under 10.

View Source
const (
	// LeadMaxTurns caps the model turns of a batch's session.
	LeadMaxTurns = 60
	// LeadMaxBudgetUSD caps what a batch's session spends, as claude counts it.
	LeadMaxBudgetUSD = 5.0
	// LeadTimeout is how long a batch's session may run.
	LeadTimeout = 30 * time.Minute
	// LeadRetryAfter is how long Djinn waits before the second session of a batch whose first failed.
	LeadRetryAfter = 10 * time.Second
)

Guards of a batch of the driven lead: a turn of the lead takes 3 to 5 model calls and a few cents (L10, 16/10), so these stop only a session that loops.

View Source
const (
	CallerYou   = "you"
	CallerLead  = "lead"
	CallerDjinn = "djinn"
)

Who runs a djinn command, in CallerHeader.

View Source
const (
	DefaultPushAfter = time.Hour
	DefaultPushTasks = 3
)

When a push is due when no azima ends: three tasks committed since the last push, and more than an hour since it. A wish sets its own (Wish.push_after_minutes, Wish.push_after_tasks).

View Source
const AgyIdleTimeout = 8 * time.Minute

AgyIdleTimeout is Antigravity's IdleTimeout by default: above agy's own idle timeout on its model's stream (5 min, then agy retries the call by itself 4 s later and keeps its session; agy 1.4.1, W360), so that agy's retry comes first, and Djinn cuts only a call that its retry did not save either.

View Source
const AgyToolIdleTimeout = 30 * time.Minute

AgyToolIdleTimeout is Antigravity's ToolIdleTimeout by default. agy's stream-json says nothing while a command runs, in the foreground or in the background: a background command is a tool step that stays ACTIVE until the command ends, and agy holds back the steps that follow it until then, the model's own included (agy 1.3.3 and 1.4.1, W16 and W308). Past this cap, a silence is taken as a model call that returns nothing: a worker runs commands under 9 minutes each (workerWaitRule), and a gate wait seldom lasts longer.

View Source
const CallerHeader = "X-Djinn-Caller"

CallerHeader is the header in which djinn's command line says who runs it: CallerYou for the developer in a shell, CallerLead for the lead's terminal ($DJINN_LEAD=1), CallerDjinn for a process Djinn started ($DJINN_TASK_ID: a worker, a watcher). A worker is told apart by its token or its process before this header.

View Source
const DefaultIfritIdle = 30 * time.Minute

DefaultIfritIdle is how long the developer may leave Djinn alone before it puts an ifrit out, when neither the ifrit, djinn up --ifrit-idle nor the window's settings say (T51).

View Source
const GB = 1_000_000_000

GB is a gigabyte, as the disk thresholds count.

View Source
const Grace = 5 * time.Second

Grace is how long a worker asked to stop has before it is killed.

View Source
const Quiet = 10 * time.Minute

Quiet is how long a worker that has messages without a result, after a result that did not say how many it still holds, may stay without a line on any output. Past it, those messages are taken as folded into the turn that ended: the input is closed, and the agent exits once done.

View Source
const SilenceLimit = 15 * time.Minute

SilenceLimit is how long a worker may produce no event before the Lamplighter checks its process tree and CPU: long builds and test runs print periodically; background tasks in agy might execute commands, and any gated command is excluded by checking the gate it holds or waits for. An idle or dead worker past this limit is ended.

View Source
const SilentAfterResult = StallSilence

SilentAfterResult is how long a worker may stay silent after its turn's result, its CPU idle, before Djinn stops it: StallSilence, the health's own threshold (W188). Picked from the runs of the wish Djinn QoL (14 to 17/10/2026, 315 results followed by an event): 7 silences after a result passed 5 minutes. Three waited for tests the worker had sent to the background, busy at 160% to 210% of a core (W7, 22.7 min; W53, 8.7; W135): the CPU test spares them. Two waited for a usage limit (W63, 18.6 min; W93, 12): a turn that ended on a limit or an error is told otherwise. W86 waited 9.5 minutes, idle (1.8%), for a monitor on the machine's load, then went on. W267 stayed idle (1.2%) 11 minutes until the lead stopped it. Ten minutes spares the longest idle wait that went on, and stops W267.

View Source
const StreamIdleTimeout = 5 * time.Minute

StreamIdleTimeout is how long a model call that returns nothing may wait before being cut and continued. Standard LLM streams produce chunks within seconds; 5 minutes without any stream event indicates a dead connection.

View Source
const TaskMaxTurns = 500

TaskMaxTurns is how many model turns a worker may take before being stopped: a guard against an endless loop, not a cap on real work. Real Opus tasks take a hundred turns and more (W442: 102, W453: 112, both stopped at the former limit of 50). The count is per run, not per task: start sets it to 1 each time a worker starts (first start, restart, resume, continue, answer); each prompt the worker says adds one; claude's count of its assistant messages (Event.Turns) and the provider's own count of a result (num_turns) replace it when larger. The task shows it (Task.turns).

View Source
const TaskMaxWallTime = 2 * time.Hour

TaskMaxWallTime is how long a task may run before being stopped: the sum of its runs in the current budget (taskWallTime), time waiting for a gate included, time held between runs (a usage limit, a pause) left out. Automatic resumes (restart, limit lifted, Lamplighter wakes) keep counting; a deliberate continue (djinn task continue) opens a new budget. Generous for heavy builds and e2e-heavy tasks (past an hour), while stopping 4h runaway zombies.

View Source
const (
	// WatchQuiet is how long a command stays silent before what it printed makes a paragraph.
	WatchQuiet = time.Second
)

What a watcher waits for, by default.

Variables

View Source
var ErrClosed = errors.New("the worker takes no more messages")

ErrClosed is returned by Send when the worker takes no more messages.

View Source
var ErrReadOnly = errors.New("it cannot be kept from writing")

ErrReadOnly is returned by Start when the provider cannot keep its agent from writing: it cannot run a read-only worker.

View Source
var PermissionsFile = plan.PermissionsFile

PermissionsFile is where a project declares what an agent may do in it (plan.PermissionsFile).

Functions

func CanonicalModel added in v0.2.0

func CanonicalModel(raw string) string

CanonicalModel returns the canonical model identifier when raw names a recognized agent model (from `agy models`, the pricing table, or a provider's model family), and "" when raw is empty, a URL, or not a model name (such as "standard-paygo").

func ClockText added in v0.2.0

func ClockText(t, now time.Time) string

ClockText writes a time of the machine's day: 07:20, or with its date when it is not today.

func DefaultModel added in v0.1.1

func DefaultModel(p planv1.Provider) string

DefaultModel is the model a provider runs when no model was requested; empty when it has none.

func Handler

func Handler(h *Harness) (string, http.Handler)

Handler returns the Connect handler of TaskService on h, and its path prefix.

func HealthLine added in v0.2.0

func HealthLine(t *planv1.Task) string

HealthLine is the line that tells a task's lead its worker needs a relaunch, and the command that does it.

func InstallWith added in v0.1.2

func InstallWith(ctx context.Context, output func(line string), low bool) context.Context

InstallWith returns ctx for Install: each line its commands write (the setup's, the install command's) told to output as it comes (nil: none), and, when low, those commands run at a low-priority worker's CPU priority: an install Djinn starts by itself.

func LeadPermissions added in v0.1.2

func LeadPermissions() *djinnv1.Permissions

LeadPermissions are the permissions pre-authorized for a lead session: reading and plan.LeadCommands; no edit.

func LimitModel added in v0.2.0

func LimitModel(text string) string

LimitModel returns the canonical model name a limit message or wait reason proves exhausted, or "" when the message names no model. It never reads a model from a URL.

func LoadPermissions

func LoadPermissions(dir string) (*djinnv1.Permissions, error)

LoadPermissions reads the permissions a project declares in dir, each field a newer Djinn knows logged once. It returns nil, and no error, when the project declares none.

func LocalBuild added in v0.1.1

func LocalBuild(version string) (commit string, dirty, ok bool)

LocalBuild is the commit a Djinn built from a checkout comes from, as go tool task install stamps its version (local-<git describe --always --dirty>: local-1a2b3c4, local-v0.1.0-3-g1a2b3c4-dirty), and whether its tree had changes not committed; ok is false for any other version.

func P95 added in v0.1.1

func P95(vals []uint64) uint64

P95 calculates the 95th percentile of uint64 values using linear interpolation.

func PlanHandler

func PlanHandler(h *Harness) (string, http.Handler)

PlanHandler returns the Connect handler of PlanService on h, and its path prefix.

func ProbeHTTP added in v0.2.0

func ProbeHTTP(ctx context.Context, provider planv1.Provider) error

ProbeHTTP is djinn up's probe: one HEAD request to provider's API host. Any answer under 500 says the network is up; a 5xx, the provider is down for its workers all the same.

func Providers

func Providers() map[planv1.Provider]Provider

Providers are the providers Djinn knows, by the name a task gives.

func ServeHandler added in v0.2.0

func ServeHandler(h *Harness) (string, http.Handler)

ServeHandler returns the Connect handler of ServeService on h, and its path prefix.

func SilentLine added in v0.2.0

func SilentLine(t *planv1.Task, why string, integrate bool) string

SilentLine is the line that tells t's lead Djinn stopped its worker, silent after its result for why, and what follows; integrate says whether its work goes to integration. "" for a failure: the failure's own line tells it.

func Touching added in v0.2.0

func Touching(next http.Handler, p *Presence) http.Handler

Touching passes every request on to next, and counts the developer's as their presence: any request of djinn's command line they type in a shell, and the window's actions (yourActions). A worker's (plan.CallerFromContext, set by server.WorkerContext around it), the lead's and those of the processes Djinn starts are none.

func WatchLine

func WatchLine(code string, w *Watched) string

WatchLine is the line that tells a lead what its watcher's command printed: the first line of the paragraph, and whether the command still watches; or that the command ended, after a paragraph that said it still watched.

Types

type AccountFunc added in v0.2.0

type AccountFunc func(ctx context.Context, provider planv1.Provider) string

AccountFunc tells which account provider's agent is signed in with on this machine, as a fingerprint that never holds the account's name; empty when it cannot tell. djinn up gives ui.Account.

type Antigravity

type Antigravity struct {
	// Command is the agy program; "agy", found on the PATH, by default.
	Command string
	// Grace is how long a worker asked to stop has before it is killed; Grace by default.
	Grace time.Duration
	// IdleTimeout is how long a model call that returns nothing may wait before being cut and continued;
	// AgyIdleTimeout by default.
	IdleTimeout time.Duration
	// ToolIdleTimeout is how long agy may say nothing while a tool step or a background task of its own runs, before
	// being cut and continued all the same; AgyToolIdleTimeout by default.
	ToolIdleTimeout time.Duration
}

Antigravity runs Google's Antigravity CLI headless: `agy --input-format stream-json --output-format stream-json`, one NDJSON message per turn on its input, one event per line on its output (docs/providers.md). Like Claude, the process stays open between turns, and ends once every message has its result.

Djinn passes its environment on and sets nothing about signing in: agy signs in by itself (decision Q20). Djinn never reads agy's configuration, its tokens, nor the Application Default Credentials file. It writes one thing of agy's: a project of its own per worktree, for a worker with permissions (agyProject).

func (Antigravity) Start

func (a Antigravity) Start(ctx context.Context, spec Spec) (Worker, error)

type Built

type Built struct {
	WishID, WishTitle, ProjectID, Project, Branch, Sha string
	// The tasks whose work the push brought, by code.
	Tasks []string
	// The titles of the commits the push brought, the latest first.
	Changes []string
	// What changed, one per task: its code and title, and its worker's summary.
	Summaries []TaskSummary
	// The install command.
	Install string
	// The commit the running Djinn was built from, when the project holds it: Tasks, Summaries and Changes are then
	// what the build adds to it (compare.go). Empty: they are what the push brought.
	Base string
	// The running Djinn was built from Branch.
	Running bool
	// How many commits, merges aside, the build adds to the running Djinn; Changes holds the latest.
	ChangesCount int
	// The titles of the commits the running Djinn holds and the build does not, the latest first, and how many.
	Lacks      []string
	LacksCount int
	// The line of the running Djinn this build carries on from another branch: Sha holds the commit the running
	// Djinn was built from (compare.go). The branch that one was built from, or its short commit; empty for a build of
	// that branch (Running) and for a parallel one.
	Continues string
	// Djinn installs it by itself (installsItself): a build of the running Djinn's line, the push checks passed, in a
	// project whose install_builds is on. Other builds are only offered.
	Auto bool
}

Built is a wish's integration branch as Djinn pushed it, in a project whose settings name an install command: djinn up proposes to install it, and to restart on it (WithBuilt).

type Capacity

type Capacity func() (slots int, rule, pressure string)

Capacity says how many workers may run at once now and the rule that gave it, and why the machine is under pressure ("" when it is not). djinn up gives the machine's (internal/machine); without one, nothing limits.

type Claude

type Claude struct {
	// Command is the claude program; "claude", found on the PATH, by default.
	Command string
	// Grace is how long a worker asked to stop has before it is killed; Grace by default.
	Grace time.Duration
	// IdleTimeout is how long a model call that returns nothing may wait before being cut and continued; StreamIdleTimeout by default.
	IdleTimeout time.Duration
	// Extra are arguments passed after Djinn's own: the workers' bench tries --bare and a system prompt file.
	Extra []string
}

Claude runs Claude Code: `claude -p` reading and writing stream-json, one JSON message per line. The process stays open between turns, so Send can give it another message; it ends once every message has its result.

func (Claude) Start

func (c Claude) Start(ctx context.Context, spec Spec) (Worker, error)

type Codex

type Codex struct {
	// Command is the codex program; "codex", found on the PATH, by default.
	Command string
	// Grace is how long a worker asked to stop has before it is killed; Grace by default. It is also how long the
	// app-server has to end once its input is closed.
	Grace time.Duration
}

Codex runs OpenAI's Codex through its app-server: `codex app-server --listen stdio://`, JSON-RPC 2.0 with one JSON message per line on stdio (docs/providers.md). Djinn opens a thread in the worktree, and runs one turn per message: the prompt, then each message Send gives, in order. Once the last turn has completed, the input is closed and the app-server ends.

Djinn passes its environment on and sets nothing about signing in: codex signs in by itself.

func (Codex) Start

func (c Codex) Start(ctx context.Context, spec Spec) (Worker, error)

type DiskGuard added in v0.2.0

type DiskGuard struct {
	// Free is the space Djinn may use on the file system that holds dir, in bytes.
	Free func(dir string) (uint64, error)
	// Under Trim bytes free where the Go build cache is, Djinn trims it; 0: never.
	Trim uint64
	// Under Full bytes free where its data folder or the Go build cache is, the lead hears it and the push checks wait;
	// 0: never.
	Full uint64
}

DiskGuard is how Djinn watches the free space of its disks (djinn up gives it).

type Event

type Event struct {
	Kind planv1.TaskEventKind
	// Text is the event for a reader.
	Text string
	// Raw is the provider's line as it came, on the first event made from it.
	Raw string
	// Usage is what the worker spent so far in this run, on a usage event.
	Usage *planv1.Usage
	// SessionID is the agent's session, when the event tells it.
	SessionID string
	// Limit is the provider's usage limit, when the event says the worker hit it: the task waits for it to reset,
	// should the worker then fail.
	Limit *Limit
	// Watched is set on a paragraph a watcher's command printed: the wish's lead is told its first line.
	Watched *Watched
	// Ran is set at the end of each run of a watcher's command, when its Watch asks for it (Watch.Runs).
	Ran *Ran
	// Model is the model the worker actually runs, when the event tells it.
	Model string
	// Ifrit is set by a worker started with Spec.Listen when its agent starts a turn on a message (WORKING), and
	// when the turn ends and the agent waits on its open input (LISTENING).
	Ifrit planv1.IfritState
	// Serve is set by Djinn on an event of an ifrit's serve (serve.go): the serve as it stands now, which replaces the
	// one of its name in Task.ifrit.serves.
	Serve *planv1.Serve
	// Turns is how many model turns the worker took so far, on the first event of a new one: the Lamplighter's count
	// grows as they come, not only at a result (num_turns).
	Turns int
	// Spent is what the worker spent so far in this run, in US dollars, as Djinn estimates it from the token counts its
	// agent says as it goes, for an agent that says its cost at a result only (claude): an investigation is asked to
	// publish at its budget before its provider cuts it (investigationDue).
	Spent float64
	// ToolError is set on a tool result whose call failed or was refused by its provider.
	ToolError bool
}

Event is something a worker said. Text and Raw stay free; Kind is what Djinn makes of it.

type Fake

type Fake struct{}

Fake is an agent that plays a script, to try Djinn and test it without a paid model. Each line of the prompt is a step:

text Hello            the agent writes Hello
tool Bash ls -la      it calls a tool
result total 8        the tool returns
usage 1200 300 0.02   it has spent so far 1200 tokens in, 300 out, $0.02
turns 37              it has taken 37 model turns so far in this run
write notes.md Hi     it writes Hi in notes.md, in its folder, when it may edit (else: permission denied)
refuse Bash gcloud x  its permissions refuse the call, as claude says it: Bash {"command":"gcloud x"}
sleep 5s              it works for a while
wait                  it works until a message comes (Send), which it says back at the end as the others
fail no tests         it fails with this reason
error API Error: 500  it says an error and goes on, as claude does on a turn that failed (its process lives on)
exit 2                its process exits with this code
djinn task list       it runs Djinn's command line, as an agent does: this djinn, in its folder, with its task's
                      environment ($DJINN_TASK_ID); "…" and '…' quote an argument

Any other line is said back as text. It runs in Djinn's process: stopping it ends its script at once, pausing it holds its script before the next step until it is resumed. Started with Spec.Listen, it listens once its script is played: each message it takes starts a turn that says it back, until its input is closed (CloseInput).

func (Fake) Start

func (Fake) Start(ctx context.Context, spec Spec) (Worker, error)

type Harness

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

Harness runs the tasks' workers and records what they say. Close it before the store.

func New

func New(s *store.Store, home string, providers map[planv1.Provider]Provider, opts ...Option) *Harness

New returns a harness on the store s. Worktrees go under home, Djinn's data folder. Without options, nothing limits the workers and the wishes are served by rank; Schedule starts the planned tasks.

func (*Harness) AddWorkerSample added in v0.1.1

func (h *Harness) AddWorkerSample(taskID string, p *machinev1.WorkerPoint)

AddWorkerSample appends a sample point for taskID (useful in tests).

func (*Harness) Answered

func (h *Harness) Answered(ctx context.Context, q *planv1.Question) string

Answered takes the answer to a question: when it is a task's edit question, a yes starts the task's worker again, allowed to edit the project's files and to run no command, through the scheduler when no worker runs it; a no leaves it reading only. When Djinn asked it about work that failed to integrate, it settles that work (answerIntegration); about a push, it pushes or waits (answerPush). The task the chosen option planned it launches, or leaves to the lead (answerPlan). The worker that asked it gets the decision: sent while it runs, or its task, which waits on its blocking question, continued with it (answerAsker). Any other answer is a decision for the lead to turn into tasks. Only the first answer counts. The plan services call it once the answer is stored. It says what Djinn did with the answer, for the lead; "" when the answer is the lead's to act on.

func (*Harness) Caller added in v0.1.1

func (h *Harness) Caller(peerPID int, token string) *plan.WorkerCaller

Caller returns the WorkerCaller if the peerPID or token matches any currently running worker.

func (*Harness) Cancel added in v0.1.1

func (h *Harness) Cancel(ctx context.Context, procedure string, req *planv1.TaskServiceCancelRequest) (*planv1.Task, error)

Cancel cancels a task: stops its worker if running or paused, records who cancelled it, removes its worktree and scratch folder while keeping the branch, and drops its work from integration. Refused on a task done or cancelled already, and on an azima.

func (*Harness) Cgroups added in v0.2.0

func (h *Harness) Cgroups() []string

Cgroups returns the cgroups of the running workers' scopes (machine.Scope.Cgroup): the Hourglass counts them, and what their processes started out of them, as Djinn's (machine.ReadWork).

func (*Harness) Clean

func (h *Harness) Clean(ctx context.Context, procedure string, req *planv1.TaskServiceCleanRequest) (*planv1.Task, error)

Clean removes the worktree and scratch folder of a task that has ended. Its branch stays.

func (h *Harness) ClearCorrectionLinks(ctx context.Context, wishID, taskID string) error

ClearCorrectionLinks clears links pointing to taskID as corrected_by on any push, main merge, or integration failure in wishID.

func (*Harness) Close

func (h *Harness) Close()

Close stops the scheduler and every worker, waits for them to end, and records their tasks as interrupted.

func (*Harness) CloseOutrun added in v0.2.0

func (h *Harness) CloseOutrun(wishID, code string)

CloseOutrun closes the failed or held investigators of the question code of the wish that it outran (outrun).

func (*Harness) Comment added in v0.1.1

Comment stores a review comment on a line or range of lines of a task's diff. While the task's worker runs, the comment is sent to it as an instruction (djinn task send, with the file and lines quoted).

func (*Harness) Continue

func (h *Harness) Continue(ctx context.Context, procedure string, req *planv1.TaskServiceContinueRequest) (*planv1.Task, error)

Continue plans again a task no worker runs, done, failed, stopped, cut short, or waiting on the blocking question its worker asked (the answer continues it so, with the decision: answerAsker): its next worker resumes its own session, in its own worktree, on the prompt. It starts in this call when the scheduler would start it; otherwise it waits, with the reason, and the scheduler starts it. Refused while the task runs or is planned, when it continues in a fork, when its worktree is gone, or when its agent cannot resume a session. A running worker the scheduler flagged stalled is the exception: it is ended and continued on its session (continueStalled).

func (*Harness) Delete

func (h *Harness) Delete(ctx context.Context, procedure string, req *planv1.TaskServiceDeleteRequest) (*planv1.Task, error)

Delete removes a task no worker of this Djinn ran, with its events: a plan item, or a task imported from another Djinn. A task a worker of this Djinn ran (it has a session or a worktree) is the record of that work: it stays. An azima goes once no task is part of it: those are named, to be regrouped first (Group), for no task may be part of an azima that is gone. A task others wait for (DependsOn, in any wish) goes once they are rewired (Depend --also): those are named too. Its code is retired with it (Wish.retired_codes): no task of the wish gets it again.

func (*Harness) Depend

func (h *Harness) Depend(ctx context.Context, procedure string, req *planv1.TaskServiceDependRequest) ([]*planv1.Task, error)

Depend sets the dependencies of the task, and of the others the request names (--also), in place of those they had: tasks of their wish, by code or identifier. All or none: a dependency on itself, a task whose worker runs, or a graph that would close a cycle refuses them all, naming the cycle. The scheduler then looks again.

func (*Harness) Describe

func (h *Harness) Describe(ctx context.Context, taskID string) (string, error)

Describe names a task for those who wait behind it: its code and title.

func (*Harness) DescribeTask added in v0.1.1

func (h *Harness) DescribeTask(ctx context.Context, procedure string, req *planv1.TaskServiceDescribeRequest) (*planv1.Task, error)

DescribeTask sets the description of an azima, and writes it back to its plan file if it has one.

func (*Harness) DescribeVersion added in v0.1.1

func (h *Harness) DescribeVersion(ctx context.Context, version string) (Built, bool)

DescribeVersion names the newer Djinn of version, ready at the path of the running one, as a build: the project whose repository holds its commit, the branch and wish it comes from, and what it holds against the running Djinn. ok is false when no project holds its commit: a release no checkout knows yet, or a development build.

func (*Harness) Diff added in v0.1.1

Diff returns the list of files changed by a task, or the unified diff with syntax tokens for a single file.

func (*Harness) DiskFolders added in v0.2.0

func (h *Harness) DiskFolders() []*machinev1.DiskFolder

DiskFolders returns the main folders Djinn knows on disk, biggest first, with their size in bytes. It measures them on the server at most once per diskFoldersEvery, without blocking the caller when a large cache takes longer.

func (*Harness) DiskItems added in v0.2.0

func (h *Harness) DiskItems() []*machinev1.DiskItem

DiskItems returns the known caches and stores on the machine, biggest first, with their size, what their cleanup command frees and its risk. It measures them at most once per diskFoldersEvery, without blocking the caller when a large cache takes longer. Djinn never runs a cleanup command: it only reports it.

func (*Harness) Done

func (h *Harness) Done(ctx context.Context, procedure string, req *planv1.TaskServiceDoneRequest) (*planv1.Task, error)

Done marks a task done by hand: a task no worker runs now, planned, waiting, cut short, failed, stopped or imported. The task records who closed it, when and why, apart from a worker's own done. A running or paused task is refused (stop it first), and so is a task done already, but one done with problems (plan.DoneWithProblems): marked done, it is closed as seen, nothing else changes. A task waiting on it may start. A lit ifrit is ended instead: its input closes, and its work integrates once its agent ends (doneIfrit).

func (*Harness) Enlightened

func (h *Harness) Enlightened(ctx context.Context, q *planv1.Question, note string)

Enlightened starts an investigator on q, which the developer wants to know more about before answering, with their note. The plan services call it once the request is stored; the lead is told next, when no investigator works on q (plan.Wishes.Enlightened). A start that hangs leaves q to the lead.

func (*Harness) FillModels added in v0.1.1

func (h *Harness) FillModels(ctx context.Context, tasks []*planv1.Task)

FillModels fills the forecast model on planned or waiting tasks whose model is empty, and ensures watchers and azimas have no model.

func (*Harness) FlushTell added in v0.1.1

func (h *Harness) FlushTell(ctx context.Context)

FlushTell sends any pending batched messages to the leads immediately.

func (*Harness) Forced added in v0.1.2

func (h *Harness) Forced() int

Forced is the number of the workers running (Running) that the developer started or resumed by hand, whatever the slots (djinn task start, djinn task resume): the ones the load bar shows beyond what it lets run.

func (*Harness) ForgetSync added in v0.2.0

func (h *Harness) ForgetSync(ctx context.Context, project *planv1.Project, branch string) error

ForgetSync forgets the sync of branch in project: Syncs leaves it out until its tip moves. A branch with commits to push keeps its sync.

func (*Harness) GatesOutside

func (h *Harness) GatesOutside(n func() (outside, merges int))

GatesOutside tells the harness how many gates are held outside its running workers, by a person's terminal, a lead, a script or Djinn's own merges and pushes, and how many of them are those merges' and pushes': each takes a slot, so no new worker starts on it while it is held. Once told, the scheduler keeps one slot for the merges and pushes on a machine of more than one (dispatch.Machine.Keep). djinn up gives the gates' (gate.Gates.Outside). n calls the harness back (Works): it runs without h.mu (W549).

func (*Harness) Group

func (h *Harness) Group(ctx context.Context, procedure string, req *planv1.TaskServiceGroupRequest) (*planv1.Task, error)

Group sets the azima the task is part of, in place of the one it had: an azima of its wish, by code or identifier, or none. One that would close a cycle with what the tasks depend on is refused, naming it. A grouping, never a wait: the scheduler looks at what the task depends on only.

func (*Harness) HasRun added in v0.1.1

func (h *Harness) HasRun(taskID string) bool

HasRun tells whether a worker of the task runs, paused or not.

func (*Harness) HeldGates

func (h *Harness) HeldGates(held, waiting func(taskID string) []string)

HeldGates tells the harness which gates a task holds, and which it waits for, by name: a worker holding or waiting for one is not paused. djinn up gives the gates' (gate.Gates.Held and Waiting), once they exist. They run under h.mu: they must never call the harness back.

func (*Harness) Ifrit added in v0.2.0

func (h *Harness) Ifrit(ctx context.Context, taskID string) (lit bool, out time.Time, why string)

Ifrit tells the gates whether the task taskID is an ifrit lit now, and when it goes out unless the developer comes back: its gates have no timeout, their expire time is its out time, and they go back once it goes out or ends (Q11). It is lit until its run ends, a djinn task done waiting for the turn under way included, unless it goes out; then why says why, from its task once its run is over. A task that is no ifrit is not lit, with no why.

func (*Harness) IfritIdle added in v0.2.0

func (h *Harness) IfritIdle(t *planv1.Task) time.Duration

IfritIdle is how long the developer may leave Djinn alone before it puts the ifrit t out: its own (djinn task spawn --idle-minutes), else djinn up --ifrit-idle, else the window's settings, else DefaultIfritIdle.

func (*Harness) Install

func (h *Harness) Install(ctx context.Context, wishID, projectID, sha string, progress func(step InstallStep, waiting string)) (string, error)

Install runs the install command of the project's settings on sha, a build of the wish's integration branch there: in the project's install worktree, checked out at it, never the person's checkout nor an integration worktree, under the install gate. It never waits for an integration: the build is a commit already made, and its worktree is its own. One install runs at a time. progress, when not nil, is told each step as it comes, and what the install waits for when it waits ("" otherwise). It returns the end of the command's output, and an error when it did not end well.

func (*Harness) Integrate

func (h *Harness) Integrate()

Integrate starts committing the tasks' finished work into their wishes' integration branches, by itself, and pushing them: woken when a task ends done or a push is approved, and every minute. djinn up calls it once the harness has recovered; Close stops it, and the work it was on is integrated again at the next start.

func (*Harness) Iterated added in v0.2.0

func (h *Harness) Iterated(ctx context.Context, q *planv1.Question, round *planv1.Round) string

Iterated starts the mockup task of round, the iteration round just stored on q, and returns its code; "" when none starts: the plan services then tell the lead (plan.Wishes.Iterated). A start that hangs leaves q to the lead.

func (*Harness) LaunchPlan added in v0.2.0

func (h *Harness) LaunchPlan(ctx context.Context, q *planv1.Question, p *planv1.PlannedTask) (*planv1.Task, error)

LaunchPlan spawns the task p plans for an option of the answered question q, its decision q, and records it in the question's plan of that option, which becomes the task as it was launched. A plan launched already is refused: one launch at a time, the question read again first. The caller checks that the plan holds.

func (*Harness) LeadDriver added in v0.2.0

func (h *Harness) LeadDriver(wishes *plan.Wishes, changed func()) *LeadDriver

LeadDriver is the driver of the lead of h's Djinn, on wishes: h's Claude, its processes tracked.

func (*Harness) LookAtMain

func (h *Harness) LookAtMain()

LookAtMain makes the integration's next pass fetch main at once, whatever the cadence: a release was found.

func (*Harness) LowerPauses added in v0.1.2

func (h *Harness) LowerPauses() bool

LowerPauses tells whether lowering the operating load pauses the workers above what it lets run, as the window says: not in Auto mode (Q124 C), nor on Windows, where a worker cannot pause; they finish their run then.

func (*Harness) Move added in v0.1.1

func (h *Harness) Move(ctx context.Context, procedure string, req *planv1.TaskServiceMoveRequest) (*planv1.Task, error)

Move moves an azima and its unstarted parts to another wish, with its plan file reference.

func (*Harness) NetworkDownSince added in v0.2.0

func (h *Harness) NetworkDownSince() *timestamppb.Timestamp

NetworkDownSince is since when the network is down, as a probe confirmed; nil while it is up, or only suspected. The window's status bar says it.

func (*Harness) Note

func (h *Harness) Note(taskID string, ev Event)

Note adds an event that comes from outside the worker, such as a gate taken or given back, to the task's events: through its run when its worker runs, directly otherwise.

func (*Harness) NotifyLead added in v0.1.1

func (h *Harness) NotifyLead(notify NotifyFunc)

NotifyLead lets Djinn queue the lead's events (decision Q191) instead of typing lines in its terminal: djinn up gives it once its terminals run. Without it, the lines go to TellLeads' function, as they did.

func (*Harness) Now added in v0.1.1

func (h *Harness) Now() time.Time

Now returns the harness's current time.

func (*Harness) OnWatched

func (h *Harness) OnWatched(f WatchedFunc)

OnWatched gives each new paragraph of a watcher to f, after its lead is told. djinn up gives it once.

func (*Harness) Open added in v0.1.1

func (h *Harness) Open(ctx context.Context, procedure string, req *planv1.TaskServiceOpenRequest) (*planv1.Task, error)

Open turns a draft azima OPEN: its plan file front matter says status: open, and the lead is told to plan its tasks.

func (*Harness) Overlaps added in v0.2.0

func (h *Harness) Overlaps(ctx context.Context, wishID string) (*planv1.TaskServiceOverlapsResponse, error)

Overlaps is TaskService.Overlaps: the files the open work of a wish touches, and the pairs of tasks of a project that touch the same ones. A task's diff that git cannot read leaves its paths unknown, never the call failed.

func (*Harness) OverlapsBrief added in v0.2.0

func (h *Harness) OverlapsBrief(ctx context.Context, wishID string) string

OverlapsBrief is the Overlaps section of a wish's brief: the pairs of open tasks that touch the same files, and the planned tasks whose paths nobody knows; empty when there is neither.

func (*Harness) Pause

func (h *Harness) Pause(ctx context.Context, procedure string, req *planv1.TaskServicePauseRequest) (*planv1.Task, error)

Pause holds the task's worker where it is, without killing it, until Resume: the task is paused, and its slot of the machine is free meanwhile. A worker whose provider cannot pause, or Windows, refuses. A worker that holds a gate is not paused: the gate would stay held, frozen, for every other worker. Nor is one that waits for a gate: it would get the gate in its turn, and hold it frozen.

func (*Harness) Paused added in v0.1.1

func (h *Harness) Paused() int

Paused is the number of workers paused now. A paused worker holds still: it takes no slot, but keeps its memory.

func (*Harness) Places added in v0.2.0

func (h *Harness) Places(ctx context.Context, taskIDs []string) map[string]int

Places gives the position of each task's azima among the azimas of its wish, in their rank (plan.AzimaOrder): the gates serve the work of the first azimas first, within its wish's rank. A task part of no azima, or unknown, is not in the map.

func (*Harness) Policy added in v0.1.1

func (h *Harness) Policy() machine.Policy

Policy returns the current scheduling policy.

func (*Harness) Presence added in v0.2.0

func (h *Harness) Presence() *Presence

Presence is the developer's presence, which keeps the ifrits lit.

func (*Harness) Pull added in v0.2.0

func (h *Harness) Pull(ctx context.Context, project *planv1.Project, branch string) ([]*planv1.BranchPull, error)

Pull brings the branches of project's syncs that are behind their remote up to it, each fetched first (pullBranch): only branch when it is named, a refusal then an error; else every sync, each refusal said in its pull. A branch work merges into is refused, as one that diverged or whose checkout holds changes; the lead of its wish is not told: the developer asked, and reads the answer.

func (*Harness) Push added in v0.1.1

func (h *Harness) Push(ctx context.Context, wishID, projectID, branch string) (*planv1.IntegrationPush, error)

Push pushes the integration branch of wishID in projectID, or under the per-azima strategy its azimas' branches too; only branch when it is not empty: the wish's integration branch or one of its azimas' own. It runs push checks under gates, never with --force. It runs to its end whatever the caller does meanwhile (a window reloaded, a command line stopped): its sync line shows it; only djinn up stopping stops it. A merge that lands during its push checks has them run again on the new tip, pushTries times at most (push_apart.go).

func (*Harness) QuestionEndLine

func (h *Harness) QuestionEndLine(ctx context.Context, t *planv1.Task) (string, error)

QuestionEndLine is the line that tells a lead what the question worker t did, once it ended.

func (*Harness) Rank added in v0.2.0

func (h *Harness) Rank(ctx context.Context, procedure string, req *planv1.TaskServiceRankRequest) ([]*planv1.Task, error)

Rank places an azima among the azimas of its wish (Task.rank): first, or just before or after another one. The scheduler starts the waiting work of the first azimas first, and the gates serve it first after the merges and pushes. It returns the wish's azimas in their new order.

func (*Harness) Ranks

func (h *Harness) Ranks(ctx context.Context, taskIDs []string) map[string]int

Ranks gives the position of each task's wish among the active wishes, the first served first; the task of a wish that is not active, or unknown, is not in the map. The gates serve their waiters in this order.

func (*Harness) Recover

func (h *Harness) Recover(ctx context.Context) error

Recover marks as interrupted the tasks a previous djinn up left running: their workers died with it. They keep what resuming them needs (provider, session, worktree). Then every interrupted task Djinn may resume waits for the scheduler to resume it (queueInterrupted). The lead's restart event names the workers the last djinn up left running, and those it stopped as it ended, interrupted since it started (lastStart). First, the azimas stored as work before tasks had kinds become azimas (migrateAzimas), and a task part of an azima that is gone becomes part of none (ungroupOrphans). Before all, the processes the last djinn up started and left running are stopped (children.sweep), so that no task resumes beside its old worker: the restart event names them; an ifrit's serves they ran are stopped, their stop commands run (recoverServes).

func (*Harness) Reference added in v0.2.0

func (h *Harness) Reference(ctx context.Context, project *planv1.Project, name string) (branch, ref string, err error)

Reference is the project's reference branch, from name, its main_branch setting, as mainRef finds it, and the ref Djinn merges it from; an error when the repository does not hold that ref, nor finds any.

func (*Harness) Release

func (h *Harness) Release(ctx context.Context, build string, dirty bool, tag string) (ReleaseFit, error)

Release says what tag, a newer release of Djinn, means for a Djinn built from the commit build, dirty when its tree had changes not committed: in the project whose repository holds that commit, main and the tags fetched when the repository does not know the release yet, it looks where the person's checkout is. On a branch, the integration looks at main at once.

func (*Harness) Resident added in v0.1.1

func (h *Harness) Resident() uint64

Resident returns the resident memory of the workers running or paused, as last read, watchers left out: what the memory available already leaves out, which the memory Djinn may commit counts back in (machine.Monitor.SetWorkerMemory). It never waits for mu: every machine snapshot reads it, and 60 of them piled up behind W549's freeze.

func (*Harness) Resume

func (h *Harness) Resume(ctx context.Context, procedure string, req *planv1.TaskServiceResumeRequest) (*planv1.Task, error)

Resume lets a paused worker go on. It does not wait for a slot: the developer asked for it, and the load bar shows it beyond what it lets run (Forced).

func (*Harness) ResumeDecisions added in v0.2.0

func (h *Harness) ResumeDecisions()

ResumeDecisions continues each task that waits on a blocking question answered already: djinn up stopped between storing the answer and continuing the task. djinn up calls it once it serves; it works in the background, and Close waits for it.

func (*Harness) ResumeInvestigations added in v0.1.2

func (h *Harness) ResumeInvestigations()

ResumeInvestigations follows up each request to investigate, or iteration on a mockup (resumeIteration), that was left without one: djinn up stopped, or hung until it was made to quit, between storing the request and starting its investigator or telling the lead, and the question stayed under investigation with no one on it (W536). Each one gets its investigator now, or else the lead's event, once: a request that an investigator took on, or the lead heard of, is followed up already. djinn up calls it once the lead's events go out; it works in the background, and Close waits for it.

func (*Harness) RunSources

func (h *Harness) RunSources(receive ReceiveFunc)

RunSources runs the inbox sources of the projects' skills until Close, and gives each item they print to receive. djinn up calls it once.

func (*Harness) Running

func (h *Harness) Running() int

Running is the number of workers that run now, each in a slot: every agent, a question worker's included (W577: the load bar's count is the agents that run). A paused worker does not count: it takes no slot; nor does a watcher, which sleeps until its command prints.

func (*Harness) RunsSeries added in v0.1.1

func (h *Harness) RunsSeries(cutoff time.Time, gateIntervals []*machinev1.GateInterval) []*machinev1.WorkerSeries

RunsSeries returns the measurement series for all running workers since cutoff, associating each worker with gate intervals matching its task ID.

func (*Harness) Schedule

func (h *Harness) Schedule()

Schedule starts the scheduler: a planned task starts as soon as its dependencies are done, its write scopes are free and a slot is free, and an asleep question wakes once its conditions hold. djinn up calls it once the harness has recovered; Close stops it.

func (*Harness) Send

func (h *Harness) Send(ctx context.Context, procedure string, req *planv1.TaskServiceSendRequest) (*planv1.TaskEvent, error)

Send gives a running worker a message, an instruction added while it works. The pump writes it on the worker's input and records it as a MESSAGE event; the first thing the worker says after it is preceded by a RECEIVED event. A worker that ends first never acknowledges it. An ifrit out, or going out, is lit again for the message (relight).

func (*Harness) SetPolicy added in v0.1.1

func (h *Harness) SetPolicy(p machine.Policy)

SetPolicy updates the scheduling policy and wakes the scheduler for the next pass.

func (*Harness) Shelve

func (h *Harness) Shelve(_ context.Context, wishID string)

Shelve stops the workers of the wish wishID, watchers too: each task waits to resume with its wish. It does not wait for them to end. The plan calls it once a wish is paused (plan.WishWorkers).

func (*Harness) Spawn

func (h *Harness) Spawn(ctx context.Context, procedure string, req *planv1.TaskServiceSpawnRequest) (*planv1.Task, error)

Spawn creates a task and starts its worker: in a Git project, in a new worktree on its own branch. procedure is the method the request came by, for the journal. A task that cannot start now (a dependency not done, its write scope taken, no slot free, the machine under pressure), or planned for later, is created pending with the reason, and the scheduler starts it as soon as it can. What the worker may do is decided when it starts (prepare). A task that repairs the wish's red push checks becomes their correction, or is refused while another one repairs them (pushrepair.go).

func (*Harness) SpawnWatcher

func (h *Harness) SpawnWatcher(ctx context.Context, wishID, projectID, title, watch string, restart bool) (string, error)

SpawnWatcher starts a watcher task in the wish wishID, in the project projectID, on the command line watch: the watcher of a wish made from a template (plan.SpawnWatcher). It gives the task's code.

func (*Harness) Start added in v0.1.1

func (h *Harness) Start(ctx context.Context, procedure string, req *planv1.TaskServiceStartRequest) (*planv1.Task, error)

Start starts a planned task that waits for the machine alone, now: the developer asked for it, whatever the slots, the pressure and the memory. Its worker takes a slot all the same: the next tasks wait for it, and the load bar counts it among the workers started by hand (Forced). A task held by a usage limit (TASK_HOLD_LIMIT) passes too when started by hand; a task held by anything else (its wish, a dependency, a push hold, a write scope) is refused, with why, and so is one that waits for a task going first: Start frees the machine and a limit hold, never the priority order. The scheduler's pass decides, as it would now.

func (*Harness) Stop

func (h *Harness) Stop(ctx context.Context, procedure string, req *planv1.TaskServiceStopRequest) (*planv1.Task, error)

Stop asks the task's worker to stop, and waits until it has, or ctx ends.

func (*Harness) StopWish

func (h *Harness) StopWish(ctx context.Context, wishID string) error

StopWish stops the workers of the wish wishID for good, watchers too, and waits until each one has ended: the wish is about to be deleted. Each task ends stopped.

func (*Harness) Stored added in v0.2.0

func (h *Harness) Stored(ctx context.Context, taskID string, after int64, send func(*planv1.TaskEvent) error) error

Stored sends the task's events stored after the position after, then returns: it follows no task, running or not.

func (*Harness) SyncPlan

SyncPlan reads the plan files of the wish's projects into its azimas, then writes what each azima depends on back into its file (PlanService.Sync). A file closes its azima when its status says done or every Done-when box is checked, the latter reported; its unchecked boxes that wait for a proof no worker can give go on the azima. An azima is found by its file's id, else its code; one the files name and the store lacks is made, taking its file's after line once, unless its code was a deleted task's: a code is never given twice. What an azima depends on is the store's: the files only follow it.

func (*Harness) Syncs added in v0.1.1

func (h *Harness) Syncs(ctx context.Context, project *planv1.Project) ([]*planv1.ProjectSync, error)

Syncs computes how far each branch Djinn pushes in project stands against its remote: the integration branch of each active or paused wish there, the active ones by rank then the paused ones, each followed by its azimas' own branches. A branch that does not exist yet, or has no remote, is left out.

func (*Harness) TellLeads

func (h *Harness) TellLeads(tell TellFunc)

TellLeads lets Djinn type lines into the terminals of the leads of wishes. djinn up gives it once its terminals run. Buffered lines waiting to be told are flushed once it is set.

func (*Harness) TrackGate added in v0.1.2

func (h *Harness) TrackGate(pid int, taskID string) (given func())

TrackGate records the process pid, djinn gate run in a worker of the task taskID, as it holds a gate: the command it runs, in the group of the worker's shell, may run for long, and must not outlive Djinn. It returns what to call once the gate is given back. A gate taken outside a running worker's task is not recorded.

func (*Harness) TurnComments added in v0.1.1

TurnComments turns the comments of an ended task that went to no worker and are not resolved into work: it continues the task when it can be continued (djinn task continue), or spawns a correction task in its azima whose prompt quotes each comment with its code excerpt. Each comment then records the task it went to.

func (*Harness) Update added in v0.1.1

func (h *Harness) Update(ctx context.Context, procedure string, req *planv1.TaskServiceUpdateRequest) (*planv1.Task, error)

Update edits a task in place: only the fields given change, in one journaled transaction. A task not started (planned, waiting) may change everything; a running or paused task may change its title and its urgent mark only (one urgent repair and one urgent feedback task per wish, refuseSecondUrgent); a finished task (done, failed, stopped, cut short) may change title, provider/model, prompt (for its next continue), azima, and integration (none clears it, pending puts a done task's work back in line); never its dependencies once it ran. An azima changes its title (renameAzima), its branch (nameAzimaBranch) or its rank (rankAzima) only.

func (*Harness) UpdateModels added in v0.2.0

UpdateModels changes the provider and model of every open task that calls a model (work, investigations, corrections, reviews, enlighten workers) and the defaults for future spawns, skipping watchers and finished tasks. Dry run by default; applied when req.GetYes() is true. Running tasks change at their next start, or now when req.GetNow() is true.

func (*Harness) Uses

func (h *Harness) Uses() []*machinev1.WorkerUse

Uses lists the workers running now that were read, with what each uses, the busiest first: the most CPU, then the most memory.

func (*Harness) Wake

func (h *Harness) Wake()

Wake asks the scheduler for a pass: a wish active again has tasks to start, or a gate held outside the workers was given back (gate.Gates.Freed).

func (*Harness) WarnIfrits added in v0.2.0

func (h *Harness) WarnIfrits(warned func(*planv1.Task))

WarnIfrits sets what shows the developer that an ifrit goes out soon (Task.ifrit.out_time): djinn up's system notification, whose Keep lit button touches the Presence. It must not wait.

func (*Harness) Watch

func (h *Harness) Watch(ctx context.Context, taskID string, after int64, send func(*planv1.TaskEvent) error) error

Watch sends the task's events after the position after, as they come, until the task has ended and all its events are sent, or ctx ends.

func (*Harness) WatchConfig added in v0.2.0

func (h *Harness) WatchConfig()

WatchConfig starts the watch of the projects' configuration on their reference branch (plan.LookAtConfig): a look at once, then every plan.ConfigLookEvery, and after each push of Djinn. djinn up calls it once; Close stops it.

func (*Harness) WorkerForecast added in v0.1.1

func (h *Harness) WorkerForecast() uint64

WorkerForecast returns the typical forecast memory per worker across providers in use, at the notch's percentile, or p.WorkerForecast() if none is measured.

func (*Harness) WorkerMemory added in v0.1.1

func (h *Harness) WorkerMemory(ctx context.Context, p machine.Policy) (engaged, actual uint64, err error)

WorkerMemory calculates engaged memory (sum of peak forecasts) and actual worker resident memory across running workers.

func (*Harness) WorkerP95Memory added in v0.1.1

func (h *Harness) WorkerP95Memory(taskID string) uint64

WorkerP95Memory returns the 95th percentile memory for a task's run samples.

func (*Harness) Works

func (h *Harness) Works(taskID string) bool

Works tells whether a worker of the task runs now and takes a slot: what it runs, a gate's command included, is in that slot. A paused worker or a watcher takes none.

type InstallStep

type InstallStep int

InstallStep is where an install stands, as Install tells it.

const (
	// InstallWaiting: it waits for its turn, for what Install says with it.
	InstallWaiting InstallStep = iota + 1
	// InstallPreparing: it checks the build out in its worktree, and sets it up.
	InstallPreparing
	// InstallBuilding: it runs the install command.
	InstallBuilding
)

type LeadDriver added in v0.2.0

type LeadDriver struct {
	// Wishes serve the lead's queue, and the plan its batches read.
	Wishes *plan.Wishes
	// Providers start each session, by the agent of the lead's seat: Djinn's own (Harness.LeadDriver).
	Providers map[planv1.Provider]Provider
	// Provider starts each session whatever the seat, when Providers is nil: a test's agent. Claude by default.
	Provider Provider
	// Ready tells whether a seat may take the lead after a limit, its agent installed and its sign-in not known to be
	// missing; by default, the agent's status command, run in the account's folder.
	Ready func(ctx context.Context, seat *planv1.LeadSeat, account *planv1.Account) bool
	// Home is Djinn's data folder: the sessions run in its lead folder (plan.LeadFolder) and may read it all.
	Home string
	// Changed tells the window that the lead changed: a batch started, ended or failed.
	Changed func()
	// Env is added to each session's environment, after DJINN_LEAD=1.
	Env []string
	// Track is told of each session's process (Spec.Track): none outlives Djinn.
	Track func(pid int, cgroup, mark string) (ended func())
	// MaxTurns, MaxBudgetUSD, Timeout and RetryAfter are the guards of a batch; the Lead constants by default.
	MaxTurns     int
	MaxBudgetUSD float64
	Timeout      time.Duration
	RetryAfter   time.Duration
	// Now is the driver's clock; time.Now by default.
	Now func() time.Time
}

func (*LeadDriver) Run added in v0.2.0

func (d *LeadDriver) Run(ctx context.Context)

Run drives the lead until ctx ends: a batch each time events wait and settle.

type Limit

type Limit struct {
	// What is the limit, for a reader: "the account's session limit".
	What string
	// Model is the model the limit message names ("claude-opus-4-6"), or "" when the message names no model.
	Model string
	// Until is when it resets; zero when the provider did not say.
	Until time.Time
	// PerMinute is true for a short per-minute rate or token bucket (TPM/RPM, HTTP 429) that refills within a minute
	// or two rather than a multi-hour session or daily quota.
	PerMinute bool
}

Limit is a provider's usage limit that stopped a worker: the account's session or weekly limit, a quota, a rate limit. The worker's task waits until it resets, then Djinn resumes it.

type Listener added in v0.2.0

type Listener interface {
	// CloseInput closes the agent's input once the turn under way, if any, has its result: the agent then ends, as
	// any worker does once every message has its result. It takes no message after.
	CloseInput()
}

Listener is a worker started with Spec.Listen, whose input stays open between turns.

type MeasureFunc

type MeasureFunc func(pid int, cgroup string) (machine.Group, error)

MeasureFunc reads what the worker whose process leads group pid uses, from its cgroup when it runs in a scope: machine.ReadWorker.

type NotifyFunc added in v0.1.1

type NotifyFunc func(ctx context.Context, e *planv1.LeadEvent) error

NotifyFunc queues an event for the lead, which its watch hands out: plan.Wishes.Notify.

type Option

type Option func(*Harness)

Option sets how the harness schedules its tasks.

func WithAccount added in v0.2.0

func WithAccount(f AccountFunc) Option

WithAccount lets the scheduler see an agent's account change while a task waits for that agent's usage limit: the limit no longer holds, and the task resumes at once.

func WithBarSlots added in v0.1.2

func WithBarSlots(n func(djinnv1.LoadNotch) int) Option

WithBarSlots gives the most workers a notch itself lets run, before the memory's share (machine.Policy.BarSlots): lowering the notch pauses the workers above it, never a dip of the memory available. It is asked of the harness's own notch, so that a pass between the monitor's change and SetPolicy weighs the notch it names. Without it, the capacity's slots.

func WithBeforeStart added in v0.1.1

func WithBeforeStart(f func()) Option

WithBeforeStart runs f before each worker's process starts: djinn up brings its PATH up to date there (machine.ExtendPath), so that a worker finds the agent the window's panel found.

func WithBuilt

func WithBuilt(built func(Built)) Option

WithBuilt calls built after each push of an integration branch in a project whose settings name an install command.

func WithCapacity

func WithCapacity(c Capacity) Option

WithCapacity limits the workers that run at once, and stops new ones while the machine is under pressure.

func WithClock

func WithClock(now func() time.Time) Option

WithClock gives the harness its time: when a usage limit resets is compared with it. Tests set a fake one.

func WithCommands

func WithCommands(run RunCommand) Option

WithCommands runs the integration's commands with run, instead of the processes they name. Tests give a fake.

func WithConfigTick added in v0.2.0

func WithConfigTick(d time.Duration) Option

WithConfigTick sets how often the watch of the configuration looks at each project's reference branch.

func WithDiskGuard added in v0.2.0

func WithDiskGuard(g DiskGuard) Option

WithDiskGuard lets Djinn watch its disks. Without it, Djinn reads no free space, trims nothing and holds no check.

func WithEnlightenWait added in v0.1.2

func WithEnlightenWait(d time.Duration) Option

WithEnlightenWait sets how long a request to investigate waits for its investigator to start before the lead is told instead: tests set a shorter one.

func WithEnlightenWorkers added in v0.1.1

func WithEnlightenWorkers(on ...bool) Option

WithEnlightenWorkers lets the harness start enlighten workers: true by default.

func WithGates

func WithGates(take TakeGate) Option

WithGates runs the integration's commands under the gates take gives; without it, they run at once.

func WithHistory added in v0.1.1

func WithHistory(history *machine.History) Option

WithHistory keeps each reading of a worker in the store's series too, which outlive a restart of Djinn.

func WithIfritIdle added in v0.2.0

func WithIfritIdle(d time.Duration) Option

WithIfritIdle sets how long the developer may leave Djinn alone before it puts an ifrit out, for an ifrit spawned without its own (djinn up --ifrit-idle); zero leaves it to the window's settings.

func WithIntegrateTick

func WithIntegrateTick(d time.Duration) Option

WithIntegrateTick sets how often the integration looks at the work waiting without being woken: an hour passes without telling anyone.

func WithMeasure

func WithMeasure(every time.Duration, read MeasureFunc) Option

WithMeasure reads what each worker uses every interval, with read, and keeps on its task the latest reading and the peaks. djinn up gives machine.ReadWorker, where the system lets it measure workers (machine.NotMeasured).

func WithMemory

func WithMemory(available func() uint64, p machine.Policy) Option

WithMemory holds a new worker until the memory available (0 when unknown) holds the typical peak of a worker of its provider, as p weighs it (machine.Policy.WorkerRoom). djinn up gives the machine's; without it, the memory holds no worker back. It needs WithCapacity.

func WithNetworkProbe added in v0.2.0

func WithNetworkProbe(p ProbeFunc) Option

WithNetworkProbe lets Djinn confirm an outage it suspects, and see it end (djinn up gives ProbeHTTP). Without one, no outage is ever confirmed: a worker a network error cut resumes at the next pass all the same.

func WithPolicy added in v0.1.1

func WithPolicy(p machine.Policy) Option

WithPolicy sets the policy Djinn runs with (operating load notch, limits).

func WithScopes

func WithScopes(scopes *machine.Scopes) Option

WithScopes runs each worker in a systemd scope of its own, which stopping, pausing and measuring it take whole, its CPU and memory capped as scopes says (djinn up --worker-cpu, --worker-memory; machine.ProbeScopes).

func WithSilenceLimit added in v0.1.1

func WithSilenceLimit(d time.Duration) Option

WithSilenceLimit sets the silence limit before the Lamplighter checks a worker: tests set a shorter one.

func WithTaskMaxTurns added in v0.1.1

func WithTaskMaxTurns(n int) Option

WithTaskMaxTurns sets the maximum turn budget per task before being stopped: tests set a lower one.

func WithTaskMaxWallTime added in v0.1.1

func WithTaskMaxWallTime(d time.Duration) Option

WithTaskMaxWallTime sets the maximum wall time budget per task before being stopped: tests set a shorter one.

func WithTellDelay added in v0.1.1

func WithTellDelay(d time.Duration) Option

WithTellDelay sets the delay before batched lines to a wish's lead are flushed: tests set a shorter one.

func WithTick

func WithTick(d time.Duration) Option

WithTick sets how often the scheduler looks at the planned tasks again without being woken: the pressure of the machine falls without telling anyone.

func WithTotal added in v0.1.1

func WithTotal(total func() uint64) Option

WithTotal gives the machine's total RAM in bytes (0 when unknown) for peak forecast committable limits.

func WithUninstalledDelay added in v0.1.1

func WithUninstalledDelay(d time.Duration) Option

WithUninstalledDelay sets how long an integrated build may stay uninstalled before Djinn asks to install it.

func WithVersion added in v0.1.1

func WithVersion(v string) Option

WithVersion sets the version of the running binary.

type Pauser

type Pauser interface {
	// Pause stops the agent, and what it started, where they are.
	Pause() error
	// Resume lets them go on.
	Resume() error
}

Pauser is a worker that can hold still without losing anything: its agent stops where it is until it is resumed. A worker that is not one cannot be paused.

type Plans

type Plans struct {
	planv1connect.UnimplementedPlanServiceHandler
	// contains filtered or unexported fields
}

Plans implements PlanService.

type Presence added in v0.2.0

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

Presence is when the developer last did something in Djinn (T51): a key, a click or a scroll in the window in front (UiService.Touch), a key in a terminal, an answer, a mark, a choice in the lead's terminal, a tell, a message, a djinn command they typed, the Keep lit button of a warning. The lead, the workers and the watchers are no activity. It keeps the ifrits lit: each one goes out once the developer left Djinn alone for its idle delay (IfritIdle), warned ifritWarnAhead before.

func (*Presence) Last added in v0.2.0

func (p *Presence) Last() time.Time

Last is when the developer last did something in Djinn; zero when they did nothing since it started.

func (*Presence) Touch added in v0.2.0

func (p *Presence) Touch()

Touch says that the developer is there, now.

type Prioritizer added in v0.1.1

type Prioritizer interface {
	// SetPriority sets the worker and its process tree to low CPU priority (nice 10 / cpu.weight 10)
	// when low is true, or standard priority (Djinn's own nice level or priority class / cpu.weight 100)
	// when low is false.
	SetPriority(low bool) error
}

Prioritizer is a worker that can change its CPU priority while running.

type ProbeFunc added in v0.2.0

type ProbeFunc func(ctx context.Context, provider planv1.Provider) error

ProbeFunc asks whether the network reaches provider's API: nil when it answered.

type Process

type Process interface {
	// PID is the process of the agent, or of a watcher's command; 0 while none runs.
	PID() int
	// Cgroup is the cgroup of the scope it runs in (Spec.Scope); empty without one.
	Cgroup() string
}

Process is a worker that runs a process of its own, which leads its process group: Djinn measures what it uses. A worker that is not one (the fake agent, which runs in Djinn's process) is not measured.

type Provider

type Provider interface {
	// Start starts a worker. Cancelling ctx stops it, as Worker.Stop does.
	Start(ctx context.Context, spec Spec) (Worker, error)
}

Provider starts the workers of one kind of agent.

type Ran added in v0.2.0

type Ran struct {
	// End is when it ended, or could not start.
	End time.Time
	// Err is why it failed: its exit code and the last lines of its error output, or why it could not start; nil
	// when it exited 0.
	Err error
}

Ran is the end of a run of a watcher's command, on its event when Watch.Runs is set. The paragraphs of that run came before it.

type ReceiveFunc

type ReceiveFunc func(ctx context.Context, src *plan.Source, text string) (*planv1.InboxItem, error)

ReceiveFunc reads an item an inbox source printed: plan.Inbox.Receive.

type ReleaseFit

type ReleaseFit int

ReleaseFit is what a newer release of Djinn means for a Djinn built from a checkout of one of the projects (go tool task install, version local-<commit>).

const (
	// ReleaseOffer: offered, as to a Djinn installed from a release; the person's click installs it. The checkout is on
	// main, or the release holds the build; or no project holds the build.
	ReleaseOffer ReleaseFit = iota
	// ReleaseInstall: installed by itself, the restart left to the person's click: the checkout is on main, the
	// release holds the build, which had no change not committed, and the project's settings install releases.
	ReleaseInstall
	// ReleaseHeld: not offered: the build holds the release already.
	ReleaseHeld
	// ReleaseMerge: not offered: the checkout is on a branch whose work the release lacks. Djinn merges main into the
	// wishes' integration branches instead, and proposes their build once the release is in.
	ReleaseMerge
)

type Result

type Result struct {
	// ExitCode is the exit code of the process; -1 when it was killed by a signal.
	ExitCode int
	// Err is why the worker failed, when it did: its process could not run, or the agent reported an error.
	Err error
}

Result is how a worker ended.

type RunCommand

type RunCommand func(ctx context.Context, dir string, args []string) (out string, code int, err error)

RunCommand runs args in dir, and returns the end of its output and its exit code; an error when it could not run.

type Serves added in v0.2.0

type Serves struct {
	planv1connect.UnimplementedServeServiceHandler
	// contains filtered or unexported fields
}

Serves implements ServeService.

func (*Serves) List added in v0.2.0

List lists an ifrit's serves: as stored, those running as they stand now.

func (*Serves) Logs added in v0.2.0

Logs prints the last lines a serve wrote, its stop command's included.

func (*Serves) Run added in v0.2.0

Run starts a serve for the ifrit that asks: only an ifrit's worker runs one (WorkerGuard points the request at its own task).

func (*Serves) Stop added in v0.2.0

Stop stops a serve for good: it does not start again when its ifrit is lit again.

type Skill

type Skill struct {
	// Name is the skill's folder name.
	Name string
	// Source is where it comes from: <project>/<skill>.
	Source string
	// Dir is its folder in the source project, absolute.
	Dir string
	// Description is what it does, from its SKILL.md.
	Description string
}

Skill is a skill summoned from another project: its folder stays in its source, and the worker reads it there.

type Spec

type Spec struct {
	// TaskID is the task the worker works on.
	TaskID string
	// Dir is the folder the worker runs in: its project's worktree or folder, or an empty folder of its own.
	Dir string
	// ReadOnly says the worker may read documents, never change a file nor run a command or code: outside any
	// project, or in a folder outside Git without agent configuration until the developer allows editing.
	ReadOnly bool
	// Permissions, when set, are what the worker may do in its project, the same for every agent: the provider
	// translates them for its agent at launch, never allowing more, and writes nothing in the project. Nil in a
	// project lets the agent's own configuration of the project decide, and Djinn passes no permission setting.
	// Ignored when ReadOnly.
	Permissions *djinnv1.Permissions
	// Prompt is the first message to the agent.
	Prompt string
	// Model is the agent's model; empty for the provider's default.
	Model string
	// MaxBudgetUSD caps what the worker may spend, when the provider can enforce it; 0 for no cap.
	MaxBudgetUSD float64
	// Resume is a session to continue instead of starting a new one: the task's own, when its worker starts again.
	Resume string
	// Fork starts a new session from a copy of Resume instead of continuing it: a task spawned with --fork or
	// --from-lead. Claude names the new session after the task; Codex forks the thread; Antigravity refuses.
	Fork bool
	// Env holds variables added to the environment Djinn passes on to the worker. Djinn never reads the
	// environment it passes, nor records it.
	Env []string
	// Skills are the skills the project summons from other projects, found on this machine. The provider shows
	// them to its agent by the agent's own path, and writes nothing in the project nor in the user's folders.
	Skills []Skill
	// SkillsDir is a folder of Djinn's own holding .claude/skills/<name> and .agents/skills/<name>, a link to each
	// skill's folder in its source project; empty without skills, or when the links could not be made.
	SkillsDir string
	// Scope, when set, gives each process the worker starts a systemd scope of its own (Harness.WithScopes): the
	// process runs under its prefix, and stopping, pausing and measuring take its cgroup. Nil: it runs as is.
	Scope func() machine.Scope
	// Restart starts a watcher's command again after an exit 0 too, until it is stopped: one that dies starts again
	// anyway (watcherLife). Agents ignore it.
	Restart bool
	// LastLine is the first line of the last paragraph a watcher's task said before this start (Task.last_line): its
	// command's first paragraph wakes no one when it says it again. Agents ignore it.
	LastLine string
	// LowPriority runs the worker process with low CPU priority (nice 10 on Unix,
	// BELOW_NORMAL_PRIORITY_CLASS on Windows) when running at minimal or medium operating load;
	// else it runs at Djinn's own priority.
	LowPriority bool
	// StartHead is the git commit hash at task start, used to verify progress.
	StartHead string
	// Branch is the task's git branch name.
	Branch string
	// IsWorkDone reports whether the worker has committed clean work since start.
	// When nil, callers compute it from git status in Dir.
	IsWorkDone func() bool
	// Listen keeps the agent's input open once every message has its result: an ifrit's agent waits on it for the
	// next message, spending nothing, until Djinn closes it (Listener). Its worker says when each turn starts and
	// ends (Event.Ifrit).
	Listen bool
	// SystemPrompt, when set, is added to the agent's own system prompt, the same text for every session that gets
	// it: the rules of the lead Djinn drives (decision Q31). Claude's appended system prompt, Codex's developer
	// instructions, Antigravity's GEMINI.md rule in the session's folder.
	SystemPrompt string
	// MaxTurns caps the model turns of the run, when the provider can enforce it; 0 for no cap.
	MaxTurns int
	// WriteDirs are folders the agent may write in even without Permissions.Edit, and ReadDirs folders it may read
	// outside its own: the driven lead's folder, where it writes plan files and tilasms, and Djinn's data folder; a
	// worker's scratch folder (workScratchDir) and the version folders of the tilasms it is given (plan.TilasmDirs).
	// Claude's folder rules; Codex's workspace-write sandbox on them (it reads everywhere already); write_file and
	// read_file grants of agy's project.
	WriteDirs, ReadDirs []string
	// Track, when set, is told of each process the worker starts, its PID, the cgroup of its scope and its mark
	// (markVar), as it starts; what it returns is called once the process, and what it left running, ended. Djinn
	// records them so that none outlives it (W514).
	Track func(pid int, cgroup, mark string) (ended func())
}

Spec is what a worker is started with.

type TakeGate

type TakeGate func(ctx context.Context, name, taskID, what, dir string, first bool, waiting func(why string)) (give func(), err error)

TakeGate takes the gate name, for the task taskID, to run the command what in the folder dir, and returns how to give it back; first when Djinn takes it to merge a task's work into its branch, settle such a merge or check a push, which goes before the workers' requests (Q26), not to install a build. It calls waiting, when not nil, each time the reason it waits changes. djinn up takes the gates of internal/gate, as djinn gate run does.

type TaskSummary added in v0.1.1

type TaskSummary struct {
	Code    string
	Title   string
	Summary string
}

TaskSummary is what a task of the build brought, and its worker's final words.

type Tasks

type Tasks struct {
	planv1connect.UnimplementedTaskServiceHandler
	// contains filtered or unexported fields
}

Tasks implements TaskService.

func (*Tasks) Cancel added in v0.1.1

func (*Tasks) Diff added in v0.1.1

func (*Tasks) Move added in v0.1.1

func (*Tasks) Open added in v0.1.1

func (*Tasks) Rank added in v0.2.0

func (*Tasks) Start added in v0.1.1

func (*Tasks) Update added in v0.1.1

type TellFunc

type TellFunc func(ctx context.Context, wishID, line string) error

TellFunc types a line in the terminal of the lead of a wish: plan.Wishes.Tell.

type Watch

type Watch struct {
	// Quiet is how long the command stays silent before what it printed makes a paragraph; 0 for WatchQuiet.
	Quiet time.Duration
	// Grace is how long the command has to stop before it is killed; 0 for Grace.
	Grace time.Duration
	// Backoff is the first wait before a command that died starts again; 0 for watchBackoff.
	Backoff time.Duration
	// Gap is the least time between two starts of a command that exits 0 at once, and between two starts of one
	// that fails; 0 for one second.
	Gap time.Duration
	// Items ends a paragraph on an empty line too, and leaves the error output out of them: each one is an item of an
	// inbox source.
	Items bool
	// Endless starts the command again however many times it dies in a row: an inbox source never gives up.
	Endless bool
	// Runs says the end of each run of the command, by an event with Ran: an inbox source keeps its last run.
	Runs bool
}

Watch runs a command instead of an agent: the task's prompt is its command line. It runs without a shell, in the worker's folder, under the worker's environment and prefix; quotes group words, as in a shell, and the harness expanded Djinn's variables in it before (watchCommand). Where the worker's permissions list the commands it may run, the command must be one of them, and not denied: a watcher has no reviewer. The harness adds the command a skill of the project declares, or the developer allows (watch_allow.go). It cannot run read-only.

func (Watch) Start

func (c Watch) Start(ctx context.Context, spec Spec) (Worker, error)

type Watched

type Watched struct {
	// First is its first line; empty on the end of the command.
	First string
	// Command is the watcher's command line.
	Command string
	// Watching says the command still watches: it runs, or starts again.
	Watching bool
	// Wake says the wish's lead is told: not when the paragraph says again what the last one said, even before Djinn
	// started the watcher again (Spec.LastLine), nor when the watcher was stopped.
	Wake bool
}

Watched is a paragraph a watcher's command printed, on its event; or, without a first line, the end of a command whose last paragraph said it still watched.

type WatchedFunc

type WatchedFunc func(ctx context.Context, task *planv1.Task, text string) (done bool, err error)

WatchedFunc reads a new paragraph a watcher printed, and says whether it holds the done line of its wish's template: plan.Wishes.Watched, which then offers to grant the wish.

type Worker

type Worker interface {
	// Events are what the worker says, in order. The channel closes when the worker ends.
	Events() <-chan Event
	// Send gives the agent another message, when its provider keeps the agent open between turns. It returns
	// ErrClosed once the worker no longer takes any.
	Send(text string) error
	// Stop asks the worker to stop, and kills it if it has not after the grace delay. It does not wait.
	Stop()
	// Wait blocks until the worker has ended and its events are all read, then says how it ended.
	Wait() Result
}

Worker is one running agent.

Jump to

Keyboard shortcuts

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