Repository navigation
feat(harness): a turn is told when its session's workspace was reset (#338) - #895
Conversation
A worker deletes a session's workspace after SH_WORKSPACE_IDLE, and the next Exec for the key gets a fresh one. The placement code reports a reset only when the session moves to another sandbox, so a reclaim on the same sandbox was silent: the next turn started in an empty workspace and nobody was told. The harness now keeps a marker file, .moca-session, holding the workspace key at the root of the session's workspace, and records in the session's log (a `workspace_marker` custom entry, the latest winning) that it wrote it. At the start of every turn, before the agent runs, one Exec reads the marker and (re)writes it. If the log says it was written and it is missing or holds another key, the turn reports `workspace_reset` with the new reason `reclaimed`: in the placement (and so the result, the done frame and the runtime record), as the stream's first frame, and in a note before the model's prompt. Moved sessions keep their own reason, and their model now gets the note too. - No record means "never written", so no session from before this change is reported on its first turn after an upgrade. - The marker is written only into a workspace that holds something, at the turn's start or, failing that, at its end, so the container worker's early removal of empty session directories (rossoctl#551) still applies. - The check never fails a turn: an Exec error is logged and gives no verdict. - It runs only when the Execs carry a workspace key, so a workload run that writes only in its context (rossoctl#613) has no check. - `.moca-*` is already left out of a templated session's patch; the marker is also listed in a root repository's info/exclude. - Cost: one Exec per turn (two on a turn that starts in an empty workspace); the script uses only shell builtins once the workspace is marked. Docs: brain-and-hands (the limits: a session that deletes the marker is reported as reset; a turn right after a compaction checkpoint counts as a first turn; it needs a per-session workspace; it does not prevent the reset), sessions-and-turns, sandboxes-and-tiers, http-api, both OpenAPI documents (control plane 1.31.0, harness 1.7.0), the changelog and change-policy. mocactl prints the new reason. Part of rossoctl#338 Assisted-By: Claude Code Signed-off-by: Rong Chang <[email protected]>
Review follow-up (from a check of the client side): the note names the cost per tier (about 2 ms on the container tier, one VM acquire on the microVM per-exec tier), that a mocactl from before harness 1.7.0 prints a `reclaimed` reset as "sandbox is gone", and that the marker stays out of git through info/exclude. Part of rossoctl#338 Assisted-By: Claude Code Signed-off-by: Rong Chang <[email protected]>
pdettori
left a comment
There was a problem hiding this comment.
The approach works: the "absent record = first turn" rule means no false resets after an upgrade or a compaction, the empty-directory sweep (#551) is kept, and the cost is stated in the upgrade note. One blocker: putting the note in front of the prompt stops Pi from expanding /skill:, prompt-template and extension commands on any reset turn (including detached/retiered), and it stores the note as the user's own words. Adding it through before_agent_start avoids both problems. There's also a smaller case where a turn that fails after the check silently uses up the reset.
Author: webchang (MEMBER — maintainer)
Areas reviewed: TypeScript (harness, mocactl), embedded shell, OpenAPI/YAML, Docs, Tests
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes
CI status: passing (17/17)
| // The model is told too, whatever the cause: its earlier files are gone. | ||
| const turnInput = { | ||
| ...input, | ||
| ...(reset ? { prompt: `${WORKSPACE_RESET_NOTE}\n\n${input.prompt}` } : {}), |
There was a problem hiding this comment.
must-fix — On a reset turn, putting the note in front of the prompt breaks slash commands. Pi's AgentSession.prompt() only runs extension commands when the text starts with / (agent-session.ts:994), and _expandSkillCommand / expandPromptTemplate only expand text starting with /skill: or /. A promoted bundle ships skills and prompt templates (additionalSkillPaths/additionalPromptTemplatePaths), so a user's /skill:review … on a reclaimed or moved turn goes to the model as plain text, without the skill.
The note is also stored in the session log as part of the user's message, so it shows up in history as if the user had typed it.
Fix: add the note through a harness extension's before_agent_start handler, returning { message: { customType: 'workspace_reset', content: NOTE, display: false } }. That leaves the user's text untouched, still reaches the model, and is easy to tell apart in the log. A regression test: a reset turn whose prompt is /skill:x still expands.
There was a problem hiding this comment.
Fixed in d5820fc: the note is now a workspace_reset custom message from a before_agent_start handler (display: false), for every reset reason, and the prompt reaches Pi unchanged. A real-Pi regression test checks that /skill:review still expands on a reset turn and that the note is its own message, not part of the user's.
| if (obs.prev === 'ours') return { verdict: 'intact', finishWrite }; | ||
| // A reset always records where the marker stands now: `false` when the fresh workspace was | ||
| // still empty, so the next turn does not report the same reset again. | ||
| return { verdict: 'reset', record: obs.now === 'ours', finishWrite }; |
There was a problem hiding this comment.
suggestion — A turn that fails after the check uses up the reset. On a reset verdict the start-of-turn Exec rewrites the marker straight away. If the turn then fails before the agent runs, nobody is told: a missing bundle returns a plain 410 before the reset frame (attachPromotedConfig in executeTurn), and a throw in executeTurnCore happens before the flush. The model never gets the note, and the next turn sees the marker plus the old written: true record and calls it intact. Only onPlacement and the runtime record saw it.
Consider not rewriting at the start on a reset: leave the script read-only and let finish() write it once the turn has run. A failed turn would then report the reset again on the next one. That costs no extra Exec, because a reset turn already sets finishWrite.
There was a problem hiding this comment.
Done in d5820fc: with a record, the start only reads, and the marker is rewritten only after the turn has run. A turn that does not complete reports the same reset again next turn, and an intact turn never touches the marker; both cases are tested.
| `if [ -n "$full" ]; then`, | ||
| ` printf '%s' ${key} >${m}.tmp.$$ && mv -f ${m}.tmp.$$ ${m} || { rm -f ${m}.tmp.$$; exit 91; }`, | ||
| ` n=ours`, | ||
| ` if [ -d .git ]; then grep -qxF /${m} .git/info/exclude 2>/dev/null || { mkdir -p .git/info && echo /${m} >>.git/info/exclude; } 2>/dev/null; fi`, |
There was a problem hiding this comment.
nit — [ -d .git ] skips the info/exclude entry when the workspace root is a git worktree or submodule, where .git is a file, so git add -A there would commit .moca-session. seedWorkspace already uses git rev-parse --git-path info/exclude for this. This branch only runs when writing, so starting a git process there doesn't hurt the builtins-only fast path.
There was a problem hiding this comment.
Done in d5820fc: the write branch now uses git rev-parse --git-path info/exclude (with --show-prefix), so worktrees, submodules and subdirectories are covered. A missing or failing git is ignored; tests cover a worktree, a broken .git file and no git on PATH.
…ter the turn Review of rossoctl#895: - The note no longer goes in front of the prompt. Pi runs extension commands, `/skill:` and prompt templates only for text that starts with `/`, so a reset turn's `/skill:review ...` went to the model as plain text, and the note was stored as the user's words. It is now a custom message (`workspace_reset`, display: false) from a harness extension's before_agent_start handler, for every reset reason. The prompt reaches Pi byte for byte. - With a record, the start-of-turn Exec only reads. A reset is rewritten by the end-of-turn write, which runs only after the agent ran. A turn that fails or is aborted before then leaves the marker missing and the record unchanged, so the next turn reports the same reset again. A turn that found the marker intact never writes or removes it. This costs no extra Exec: a reset turn already wrote at its end. - The info/exclude step finds the repository with `git rev-parse --git-path info/exclude` and `--show-prefix`, so a worktree or submodule (where .git is a file) and a workspace below a repository's root are covered. It is skipped without git, and a failing git is ignored, never failing the marker write. It stays on the write branch only, so the read path is still builtins only. Tests: - A real-Pi test with a faux model: a `/skill:` prompt on a reset turn still expands, the note is a separate message, and the log keeps it as a custom_message. With the old prepend, the expansion test fails. - In the executeTurn tests, the prompt is identical to the one sent, and the note arrives through before_agent_start. A reset turn that throws, or one aborted before its prompt, is reported again on the next turn. An intact turn that throws stays intact. - For the script: read-only mode, a git worktree, a subdirectory of a repository, a broken .git file, and no git on PATH. Part of rossoctl#338 Assisted-By: Claude Code Signed-off-by: Rong Chang <[email protected]>
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Author: webchang (MEMBER — maintainer)
Areas reviewed: the d5820fc fix commit (harness/src/run-turn.ts, harness/src/workspace-marker.ts, tests, docs), plus a re-check of the full PR's harness/control-plane/mocactl surface
Agent/IDE config (.claude/.vscode): none
Commits: 3, all signed off (DCO pass)
CI status: 18/18 green at d5820fc (all checks passed, including check, deploy-scripts, deploy-scripts-bash32, k8s-kind-e2e) (base 156530f7, main 28db50d6, clean merge)
All three items from @pdettori's CHANGES_REQUESTED at a5a0756 are fixed here, and I verified each independently against the pinned Pi fork (pi-fork @ 2c28be5).
The note now travels beside the prompt, not inside it — correct. BeforeAgentStartEventResult.message is exactly Pick<CustomMessage, 'customType' | 'content' | 'display' | 'details'> (packages/coding-agent/src/core/extensions/types.ts:1045); ExtensionRunner.emitBeforeAgentStart collects each handler's singular message and returns them as messages (extensions/runner.ts:980+); AgentSession.prompt emits the event after expansion and appends the custom messages after the user message (agent-session.ts ~1076–1112); and convertToLlm maps a custom message to a user-role message, so the note reaches the model even with display: false (packages/agent/src/harness/messages.ts:133). The two session-log entry kinds do not collide: appendCustomEntry writes type: 'custom' (outside LLM context, which the workspace_marker record uses), while the note becomes a custom_message entry — which is what the new real-Pi test asserts. resetNote is set for every reset (withMarkerVerdict's reset !== undefined), so detached/retiered turns get it too.
A reset is no longer used up by a turn that never ran. With a record, the start Exec is read-only (observeMarker(..., { write: !recorded })); a reset no longer records at the start; and finish() moved inside the post-prompt path (after session.prompt, before backend.flush()), so a throw or an abort before the prompt skips it and the next turn reports the same reset again. I walked the state machine — intact → no write; reset with content → rewritten at the end with the record unchanged; reset into a workspace the turn leaves empty → records false, reported once; first turn still writes at the start and again at the end when needed — and the new tests cover the throw and abort-before-prompt paths. finish() now runs before capacity.throwIfRefused(), which is harmless.
The git step now finds the real exclude file. Checked directly: at a repo root, .git/info/exclude with an empty --show-prefix; under docs/, ../.git/info/exclude with prefix docs/; in a linked worktree, the common absolute path with an empty prefix. The resulting /<prefix>.moca-session is root-relative, as info/exclude expects, so the subdirectory and worktree cases are right. The step stays on the write branch, is guarded by command -v git, and a failure is swallowed.
Docs are consistent (no remaining "note before the prompt" wording), and the rest of the PR is unchanged since a5a0756, where it checked out.
One carried, non-blocking coordination note is inline (the 1.31.0 collision with #888).
Note: @pdettori's CHANGES_REQUESTED was at a5a0756; this approval does not replace his re-review.
Assisted-By: Claude Code
| info: | ||
| title: MOCA control plane | ||
| version: 1.30.0 | ||
| version: 1.31.0 |
There was a problem hiding this comment.
Brings 15 upstream merges since 2eb0219, among them the R2 host sampler in its reviewed form (rossoctl#904), the workspace-reset marker (rossoctl#895), turn budgets and cancel (rossoctl#856), the egress allow-all option (rossoctl#886), the sbx installer token (rossoctl#888), and the docs site with the product-name prose (rossoctl#884, rossoctl#885, rossoctl#899). One conflict, deploy/sbx/template-onboarding/README.md: upstream's product-name wording for the deploy/sbx table, keeping the fork's mint-login.sh row. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Rong Chang <[email protected]>
Part of #338 (option 2): report a workspace reset on the session's own sandbox, with a marker file and no wire change
What changed and why
A worker deletes a session's workspace after
SH_WORKSPACE_IDLEwith no Exec, on both tiers, and the next Exec for thatworkspace_keygets a fresh one. The harness reports a reset only when the session moves (detached,retiered), so a reclaim on the same sandbox was silent: the next turn started in an empty workspace, and neither the user nor the model was told. This is option 2 from the 2026-11-17 comment, approved by the maintainer.The marker (
harness/src/workspace-marker.ts). The harness keeps.moca-session, holding the workspace key (the session id), at the root of the session's workspace. The name is in the.moca-*namespace the seed's files already use, which a templated session's patch already leaves out (PATCH_EXCLUDES). When the workspace is in a git repository, the marker is also listed in that repository'sinfo/exclude, found withgit rev-parse --git-path info/excludeasseedWorkspacedoes, so worktrees and submodules (where.gitis a file) are covered too. This keeps an agent'sgit add -Afrom committing it. The git step runs only when writing, and a missing or failing git is ignored.The record. The harness appends a
workspace_markercustom entry ({ key, written }, the latest one winning) to the session's own Pi log in Redis. It adds no new Redis key: the log is deleted with the session, and it already carries the harness'scheckpoint,abort, gate and verdict entries. Pi never sends a custom entry to the model. An absent entry means "never written", so no existing session is reported as reset on its first turn after an upgrade.The check. At the start of every turn, before the agent runs and before the placement is reported, one Exec reads the marker. A first turn (no record) may also write it there; with a record, the start only reads. If the record says it was written and the file is missing or holds another key, the turn:
workspace_resetwith a new reason,reclaimed. The reset goes in the turn's placement, so it reachesonPlacement, the result'ssandbox.workspaceReset, thedoneframe and the runtime record (GET /v1/sessions/{id}/resources). It is also the stream's first frame.fromis the sandbox the session is still on.before_agent_starthandler (customType: 'workspace_reset',display: false). It is never part of the prompt: the user's text reaches Pi byte for byte, so/skill:, prompt templates and extension commands still work, and the session log keeps the user's own words.A session that moved keeps its own reason (
detached/retiered). Its model now gets the same note.The empty-directory sweep (
/workspace/<sessionId>/directories accumulate on sandbox pods for workload runs #551) still works. The marker is written only into a workspace that holds something: at the turn's start, or, if the workspace was still empty then, at the turn's end (before the session log is flushed). So a container directory that is still empty stays empty, and the early removal still applies. A session whose first turn clones a repository is marked before it goes idle.Failure and scope.
SelectedSandboxnow reports the key it sent (workspaceKey), so a workload run that writes only in its context (fix: 🐛 Skip empty per-session scratch dir on writable workload runs #613) gets no check.Cost. One Exec per turn, or two on a turn that starts in an empty workspace or finds a reset. Once the workspace is marked, the script uses only shell builtins (
read,[, a glob): measured locally underbash -c, on a loaded machine, a 26 ms median against 24 ms forbash -c true, so about 2 ms over the Exec round trip on the container tier. On the microVM per-exec tier that extra Exec is one more VM acquire per turn (a standby restore, then its replenish). The upgrade note indocs/operations/upgrades.mdsays both, and that amocactlfrom before harness 1.7.0 prints areclaimedreset as "sandbox is gone".Contract.
reclaimedjoins thereasonenum of theworkspace_resetframe and ofTurnPlacement.workspaceReset, soharness-openapi.yamlgoes to 1.7.0.placement.workspaceReset.fromnow also names the sandbox a session is still on, soopenapi.yamlgoes to 1.31.0.mocactlprints the new reason: "the session's workspace on sandbox 'X' was reclaimed ...". An oldermocactlprints it as a gone sandbox.Docs.
docs/concepts/brain-and-hands.mdreplaces "the next turn is not told" with how a turn learns of a reset, and lists its limits:.moca-sessionitself is reported as reset on its next turn, because that cannot be told apart from a reclaim.workspace-subdirshares one directory among sessions.Also updated:
sessions-and-turns.md,sandboxes-and-tiers.mdandhttp-api.md. No new configuration: the check costs one command per turn and never fails one, so there is nothing an opt-out would protect.For your decision
The frame shape. This reuses the existing
workspace_resetframe with a newreason,reclaimed, rather than adding a frame type, so every surface that already reports a reset (the stream's first frame,result.sandbox.workspaceReset, the done frame, the run record) reports this one too. The cost: amocactlolder than this PR prints areclaimedreset as its existing "sandbox is gone" message, which is wrong in its words though right that the files are gone; this PR'smocactlprints areclaimedmessage. The alternative, a new frame type, would be ignored silently by older clients. Happy to switch if you prefer that.Where the record lives. A
workspace_markercustom entry in the session's own log in Redis (latest wins), beside the harness'scheckpointandabortentries, rather than a new key: it goes when the session goes, and an absent entry means "never written".The marker is visible and not a secret.
.moca-sessionsits in the workspace (ls -ashows it) and holds the session id, which the agent already knows. It is kept out of git throughinfo/exclude, sogit status,git add -Aandgit clean -fdleave it alone;git clean -fdx, or anyrm -rfof dotfiles, deletes it, and the next turn is then told of a reset that did not happen (the docs say so).Two edges of the end-of-turn rewrite. A turn that does not complete (it fails, or is aborted, before
finish()) leaves the marker missing, so the next turn reports the same reset again. That includes a turn that threw inside the prompt after the model had already seen the note: it sees it again, which errs on the safe side. And theinfo/excludestep is best effort: if git refuses the repository (for example "dubious ownership", when the workspace's owner differs from git's user), the marker is not excluded andgit add -Awould stage it. That's rare on these tiers, where the agent and the workspace share a uid.Tests
harness/test/workspace-marker.test.ts(26, new):decideWorkspaceMarker, case by case:recordedMarker: the latest record wins, and other keys are ignored.write, it only reads.info/excludeonce, andgit statusshows only the agent's file. This also holds in a git worktree (.gitis a file) and in a subdirectory of a repository..gitfile, or no git onPATH, is ignored, and the marker is still written.checkWorkspaceMarker:written: false, so it is reported once.harness/test/turn-workspace-marker.test.ts(10, new): drivesexecuteTurnturn by turn, with Pi and the session log faked (the log persists across turns) and a transport that runs every Exec under bash in a scratch workspace.workspace_reset/reclaimedand its prompt is the one sent, byte for byte, with the note as a separate message; the fourth turn is intact again.end_turnwith no frame.onPlacement, the frame andresult.sandbox.detachedand its model gets the note./skill:prompt on a reset turn reaches Pi unchanged.harness/test/workspace-reset-note.test.ts(3, new): real Pi, with a faux model and a skill. A/skill:reviewprompt on a reset turn still expands, and the note reaches the model as its own message and is logged as acustom_message(workspace_reset, not displayed). A plain prompt is sent as typed. Without a reset, there is no note. When the note is put in front of the prompt instead, the expansion test fails.harness/srcchanges stashed (andworkspace-marker.tskept), 3 of the 6 integration tests fail: no Exec is made, there is no reset in the placement, and there is no note. With the changes, all 6 pass.harness/test/run-leaf-context.test.ts: a prompt leaf hands the turn the session's own directory as its workspace, not the context view, and hands none when the key was dropped.harness/test/select-sandbox.test.ts: the selection reports the key it sent, both the session id and''.packages/mocactl/test/blocks.test.ts: thereclaimednotice text.info.versionto the CHANGELOG and the change policy.sbxcommand tests) failed in the full parallel run and pass when rerun alone.detachable-turn-route.test.tsfailed 7 under load in the full run and passes 35/35 alone.tsc --noEmitin harness, mocactl, server and control-plane;prettier --check;python3 scripts/check-doc-links.py(0 broken).Out of scope
Release{workspace_key}when a session ends, is the next step of P4 microVM tier: WorkspaceIdle=30min deletes a HITL session's workspace mid-session, silently #338.rm. A marker cannot do that. Option 1, a worker-side signal on the wire, could.Every commit is signed off (DCO).
Assisted-By: Claude Code