coding agent init script worktree isolation health check

Lab

Bootstrap and isolate the environment: make every run start from truth

Turn undocumented local setup into a deterministic startup ritual with health checks, fixture data, worktree-safe resources, bounded cleanup, and actionable failure output.

DIFFICULTY
Intermediate
ESTIMATED TIME
120 min
UPDATED
2026-08-26
COPY REVIEW
blader/humanizer
2 passes
On this page
  1. 01Working definition
  2. 02Field situation
  3. 03Worked example
  4. 04Build it, with checkpoints
  5. 05Operating context
  6. 06Hands-on lab
  7. 07Failure clinic
  8. 08Production boundary
  9. 09Sources and claim limits

Learning objectives

  • Define a clean-clone startup contract that an agent can execute without personal machine knowledge
  • Separate installation success from application health and user-visible readiness
  • Isolate ports, state, logs, credentials, and cleanup for concurrent worktrees
  • Return actionable startup failures while keeping cleanup targets explicit and recoverable

Before you start

  • Module 02 repository map with an owned startup source
  • A machine able to run the Release Desk fixture locally without production credentials

Working definition

Bootstrap and isolation

Environment bootstrapping is the deterministic path from a clean clone to a verified, agent-operable application. Isolation gives each task its own ports, data, logs, processes, and scoped credentials so one run cannot corrupt another. A useful initializer reports exact health and repair information; it does not declare success merely because dependencies installed or a process opened a socket.

Long agent sessions waste time when every fresh context must rediscover commands, seed data, ports, and hidden prerequisites. Worse, a partially healthy app can invite feature work on top of an existing failure. The agent then expands the incident while believing it is advancing the task.

A startup ritual turns current state into evidence. It checks the repository, installs deterministically, initializes fixture data, starts the correct worktree instance, and exercises one basic user journey. Isolation makes parallel work possible later, but its first value is safety: cleanup and failure remain inside one named task environment.

Field situation

Two Release Desk changes on one developer machine

Ports, databases, and failure modes in this lesson are local synthetic fixtures.

Owner
A platform engineer enabling one human to supervise two isolated coding-agent tasks without shared-state collisions.
Decision
Which resources require per-task isolation, and what exact evidence proves an instance is ready for feature work?
Starting state
The app uses port 3000, a shared SQLite file, a global screenshot folder, and an undocumented seed command. A second worktree either fails to start or mutates the first task's data.
Expected outcome
Two worktrees start concurrently on resolved ports, use separate fixture state, pass independent health checks, and clean up only their own resources.

Constraints

  • The initializer must run from a clean clone and may create state only inside the named task environment
  • It may not stop unrelated listeners, overwrite a real environment file, or read credentials from another project
  • Readiness requires the basic Release Desk browser path, not a process or port check alone

Worked example

A healthy process with an unusable application

Evidence status: Named synthetic scenario

The first initializer returned success when the Next.js process listened on port 3000. The database migration had failed, so the request list returned 500. A second run seeded duplicate reviewer accounts and cleanup killed a listener that belonged to another local project.

The platform engineer split startup into phases, created a worktree-derived environment ID, added an idempotent fixture seed, and made the final check load the request list through the browser. Cleanup read exact process metadata and printed the resolved directory before removal.

Two worktrees passed their own browser smoke path and wrote separate environment receipts. A missing migration produced `database_not_ready` with the scoped repair command. The unrelated listener remained untouched.

Limits

Local process and SQLite isolation teach the contract but do not replace container, microVM, network, or cloud identity controls required by a production coding-agent platform.

Method

Build it, with checkpoints

Two Release Desk worktrees connected to separate ports, databases, logs, caches, screenshots, and process records, with task-scoped cleanup.

Field situation

Which resources require per-task isolation, and what exact evidence proves an instance is ready for feature work?

  1. 01Specify startup phases
  2. 02Resolve isolated resources
  3. 03Verify the basic user journey

Acceptance checks

A new coding-agent session can initialize one named environment, prove it is usable, locate its evidence, and tear it down without personal setup knowledge or collateral damage.

Why this visualA worktree resource map makes hidden shared state and safe cleanup boundaries visible before learners run concurrent environments.
  1. 01

    Specify startup phases

    Write preconditions and terminal statuses for repository inspection, deterministic installation, fixture preparation, process start, and user-path verification. Give each failure a stable code and a task-scoped repair command.

    CHECKPOINT · A failed phase cannot be mistaken for application readiness, and its output identifies the affected environment.

  2. 02

    Resolve isolated resources

    Create the environment ID and derive ports, state paths, logs, screenshots, caches, and process metadata. Persist the resolved map locally. Refuse to start when a target belongs to another environment rather than killing or overwriting it.

    CHECKPOINT · Two worktrees resolve distinct resources and an occupied foreign port returns a safe conflict status.

  3. 03

    Verify the basic user journey

    After process startup, run the minimum Release Desk journey from fixture login through request-list load and one safe detail read. Capture service, database, and browser evidence under the environment ID.

    CHECKPOINT · The final ready status proves the task's basic dependencies, not only process liveness.

  4. 04

    Rehearse failure and cleanup

    Inject missing runtime, migration failure, duplicate seed, and stale process metadata. Run cleanup in dry-run first, compare printed targets with the receipt, then remove only task resources and verify the other worktree remains healthy.

    CHECKPOINT · All injected failures have actionable output and cleanup preserves unrelated processes, files, and the second worktree.

Operating context

Beyond the demo

G1

Define readiness at the user boundary

Split the initializer into inspect, install, prepare, start, and verify phases. Each phase emits a distinct status and repair hint. The final health check should cover the minimum path required before feature work: server response, database access, fixture login, request list load, and one safe read. A PID or HTTP 200 from the root page is too weak when the task depends on authenticated state and persistence.

Keep setup idempotent. Running init twice should converge on the same healthy fixture rather than duplicate records or hide a broken migration. Pin package-manager behavior and fail when the lockfile or required runtime is inconsistent. A repair command should be safe to copy, scoped to the task, and free of secrets.

G2

Give every worktree its own address

Derive a short environment ID from the worktree path or an explicit task name. Use it to allocate application port, database or schema, log directory, cache namespace, screenshot folder, and process metadata. Write the resolved values to a local environment receipt so a later agent can find the correct instance.

Cleanup must resolve and print exact targets before it acts. It may stop only processes carrying the task environment ID and remove only fixture state created for that ID. Never use a broad home directory, workspace root, unresolved variable, or global listener as the cleanup target.

Hands-on lab

Build a clean-clone initializer and worktree-safe preflight

Implement the initializer contract against Release Desk. Inject a missing runtime, a failed migration, an occupied derived port, and a second worktree. Verify failure output and cleanup boundaries before using it in later modules.

Prepare

  • Confirm current ports and local processes without stopping anything, then create two named worktrees
  • Use fixture credentials and a task-local database only; keep real environment files outside the lab

Deliverable

An initializer, health check, cleanup command, environment receipt, two-worktree proof, and failure fixtures for runtime, migration, port, and seed errors.

Starter kit: Initializer contract

YAML
version: 1
environmentId: derive-from-worktree
phases:
  - inspect
  - install
  - prepare-fixture
  - start
  - verify-user-path
resources:
  port: task-scoped
  database: task-scoped
  logs: task-scoped
  screenshots: task-scoped
cleanup:
  printResolvedTargets: true
  requireEnvironmentId: true

Downloadable artifacts

Initializer contract

initializer-contract.yml · YAML

An editable course fixture for the main lab. Save it inside the Release Desk repository before running the acceptance command.

Run receipt template

he-03-receipt.json · JSON

A compact evidence record for the check, environment, result, and limits that another reviewer must be able to inspect.

Acceptance command

npm run harness:init -- --environment he-03-a && npm run harness:health -- --environment he-03-a

Expected receipt

PASS he-03 environment-ready
environment=he-03-a userPathReady=true
isolation=verified cleanupScope=task-only

Expected result

A new coding-agent session can initialize one named environment, prove it is usable, locate its evidence, and tear it down without personal setup knowledge or collateral damage.

Carry forward

Every later session begins with this initializer and saves its environment receipt next to progress. Module 09 will reuse the worktree contract for gated parallel work.

Acceptance checks

  1. 01A clean clone reaches user-path ready through one documented command and an idempotent seed
  2. 02Two worktrees use distinct ports, state, logs, screenshots, caches, and process metadata
  3. 03Missing runtime, migration failure, duplicate seed, and foreign port return stable actionable errors
  4. 04Cleanup prints resolved targets, requires a task ID, removes only course fixture resources, and preserves the other worktree

What breaks

Failure clinic

F1The initializer reports ready, but the first authenticated page returns an application error.
Inspect
Compare process liveness, migration status, fixture seed, session setup, and browser smoke evidence.
Likely cause
Readiness ended at the process or root-page boundary instead of the task's minimum user journey.
Repair
Move ready after database, fixture authentication, request list, and safe detail verification.
Prevent next time
Define readiness from the first task dependency and keep the smoke path in the acceptance suite.
F2Starting a second worktree changes the first task's records or screenshots.
Inspect
Diff resolved ports, data paths, cache keys, log directories, and fixture identifiers from both receipts.
Likely cause
One or more resources remained global even though the application port was isolated.
Repair
Include every mutable and observable resource in the environment-ID map and re-seed both tasks.
Prevent next time
Run the two-worktree collision fixture whenever startup configuration changes.
F3Cleanup fixes the lab by stopping a process from another project.
Inspect
Review how the command resolved PIDs, ports, paths, and environment ownership before action.
Likely cause
Cleanup used a broad port lookup or unresolved variable without task metadata validation.
Repair
Restore the unrelated project, require environment ID ownership, and add dry-run plus exact-target checks.
Prevent next time
Never authorize recursive deletion or process termination from a broad directory, port, or empty variable.

Beyond the demo

Production boundary

  1. 01Initializer inputs, package locks, runtime requirements, phases, and terminal statuses are versioned
  2. 02Health checks prove the minimum authenticated user path and authoritative persistence needed by the task
  3. 03Every worktree receives isolated network, data, cache, log, screenshot, and process resources
  4. 04Fixture seeds are idempotent and never read or overwrite production data or credentials
  5. 05Failure output exposes a stable code and safe scoped repair while redacting sensitive values
  6. 06Cleanup resolves, prints, validates, and removes only resources carrying the explicit task environment identity

Evidence status

Sources and claim limits

Sources support the named claims; they do not guarantee the same result in another system.

  1. [1]
    Effective harnesses for long-running agents

    Anthropic · Published research · 2026-08-26

    initializer pattern · feature ledger · session handoff · end-to-end verification
  2. [2]repository knowledge · agent legibility · mechanical enforcement · entropy management
  3. [3]
    Harness Engineering Guide

    Nexu · Public case · 2026-08-26

    runtime boundary · tool systems · sandboxing · recovery patterns
  4. [4]
    Learn Harness Engineering

    Walking Labs · Public case · 2026-08-26

    project-based sequence · five harness subsystems · loop engineering · graph engineering
  5. [5]
    Harness Engineering learning guide

    deusyu · Public case · 2026-08-26

    repository as record · mechanical rules · agent readability · continuous cleanup

Related Tenten resources

When a local harness meets a real codebase

Bring the receipt, the failed case, and the control you are unsure about.

Tenten can review repository legibility, permissions, evaluator coverage, worktree isolation, recovery, and rollout evidence before your team increases agent autonomy.