Compare commits

..
Author SHA1 Message Date
CodeWhale BotandClaude Opus 5.5 2c78235cff fix(subagent): remove the workspace-wide coordination lock
The v3 transaction lock and per-writer boot leases already own coordination.
Remove the lifetime process lock and its read-only fallback so one stale
session cannot keep later sessions read-only. Retry failed store admission
on later delegated writes, preserving image validation and lease ownership.

Pin an admitted Windows workspace directory without delete sharing. Keep
ordinary directory handles unchanged for plugin staging. The pin protects
the workspace and its ancestors, not children under .codewhale; that residual
boundary remains explicit in the review and release acceptance.

Integrated from 9a1e8e3b9f993a6adad30ad26d17a6d16e90737c; preserve the
original candidate and historical evidence. Updated lifecycle/architecture
docs, conformance fixtures, call sites and mirrored release notes together.

Validation on the integrated source: formatting, preflight and diff checks
passed (121 dead-code suppressions, 665 blocking sites, 244 runtime routes).
Independent source review approved. Focused Linux tests are running; exact
Windows convergence PASS and app-server compilation on all three platforms
remain required before landing. Earlier test counts are historical and are
not claimed for this integrated candidate.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 22:47:51 -08:00
CodeWhale Bot bf43019b24 fix(api): keep repeated hook labels distinct in plugin index
Use the existing per-event ordinal for hook row identity. Hook names are optional labels and validation deliberately retains repeated names. The route regression covers repeated explicit labels and a label matching the unnamed fallback.

Validation: plugin-index route tests: 2 passed, 0 failed, 844 filtered out; cargo fmt --all -- --check and git diff --check passed; scripts/preflight.sh --check passed. macOS linker reported the existing __eh_frame size warning. Refs CW-7875.
2026-11-12 22:31:45 -08:00
CodeWhale BotandClaude Sonnet 5.5 de339044aa fix(config): show the telemetry setting default as on, matching the runtime
The settings schema declared telemetry default false while the resolver
(telemetry_consent_from_env) treats an unset value as on, so the settings
API reported default false for a default-on policy.

Landed in Engine push 18 (CW-7875) with the CHANGELOG line the review wrote
(CW-7987 REVIEW.md finding 2; the packet's line was not used). This is the
committed part only: CW-7987 stays open for the active-version readback and
the ingest bundle rebuilt from the frozen candidate. Review: farm runs
20261112T110021Z-gtelrev-config-37102e (codewhale-config, 21 run, 21 passed,
823 skipped) and 20261112T110024Z-gtelrev-telem-751b20 (codewhale-telemetry,
53 run, 53 passed).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 22:31:44 -08:00
CodeWhale BotandClaude Sonnet 5.5 203b54986d feat(router): preserve explicit per-question decision abstention
An explicit abstained:true on a System One answer now survives decoding and the
routing receipt, and can never authorize Auto (tier), the thinking effort, a
shadow noul read or a shadow chat intent, even at a zero confidence floor. A
non-boolean abstained value fails answer decoding and is refused like any other
malformed answer. Provider usage evidence and the declared fallback are
unchanged. The custom decision endpoint half of the original change is not
included.

Receipt field abstained_questions touches crates/models, cost_status and the
tui activity_detail fixture outside the slice owner list; it is additive with a
serde default.

Landed in Engine push 18 (CW-7875) with the CHANGELOG line from the review (CW-7992 REVIEW.md finding 1). Review: farm run 20261112T112213Z-leg01review-tip-faf9ea, 42 run, 42 passed, 7181 skipped; counterfactual run 20261112T112313Z-leg01review-cf-032c60 fails 2 of 3 with the guards removed.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 22:31:42 -08:00
CodeWhale BotandClaude Sonnet 5.5 0b643a7340 test(engine): expire the dropped-dispatch deadline only after the client call is entered (CW-8127)
The dropped-dispatch test gave the nested call a real 100 ms deadline. On a
slow runner that deadline could expire before bind_dispatch settled the
unknown-usage record, so the biased wall-clock select won with zero records
(left: 0, right: 1). Give the call a 600 s deadline, wait until the fixture
client is entered (the record is settled before the client is called), then
pause tokio time and advance 601 s so the deadline always fires after dispatch.
The wait selects on entered against the dispatch with a panic if the dispatch
ends first, inside a 10 s real-time timeout, so a regression that stops the
dispatch before the client fails at once instead of hanging. Every assertion is
unchanged. Product code is unchanged.

nextest stress 40/40 passed, 6 tests per iteration, target test 40/40 (farm run
20261112T113538Z-cw8127r1-new-33edc8); the old test under the same stress failed
1 of 20 at left: 0 (farm run 20261112T104528Z-cw8127-old-7569e0).
clippy -p codewhale-engine --all-targets --all-features -D warnings clean (farm
run 20261112T113538Z-cw8127r1-clippy-373b1e); cargo fmt --check and
scripts/preflight.sh --check OK.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 22:31:41 -08:00
CodeWhale BotandClaude Sonnet 5.5 e14b4393f8 fix(app-server): plugin index names plugins by id, labels tools, signals cut name lists (CW-8049 PL-02 repair 1)
/v1/commands rows carry plugin_id (not the name) and workspace_sourced; the
index projects an active plugin's commands from those rows, labels native and
language-server plugins as tool, sources project commands as project, and
reports a cut or control-character name list under problems. Doc comment
removed.

Checks (Boat farm, Linux x86_64, at c3bc310042): nextest -p codewhale-app-server
-p codewhale-tui -E 'test(/plugin_index|command_catalog|get_v1_commands|user_registry|commands::discovery/)':
51 run, 51 passed, 6713 skipped (run 20261112T080110Z-plidx4-test-26f07e);
clippy -D warnings for engine, app-server and tui: clean
(run 20261112T080110Z-plidx4-clippy-124ba8). fmt, runtime-routes and facts
were the worker's local checks; preflight was not run on that tip.

Landing (push 18): rebased onto push 17; agent-docs.generated.json conflicted
with push 17's regeneration and was regenerated with derive-facts at each of
the two picks. docs/RUNTIME_ROUTES.md: check-runtime-routes PASS, no change.
CHANGELOG line from the round-2 review wording.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 22:31:40 -08:00
CodeWhale BotandClaude Sonnet 5.5 c7cf758da4 feat(app-server): one read route lists every plugin kind (CW-8049 PL-02)
GET /v1/apps/plugin-index projects the plugin registry, the built-in
switch catalog, skills, connectors, hooks and hand-written commands into
one list with kind, source and state. Each item embeds the row its owner's
route returns by calling that owner's handler, so a field an owner adds
appears here without a second edit; an owner that fails is named under
unavailable and the rest still list. A plugin item carries the names of the
skills, connectors, hooks, commands and profiles it adds, and those are
not listed again as items. Replaces nothing; the owners keep their routes.

A user command row now says which plugin added it (UserCommand.plugin,
CommandCatalogEntry.plugin, filled from the registry's plugin authority),
so a plugin's markdown command is not shown as hand-written. The wiring
in runtime_api.rs (mod line, route line, that field) and the
command_catalog and tui hunks are separable from plugin_index.rs.

Checks: farm nextest 6 run, 6 passed; farm clippy -D warnings clean for
engine, app-server, tui; preflight OK.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 22:31:38 -08:00
CodeWhale BotandClaude Fable 5.2 2f31fe1900 refactor(catalog): one model listing for both commands, and the inventory stops judging windows by name
With the readings proved equal on one captured catalog, the second copies
go:

- `route_preferences::list_models` no longer assembles its own roster
  (catalog rows, saved default, sort, dedup). It calls
  `provider_lake::listed_models_for_route`, the same function `models`
  prints.
- The routing inventory no longer asks the bundled catalog whether a model
  name has a context window to decide if a number is verified. The
  resolved route's own source decides; a route that does not resolve is
  unverified.

Farm (Linux x86_64), this commit: catalog_parity 1 test run: 1 passed;
config and engine lib tests filtered
`catalog model pricing cost_status route`: 1316 passed, 0 failed; clippy
-D warnings for config and engine (all targets, all features) and for cli
and app-server (all targets): clean.

Landing (push 18): CHANGELOG line for the pair (REF-05, CW-7971) from the
round-2 review, added in this commit.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-12 22:31:37 -08:00
CodeWhale BotandClaude Fable 5.2 cfc6182f03 fix(catalog): both model commands, the Runtime API, routing and cost read one captured catalog the same way
The new check loads one captured Models.dev catalog (the bundled seed,
sha256 7c48830c…d256) and an id-only Anthropic roster into a sealed home,
then reads three routes through `model list` / `model resolve`, `models`,
`GET /v1/providers/{id}/models`, the routing inventory and the cost
envelope: the official Anthropic route, a custom endpoint serving a
same-named model, and the Z.ai plan endpoint. It prints every reading and
fails on any disagreement.

On the previous source it found three:

- `model list` skipped a custom endpoint unless its table was literally
  named `custom`. It now lists every configured custom route under the
  route's own name.
- `model resolve` refused a custom endpoint's saved model ("no registered
  model") because the legacy registry was asked about an endpoint that owns
  its own roster. The registry is no longer consulted for those routes; the
  route resolver and a fetched roster still decide.
- The routing inventory gave a custom endpoint the context window and
  output limit of a same-named model and marked the window verified. It
  now takes the window, its source and the output limit from the resolved
  route, so a borrowed number is marked unverified and an unpublished
  output limit stays unknown.

`provider_lake::listed_models_for_route` is the list body of `models`
moved out unchanged so the check can read it.

One spelling difference is left and reported, not asserted: the inventory
normalises a listed `glm-5.1` to `GLM-5.1`.

One disagreement is also named, not hidden: a custom endpoint has no
published window, so routing still reports 200,000 for a saved model whose
name matches a known one (the router's long-context tag reads it), marked
unverified, while the Runtime API reports unknown. The check records the
Runtime reading as unknown and allows exactly that pair as a known
difference; any other window disagreement fails.

The check also pins the charge side: a custom endpoint gets no charge
(`UnknownBillingBasis`); the Z.ai plan route gets no charge
(`NotMoneyMetered`) even for a model that has a list rate, and both
surfaces show that same list rate; an id-only first-party model with no
price row reads unknown on both surfaces and produces no charge.

Farm (Linux x86_64): config, engine and app-server lib tests filtered
`catalog_parity catalog model pricing cost_status route`: 1444 passed,
0 failed; clippy -D warnings for config, engine, cli and app-server (all
targets, all features): clean.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 22:31:36 -08:00
CodeWhale BotandClaude Sonnet 5.5 85e9cff918 fix(acp): a plugin tool's nested approval reaches the editor as a permission request that names the nested tool (CW-8050)
When a plugin tool asks the core to run a tool that needs approval, the ACP
projection resolves the nested execution id to the admitted plugin call and
shows the request on it. The request is built from the approval.required
payload (nested tool name, input, summary) so title, kind and rawInput show
what is being approved, and it carries no status so the running plugin call is
not reset to pending. The gates test and journey test live in acp_journey and
assert the second request names write and carries nested.txt.

Docs (RUNTIME_API, EXTENSIONS, zh_hans) and web/data/agent-docs.generated.json
updated.

Checks: nextest -p codewhale-app-server -E 'test(acp)' on the build farm,
48 run, 48 passed, 815 skipped; cargo fmt --check clean; preflight --check OK.

Landing (push 18): rebased onto push 17. The zh_hans EXTENSIONS and
RUNTIME_API paragraphs conflicted with push 17's CW-8071 wording of the same
ACP paragraph; kept push 17's text and added this change's sentences where
the English copies have them. agent-docs.generated.json regenerated with
derive-facts. CHANGELOG line from the round-2 review.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 22:31:34 -08:00
40 changed files with 518 additions and 1102 deletions

No files matched your search

+17 -47
View File
@@ -810,20 +810,6 @@ assert.doesNotMatch(
// A job that calls a reusable workflow (`uses:`) cannot carry the key at all —
// GitHub rejects it — so the callee owns its own caps. That is why the artifact
// bounds live in release-artifacts.yml rather than in its callers.
function timeoutMinutes(value) {
const literal = /^\d+$/.test(value);
const conditional = value.match(
/^\$\{\{\s*startsWith\(matrix\.os,\s*'macos-'\)\s*&&\s*(\d+)\s*\|\|\s*(\d+)\s*\}\}$/,
);
if (!literal && !conditional) return null;
const macos = Number(literal ? value : conditional[1]);
const other = Number(literal ? value : conditional[2]);
if (![macos, other].every((cap) => Number.isInteger(cap) && cap > 0 && cap <= 360)) {
return null;
}
return { macos, other };
}
function jobsWithoutTimeout(source) {
const lines = source.split("\n");
const jobsAt = lines.findIndex((line) => /^jobs:\s*$/.test(line));
@@ -837,8 +823,7 @@ function jobsWithoutTimeout(source) {
for (let j = i + 1; j < lines.length; j += 1) {
if (/^ [A-Za-z0-9_-]+:\s*$/.test(lines[j])) break;
if (/^ uses:/.test(lines[j])) reusable = true;
const timeout = lines[j].match(/^ timeout-minutes:\s*(.+?)\s*$/);
if (timeout && timeoutMinutes(timeout[1])) capped = true;
if (/^ timeout-minutes:\s*\d+\s*$/.test(lines[j])) capped = true;
}
if (!reusable && !capped) offenders.push(header[1]);
}
@@ -877,41 +862,26 @@ for (const [name, source] of [
);
}
function jobTimeout(source, job, platform = "other") {
// The Windows artifact build historically runs 40-45 minutes, so its cap has to
// keep real margin — a tight bound here fails healthy releases.
const buildTimeout = artifacts.match(/^ build:\n(?:.*\n)*? timeout-minutes: (\d+)$/m);
assert.ok(buildTimeout, "release-artifacts build job must be capped");
assert.ok(
Number(buildTimeout[1]) >= 60,
`artifact build cap ${buildTimeout[1]}m leaves no margin over a healthy 40-45m Windows build`,
);
function jobTimeout(source, job) {
const match = source.match(
new RegExp(`^ ${job}:\\n(?:.*\\n)*? timeout-minutes: (.+)$`, "m"),
new RegExp(`^ ${job}:\\n(?:.*\\n)*? timeout-minutes: (\\d+)$`, "m"),
);
assert.ok(match, `${job} must declare timeout-minutes`);
const caps = timeoutMinutes(match[1].trim());
assert.ok(caps, `${job} must declare a bounded timeout`);
return caps[platform];
return Number(match[1]);
}
const macosTimeout = "${{ startsWith(matrix.os, 'macos-') && 360 || 210 }}";
assert.deepEqual(timeoutMinutes(macosTimeout), { macos: 360, other: 210 });
for (const invalid of [
"0", "361", "Infinity", "${{ matrix.timeout }}",
"${{ startsWith(matrix.os, 'macos-') && 361 || 210 }}",
"${{ startsWith(matrix.os, 'macos-') && 360 || 0 }}",
]) {
assert.equal(timeoutMinutes(invalid), null, `${invalid} must not count as a bounded cap`);
}
assert.deepEqual(
jobsWithoutTimeout(`jobs:\n capped:\n timeout-minutes: ${macosTimeout}\n`),
[],
);
assert.equal(jobTimeout(artifacts, "build", "macos"), 360);
assert.equal(jobTimeout(artifacts, "build"), 210);
const artifactCacheSetup = artifacts.match(
/ - uses: mozilla-actions\/sccache-action@[^\n]+\n(?:(?! - ).*\n)*/,
);
assert.ok(artifactCacheSetup, "artifact compiler cache setup must be explicit");
assert.match(artifactCacheSetup[0], /^ if: runner\.os == 'Linux'$/m);
assert.match(
namedStep(artifacts, "Enable sccache"),
/^ if: steps\.sccache\.outcome == 'success' && runner\.os == 'Linux'$/m,
);
// Fast setup and packaging fail quickly. Native builds need the same finite
// cold-build allowance as full CI: both 0.10.1 macOS artifacts hit the old
// 90m compilation cap before reaching their launch and inventory checks.
assert.equal(jobTimeout(candidate, "resolve"), 10);
assert.equal(jobTimeout(candidate, "web"), 15);
assert.equal(jobTimeout(artifacts, "pin"), 10);
@@ -924,7 +894,7 @@ for (const job of ["bundle", "windows-installer", "assemble", "smoke"]) {
}
assert.equal(
jobTimeout(nightly, "build"), jobTimeout(artifacts, "build"),
"nightly and non-macOS release builds must share the cold-build allowance",
"nightly and release must share the native cold-build allowance",
);
assert.equal(jobTimeout(release, "resolve"), 10);
// The 0.10.1 cold parity build exhausted 45 minutes before tests started.
+1 -14
View File
@@ -21,7 +21,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Plugin index (Runtime API):** a new `GET /v1/apps/plugin-index` route lists plugins, skills, connectors, hooks and hand-written commands with kind, source and state, and `/v1/commands` rows say which plugin (`plugin_id`) added a command and whether a command came from the project (`workspace_sourced`) (CW-8092).
- **Model commands and routing:** `codewhale model list` now lists every custom endpoint you have configured, under its own name. `codewhale model resolve` no longer refuses a model on a custom endpoint, router or local server whose model list has not been fetched yet; once a list is fetched, a model missing from it is still refused. Automatic routing marks a context window as verified only when the route itself supplies it, and no longer reports a guessed output limit.
- **ACP:** when a plugin tool asks the core to run a tool that needs approval, the editor now gets a `session/request_permission` on the plugin tool's call that names the nested tool and its input; before, the prompt ended with an internal error (CW-8050).
- **Website maintainer and cron secrets:** the manual cron trigger is rate limited, admin sign-in and the cron secret require a 32 to 512 character secret with at least 8 distinct characters that is not a repeated pattern, and changing the maintainer token signs out existing admin sessions.
- **README and contributor credit:** the repository front page now opens the way the website does: the line "The model can be anyone's. The agent should be yours.", one sentence on what Codewhale is, the install command and one picture, with reference detail moved into the linked guides; the 18 translated READMEs follow the same structure and say they are machine-drafted. The contributor wall and the website now count the same 433 people (407 GitHub accounts and the commit authors whose email is not linked to an account), where the website had counted accounts only. `DEPENDENCY_SECURITY.md` moved into `docs/dependency-maintenance.md`, and `.github/SUPPORT.md` says where to ask for help.
- **Website Plugins page:** The website's Plugins page now describes what the released version does, and a labelled section says what 0.10.3 adds: one Plugins place, Standard and Creator mode, and the Permissions control.
- **First-time guide on the website:** a new docs page, "Use Codewhale for the first time" (`/docs/first-time`, English and Simplified Chinese), walks someone who has never used a terminal through opening one, installing, choosing the folder Codewhale works in and when that choice matters, opening a terminal in a folder from Finder or File Explorer, connecting a model, a first task, and stopping, undoing and quitting. The install page gains a short "New to the terminal?" block for macOS and Windows that links to it, and `llms.txt` carries the same steps.
@@ -685,7 +684,7 @@ work is declared complete here. Items moved to 0.10.4 by name are marked below.
- **Windows uninstall removes the receipt and update leftovers.** The installer's uninstaller also deletes `.codewhale-install.sha256` and `codewhale.old-*`/`codew.old-*` left by a self-update, so `bin` can be removed. Refs #7091.
- **Windows `/undo` matches recorded file paths regardless of case.** A write recorded under a different drive-letter or directory case, or a `\\?\` prefix, is no longer dropped from the restore plan. Refs #6970.
- **Windows: Fleet and metrics read live files again.** Replaying a Fleet ledger and reading audit or receipt records no longer fail with a sharing violation while their writer is still open; the same regular-file, link and identity checks apply. Plugin enablement now says which snapshot check refused (stage root, content identity or final check) instead of one generic message. Generated protocol and SDK exports keep LF line endings in Windows checkouts.
- **A held coordination lock no longer makes a new session read-only.** When another session owns the delegated-agent store, the new session starts on private state and says so, instead of refusing every sub-agent with “Failed to clean up sub-agents”.
- **Sessions in one folder no longer leave each other's sub-agents read-only or private:** a second session works beside another one, stale or suspended included, the older sub-agent store upgrades right away, and a store that cannot be opened is retried on the next sub-agent change instead of needing a restart. While another Codewhale session, a suspended one included, is open in a folder the desktop app or `serve` was asked to work in (other than the folder it started in), that Runtime still refuses sub-agents that would edit the folder directly; isolated worktrees are unaffected. A sub-agent store that cannot be opened shows its refusal once instead of repeating cleanup warnings on every sidebar refresh. Restart any session started with Codewhale 0.10.2 or older: once the folder upgrades it can no longer save sub-agent state (Refs #7232).
- **A dev server can outlive the turn in an interactive session.** `persist:true` now works in the TUI and desktop when the thread has Full Access; restricted postures and Fleet/sub-agents still refuse it.
- **`codewhale exec --add-dir <path>`** (repeatable) and `addDirs` on `POST /v1/threads` let the file tools read and write a sibling directory, a second checkout or a shared scratch root without turning on Full Access.
- **Unsettled usage is persisted in production, not only in tests.** The interactive sink now records a legacy usage receipt when a provider response has no settlement, so children and turns stop reporting settlement failure.
@@ -722,12 +721,6 @@ work is declared complete here. Items moved to 0.10.4 by name are marked below.
composer. Real Pinyin input on macOS and Windows is not yet confirmed.
Thanks [@cmdcorp6534](https://github.com/cmdcorp6534) for the report
(Refs #2323).
- **Sub-agents beside an older session:** while a Codewhale 0.10.2 session
still uses a folder's older delegated-agent store, a 0.10.3 session in the
same folder keeps working sub-agents with private state that is not saved,
instead of refusing every sub-agent action. The older session's files are
left untouched, and the store upgrades when a session starts after the older
one exits (Refs #7232).
- **Fleet members:** a replayed member start now matches only within its own
session, so two sessions that reuse an operation key no longer receive each
other's agent.
@@ -756,12 +749,6 @@ work is declared complete here. Items moved to 0.10.4 by name are marked below.
bare self-package exports resolve inside the selected package directory.
Invalid or incompatible ranges and paths outside the reviewed package still
refuse. Real published-plugin activation remains unqualified.
- **Coordination lock diagnostics (#7232):** stale lock-file contents no longer
identify an owner PID. A refused legacy admission keeps its reason in Work
and shows one notice per cause instead of repeating cleanup warnings on
every sidebar refresh. Legacy migration still requires the actual holder to
exit and the refused owning Runtime to restart; locks and retained state
remain protected.
- **A local proxy that stops mid-session no longer strands the session (#7231):** the model, catalog, search, vision, finance, MCP-registry, profile and remote-control clients watch a loopback proxy port and go direct while it refuses connections, then resume proxying when it returns. Only a definite refusal from every resolved address changes the route; remote proxies, `NO_PROXY` matches, credentials and the existing precedence are unchanged. Set `CODEWHALE_LOCAL_PROXY_FALLBACK=0` to keep the old build-time snapshot.
- **Proxy diagnostic privacy ([#7233](https://github.com/codewhale-hq/codewhale/issues/7233)):** malformed MCP proxy warnings omit configured values; local-proxy log labels mask userinfo and omit URL paths, queries and fragments. Routing is unchanged. All 23 existing proxy tests passed on macOS; runtime log capture and other platforms remain unqualified. Thanks [@SparkofSpike](https://github.com/SparkofSpike) for the report.
- **Fork, undo and retry work after a workspace drift notice (#7234):** the history-boundary walks now treat a whole `<context_update>` envelope as engine-owned, so a session that received one can be cut at every saved turn. A person quoting a notice or a truncated envelope still counts as their own prompt.
+1 -1
View File
@@ -387,7 +387,7 @@ impl RuntimeWorkspaceScopes {
let owner = self.clone();
codewhale_runtime::runtime_control::owner_work(move || {
let (canonical, directory) =
codewhale_util::workspace_dir::open_workspace_directory(&lexical)?;
codewhale_util::workspace_dir::open_pinned_workspace_directory(&lexical)?;
let directory = Arc::new(directory);
let mut scopes = owner.scopes.lock();
if let Some(scope) = scopes.get(&lexical) {
@@ -1202,15 +1202,15 @@ async fn real_owner_two_workspace_services_share_scope_caches_and_settle_global_
{
let error = fs::rename(&selected_workspace, &retired_workspace)
.expect_err("a live Runtime owner must prevent workspace replacement");
assert_eq!(error.raw_os_error(), Some(5), "{error}");
assert_eq!(error.raw_os_error(), Some(32), "{error}");
assert!(!retired_workspace.exists());
}
manager.shutdown_and_wait().await?;
#[cfg(windows)]
{
let error = fs::rename(&selected_workspace, &retired_workspace)
.expect_err("Engine shutdown must retain the Runtime owner's workspace lock");
assert_eq!(error.raw_os_error(), Some(5), "{error}");
.expect_err("Engine shutdown must retain the Runtime owner's pinned workspace");
assert_eq!(error.raw_os_error(), Some(32), "{error}");
assert!(!retired_workspace.exists());
assert!(Arc::ptr_eq(
&scopes.admit(selected_workspace.clone()).await?,
+2 -2
View File
@@ -314,8 +314,8 @@ pub struct EngineConfig {
pub session_id: Option<String>,
/// Optional host-owned root for delegated-agent runtime state.
///
/// When unset, the worker ledger, complete transcript artifacts and
/// coordination lock retain their historical location under
/// When unset, the worker ledger and complete transcript artifacts
/// retain their historical location under
/// `workspace/.codewhale/state`. Embedders may set a session-scoped root
/// to separate that control-plane state from the execution workspace.
/// Child cwd and file authority still derive from `workspace`; hosts using
+1 -2
View File
@@ -11615,10 +11615,9 @@ async fn compact_thread_receipt_keeps_exact_named_custom_identity() -> Result<()
#[tokio::test]
async fn compact_thread_with_real_engine_reaches_terminal_status() -> Result<()> {
// A real engine takes the workspace coordination lock exclusively, and
// nextest runs tests in parallel processes with this crate as their working
// directory. A `"."` workspace would therefore be the crate directory
// itself, and two exclusive holders of it cannot both start.
// itself, shared by every test process.
let workspace = tempfile::tempdir()?;
let manager = RuntimeThreadManager::open(
{
+1 -1
View File
@@ -1721,7 +1721,7 @@ mod tests {
.expect_err("mutation must fail when its receipt cannot persist")
.to_string();
assert!(
error.contains("Runtime coordination was opened without its writer lock"),
error.contains("delegated durable store admission failed"),
"{error}"
);
assert!(
@@ -321,9 +321,10 @@ pub struct CoordinationDetailProjection {
pub metrics: CoordinationDetailMetrics,
pub bounded: bool,
pub limit: usize,
/// Whether this process currently holds the workspace coordination flock.
/// When false, durable ledger writes are skipped and the UI must say so —
/// a counter must never tick on a turn the engine has already settled.
/// Whether this manager's durable store is admitted. When false, durable
/// ledger writes are refused until admission is retried and the UI must
/// say so — a counter must never tick on a turn the engine has already
/// settled.
#[serde(default = "default_process_lock_held")]
pub process_lock_held: bool,
/// Human-readable reason when [`Self::process_lock_held`] is false.
+134 -435
View File
@@ -499,7 +499,6 @@ const SUBAGENT_TRANSCRIPT_ARTIFACT_DIR: &str = "subagent-transcripts";
const SUBAGENT_STATE_SCHEMA_VERSION: u32 = 1;
const SUBAGENT_STATE_FILE: &str = "subagents.v3.json";
const LEGACY_SUBAGENT_STATE_FILE: &str = "subagents.v1.json";
const SUBAGENT_STATE_LOCK_FILE: &str = "subagents.v1.lock";
const SUBAGENT_RESTART_REASON: &str = "Interrupted by process restart";
const SUBAGENT_SESSION_CLOSED_REASON: &str = "Interrupted: parent session closed";
#[cfg(test)]
@@ -3933,12 +3932,6 @@ impl SubAgent {
}
}
/// Manager for active sub-agents.
struct CoordinationProcessLock {
release: Option<std::sync::mpsc::SyncSender<()>>,
thread: Option<std::thread::JoinHandle<()>>,
}
/// Marker prefix retained for presentation compatibility with same-process
/// handover notes from earlier hosts. It does not control lock acquisition
/// or retry.
@@ -3954,123 +3947,6 @@ pub const COORDINATION_LOCK_TIMEOUT_MARKER: &str =
pub const SESSION_PRIVATE_COORDINATION: &str = "another Codewhale session still uses this folder's older delegated-agent store, so its upgrade waits; sub-agents in this session keep private state that other sessions do not see and that is not saved, and the store upgrades when a session starts after the other one exits";
#[derive(Debug)]
struct SubAgentCutoverBlocked(anyhow::Error);
impl std::fmt::Display for SubAgentCutoverBlocked {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::error::Error for SubAgentCutoverBlocked {}
impl CoordinationProcessLock {
fn acquire(state_root: &Path, exclusive: bool) -> Result<Self> {
let requested_root = normalize_subagent_workspace(state_root);
// Root and path for the lock. A non-home workspace keeps itself as the
// root, so a repository-supplied `.codewhale` link is walked and
// refused before `create_dir_all` could follow it into the target. A
// home workspace resolves its own junction once and still walks
// everything below it.
let (walk_root, lock_path) = codewhale_util::files::workspace_state_path(
&requested_root,
&Path::new("state").join(SUBAGENT_STATE_LOCK_FILE),
);
let lock_dir = lock_path
.parent()
.map_or_else(|| walk_root.clone(), Path::to_path_buf);
// Refuse a linked `.codewhale` or `state` before creating anything:
// `create_dir_all` follows links and would populate the target.
reject_root_relative_symlinks(&walk_root, &lock_path)?;
fs::create_dir_all(&lock_dir)?;
let ignore = lock_dir.join(".gitignore");
let ignored = reject_root_relative_symlinks(&walk_root, &ignore).and_then(|()| {
match fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&ignore)
{
Ok(mut file) => file.write_all(b"*\n").map_err(Into::into),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
Err(error) => Err(error.into()),
}
});
if let Err(error) = ignored {
tracing::warn!(target: "subagent", %error, "could not write {}", ignore.display());
}
// Creating a missing root can change its canonical spelling on
// Windows (for example by adding a `\\?\` prefix). Re-resolve both
// sides before checking containment.
let state_root = normalize_subagent_workspace(state_root);
let (walk_root, lock_path) = codewhale_util::files::workspace_state_path(
&state_root,
&Path::new("state").join(SUBAGENT_STATE_LOCK_FILE),
);
reject_root_relative_symlinks(&walk_root, &lock_path)?;
let lock_file = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.open(&lock_path)?;
let (ready_tx, ready_rx) = std::sync::mpsc::sync_channel(1);
let (release_tx, release_rx) = std::sync::mpsc::sync_channel(0);
let thread = std::thread::spawn(move || {
let mut lock = fd_lock::RwLock::new(lock_file);
let acquired = if exclusive {
lock.try_write().map(|guard| {
let _ = ready_tx.send(Ok::<(), String>(()));
let _guard = guard;
let _ = release_rx.recv();
})
} else {
lock.try_read().map(|guard| {
let _ = ready_tx.send(Ok::<(), String>(()));
let _guard = guard;
let _ = release_rx.recv();
})
};
match acquired {
Ok(()) => {}
Err(error) => {
let _ = ready_tx.send(Err(error.to_string()));
}
}
});
match ready_rx.recv_timeout(Duration::from_secs(5)) {
Ok(Ok(())) => Ok(Self {
release: Some(release_tx),
thread: Some(thread),
}),
Ok(Err(error)) => {
let _ = thread.join();
Err(anyhow!(
"delegated coordination lock is unavailable for {}: {error}; close any other running or suspended Codewhale session using this workspace, then restart this Runtime if admission was refused",
state_root.display()
))
}
Err(error) => {
drop(release_tx);
let _ = thread.join();
Err(anyhow!(
"{COORDINATION_LOCK_TIMEOUT_MARKER} for {}: {error}",
state_root.display()
))
}
}
}
}
impl Drop for CoordinationProcessLock {
fn drop(&mut self) {
self.release.take();
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
/// Only the captured Runtime owner admits roots. Held handles are not serialized;
/// a restored attributed claim must be re-admitted before it can authorize work.
struct AdmittedCoordinationRoot {
@@ -4106,19 +3982,12 @@ pub struct SubAgentManager {
worker_origins: HashMap<String, WorkerOrigin>,
worker_origin_schema: u32,
workspace: PathBuf,
/// Root that owns the delegated-agent ledger, complete transcript
/// artifacts and coordination lock. Defaults to `workspace`; embedders may
/// Root that owns the delegated-agent ledger and complete transcript
/// artifacts. Defaults to `workspace`; embedders may
/// isolate it without changing child execution cwd or file authority.
state_root: PathBuf,
state_path: Option<PathBuf>,
state_unreachable_warned: bool,
coordination_process_lock: std::sync::Mutex<Option<Arc<CoordinationProcessLock>>>,
coordination_process_lock_required: bool,
coordination_exclusive: bool,
coordination_snapshot_read_only: bool,
store_cutover_blocked: bool,
session_private: bool,
workspace_writer_locks: HashMap<PathBuf, Arc<CoordinationProcessLock>>,
/// Configured default per-child model-turn budget (`[subagents]
/// default_max_steps`, #5324). `None` keeps the unbounded Fleet default;
/// an explicit spawn `max_steps` still wins. Zero means unbounded.
@@ -4759,13 +4628,6 @@ impl SubAgentManager {
state_root,
state_path: None,
state_unreachable_warned: false,
coordination_process_lock: std::sync::Mutex::new(None),
coordination_process_lock_required: false,
coordination_exclusive: false,
coordination_snapshot_read_only: false,
store_cutover_blocked: false,
session_private: false,
workspace_writer_locks: HashMap::new(),
max_steps: None,
wall_time: None,
max_agents,
@@ -4831,22 +4693,6 @@ impl SubAgentManager {
return Err("coordination workspace identity is unsupported on this platform".into());
#[cfg(any(unix, windows))]
{
if self.coordination_exclusive
&& !self.coordination_snapshot_read_only
&& normalize_subagent_workspace(&lexical)
!= normalize_subagent_workspace(&self.state_root)
&& !self.workspace_writer_locks.contains_key(&canonical_root)
{
match CoordinationProcessLock::acquire(&lexical, true) {
Ok(lock) => {
self.workspace_writer_locks
.insert(canonical_root.clone(), Arc::new(lock));
}
Err(error) => {
tracing::warn!(target: "subagent", %error, "admitted coordination workspace without its writer lock; shared-workspace writers there stay refused until it is free");
}
}
}
let receipt = CoordinationClaimScope {
canonical_root,
platform: platform.into(),
@@ -4866,44 +4712,61 @@ impl SubAgentManager {
}
}
fn ensure_origin_writer_lock(&mut self, origin: &WorkerOrigin) -> Result<(), String> {
let (Some(selected), Some(scope)) = (&origin.selected_workspace, &origin.scope) else {
fn refuse_live_selected_store_writers(&self, origin: &WorkerOrigin) -> Result<(), String> {
let (Some(selected), Some(_)) = (&origin.selected_workspace, &origin.scope) else {
return Ok(());
};
if !self.coordination_exclusive
|| normalize_subagent_workspace(selected)
== normalize_subagent_workspace(&self.state_root)
|| self
.workspace_writer_locks
.contains_key(&scope.canonical_root)
if normalize_subagent_workspace(selected) == normalize_subagent_workspace(&self.state_root)
{
return Ok(());
}
let lock =
CoordinationProcessLock::acquire(selected, true).map_err(|error| error.to_string())?;
self.workspace_writer_locks
.insert(scope.canonical_root.clone(), Arc::new(lock));
let path = default_state_path(selected).map_err(|error| error.to_string())?;
let unreadable = |error: std::io::Error| {
format!(
"cannot check {} for another open Codewhale session ({error}); shared-workspace writers there stay refused, or launch the builder in an isolated worktree",
selected.display()
)
};
let directory = path
.parent()
.ok_or_else(|| "delegated store has no parent".to_string())?;
let entries = match fs::read_dir(directory) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(unreadable(error)),
};
for entry in entries {
let name = entry.map_err(unreadable)?.file_name();
let Some(writer) = name
.to_str()
.and_then(|name| name.strip_prefix("subagents.v3.writer."))
.and_then(|name| name.strip_suffix(".lock"))
else {
continue;
};
if valid_store_writer(writer) && store_writer_is_live(&path, writer) {
return Err(format!(
"another Codewhale session ({writer}) has {} open; shared-workspace writers there stay refused until it exits, or launch the builder in an isolated worktree",
selected.display()
));
}
}
Ok(())
}
fn ensure_worker_coordination_locks(
&mut self,
fn admit_worker_shared_writes(
&self,
spec: &AgentWorkerSpec,
origin: &WorkerOrigin,
) -> Result<(), String> {
let claim = worker_coordination_claim(spec)?;
if claim.as_ref().is_some_and(|(_, isolated)| *isolated) {
return Ok(());
match worker_coordination_claim(spec)? {
Some((_, false)) => self.refuse_live_selected_store_writers(origin),
_ => Ok(()),
}
self.ensure_coordination_process_lock()?;
if claim.is_some() {
self.ensure_origin_writer_lock(origin)?;
}
Ok(())
}
pub fn ensure_registered_worker_coordination_locks(
&mut self,
&self,
worker_id: &str,
) -> Result<(), String> {
let spec = self
@@ -4918,7 +4781,7 @@ impl SubAgentManager {
.cloned()
.ok_or_else(|| "worker origin is missing from the owner journal".to_string())?;
self.validate_worker_origin(&origin)?;
self.ensure_worker_coordination_locks(&spec, &origin)
self.admit_worker_shared_writes(&spec, &origin)
}
fn admitted_coordination_root(&self, workspace: &Path) -> Option<&AdmittedCoordinationRoot> {
@@ -5316,7 +5179,6 @@ impl SubAgentManager {
.map_err(|error| error.to_string());
}
self.ensure_coordination_process_lock()?;
if let Some(root) = self.admitted_coordination_root(workspace) {
root.validate()?;
}
@@ -5395,7 +5257,6 @@ impl SubAgentManager {
.map_err(|error| error.to_string());
}
self.ensure_coordination_process_lock()?;
self.coordination
.update_decision_status(decision_id, status, owner, expected_version)
}
@@ -5442,7 +5303,6 @@ impl SubAgentManager {
.map_err(|error| error.to_string());
}
self.ensure_coordination_process_lock()?;
let expected_owner = self.nearest_common_fan_in_owner(&input_decisions)?;
if owner != expected_owner {
return Err(format!(
@@ -5714,19 +5574,13 @@ impl SubAgentManager {
},
bounded: true,
limit,
process_lock_held: !self.session_private && {
// Retry acquire on each projection so a session that lost the
// flock at construction recovers once the previous owner exits.
let _ = self.coordination_process_lock_status();
self.holds_coordination_process_lock()
},
process_lock_note: if self.session_private {
Some(SESSION_PRIVATE_COORDINATION.to_string())
} else if self.holds_coordination_process_lock() {
None
} else {
self.coordination_process_lock_status().err()
},
process_lock_held: self.state_path.is_none() || self.store_authority.is_some(),
process_lock_note: (self.state_path.is_some() && self.store_authority.is_none()).then(
|| {
"delegated store admission failed; it is retried on the next delegated write"
.to_string()
},
),
}
}
@@ -5861,7 +5715,6 @@ impl SubAgentManager {
.and_then(|outcome| outcome);
}
self.ensure_coordination_process_lock()?;
let Some(existing) = self
.coordination
.write_claims
@@ -5948,7 +5801,6 @@ impl SubAgentManager {
.map_err(|error| error.to_string());
}
self.ensure_coordination_process_lock()?;
let active = self.active_coordination_owners();
let released = self
.coordination
@@ -6073,109 +5925,12 @@ impl SubAgentManager {
match SubAgentStoreAuthority::open(&self.state_root, &path, &self.current_session_boot_id) {
Ok(authority) => self.store_authority = Some(authority),
Err(error) => {
self.coordination_snapshot_read_only = true;
self.store_cutover_blocked = error
.chain()
.any(|cause| cause.is::<SubAgentCutoverBlocked>());
tracing::warn!(target: "subagent", %error, "delegated store admission failed; writable state remains refused");
tracing::warn!(target: "subagent", %error, "delegated store admission failed; it is retried on the next delegated write");
}
}
self
}
fn into_session_private(mut self) -> Self {
self.state_path = None;
self.store_authority = None;
self.coordination_snapshot_read_only = false;
self.coordination_process_lock_required = false;
self.session_private = true;
tracing::warn!(target: "subagent", "{SESSION_PRIVATE_COORDINATION}");
self
}
fn require_coordination_process_lock(mut self) -> Self {
self.coordination_process_lock_required = true;
if self.store_authority.is_none()
&& let Some(path) = self.state_path.as_ref()
{
match SubAgentStoreAuthority::open(
&self.state_root,
path,
&self.current_session_boot_id,
) {
Ok(authority) => self.store_authority = Some(authority),
Err(error) => {
self.coordination_snapshot_read_only = true;
tracing::warn!(target: "subagent", %error, "delegated store migration or admission failed; no durable writes are admitted");
return self;
}
}
}
let acquired =
CoordinationProcessLock::acquire(&self.state_root, self.coordination_exclusive)
.ok()
.map(Arc::new);
if acquired.is_none() {
return self.into_session_private();
}
*self
.coordination_process_lock
.get_mut()
.expect("coordination lock slot poisoned") = acquired;
self
}
/// Terminal sessions retry failed acquisition when the previous owner
/// exits. A Runtime loaded without its writer lock must restart rather
/// than publish its stale snapshot. The flock is held on an open fd —
/// deleting the lock file does not release it (#5036).
fn ensure_coordination_process_lock(&self) -> Result<(), String> {
if self.coordination_snapshot_read_only {
return Err(
"Runtime coordination was opened without its writer lock; stop and restart this Runtime process after the other session exits"
.into(),
);
}
if !self.coordination_process_lock_required {
return Ok(());
}
let mut slot = self
.coordination_process_lock
.lock()
.expect("coordination lock slot poisoned");
if slot.is_some() {
return Ok(());
}
match CoordinationProcessLock::acquire(&self.state_root, self.coordination_exclusive) {
Ok(lock) => {
*slot = Some(Arc::new(lock));
Ok(())
}
Err(error) => Err(error.to_string()),
}
}
/// Whether this process currently owns the workspace coordination flock.
/// Read-only inspection of the in-process slot — does not attempt acquire.
#[must_use]
pub fn holds_coordination_process_lock(&self) -> bool {
if !self.coordination_process_lock_required {
// Tests and non-durable managers do not require the flock.
return true;
}
self.coordination_process_lock
.lock()
.expect("coordination lock slot poisoned")
.is_some()
}
/// Probe lock ownership for UI/inspect surfaces. Retries acquire when the
/// slot is empty so a terminal session can recover after the previous
/// owner exits (#2.6 / #5036); read-only Runtime snapshots require restart.
pub fn coordination_process_lock_status(&self) -> Result<(), String> {
self.ensure_coordination_process_lock()
}
#[must_use]
pub fn with_running_heartbeat_timeout(mut self, timeout: Duration) -> Self {
self.running_heartbeat_timeout = if timeout.is_zero() {
@@ -6223,18 +5978,31 @@ impl SubAgentManager {
.is_some_and(|authority| authority.owned.lock().contains(id))
}
fn admitted_store_authority(&mut self) -> Result<Option<Arc<SubAgentStoreAuthority>>> {
let Some(path) = self.state_path.as_ref() else {
return Ok(None);
};
if let Some(authority) = self.store_authority.as_ref() {
return Ok(Some(authority.clone()));
}
let authority =
SubAgentStoreAuthority::open(&self.state_root, path, &self.current_session_boot_id)
.map_err(|error| {
anyhow!(
"delegated durable store admission failed ({error:#}); it is retried on the next delegated write"
)
})?;
self.store_authority = Some(authority.clone());
Ok(Some(authority))
}
pub(crate) fn with_store_transaction<T>(
&mut self,
operation: impl FnOnce(&mut Self) -> Result<T>,
) -> Result<T> {
if self.state_path.is_none() {
let Some(authority) = self.admitted_store_authority()? else {
return operation(self);
}
self.ensure_coordination_process_lock()
.map_err(anyhow::Error::msg)?;
let authority = self.store_authority.clone().ok_or_else(|| {
anyhow!("delegated durable store admission failed; inspect before retrying")
})?;
};
if authority.is_current_transaction() {
return operation(self);
}
@@ -6435,8 +6203,6 @@ impl SubAgentManager {
worker_id: &str,
payload: PersistedSubAgentState,
) -> Result<Option<AgentWorkerRecord>> {
self.ensure_coordination_process_lock()
.map_err(anyhow::Error::msg)?;
if self.state_path.is_none() {
return Ok(None);
}
@@ -6534,8 +6300,6 @@ impl SubAgentManager {
/// completes. Callers may `.join()` for synchronous semantics or drop it
/// for fire-and-forget.
fn persist_state(&self) -> Result<std::thread::JoinHandle<()>> {
self.ensure_coordination_process_lock()
.map_err(anyhow::Error::msg)?;
let Some((_, payload)) = self.build_persist_payload()? else {
return Ok(std::thread::spawn(|| {}));
};
@@ -6543,16 +6307,7 @@ impl SubAgentManager {
.store_authority
.clone()
.ok_or_else(|| anyhow!("delegated store authority is unavailable"))?;
let writer_locks = self
.coordination_process_lock
.lock()
.expect("coordination lock slot poisoned")
.iter()
.cloned()
.chain(self.workspace_writer_locks.values().cloned())
.collect::<Vec<_>>();
Ok(std::thread::spawn(move || {
let _writer_locks = writer_locks;
if let Err(error) = authority.publish(&payload, None, None) {
tracing::warn!(target: "subagent", %error, "failed to persist sub-agent checkpoint");
}
@@ -6560,8 +6315,6 @@ impl SubAgentManager {
}
fn persist_state_synchronously(&self) -> Result<()> {
self.ensure_coordination_process_lock()
.map_err(anyhow::Error::msg)?;
let Some((_, payload)) = self.build_persist_payload()? else {
return Ok(());
};
@@ -6624,8 +6377,6 @@ impl SubAgentManager {
/// Unlike `persist_state`, this performs disk I/O **synchronously** to
/// guarantee data is flushed before the process exits.
pub fn flush_pending_persist(&mut self) -> Result<()> {
self.ensure_coordination_process_lock()
.map_err(anyhow::Error::msg)?;
if self.persist_pending {
self.persist_state_synchronously()?;
self.last_persist_at = Some(Instant::now());
@@ -6848,8 +6599,7 @@ impl SubAgentManager {
}
pub fn finalize_session_close_for_session(&mut self, active_session_id: &str) -> Result<usize> {
if !self.coordination_snapshot_read_only
&& (self.state_path.is_none() || self.store_authority.is_some())
if (self.state_path.is_none() || self.store_authority.is_some())
&& !self.agents.values().any(|agent| {
self.owns_store_record(&agent.id)
&& self.agent_is_owned_by_session(agent, active_session_id)
@@ -7108,10 +6858,9 @@ impl SubAgentManager {
let Some((claim, isolated_worktree)) = worker_coordination_claim(spec)? else {
return Ok(());
};
// Isolated-worktree builders mutate their own checkout, not the
// shared workspace, so they must not contend for the per-workspace
// coordination process lock (#5036).
self.ensure_worker_coordination_locks(spec, origin)?;
if !isolated_worktree {
self.refuse_live_selected_store_writers(origin)?;
}
let claim = self.namespace_write_claim(&origin_workspace, isolated_worktree, claim)?;
let scope = if isolated_worktree {
None
@@ -7191,11 +6940,7 @@ impl SubAgentManager {
let previous_origins = self.worker_origins.clone();
let previous_schema = self.worker_origin_schema;
let claim = worker_coordination_claim(&spec)?;
// Same isolation rule as `preflight_worker_coordination` (#5036).
let isolated_worktree = claim
.as_ref()
.is_some_and(|(_, isolated_worktree)| *isolated_worktree);
self.ensure_worker_coordination_locks(&spec, &origin)?;
self.admit_worker_shared_writes(&spec, &origin)?;
let previous_worker_records = self.worker_records.clone();
let previous_coordination = self.coordination.clone();
let persisted_claim = claim
@@ -7247,18 +6992,6 @@ impl SubAgentManager {
let worker_id_for_log = spec.worker_id.clone();
self.register_worker_for_session(spec, &origin.owner_session_id, None);
self.install_worker_origin(&worker_id_for_log, origin);
if isolated_worktree && self.ensure_coordination_process_lock().is_err() {
// This process does not own the durable coordination state and an
// isolated-worktree builder must not be blocked on it: register
// in memory only and leave the durable ledger to the lock owner.
// The persist-layer lock check stays intact (#5036).
tracing::warn!(
target: "subagent",
worker = %worker_id_for_log,
"registered isolated-worktree worker in memory only; delegated coordination lock is owned elsewhere"
);
return Ok(());
}
if let Err(error) = self.persist_state_synchronously() {
self.worker_records = previous_worker_records;
self.coordination = previous_coordination;
@@ -7684,7 +7417,6 @@ impl SubAgentManager {
.map_err(|error| error.to_string());
}
self.ensure_coordination_process_lock()?;
let worker_id = spec.worker_id.clone();
let previous = self
.worker_records
@@ -10327,20 +10059,9 @@ impl SubAgentManager {
));
}
}
if write_capable {
// Isolated-worktree children mutate their own checkout, so they
// do not contend for the shared-workspace process lock (#5036).
if !options.isolated_worktree {
self.ensure_coordination_process_lock()
.map_err(anyhow::Error::msg)?;
self.ensure_origin_writer_lock(&origin)
.map_err(anyhow::Error::msg)?;
}
if self.coordination_process_lock_required && self.state_path.is_none() {
return Err(anyhow!(
"write-capable sub-agent launch requires a durable coordination state path"
));
}
if write_capable && !options.isolated_worktree {
self.refuse_live_selected_store_writers(&origin)
.map_err(anyhow::Error::msg)?;
}
let runtime_origin_turn_id = if runtime.context.runtime.active_thread_id.as_deref()
== Some(runtime.context.state_namespace.as_str())
@@ -10574,7 +10295,9 @@ impl SubAgentManager {
self.resume_targets.insert(source.clone(), agent_id.clone());
}
self.agents.insert(agent_id.clone(), agent);
let persist_result = self.persist_state_synchronously();
let persist_result = self
.admitted_store_authority()
.and_then(|_| self.persist_state_synchronously());
agent = self
.agents
.remove(&agent_id)
@@ -10887,8 +10610,6 @@ impl SubAgentManager {
identity: &ChildActivationIdentity,
) -> Result<impl FnOnce() -> Result<()> + Send + 'static + use<>> {
self.exact_activation(identity)?;
self.ensure_coordination_process_lock()
.map_err(anyhow::Error::msg)?;
let (path, payload) = self
.build_persist_payload()?
.ok_or_else(|| anyhow!("child activation has no durable worker store"))?;
@@ -10913,16 +10634,7 @@ impl SubAgentManager {
.clone()
.ok_or_else(|| anyhow!("child activation has no store authority"))?;
let identity = identity.clone();
let writer_locks = self
.coordination_process_lock
.lock()
.expect("coordination lock slot poisoned")
.iter()
.cloned()
.chain(self.workspace_writer_locks.values().cloned())
.collect::<Vec<_>>();
Ok(move || {
let _writer_locks = writer_locks;
store_authority.publish(&payload, None, None)?;
let persisted = read_durable_subagent_store(&state_root, &path)?.state;
let worker = persisted
@@ -11509,13 +11221,10 @@ impl SubAgentManager {
}
}
// Deliberately NOT here: a pass that terminalized every Running agent
// without a live task handle whenever this process lacked the
// coordination flock (#2.6). Two Codewhale sessions in one workspace is
// ordinary usage, and failure to append to a shared bookkeeping ledger
// is not evidence that live work has stopped. Liveness is decided by
// the heartbeat above — which is actual evidence — never by who owns
// the flock (owner report, 2026-08-04). See `docs/architecture/
// delegated-coordination.md` for what lock loss legitimately costs.
// without a live task handle because another session shares the
// workspace (#2.6). Two Codewhale sessions in one workspace is ordinary
// usage, and liveness is decided by the heartbeat above — which is
// actual evidence (owner report, 2026-08-04).
// The retained lineage owns continuation lookup and descendant
// control. Keep the agents projection while live work references it.
@@ -11645,11 +11354,12 @@ impl SubAgentManager {
}
/// #3803: whether the next sidebar refresh should attempt cleanup.
/// Read-only managers without a process lock only render their refusal.
/// Other managers use the last attempt's interval to bound cleanup locking.
/// A manager whose durable store is not admitted only renders its refusal;
/// admission is retried on the next delegated write. Other managers use the
/// last attempt's interval to bound cleanup locking.
#[must_use]
pub fn cleanup_due(&self, min_interval: Duration) -> bool {
(!self.coordination_snapshot_read_only || self.holds_coordination_process_lock())
(self.state_path.is_none() || self.store_authority.is_some())
&& self
.last_cleanup_at
.is_none_or(|last| last.elapsed() >= min_interval)
@@ -13790,22 +13500,6 @@ fn ensure_subagent_store_cutover(root: &Path, path: &Path) -> Result<()> {
let _ = codewhale_config::private_directory::PrivateDirectory::inspect(&legacy)?;
return Ok(());
}
let _migration = if legacy.is_dir() {
None
} else {
Some(
CoordinationProcessLock::acquire(root, true)
.map_err(|error| anyhow::Error::new(SubAgentCutoverBlocked(error)))?,
)
};
if path.exists() {
read_durable_subagent_store(root, path)?;
anyhow::ensure!(
legacy.is_dir(),
"delegated migration did not retain its legacy-write tombstone"
);
return Ok(());
}
let staging = parent.join("subagents.v1.cutover");
let backup_name = "legacy.json";
let original_name = "original.json";
@@ -13882,6 +13576,20 @@ fn ensure_subagent_store_cutover(root: &Path, path: &Path) -> Result<()> {
write_json_atomic(root, path, &DurableSubAgentStore::from_legacy(state))
}
fn write_state_gitignore(root: &Path, path: &Path) -> Result<()> {
let ignore = checked_subagent_state_path(root, &path.with_file_name(".gitignore"))?;
match fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&ignore)
{
Ok(mut file) => file.write_all(b"*\n")?,
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(error) => return Err(error.into()),
}
Ok(())
}
fn store_writer_is_live(path: &Path, writer: &str) -> bool {
if !valid_store_writer(writer) {
return true;
@@ -13954,6 +13662,9 @@ impl SubAgentStoreAuthority {
let _opening = acquire_store_transaction(root, path)?;
ensure_subagent_store_cutover(root, path)?;
let image = read_durable_subagent_store(root, path)?;
if let Err(error) = write_state_gitignore(root, path) {
tracing::warn!(target: "subagent", %error, "could not ignore the delegated state directory");
}
sync_subagent_store_directory(
path.parent()
.ok_or_else(|| anyhow!("delegated store has no parent"))?,
@@ -14494,24 +14205,16 @@ pub fn new_shared_subagent_manager_with_timeout(
)
}
pub fn new_shared_runtime_subagent_manager(
workspace: PathBuf,
workers: usize,
) -> Result<SharedSubAgentManager> {
new_runtime_subagent_manager(workspace, workers, false)
}
pub fn new_exclusive_runtime_subagent_manager(
workspace: PathBuf,
workers: usize,
) -> Result<SharedSubAgentManager> {
new_runtime_subagent_manager(workspace, workers, true)
new_shared_runtime_subagent_manager(workspace, workers)
}
fn new_runtime_subagent_manager(
pub fn new_shared_runtime_subagent_manager(
workspace: PathBuf,
workers: usize,
exclusive: bool,
) -> Result<SharedSubAgentManager> {
type RuntimeManagerRegistry =
parking_lot::Mutex<HashMap<PathBuf, (usize, std::sync::Weak<RwLock<SubAgentManager>>)>>;
@@ -14536,12 +14239,6 @@ fn new_runtime_subagent_manager(
.with_admission_limit(workers)
.with_launch_concurrency(workers)
.with_state_path(state_path);
manager.coordination_exclusive = exclusive;
manager = manager.require_coordination_process_lock();
if let Err(error) = manager.ensure_coordination_process_lock() {
manager.coordination_snapshot_read_only = true;
tracing::warn!(target: "subagent", %error, "Runtime coordination is read-only; stop and restart this Runtime process after the other session exits to load current state and regain delegated writes");
}
manager.load_state()?;
let manager = Arc::new(RwLock::new(manager));
managers.insert(key, (workers, Arc::downgrade(&manager)));
@@ -14551,7 +14248,7 @@ fn new_runtime_subagent_manager(
/// Create a shared sub-agent manager with an explicit control-plane state root.
///
/// `workspace` remains the child execution and file-authority root. The worker
/// ledger, complete transcript artifacts and coordination lock live under
/// ledger and complete transcript artifacts live under
/// `state_root/.codewhale/state`. Distinct state roots intentionally do not
/// share write claims; an embedding host that runs them against the same
/// workspace must provide any required cross-session write coordination.
@@ -14594,25 +14291,8 @@ pub fn new_shared_subagent_manager_with_state_root_and_timeout(
if let Some(state_path) = state_path {
manager = manager.with_state_path(state_path);
}
manager = if manager.store_cutover_blocked {
manager.into_session_private()
} else {
manager.require_coordination_process_lock()
};
if let Err(error) = manager.ensure_coordination_process_lock() {
tracing::warn!(target: "subagent", %error, "this session cannot append to the shared coordination ledger");
}
// Loading is a read. It was previously gated behind the *write* flock,
// which left a second session in the same workspace blind to every
// decision and write claim already recorded — and holding a default,
// empty ledger that would be written straight over the real one the
// moment the first session exited and the flock became acquirable
// (owner report, 2026-08-04). Read unconditionally; the write gate on
// `persist_state`/`persist_state_synchronously` still checks this
// manager's coordinator admission before publishing.
if let Err(err) = manager.load_state() {
manager.coordination_snapshot_read_only = true;
tracing::warn!(target: "subagent", ?err, "failed to load sub-agent state; durable writes remain refused");
tracing::warn!(target: "subagent", ?err, "failed to load sub-agent state");
}
Arc::new(RwLock::new(manager))
}
@@ -23153,10 +22833,29 @@ mod owner_scoped_coordination_tests {
let mut manager = authority.try_write().unwrap();
admit(&mut manager, &original);
admit(&mut manager, &selected);
let independent =
SubAgentManager::new(selected.clone(), 2).require_coordination_process_lock();
assert!(independent.session_private);
assert!(independent.ensure_coordination_process_lock().is_ok());
let independent = SubAgentManager::new(selected.clone(), 2)
.with_state_path(default_state_path(&selected).unwrap());
assert!(independent.store_authority.is_some());
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let state_directory = default_state_path(&selected)
.unwrap()
.parent()
.unwrap()
.to_path_buf();
let mode = fs::metadata(&state_directory).unwrap().permissions().mode();
fs::set_permissions(&state_directory, fs::Permissions::from_mode(0o000)).unwrap();
let unreadable =
manager.preflight_worker_coordination(&writer("selected", &selected, "src"));
fs::set_permissions(&state_directory, fs::Permissions::from_mode(mode)).unwrap();
assert!(unreadable.is_err(), "an unlistable store must fail closed");
}
let refused = manager
.preflight_worker_coordination(&writer("selected", &selected, "src"))
.unwrap_err();
assert!(refused.contains("another Codewhale session"), "{refused}");
drop(independent);
manager
.preflight_worker_coordination(&writer("original", &original, "src"))
.unwrap();
+236 -272
View File
@@ -1223,21 +1223,18 @@ fn coordination_hot_paths_count_only_active_authoritative_owners() {
}
#[test]
fn runtime_mount_coordination_lock_is_shared_with_parallel_sessions() {
fn runtime_mount_and_parallel_sessions_both_append_durably() {
let tmp = tempdir().expect("tempdir");
let runtime_authority = new_shared_runtime_subagent_manager(tmp.path().to_path_buf(), 8)
.expect("admit TUI runtime writer");
let session =
SubAgentManager::new(tmp.path().to_path_buf(), 8).require_coordination_process_lock();
session
.ensure_coordination_process_lock()
.expect("a second session appends beside the runtime");
assert!(!session.coordination_snapshot_read_only);
let session = SubAgentManager::new(tmp.path().to_path_buf(), 8)
.with_state_path(default_state_path(tmp.path()).expect("state path"));
assert!(session.store_authority.is_some());
session
.persist_state_synchronously()
.expect("session append");
let runtime = runtime_authority.try_write().expect("runtime lock");
assert!(!runtime.coordination_snapshot_read_only);
assert!(runtime.store_authority.is_some());
runtime
.persist_state_synchronously()
.expect("runtime append");
@@ -1363,10 +1360,9 @@ fn headless_worker_registration_enforces_live_claims_and_projects_context() {
.iter()
.any(|record| record.owner_session_id == "owner-worker-c")
);
let independent =
SubAgentManager::new(tmp.path().to_path_buf(), 8).require_coordination_process_lock();
assert!(independent.session_private);
assert!(independent.ensure_coordination_process_lock().is_ok());
let independent = SubAgentManager::new(tmp.path().to_path_buf(), 8)
.with_state_path(default_state_path(tmp.path()).expect("state path"));
assert!(independent.store_authority.is_some());
drop(independent);
drop(authority_a);
drop(authority_b);
@@ -1575,25 +1571,21 @@ fn prior_session_owners_never_count_as_active_coordination_owners() {
}
#[test]
fn isolated_worktree_workers_skip_the_coordination_process_lock() {
fn parallel_sessions_admit_shared_and_isolated_writers_durably() {
let tmp = tempdir().expect("tempdir");
let workspace = tmp.path().canonicalize().expect("canonical workspace");
let state_path = default_state_path(&workspace).expect("state path");
let holder = SubAgentManager::new(workspace.clone(), 4).require_coordination_process_lock();
holder
.ensure_coordination_process_lock()
.expect("holder owns the lock");
let holder = SubAgentManager::new(workspace.clone(), 4).with_state_path(state_path.clone());
assert!(holder.store_authority.is_some());
let mut contender =
SubAgentManager::new(workspace.clone(), 4).require_coordination_process_lock();
contender
.ensure_coordination_process_lock()
.expect("second manager now also owns shared lock (coexistence)");
let mut contender = SubAgentManager::new(workspace.clone(), 4).with_state_path(state_path);
assert!(contender.store_authority.is_some());
let shared = make_write_worker_spec("shared-writer", workspace.clone(), "src/shared");
contender
.preflight_worker_coordination(&shared)
.expect("shared-workspace writer proceeds with shared lock");
.expect("shared-workspace writer proceeds beside another session");
let mut isolated = make_write_worker_spec("isolated-writer", workspace.clone(), "src/iso");
isolated
@@ -1603,69 +1595,64 @@ fn isolated_worktree_workers_skip_the_coordination_process_lock() {
.worktree = true;
contender
.preflight_worker_coordination(&isolated)
.expect("isolated-worktree writer preflights without the lock");
.expect("isolated-worktree writer preflights beside another session");
contender
.register_worker_with_coordination(isolated)
.expect("isolated-worktree writer registers without the lock");
// Once the previous owner exits, a manager that failed earlier must
// acquire the lock on retry instead of replaying a memoized failure.
.expect("isolated-worktree writer registers durably");
drop(holder);
contender
.ensure_coordination_process_lock()
.expect("lock acquisition retries after the holder exits");
contender
.preflight_worker_coordination(&shared)
.expect("shared-workspace writer proceeds once the lock is held");
.expect("shared-workspace writer proceeds after the other session exits");
}
#[test]
fn coordination_detail_projection_reports_process_lock_ownership() {
fn coordination_detail_projection_reports_store_admission_and_its_retry() {
let tmp = tempdir().expect("tempdir");
let workspace = tmp.path().canonicalize().expect("canonical workspace");
let state_path = default_state_path(&workspace).expect("state path");
let holder = SubAgentManager::new(workspace.clone(), 4).require_coordination_process_lock();
holder
.ensure_coordination_process_lock()
.expect("holder owns the lock");
let holder = SubAgentManager::new(workspace.clone(), 4).with_state_path(state_path.clone());
let held = holder.coordination_detail_projection(None, 8);
assert!(
held.process_lock_held,
"holder projection must report lock held"
);
assert!(held.process_lock_held);
assert!(held.process_lock_note.is_none());
let contender = SubAgentManager::new(workspace, 4).require_coordination_process_lock();
let contender = SubAgentManager::new(workspace.clone(), 4).with_state_path(state_path.clone());
let shared = contender.coordination_detail_projection(None, 8);
// With shared locks both holders coexist — contender reports held and no note.
assert!(shared.process_lock_held);
assert!(shared.process_lock_note.is_none());
let committed = std::fs::read(&state_path).expect("committed store");
std::fs::write(&state_path, b"{").expect("corrupt store");
let mut refused = SubAgentManager::new(workspace, 4).with_state_path(state_path.clone());
let projection = refused.coordination_detail_projection(None, 8);
assert!(!projection.process_lock_held);
assert!(projection.process_lock_note.is_some());
assert!(!refused.cleanup_due(Duration::ZERO));
assert!(refused.release_stale_write_claims(None).is_err());
assert!(!refused.cleanup_due(Duration::ZERO));
std::fs::write(&state_path, committed).expect("restore store");
refused
.release_stale_write_claims(None)
.expect("admission is retried once the store is readable");
assert!(
shared.process_lock_held,
"contender projection must report lock held with shared locks"
);
assert!(
shared.process_lock_note.is_none(),
"shared projection carries no note"
refused
.coordination_detail_projection(None, 8)
.process_lock_held
);
assert!(refused.cleanup_due(Duration::ZERO));
}
/// A second Codewhale session in the same workspace is ordinary usage. Losing
/// the coordination flock means "I cannot append to the shared ledger" — it
/// must never mean "my agents are dead". Bookkeeping failure and liveness are
/// separate concerns (owner report, 2026-08-04).
/// A second Codewhale session in the same workspace is ordinary usage and
/// must never mean "my agents are dead". Bookkeeping and liveness are separate
/// concerns (owner report, 2026-08-04).
#[test]
fn a_second_session_without_the_lock_keeps_its_running_agents_live() {
fn a_second_session_keeps_its_running_agents_live() {
let tmp = tempdir().expect("tempdir");
let workspace = tmp.path().canonicalize().expect("canonical workspace");
let holder = SubAgentManager::new(workspace.clone(), 4).require_coordination_process_lock();
holder
.ensure_coordination_process_lock()
.expect("holder owns the lock");
let mut contender = SubAgentManager::new(workspace, 4).require_coordination_process_lock();
contender
.ensure_coordination_process_lock()
.expect("contender now also owns shared lock");
let _first = SubAgentManager::new(workspace.clone(), 4);
let mut contender = SubAgentManager::new(workspace, 4);
let (input_tx, _input_rx) = mpsc::unbounded_channel();
let mut agent = SubAgent::new(
@@ -1680,9 +1667,6 @@ fn a_second_session_without_the_lock_keeps_its_running_agents_live() {
PathBuf::from("."),
contender.session_boot_id().to_string(),
);
// Fresh, well inside the heartbeat window: nothing about this agent is
// stale. The only thing "wrong" with it is that this process cannot write
// the shared ledger.
agent.last_activity_at = Instant::now();
let agent_id = agent.id.clone();
contender.agents.insert(agent_id.clone(), agent);
@@ -1692,7 +1676,7 @@ fn a_second_session_without_the_lock_keeps_its_running_agents_live() {
.expect("durable worker operation");
assert_eq!(
cancelled, 0,
"lock loss alone must not terminalize anything"
"another session alone must not terminalize anything"
);
let snap = contender
.get_result(&agent_id)
@@ -1700,26 +1684,21 @@ fn a_second_session_without_the_lock_keeps_its_running_agents_live() {
assert_eq!(
snap.status,
SubAgentStatus::Running,
"a live agent stays Running when this session cannot write the ledger: {:?}",
"a live agent stays Running beside another session: {:?}",
snap.status
);
}
/// A second session shares the workspace coordination read-lock and must load
/// the existing ledger before it persists any of its own state. That preserves
/// prior decisions instead of replacing them with an empty ledger.
/// A second session must load the existing ledger before it persists any of
/// its own state. That preserves prior decisions instead of replacing them
/// with an empty ledger.
#[test]
fn a_second_session_with_the_shared_lock_loads_the_workspace_ledger() {
fn a_second_session_loads_the_workspace_ledger() {
let tmp = tempdir().expect("tempdir");
let workspace = tmp.path().canonicalize().expect("canonical workspace");
let state_path = default_state_path(&workspace).expect("state path");
let mut first = SubAgentManager::new(workspace.clone(), 4)
.with_state_path(state_path.clone())
.require_coordination_process_lock();
first
.ensure_coordination_process_lock()
.expect("first session owns the lock");
let mut first = SubAgentManager::new(workspace.clone(), 4).with_state_path(state_path.clone());
first
.record_coordination_decision(DecisionRecord {
decision_id: "shared-decision".to_string(),
@@ -1737,20 +1716,15 @@ fn a_second_session_with_the_shared_lock_loads_the_workspace_ledger() {
.persist_state_synchronously()
.expect("first session persists the ledger");
// Second session in the same workspace while the first still holds the
// shared flock. It coexists and must see the workspace ledger.
let second = new_shared_subagent_manager(workspace.clone(), 4);
{
let guard = second.blocking_read();
assert!(
guard.holds_coordination_process_lock(),
"test premise: the second session joins the shared flock"
);
assert!(guard.store_authority.is_some());
let ledger = guard.coordination_snapshot();
assert_eq!(
ledger.decisions.len(),
1,
"second session must load the workspace ledger it cannot write"
"second session must load the workspace ledger"
);
assert_eq!(ledger.decisions[0].decision_id, "shared-decision");
}
@@ -1759,12 +1733,9 @@ fn a_second_session_with_the_shared_lock_loads_the_workspace_ledger() {
drop(first);
{
let guard = second.blocking_write();
guard
.ensure_coordination_process_lock()
.expect("shared lock remains available after the first session exits");
guard
.persist_state_synchronously()
.expect("second session persists once it owns the lock");
.expect("second session persists after the first exits");
}
let mut replayed = SubAgentManager::new(workspace, 4).with_state_path(state_path);
replayed.load_state().expect("reload the workspace ledger");
@@ -1776,23 +1747,15 @@ fn a_second_session_with_the_shared_lock_loads_the_workspace_ledger() {
}
/// The complement of the test above: an orphan still terminalizes, but only on
/// heartbeat evidence. Lock ownership is not part of the decision either way.
/// heartbeat evidence. Another session is not part of the decision either way.
#[test]
fn cleanup_terminalizes_orphans_on_heartbeat_evidence_not_on_lock_ownership() {
fn cleanup_terminalizes_orphans_on_heartbeat_evidence_not_on_other_sessions() {
let tmp = tempdir().expect("tempdir");
let workspace = tmp.path().canonicalize().expect("canonical workspace");
let holder = SubAgentManager::new(workspace.clone(), 4).require_coordination_process_lock();
holder
.ensure_coordination_process_lock()
.expect("holder owns the lock");
let mut contender = SubAgentManager::new(workspace, 4)
.with_running_heartbeat_timeout(Duration::from_secs(30))
.require_coordination_process_lock();
contender
.ensure_coordination_process_lock()
.expect("contender now also owns shared lock");
let _first = SubAgentManager::new(workspace.clone(), 4);
let mut contender =
SubAgentManager::new(workspace, 4).with_running_heartbeat_timeout(Duration::from_secs(30));
let insert_orphan = |manager: &mut SubAgentManager, name: &str, idle: Duration| {
let (input_tx, _input_rx) = mpsc::unbounded_channel();
@@ -1832,7 +1795,7 @@ fn cleanup_terminalizes_orphans_on_heartbeat_evidence_not_on_lock_ownership() {
.expect("fresh orphan still listed")
.status,
SubAgentStatus::Running,
"a fresh orphan is not terminalized just because the flock is elsewhere"
"a fresh orphan is not terminalized just because another session is open"
);
assert!(
matches!(
@@ -11351,7 +11314,7 @@ async fn write_capable_agent_does_not_launch_when_durable_registration_fails() {
.expect_err("writer must fail before spawn when its durable claim cannot commit")
.to_string();
assert!(
error.contains("durably register") || error.contains("writer lock"),
error.contains("durably register") || error.contains("store admission failed"),
"{error}"
);
@@ -12230,7 +12193,10 @@ fn persist_state_rejects_state_path_outside_state_root() {
.persist_state()
.expect_err("outside state path should fail");
assert!(format!("{err:#}").contains("without its writer lock"));
assert!(
format!("{err:#}").contains("must stay within state root"),
"{err:#}"
);
}
/// A user who keeps application state on another volume makes the workspace's
@@ -12405,9 +12371,7 @@ fn explicit_state_roots_isolate_managers_for_the_same_execution_workspace() {
let mut manager = manager.try_write().expect("manager write lock");
assert_eq!(manager.workspace.as_path(), workspace.as_path());
assert_eq!(manager.state_root.as_path(), expected_root.as_path());
manager
.ensure_coordination_process_lock()
.expect("independent state-root coordination lock");
assert!(manager.store_authority.is_some());
manager.register_worker(make_worker_spec(worker_id, workspace.clone()));
manager
.persist_state_synchronously()
@@ -12462,31 +12426,21 @@ fn persist_state_rejects_symlinked_state_directory() {
);
}
/// A linked `.codewhale` must be refused before anything is created: the
/// coordination lock used to `create_dir_all` through the link first.
#[cfg(unix)]
#[test]
fn coordination_lock_refuses_linked_codewhale_without_writing_through_it() {
fn a_linked_codewhale_admission_writes_no_gitignore_through_it() {
let tmp = tempdir().expect("tempdir");
let workspace = tmp.path().join("workspace");
let outside = tmp.path().join("outside");
let root = tmp.path().canonicalize().expect("canonical root");
let workspace = root.join("workspace");
let outside = root.join("outside");
std::fs::create_dir_all(&workspace).expect("mkdir workspace");
std::fs::create_dir_all(&outside).expect("mkdir outside");
std::os::unix::fs::symlink(&outside, workspace.join(".codewhale")).expect("link .codewhale");
let Err(err) = CoordinationProcessLock::acquire(&workspace, false) else {
panic!("a linked .codewhale must be refused");
};
let message = format!("{err:#}");
let manager = new_shared_subagent_manager(workspace, 4);
assert!(manager.blocking_read().store_authority.is_none());
assert!(
message.contains("must not traverse symlinks")
|| message.contains("must stay within state root"),
"{message}"
);
assert_eq!(
std::fs::read_dir(&outside).expect("read outside").count(),
0,
"nothing may be created through the link"
!outside.join("state").join(".gitignore").exists(),
"a refused admission writes no .gitignore through the link"
);
}
@@ -20874,24 +20828,66 @@ fn write_json_atomic_survives_concurrent_writers() {
assert!(leftover.is_empty(), "temp files leaked: {leftover:?}");
}
fn two_process_decision(id: &str) -> DecisionRecord {
DecisionRecord {
decision_id: id.to_string(),
subject: id.to_string(),
status: DecisionStatus::Accepted,
owner: "root".to_string(),
scope: vec!["src".to_string()],
constraints: Vec::new(),
evidence_handles: Vec::new(),
version: 1,
sequence: 0,
}
}
fn wait_for_two_process_file(path: &Path, child: &mut std::process::Child, what: &str) {
let deadline = Instant::now() + Duration::from_secs(30);
while !path.exists() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
if !path.exists() {
let _ = child.kill();
panic!("{what} never became ready");
}
}
#[test]
fn coordination_process_lock_rejects_second_process() {
const ROLE_ENV: &str = "CODEWHALE_TEST_COORDINATION_LOCK_ROLE";
const WORKSPACE_ENV: &str = "CODEWHALE_TEST_COORDINATION_LOCK_WORKSPACE";
fn a_stale_session_never_makes_a_new_session_read_only() {
const ROLE_ENV: &str = "CODEWHALE_TEST_COORDINATION_ROLE";
const WORKSPACE_ENV: &str = "CODEWHALE_TEST_COORDINATION_WORKSPACE";
const TEST_NAME: &str =
"tools::subagent::tests::coordination_process_lock_rejects_second_process";
"tools::subagent::tests::a_stale_session_never_makes_a_new_session_read_only";
if let Some(role) = std::env::var_os(ROLE_ENV) {
let workspace = PathBuf::from(std::env::var_os(WORKSPACE_ENV).expect("workspace env"));
if role == "legacy-holder" {
let _legacy_session = CoordinationProcessLock::acquire(&workspace, false)
.expect("an older session holds the shared lock");
std::fs::write(workspace.join("holder.ready"), b"ready").unwrap();
let deadline = Instant::now() + Duration::from_secs(10);
let wait_for_release = || {
let deadline = Instant::now() + Duration::from_secs(60);
while !workspace.join("holder.release").exists() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
assert!(workspace.join("holder.release").exists(), "release timeout");
};
if role == "legacy-holder" {
let lock_file = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.open(
workspace
.join(".codewhale")
.join("state")
.join("subagents.v1.lock"),
)
.expect("open legacy lock");
let legacy = fd_lock::RwLock::new(lock_file);
let _guard = legacy
.try_read()
.expect("an older session holds the legacy lock");
std::fs::write(workspace.join("holder.ready"), b"ready").unwrap();
wait_for_release();
return;
}
let manager = new_shared_subagent_manager_with_timeout(
@@ -20901,78 +20897,82 @@ fn coordination_process_lock_rejects_second_process() {
Duration::from_secs(30),
4,
);
let mut guard = manager.try_write().unwrap();
assert!(guard.store_authority.is_some(), "{role:?} store admitted");
assert!(
guard
.coordination_detail_projection(None, 8)
.process_lock_held
);
let name = role.to_string_lossy().into_owned();
guard
.record_coordination_decision(two_process_decision(&format!("{name}-decision")))
.expect("record a decision beside the other session");
guard.register_worker(make_worker_spec(
&format!("{name}-worker"),
workspace.clone(),
));
guard
.persist_state_synchronously()
.expect("publish beside the other session");
if role == "holder" {
manager
.try_read()
.unwrap()
.ensure_coordination_process_lock()
.expect("holder owns lock");
std::fs::write(workspace.join("holder.ready"), b"ready").unwrap();
let deadline = Instant::now() + Duration::from_secs(10);
while !workspace.join("holder.release").exists() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
assert!(workspace.join("holder.release").exists(), "release timeout");
wait_for_release();
} else {
manager
.try_read()
.unwrap()
.ensure_coordination_process_lock()
.expect("second process now also succeeds with shared lock");
assert!(
guard
.coordination_snapshot()
.decisions
.iter()
.any(|decision| decision.decision_id == "holder-decision"),
"the new session merges the open session's ledger"
);
}
return;
}
let dir = tempdir().expect("tempdir");
let workspace = dir.path().canonicalize().expect("canonical workspace");
let test_binary = std::env::current_exe().expect("test binary");
let mut holder = std::process::Command::new(&test_binary)
.arg("--exact")
.arg(TEST_NAME)
.arg("--nocapture")
.env(ROLE_ENV, "holder")
.env(WORKSPACE_ENV, &workspace)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("spawn lock holder");
let deadline = Instant::now() + Duration::from_secs(5);
while !workspace.join("holder.ready").exists() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
if !workspace.join("holder.ready").exists() {
let _ = holder.kill();
let output = holder.wait_with_output().expect("holder output");
panic!(
"holder never acquired lock:\nstdout:\n{}\nstderr:\n{}",
let spawn = |role: &str, workspace: &Path| {
std::process::Command::new(&test_binary)
.arg("--exact")
.arg(TEST_NAME)
.arg("--nocapture")
.env(ROLE_ENV, role)
.env(WORKSPACE_ENV, workspace)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("spawn session process")
};
let finish = |child: std::process::Child, what: &str| {
let output = child.wait_with_output().expect("session output");
assert!(
output.status.success(),
"{what} failed:\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
let contender = std::process::Command::new(&test_binary)
.arg("--exact")
.arg(TEST_NAME)
.arg("--nocapture")
.env(ROLE_ENV, "contender")
.env(WORKSPACE_ENV, &workspace)
.output()
.expect("spawn lock contender");
assert!(
contender.status.success(),
"contender failed:\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&contender.stdout),
String::from_utf8_lossy(&contender.stderr)
);
};
let dir = tempdir().expect("tempdir");
let workspace = dir.path().canonicalize().expect("canonical workspace");
let mut holder = spawn("holder", &workspace);
wait_for_two_process_file(&workspace.join("holder.ready"), &mut holder, "open session");
finish(spawn("contender", &workspace), "new session");
std::fs::write(workspace.join("holder.release"), b"release").unwrap();
let output = holder.wait_with_output().expect("holder output");
assert!(
output.status.success(),
"holder failed:\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
finish(holder, "open session");
let workers = load_persisted_agent_worker_records_with_state_root(&workspace, &workspace)
.expect("read merged store");
for id in ["holder-worker", "contender-worker"] {
assert!(
workers.iter().any(|record| record.spec.worker_id == id),
"{id} survives the other session's publication"
);
}
let mut replayed = SubAgentManager::new(workspace.clone(), 4)
.with_state_path(default_state_path(&workspace).unwrap());
replayed.load_state().expect("reload merged ledger");
assert_eq!(replayed.coordination.decisions.len(), 2);
let legacy_dir = tempdir().expect("tempdir");
let legacy_workspace = legacy_dir
@@ -20988,75 +20988,42 @@ fn coordination_process_lock_rejects_second_process() {
)
.unwrap();
let legacy_bytes = std::fs::read(&legacy_file).unwrap();
let mut legacy_holder = std::process::Command::new(&test_binary)
.arg("--exact")
.arg(TEST_NAME)
.arg("--nocapture")
.env(ROLE_ENV, "legacy-holder")
.env(WORKSPACE_ENV, &legacy_workspace)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("spawn legacy lock holder");
let deadline = Instant::now() + Duration::from_secs(5);
while !legacy_workspace.join("holder.ready").exists() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
if !legacy_workspace.join("holder.ready").exists() {
let _ = legacy_holder.kill();
let output = legacy_holder
.wait_with_output()
.expect("legacy holder output");
panic!(
"legacy holder never acquired lock:\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
let private = new_shared_subagent_manager(legacy_workspace.clone(), 4);
let mut legacy_holder = spawn("legacy-holder", &legacy_workspace);
wait_for_two_process_file(
&legacy_workspace.join("holder.ready"),
&mut legacy_holder,
"older session",
);
let upgraded = new_shared_subagent_manager(legacy_workspace.clone(), 4);
{
let guard = private.blocking_read();
let mut guard = upgraded.blocking_write();
assert!(
guard.ensure_coordination_process_lock().is_ok(),
"a session beside an older one keeps working sub-agents"
guard.store_authority.is_some(),
"a stale older session must not leave the new one read-only"
);
let projection = guard.coordination_detail_projection(None, 8);
assert!(!projection.process_lock_held);
assert!(
projection
.process_lock_note
.as_deref()
.is_some_and(|note| note.starts_with(SESSION_PRIVATE_COORDINATION)),
projection.process_lock_held,
"{:?}",
projection.process_lock_note
);
assert!(projection.process_lock_note.is_none());
guard
.record_coordination_decision(two_process_decision("upgraded-decision"))
.expect("the new session writes while the older one is still open");
assert!(guard.cleanup_due(Duration::from_secs(3600)));
}
assert_eq!(
std::fs::read(&legacy_file).unwrap(),
legacy_bytes,
"the older session's store stays untouched"
);
assert!(
!state_dir.join(SUBAGENT_STATE_FILE).exists(),
"no forced cutover while the older session runs"
);
std::fs::write(legacy_workspace.join("holder.release"), b"release").unwrap();
let output = legacy_holder
.wait_with_output()
.expect("legacy holder output");
assert!(
output.status.success(),
"legacy holder failed:\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
let upgraded = new_shared_subagent_manager(legacy_workspace, 4);
assert!(
state_dir.join(SUBAGENT_STATE_FILE).exists() && legacy_file.is_dir(),
"the next session upgrades the store once the older one exits"
"the store upgrades without waiting for the older session to exit"
);
assert!(upgraded.blocking_read().holds_coordination_process_lock());
drop(private);
assert_eq!(
std::fs::read(legacy_file.join("legacy.json")).unwrap(),
legacy_bytes,
"the older store is retained byte for byte"
);
std::fs::write(legacy_workspace.join("holder.release"), b"release").unwrap();
finish(legacy_holder, "older session");
}
// === agent(action="wait") + peek throttling (#4097) ===
@@ -24171,35 +24138,32 @@ fn validate_resume_from_source(
}
/// Owner report 2026-08-04: a model/provider switch spawns the new engine's
/// manager while the old engine still holds the workspace coordination flock
/// in this same process. That losing acquisition must classify itself as a
/// same-process handover (not "another Codewhale process"), and must
/// self-heal via the projection retry once the previous owner drops.
/// manager while the old engine's manager is still open in this same process.
/// Both stay admitted, and the new one keeps writing after the old one drops.
#[test]
fn coordination_lock_loss_to_own_process_reads_as_handover_and_self_heals() {
fn a_same_process_engine_handover_keeps_both_managers_admitted() {
let tmp = tempdir().expect("tempdir");
let state_path = default_state_path(tmp.path()).expect("state path");
let first =
SubAgentManager::new(tmp.path().to_path_buf(), 1).require_coordination_process_lock();
SubAgentManager::new(tmp.path().to_path_buf(), 1).with_state_path(state_path.clone());
let second = SubAgentManager::new(tmp.path().to_path_buf(), 1).with_state_path(state_path);
assert!(
first.holds_coordination_process_lock(),
"first manager must own the flock"
first
.coordination_detail_projection(None, 8)
.process_lock_held
);
let second =
SubAgentManager::new(tmp.path().to_path_buf(), 1).require_coordination_process_lock();
assert!(
second.holds_coordination_process_lock(),
"second manager now also holds shared flock (coexistence)"
second
.coordination_detail_projection(None, 8)
.process_lock_held
);
let note = second.coordination_process_lock_status();
assert!(note.is_ok(), "shared lock should not error: {note:?}");
first
.persist_state_synchronously()
.expect("old engine publishes");
drop(first);
assert!(
second.coordination_process_lock_status().is_ok(),
"retry must acquire once the previous engine dropped the flock"
);
assert!(second.holds_coordination_process_lock());
second
.persist_state_synchronously()
.expect("new engine publishes after the old one drops");
}
// -- resume-from-checkpoint tests (checkpoint-based continuation) --
+1 -14
View File
@@ -21,7 +21,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Plugin index (Runtime API):** a new `GET /v1/apps/plugin-index` route lists plugins, skills, connectors, hooks and hand-written commands with kind, source and state, and `/v1/commands` rows say which plugin (`plugin_id`) added a command and whether a command came from the project (`workspace_sourced`) (CW-8092).
- **Model commands and routing:** `codewhale model list` now lists every custom endpoint you have configured, under its own name. `codewhale model resolve` no longer refuses a model on a custom endpoint, router or local server whose model list has not been fetched yet; once a list is fetched, a model missing from it is still refused. Automatic routing marks a context window as verified only when the route itself supplies it, and no longer reports a guessed output limit.
- **ACP:** when a plugin tool asks the core to run a tool that needs approval, the editor now gets a `session/request_permission` on the plugin tool's call that names the nested tool and its input; before, the prompt ended with an internal error (CW-8050).
- **Website maintainer and cron secrets:** the manual cron trigger is rate limited, admin sign-in and the cron secret require a 32 to 512 character secret with at least 8 distinct characters that is not a repeated pattern, and changing the maintainer token signs out existing admin sessions.
- **README and contributor credit:** the repository front page now opens the way the website does: the line "The model can be anyone's. The agent should be yours.", one sentence on what Codewhale is, the install command and one picture, with reference detail moved into the linked guides; the 18 translated READMEs follow the same structure and say they are machine-drafted. The contributor wall and the website now count the same 433 people (407 GitHub accounts and the commit authors whose email is not linked to an account), where the website had counted accounts only. `DEPENDENCY_SECURITY.md` moved into `docs/dependency-maintenance.md`, and `.github/SUPPORT.md` says where to ask for help.
- **Website Plugins page:** The website's Plugins page now describes what the released version does, and a labelled section says what 0.10.3 adds: one Plugins place, Standard and Creator mode, and the Permissions control.
- **First-time guide on the website:** a new docs page, "Use Codewhale for the first time" (`/docs/first-time`, English and Simplified Chinese), walks someone who has never used a terminal through opening one, installing, choosing the folder Codewhale works in and when that choice matters, opening a terminal in a folder from Finder or File Explorer, connecting a model, a first task, and stopping, undoing and quitting. The install page gains a short "New to the terminal?" block for macOS and Windows that links to it, and `llms.txt` carries the same steps.
@@ -685,7 +684,7 @@ work is declared complete here. Items moved to 0.10.4 by name are marked below.
- **Windows uninstall removes the receipt and update leftovers.** The installer's uninstaller also deletes `.codewhale-install.sha256` and `codewhale.old-*`/`codew.old-*` left by a self-update, so `bin` can be removed. Refs #7091.
- **Windows `/undo` matches recorded file paths regardless of case.** A write recorded under a different drive-letter or directory case, or a `\\?\` prefix, is no longer dropped from the restore plan. Refs #6970.
- **Windows: Fleet and metrics read live files again.** Replaying a Fleet ledger and reading audit or receipt records no longer fail with a sharing violation while their writer is still open; the same regular-file, link and identity checks apply. Plugin enablement now says which snapshot check refused (stage root, content identity or final check) instead of one generic message. Generated protocol and SDK exports keep LF line endings in Windows checkouts.
- **A held coordination lock no longer makes a new session read-only.** When another session owns the delegated-agent store, the new session starts on private state and says so, instead of refusing every sub-agent with “Failed to clean up sub-agents”.
- **Sessions in one folder no longer leave each other's sub-agents read-only or private:** a second session works beside another one, stale or suspended included, the older sub-agent store upgrades right away, and a store that cannot be opened is retried on the next sub-agent change instead of needing a restart. While another Codewhale session, a suspended one included, is open in a folder the desktop app or `serve` was asked to work in (other than the folder it started in), that Runtime still refuses sub-agents that would edit the folder directly; isolated worktrees are unaffected. A sub-agent store that cannot be opened shows its refusal once instead of repeating cleanup warnings on every sidebar refresh. Restart any session started with Codewhale 0.10.2 or older: once the folder upgrades it can no longer save sub-agent state (Refs #7232).
- **A dev server can outlive the turn in an interactive session.** `persist:true` now works in the TUI and desktop when the thread has Full Access; restricted postures and Fleet/sub-agents still refuse it.
- **`codewhale exec --add-dir <path>`** (repeatable) and `addDirs` on `POST /v1/threads` let the file tools read and write a sibling directory, a second checkout or a shared scratch root without turning on Full Access.
- **Unsettled usage is persisted in production, not only in tests.** The interactive sink now records a legacy usage receipt when a provider response has no settlement, so children and turns stop reporting settlement failure.
@@ -722,12 +721,6 @@ work is declared complete here. Items moved to 0.10.4 by name are marked below.
composer. Real Pinyin input on macOS and Windows is not yet confirmed.
Thanks [@cmdcorp6534](https://github.com/cmdcorp6534) for the report
(Refs #2323).
- **Sub-agents beside an older session:** while a Codewhale 0.10.2 session
still uses a folder's older delegated-agent store, a 0.10.3 session in the
same folder keeps working sub-agents with private state that is not saved,
instead of refusing every sub-agent action. The older session's files are
left untouched, and the store upgrades when a session starts after the older
one exits (Refs #7232).
- **Fleet members:** a replayed member start now matches only within its own
session, so two sessions that reuse an operation key no longer receive each
other's agent.
@@ -756,12 +749,6 @@ work is declared complete here. Items moved to 0.10.4 by name are marked below.
bare self-package exports resolve inside the selected package directory.
Invalid or incompatible ranges and paths outside the reviewed package still
refuse. Real published-plugin activation remains unqualified.
- **Coordination lock diagnostics (#7232):** stale lock-file contents no longer
identify an owner PID. A refused legacy admission keeps its reason in Work
and shows one notice per cause instead of repeating cleanup warnings on
every sidebar refresh. Legacy migration still requires the actual holder to
exit and the refused owning Runtime to restart; locks and retained state
remain protected.
- **A local proxy that stops mid-session no longer strands the session (#7231):** the model, catalog, search, vision, finance, MCP-registry, profile and remote-control clients watch a loopback proxy port and go direct while it refuses connections, then resume proxying when it returns. Only a definite refusal from every resolved address changes the route; remote proxies, `NO_PROXY` matches, credentials and the existing precedence are unchanged. Set `CODEWHALE_LOCAL_PROXY_FALLBACK=0` to keep the old build-time snapshot.
- **Proxy diagnostic privacy ([#7233](https://github.com/codewhale-hq/codewhale/issues/7233)):** malformed MCP proxy warnings omit configured values; local-proxy log labels mask userinfo and omit URL paths, queries and fragments. Routing is unchanged. All 23 existing proxy tests passed on macOS; runtime log capture and other platforms remain unqualified. Thanks [@SparkofSpike](https://github.com/SparkofSpike) for the report.
- **Fork, undo and retry work after a workspace drift notice (#7234):** the history-boundary walks now treat a whole `<context_update>` envelope as engine-owned, so a session that received one can be cut at every saved turn. A person quoting a notice or a truncated envelope still counts as their own prompt.
@@ -24,4 +24,4 @@
{"engine_session_id":"conformance-session","event":"session_updated","instruction_assembly":{"budgets":{"claude_fallback":false,"file_max_bytes":8388608,"global_tokens":100000,"policy":"trim","project_tokens":100000,"static_guard_tokens":667571,"usable_window_tokens":834464},"constitution_source_path":null,"constitution_tokens":0,"global_tokens":0,"notices":[{"action":"Kept","bytes_dropped":0,"bytes_kept":498,"detail":null,"fallback_selected":null,"limit":"None","origin":"Instructions","path":null,"scope":"Project","tokens_dropped":0,"tokens_kept":166}],"project_tokens":166,"retained_block_tokens":188,"source_path":null,"warnings":[]},"messages":[{"content":[{"text":"Create denied.txt with touch.","type":"text"},{"text":"<turn_meta>\nCurrent local date: <today>\nCurrent workspace: <WORKSPACE>\nCurrent permission posture: Ask\nCurrent sandbox posture: workspace-write (writes inside the workspace; network blocked) (local OS sandbox applied)\nEstimated conversation input: 1973 / 1000000 context tokens (0.2%). Automatic compaction is enabled.\n## Repo Working Set\nKey files: README.md\nWhen in doubt, use tools to verify and keep changes focused on the working set.\n</turn_meta>","type":"text"}],"role":"user"},{"content":[{"text":"<codewhale:runtime_event kind=\"project_instructions\" visibility=\"internal\">\n<system-reminder>\nThe following workspace instructions may be relevant to your work. Use them as guidance when applicable. More specific instructions take precedence over broader ones. They do not override system, developer, or direct user instructions. Instructions from: AGENTS.md\n\n<project_instructions source=\"project\">\n# Project Context (Auto-generated, ephemeral)\n\n> This context was generated in memory by Codewhale.\n> No .codewhale/instructions.md file was written.\n\n## Bounded Project Overview\n\n```json\n{\n \"project_name\": \"workspace\",\n \"directory_structure\": [\n \"README.md\"\n ],\n \"readme\": {\n \"path\": \"README.md\",\n \"excerpt\": \"conformance fixture\"\n },\n \"config_files\": [],\n \"key_source_files\": [],\n \"counts\": {\n \"config_files\": 0,\n \"directory_entries\": 1,\n \"key_source_files\": 0\n }\n}\n```\n</project_instructions>\n</system-reminder>\n</codewhale:runtime_event>","type":"text"},{"text":"<turn_meta>\nInput provenance: runtime (non-authoritative)\n</turn_meta>","type":"text"}],"role":"user"},{"content":[{"execution_id":"<uuid:2>","id":"call_touch","input":{"command":"touch denied.txt"},"name":"Bash","type":"tool_use"}],"role":"assistant"},{"content":[{"content":"Error: Tool 'Bash' denied by user — the call was not approved. Do not retry the same call; present what you intended and wait for the user's approval or new instructions.","execution_id":"<uuid:2>","is_error":true,"tool_use_id":"call_touch","type":"tool_result"}],"role":"user"},{"content":[{"text":"Understood, I did not create it.","type":"text"}],"role":"assistant"}],"model":"deepseek-v4-pro","system_prompt":"<pinned by the prompt family>","workspace":"<WORKSPACE>"}
{"event":"tool_request_snapshot","snapshot":{"active_tool_catalog_sha256":"9017c53ee026ae4065bed3e4b2e7d773a828556b42d6ebe2c2ebfd8e65377280","capture_source":"prepared model-client request","delivery_status":"unknown (capture does not prove provider delivery)","omitted_tool_count":0,"payload_json_bytes":17394,"payload_measurement_status":"exact (within 1048576-byte measurement bound)","provider":{"model":"deepseek-v4-pro","provider":"Deepseek","status":"available"},"registry_facts_present":true,"registry_only_tools":{"status":"known","value":{"count":40,"omitted":8,"rendered":[{"truncated":false,"value":"Git"},{"truncated":false,"value":"Run"},{"truncated":false,"value":"Web"},{"truncated":false,"value":"apply_patch"},{"truncated":false,"value":"automation"},{"truncated":false,"value":"context_archive_get"},{"truncated":false,"value":"context_archive_search"},{"truncated":false,"value":"diagnostics"},{"truncated":false,"value":"finance"},{"truncated":false,"value":"github"},{"truncated":false,"value":"handle_read"},{"truncated":false,"value":"harness"},{"truncated":false,"value":"image_ocr"},{"truncated":false,"value":"list_dir"},{"truncated":false,"value":"lsp"},{"truncated":false,"value":"note"},{"truncated":false,"value":"notify"},{"truncated":false,"value":"pandoc_convert"},{"truncated":false,"value":"project_map"},{"truncated":false,"value":"registry_sync"},{"truncated":false,"value":"request_plugin_install"},{"truncated":false,"value":"request_user_input"},{"truncated":false,"value":"retrieve_tool_result"},{"truncated":false,"value":"revert_turn"},{"truncated":false,"value":"review"},{"truncated":false,"value":"send_later"},{"truncated":false,"value":"session_get"},{"truncated":false,"value":"session_search"},{"truncated":false,"value":"start_mcp_server"},{"truncated":false,"value":"start_registry_mcp_server"},{"truncated":false,"value":"tasks"},{"truncated":false,"value":"terminal/cancel"}]}},"registry_tool_count":{"status":"known","value":65},"rendered_tool_count":15,"schema_version":1,"step":1,"terminal":{"automatic_compaction_attempts":0,"effective_max_steps":null,"emergency_compaction_attempts":0,"empty_stop_retries":0,"final_report_requested":false,"last_prepared_output_limit_tokens":65536,"last_provider_finish_reason":{"truncated":false,"value":"end_turn"},"last_reported_input_tokens":200,"last_response_tool_calls":0,"last_response_tool_calls_suppressed":0,"model_requests_started":2,"model_step_index":1,"permission_denial_rounds_without_progress":0,"permission_strategy_switches":0,"reason":"provider_no_tool_call","reasoning_only_reprompts":0,"route_context_window_tokens":1000000,"status":"completed","step_budget_source":"max_steps","stream_resumes":0,"transparent_stream_retries":0,"transport_retries":0},"tool_count":15,"tools":[{"allowed_callers":{"status":"known","value":{"count":1,"omitted":0,"rendered":[{"truncated":false,"value":"direct"}]}},"approval":{"status":"known","value":{"truncated":false,"value":"Required"}},"cache_control_type":{"reason":"request field absent","status":"unknown"},"capabilities":{"status":"known","value":{"count":3,"omitted":0,"rendered":[{"truncated":false,"value":"ExecutesCode"},{"truncated":false,"value":"Sandboxable"},{"truncated":false,"value":"RequiresApproval"}]}},"defer_loading":{"status":"known","value":false},"description":{"truncated":true,"value":"Execute a shell command in the workspace and return stdout and stderr (last 2000 lines or 50KB). Optional timeout is foreground seconds (default 30 seconds); a command still running then moves to the background by itself — never killed for time — returning output so far, last-output age, build phase, and a task_id. Call task_shell_wait with that task_id to read more or wait; do not sleep-poll with bash. Before a final answer, collect every still-relevant background task (wait only when genuinely blocked) an"},"input_examples":{"reason":"request field absent","status":"unknown"},"input_schema_json":{"truncated":false,"value":"{\"additionalProperties\":false,\"properties\":{\"command\":{\"description\":\"The command to execute. Actual execution shell: `/bin/bash`. Use Bash syntax: pipelines, redirections, $(command), and && / || are supported. Quote paths and variable expansions, such as \\\"$path\\\"; use single quotes for literal text. For literal multiline input, use a quoted heredoc delimiter (<<'EOF') with its closing delimiter on a separate line. Use only installed programs; do not assume GNU-specific flags on macOS/BSD. Example: printf '%s\\\\n' 'sample'.\",\"type\":\"string\"},\"description\":{\"description\":\"Optional few-word summary shown to the user beside the command.\",\"type\":\"string\"},\"justification\":{\"description\":\"Required with sandbox_permissions: one sentence explaining why this exact command needs wider access.\",\"type\":\"string\"},\"read_only\":{\"description\":\"Set true to run analysis code (including Python/SQLite) or a network fetch (curl) with mandatory native filesysteLine truncated
{"event":"turn_complete","parent_route_usage":{"input_tokens":350,"output_tokens":21},"routed_usage_dropped_records":0,"status":"completed","tool_catalog":"<pinned by the prompt family>","turn_id":"<uuid:1>","usage":{"input_tokens":350,"output_tokens":21}}
{"harness_summary":{"model_requests":2,"non_streaming_requests":0,"workspace_after":{".codewhale/state/.gitignore":"cdbcae15105d6b78",".codewhale/state/subagents.v1.json/legacy.json":"9064f16acf90984c",".codewhale/state/subagents.v1.lock":"e3b0c44298fc1c14",".codewhale/state/subagents.v3.json":"e874da2951e53d2b",".codewhale/state/subagents.v3.transaction.lock":"e3b0c44298fc1c14","README.md":"41f49bffb38de5ba"}}}
{"harness_summary":{"model_requests":2,"non_streaming_requests":0,"workspace_after":{".codewhale/state/.gitignore":"cdbcae15105d6b78",".codewhale/state/subagents.v1.json/legacy.json":"9064f16acf90984c",".codewhale/state/subagents.v3.json":"e874da2951e53d2b",".codewhale/state/subagents.v3.transaction.lock":"e3b0c44298fc1c14","README.md":"41f49bffb38de5ba"}}}
@@ -15,4 +15,4 @@
{"event":"tool_request_snapshot","snapshot":{"active_tool_catalog_sha256":"9017c53ee026ae4065bed3e4b2e7d773a828556b42d6ebe2c2ebfd8e65377280","capture_source":"prepared model-client request","delivery_status":"unknown (capture does not prove provider delivery)","omitted_tool_count":0,"payload_json_bytes":17394,"payload_measurement_status":"exact (within 1048576-byte measurement bound)","provider":{"model":"deepseek-v4-pro","provider":"Deepseek","status":"available"},"registry_facts_present":true,"registry_only_tools":{"status":"known","value":{"count":40,"omitted":8,"rendered":[{"truncated":false,"value":"Git"},{"truncated":false,"value":"Run"},{"truncated":false,"value":"Web"},{"truncated":false,"value":"apply_patch"},{"truncated":false,"value":"automation"},{"truncated":false,"value":"context_archive_get"},{"truncated":false,"value":"context_archive_search"},{"truncated":false,"value":"diagnostics"},{"truncated":false,"value":"finance"},{"truncated":false,"value":"github"},{"truncated":false,"value":"handle_read"},{"truncated":false,"value":"harness"},{"truncated":false,"value":"image_ocr"},{"truncated":false,"value":"list_dir"},{"truncated":false,"value":"lsp"},{"truncated":false,"value":"note"},{"truncated":false,"value":"notify"},{"truncated":false,"value":"pandoc_convert"},{"truncated":false,"value":"project_map"},{"truncated":false,"value":"registry_sync"},{"truncated":false,"value":"request_plugin_install"},{"truncated":false,"value":"request_user_input"},{"truncated":false,"value":"retrieve_tool_result"},{"truncated":false,"value":"revert_turn"},{"truncated":false,"value":"review"},{"truncated":false,"value":"send_later"},{"truncated":false,"value":"session_get"},{"truncated":false,"value":"session_search"},{"truncated":false,"value":"start_mcp_server"},{"truncated":false,"value":"start_registry_mcp_server"},{"truncated":false,"value":"tasks"},{"truncated":false,"value":"terminal/cancel"}]}},"registry_tool_count":{"status":"known","value":65},"rendered_tool_count":15,"schema_version":1,"step":0,"terminal":{"automatic_compaction_attempts":0,"effective_max_steps":null,"emergency_compaction_attempts":0,"empty_stop_retries":0,"final_report_requested":false,"last_prepared_output_limit_tokens":65536,"last_provider_finish_reason":null,"last_reported_input_tokens":120,"last_response_tool_calls":0,"last_response_tool_calls_suppressed":null,"model_requests_started":1,"model_step_index":0,"permission_denial_rounds_without_progress":0,"permission_strategy_switches":0,"reason":"interrupted","reasoning_only_reprompts":0,"route_context_window_tokens":1000000,"status":"interrupted","step_budget_source":"max_steps","stream_resumes":0,"transparent_stream_retries":0,"transport_retries":0},"tool_count":15,"tools":[{"allowed_callers":{"status":"known","value":{"count":1,"omitted":0,"rendered":[{"truncated":false,"value":"direct"}]}},"approval":{"status":"known","value":{"truncated":false,"value":"Required"}},"cache_control_type":{"reason":"request field absent","status":"unknown"},"capabilities":{"status":"known","value":{"count":3,"omitted":0,"rendered":[{"truncated":false,"value":"ExecutesCode"},{"truncated":false,"value":"Sandboxable"},{"truncated":false,"value":"RequiresApproval"}]}},"defer_loading":{"status":"known","value":false},"description":{"truncated":true,"value":"Execute a shell command in the workspace and return stdout and stderr (last 2000 lines or 50KB). Optional timeout is foreground seconds (default 30 seconds); a command still running then moves to the background by itself — never killed for time — returning output so far, last-output age, build phase, and a task_id. Call task_shell_wait with that task_id to read more or wait; do not sleep-poll with bash. Before a final answer, collect every still-relevant background task (wait only when genuinely blocked) an"},"input_examples":{"reason":"request field absent","status":"unknown"},"input_schema_json":{"truncated":false,"value":"{\"additionalProperties\":false,\"properties\":{\"command\":{\"description\":\"The command to execute. Actual execution shell: `/bin/bash`. Use Bash syntax: pipelines, redirections, $(command), and && / || are supported. Quote paths and variable expansions, such as \\\"$path\\\"; use single quotes for literal text. For literal multiline input, use a quoted heredoc delimiter (<<'EOF') with its closing delimiter on a separate line. Use only installed programs; do not assume GNU-specific flags on macOS/BSD. Example: printf '%s\\\\n' 'sample'.\",\"type\":\"string\"},\"description\":{\"description\":\"Optional few-word summary shown to the user beside the command.\",\"type\":\"string\"},\"justification\":{\"description\":\"Required with sandbox_permissions: one sentence explaining why this exact command needs wider access.\",\"type\":\"string\"},\"read_only\":{\"description\":\"Set true to run analysis code (including Python/SQLite) or a network fetch (curl) with mandatory native filesystem read-only isolation. Outbound networkLine truncated
{"event":"turn_complete","parent_route_usage":{"input_tokens":120,"output_tokens":0},"routed_usage_dropped_records":0,"status":"interrupted","tool_catalog":"<pinned by the prompt family>","turn_id":"<uuid:1>","usage":{"input_tokens":120,"output_tokens":0}}
{"event":"status","message":"Turn interrupted."}
{"harness_summary":{"model_requests":1,"non_streaming_requests":0,"workspace_after":{".codewhale/state/.gitignore":"cdbcae15105d6b78",".codewhale/state/subagents.v1.json/legacy.json":"9064f16acf90984c",".codewhale/state/subagents.v1.lock":"e3b0c44298fc1c14",".codewhale/state/subagents.v3.json":"e874da2951e53d2b",".codewhale/state/subagents.v3.transaction.lock":"e3b0c44298fc1c14","NOTES.md":"f957b19529906961","README.md":"41f49bffb38de5ba"}}}
{"harness_summary":{"model_requests":1,"non_streaming_requests":0,"workspace_after":{".codewhale/state/.gitignore":"cdbcae15105d6b78",".codewhale/state/subagents.v1.json/legacy.json":"9064f16acf90984c",".codewhale/state/subagents.v3.json":"e874da2951e53d2b",".codewhale/state/subagents.v3.transaction.lock":"e3b0c44298fc1c14","NOTES.md":"f957b19529906961","README.md":"41f49bffb38de5ba"}}}
@@ -25,4 +25,4 @@
{"engine_session_id":"conformance-session","event":"session_updated","instruction_assembly":{"budgets":{"claude_fallback":false,"file_max_bytes":8388608,"global_tokens":100000,"policy":"trim","project_tokens":100000,"static_guard_tokens":667571,"usable_window_tokens":834464},"constitution_source_path":null,"constitution_tokens":0,"global_tokens":0,"notices":[{"action":"Kept","bytes_dropped":0,"bytes_kept":514,"detail":null,"fallback_selected":null,"limit":"None","origin":"Instructions","path":null,"scope":"Project","tokens_dropped":0,"tokens_kept":172}],"project_tokens":172,"retained_block_tokens":193,"source_path":null,"warnings":[]},"messages":[{"content":[{"text":"What does README.md say?","type":"text"},{"text":"<turn_meta>\nCurrent local date: <today>\nCurrent workspace: <WORKSPACE>\nCurrent permission posture: Ask\nCurrent sandbox posture: workspace-write (writes inside the workspace; network blocked) (local OS sandbox applied)\nEstimated conversation input: 1972 / 1000000 context tokens (0.2%). Automatic compaction is enabled.\n## Repo Working Set\nKey files: README.md\nActive paths (prioritize these):\n- README.md (file)\nWhen in doubt, use tools to verify and keep changes focused on the working set.\n</turn_meta>","type":"text"}],"role":"user"},{"content":[{"text":"<codewhale:runtime_event kind=\"project_instructions\" visibility=\"internal\">\n<system-reminder>\nThe following workspace instructions may be relevant to your work. Use them as guidance when applicable. More specific instructions take precedence over broader ones. They do not override system, developer, or direct user instructions. Instructions from: AGENTS.md\n\n<project_instructions source=\"project\">\n# Project Context (Auto-generated, ephemeral)\n\n> This context was generated in memory by Codewhale.\n> No .codewhale/instructions.md file was written.\n\n## Bounded Project Overview\n\n```json\n{\n \"project_name\": \"workspace\",\n \"directory_structure\": [\n \"README.md\",\n \"NOTES.md\"\n ],\n \"readme\": {\n \"path\": \"README.md\",\n \"excerpt\": \"conformance fixture\"\n },\n \"config_files\": [],\n \"key_source_files\": [],\n \"counts\": {\n \"config_files\": 0,\n \"directory_entries\": 2,\n \"key_source_files\": 0\n }\n}\n```\n</project_instructions>\n</system-reminder>\n</codewhale:runtime_event>","type":"text"},{"text":"<turn_meta>\nInput provenance: runtime (non-authoritative)\n</turn_meta>","type":"text"}],"role":"user"},{"content":[{"execution_id":"<uuid:2>","id":"call_read_readme","input":{"action":"read","path":"README.md"},"name":"File","type":"tool_use"}],"role":"assistant"},{"content":[{"content":"content_hash=\"sha256:41f49bffb38de5ba88945f09121ffc590f9d7f6ff80fdb9ea8ad10224fecea61\"\nconformance fixture","execution_id":"<uuid:2>","tool_use_id":"call_read_readme","type":"tool_result"}],"role":"user"},{"content":[{"text":"It says: conformance fixture.","type":"text"}],"role":"assistant"}],"model":"deepseek-v4-pro","system_prompt":"<pinned by the prompt family>","workspace":"<WORKSPACE>"}
{"event":"tool_request_snapshot","snapshot":{"active_tool_catalog_sha256":"9017c53ee026ae4065bed3e4b2e7d773a828556b42d6ebe2c2ebfd8e65377280","capture_source":"prepared model-client request","delivery_status":"unknown (capture does not prove provider delivery)","omitted_tool_count":0,"payload_json_bytes":17394,"payload_measurement_status":"exact (within 1048576-byte measurement bound)","provider":{"model":"deepseek-v4-pro","provider":"Deepseek","status":"available"},"registry_facts_present":true,"registry_only_tools":{"status":"known","value":{"count":40,"omitted":8,"rendered":[{"truncated":false,"value":"Git"},{"truncated":false,"value":"Run"},{"truncated":false,"value":"Web"},{"truncated":false,"value":"apply_patch"},{"truncated":false,"value":"automation"},{"truncated":false,"value":"context_archive_get"},{"truncated":false,"value":"context_archive_search"},{"truncated":false,"value":"diagnostics"},{"truncated":false,"value":"finance"},{"truncated":false,"value":"github"},{"truncated":false,"value":"handle_read"},{"truncated":false,"value":"harness"},{"truncated":false,"value":"image_ocr"},{"truncated":false,"value":"list_dir"},{"truncated":false,"value":"lsp"},{"truncated":false,"value":"note"},{"truncated":false,"value":"notify"},{"truncated":false,"value":"pandoc_convert"},{"truncated":false,"value":"project_map"},{"truncated":false,"value":"registry_sync"},{"truncated":false,"value":"request_plugin_install"},{"truncated":false,"value":"request_user_input"},{"truncated":false,"value":"retrieve_tool_result"},{"truncated":false,"value":"revert_turn"},{"truncated":false,"value":"review"},{"truncated":false,"value":"send_later"},{"truncated":false,"value":"session_get"},{"truncated":false,"value":"session_search"},{"truncated":false,"value":"start_mcp_server"},{"truncated":false,"value":"start_registry_mcp_server"},{"truncated":false,"value":"tasks"},{"truncated":false,"value":"terminal/cancel"}]}},"registry_tool_count":{"status":"known","value":65},"rendered_tool_count":15,"schema_version":1,"step":1,"terminal":{"automatic_compaction_attempts":0,"effective_max_steps":null,"emergency_compaction_attempts":0,"empty_stop_retries":0,"final_report_requested":false,"last_prepared_output_limit_tokens":65536,"last_provider_finish_reason":{"truncated":false,"value":"end_turn"},"last_reported_input_tokens":200,"last_response_tool_calls":0,"last_response_tool_calls_suppressed":0,"model_requests_started":2,"model_step_index":1,"permission_denial_rounds_without_progress":0,"permission_strategy_switches":0,"reason":"provider_no_tool_call","reasoning_only_reprompts":0,"route_context_window_tokens":1000000,"status":"completed","step_budget_source":"max_steps","stream_resumes":0,"transparent_stream_retries":0,"transport_retries":0},"tool_count":15,"tools":[{"allowed_callers":{"status":"known","value":{"count":1,"omitted":0,"rendered":[{"truncated":false,"value":"direct"}]}},"approval":{"status":"known","value":{"truncated":false,"value":"Required"}},"cache_control_type":{"reason":"request field absent","status":"unknown"},"capabilities":{"status":"known","value":{"count":3,"omitted":0,"rendered":[{"truncated":false,"value":"ExecutesCode"},{"truncated":false,"value":"Sandboxable"},{"truncated":false,"value":"RequiresApproval"}]}},"defer_loading":{"status":"known","value":false},"description":{"truncated":true,"value":"Execute a shell command in the workspace and return stdout and stderr (last 2000 lines or 50KB). Optional timeout is foreground seconds (default 30 seconds); a command still running then moves to the background by itself — never killed for time — returning output so far, last-output age, build phase, and a task_id. Call task_shell_wait with that task_id to read more or wait; do not sleep-poll with bash. Before a final answer, collect every still-relevant background task (wait only when genuinely blocked) an"},"input_examples":{"reason":"request field absent","status":"unknown"},"input_schema_json":{"truncated":false,"value":"{\"additionalProperties\":false,\"properties\":{\"command\":{\"description\":\"The command to execute. Actual execution shell: `/bin/bash`. Use Bash syntax: pipelines, redirections, $(command), and && / || are supported. Quote paths and variable expansions, such as \\\"$path\\\"; use single quotes for literal text. For literal multiline input, use a quoted heredoc delimiter (<<'EOF') with its closing delimiter on a separate line. Use only installed programs; do not assume GNU-specific flags on macOS/BSD. Example: printf '%s\\\\n' 'sample'.\",\"type\":\"string\"},\"description\":{\"description\":\"Optional few-word summary shown to the user beside the command.\",\"type\":\"string\"},\"justification\":{\"description\":\"Required with sandbox_permissions: one sentence explaining why this exact command needs wider access.\",\"type\":\"string\"},\"read_only\":{\"description\":\"Set true to run analysis code (including Python/SQLite) or a network fetch (curl) with mandatory native filesysteLine truncated
{"event":"turn_complete","parent_route_usage":{"input_tokens":350,"output_tokens":26},"routed_usage_dropped_records":0,"status":"completed","tool_catalog":"<pinned by the prompt family>","turn_id":"<uuid:1>","usage":{"input_tokens":350,"output_tokens":26}}
{"harness_summary":{"model_requests":2,"non_streaming_requests":0,"workspace_after":{".codewhale/state/.gitignore":"cdbcae15105d6b78",".codewhale/state/subagents.v1.json/legacy.json":"9064f16acf90984c",".codewhale/state/subagents.v1.lock":"e3b0c44298fc1c14",".codewhale/state/subagents.v3.json":"e874da2951e53d2b",".codewhale/state/subagents.v3.transaction.lock":"e3b0c44298fc1c14","NOTES.md":"f957b19529906961","README.md":"41f49bffb38de5ba"}}}
{"harness_summary":{"model_requests":2,"non_streaming_requests":0,"workspace_after":{".codewhale/state/.gitignore":"cdbcae15105d6b78",".codewhale/state/subagents.v1.json/legacy.json":"9064f16acf90984c",".codewhale/state/subagents.v3.json":"e874da2951e53d2b",".codewhale/state/subagents.v3.transaction.lock":"e3b0c44298fc1c14","NOTES.md":"f957b19529906961","README.md":"41f49bffb38de5ba"}}}
@@ -31,4 +31,4 @@
{"engine_session_id":"conformance-session","event":"session_updated","instruction_assembly":{"budgets":{"claude_fallback":false,"file_max_bytes":8388608,"global_tokens":100000,"policy":"trim","project_tokens":100000,"static_guard_tokens":667571,"usable_window_tokens":834464},"constitution_source_path":null,"constitution_tokens":0,"global_tokens":0,"notices":[{"action":"Kept","bytes_dropped":0,"bytes_kept":514,"detail":null,"fallback_selected":null,"limit":"None","origin":"Instructions","path":null,"scope":"Project","tokens_dropped":0,"tokens_kept":172}],"project_tokens":172,"retained_block_tokens":193,"source_path":null,"warnings":[]},"messages":[{"content":[{"text":"Read README.md and NOTES.md.","type":"text"},{"text":"<turn_meta>\nCurrent local date: <today>\nCurrent workspace: <WORKSPACE>\nCurrent permission posture: Ask\nCurrent sandbox posture: workspace-write (writes inside the workspace; network blocked) (local OS sandbox applied)\nEstimated conversation input: 1973 / 1000000 context tokens (0.2%). Automatic compaction is enabled.\n## Repo Working Set\nKey files: README.md\nActive paths (prioritize these):\n- NOTES.md (file)\n- README.md (file)\nWhen in doubt, use tools to verify and keep changes focused on the working set.\n</turn_meta>","type":"text"}],"role":"user"},{"content":[{"text":"<codewhale:runtime_event kind=\"project_instructions\" visibility=\"internal\">\n<system-reminder>\nThe following workspace instructions may be relevant to your work. Use them as guidance when applicable. More specific instructions take precedence over broader ones. They do not override system, developer, or direct user instructions. Instructions from: AGENTS.md\n\n<project_instructions source=\"project\">\n# Project Context (Auto-generated, ephemeral)\n\n> This context was generated in memory by Codewhale.\n> No .codewhale/instructions.md file was written.\n\n## Bounded Project Overview\n\n```json\n{\n \"project_name\": \"workspace\",\n \"directory_structure\": [\n \"README.md\",\n \"NOTES.md\"\n ],\n \"readme\": {\n \"path\": \"README.md\",\n \"excerpt\": \"conformance fixture\"\n },\n \"config_files\": [],\n \"key_source_files\": [],\n \"counts\": {\n \"config_files\": 0,\n \"directory_entries\": 2,\n \"key_source_files\": 0\n }\n}\n```\n</project_instructions>\n</system-reminder>\n</codewhale:runtime_event>","type":"text"},{"text":"<turn_meta>\nInput provenance: runtime (non-authoritative)\n</turn_meta>","type":"text"}],"role":"user"},{"content":[{"execution_id":"<uuid:2>","id":"call_read_a","input":{"action":"read","path":"README.md"},"name":"File","type":"tool_use"},{"execution_id":"<uuid:3>","id":"call_read_b","input":{"action":"read","path":"NOTES.md"},"name":"File","type":"tool_use"}],"role":"assistant"},{"content":[{"content":"content_hash=\"sha256:41f49bffb38de5ba88945f09121ffc590f9d7f6ff80fdb9ea8ad10224fecea61\"\nconformance fixture","execution_id":"<uuid:2>","tool_use_id":"call_read_a","type":"tool_result"}],"role":"user"},{"content":[{"content":"content_hash=\"sha256:f957b19529906961933c5c30f8713c500a9bb5d9d0695c40d48c97a26a3594ec\"\nsecond file","execution_id":"<uuid:3>","tool_use_id":"call_read_b","type":"tool_result"}],"role":"user"},{"content":[{"text":"Both files read.","type":"text"}],"role":"assistant"}],"model":"deepseek-v4-pro","system_prompt":"<pinned by the prompt family>","workspace":"<WORKSPACE>"}
{"event":"tool_request_snapshot","snapshot":{"active_tool_catalog_sha256":"9017c53ee026ae4065bed3e4b2e7d773a828556b42d6ebe2c2ebfd8e65377280","capture_source":"prepared model-client request","delivery_status":"unknown (capture does not prove provider delivery)","omitted_tool_count":0,"payload_json_bytes":17394,"payload_measurement_status":"exact (within 1048576-byte measurement bound)","provider":{"model":"deepseek-v4-pro","provider":"Deepseek","status":"available"},"registry_facts_present":true,"registry_only_tools":{"status":"known","value":{"count":40,"omitted":8,"rendered":[{"truncated":false,"value":"Git"},{"truncated":false,"value":"Run"},{"truncated":false,"value":"Web"},{"truncated":false,"value":"apply_patch"},{"truncated":false,"value":"automation"},{"truncated":false,"value":"context_archive_get"},{"truncated":false,"value":"context_archive_search"},{"truncated":false,"value":"diagnostics"},{"truncated":false,"value":"finance"},{"truncated":false,"value":"github"},{"truncated":false,"value":"handle_read"},{"truncated":false,"value":"harness"},{"truncated":false,"value":"image_ocr"},{"truncated":false,"value":"list_dir"},{"truncated":false,"value":"lsp"},{"truncated":false,"value":"note"},{"truncated":false,"value":"notify"},{"truncated":false,"value":"pandoc_convert"},{"truncated":false,"value":"project_map"},{"truncated":false,"value":"registry_sync"},{"truncated":false,"value":"request_plugin_install"},{"truncated":false,"value":"request_user_input"},{"truncated":false,"value":"retrieve_tool_result"},{"truncated":false,"value":"revert_turn"},{"truncated":false,"value":"review"},{"truncated":false,"value":"send_later"},{"truncated":false,"value":"session_get"},{"truncated":false,"value":"session_search"},{"truncated":false,"value":"start_mcp_server"},{"truncated":false,"value":"start_registry_mcp_server"},{"truncated":false,"value":"tasks"},{"truncated":false,"value":"terminal/cancel"}]}},"registry_tool_count":{"status":"known","value":65},"rendered_tool_count":15,"schema_version":1,"step":1,"terminal":{"automatic_compaction_attempts":0,"effective_max_steps":null,"emergency_compaction_attempts":0,"empty_stop_retries":0,"final_report_requested":false,"last_prepared_output_limit_tokens":65536,"last_provider_finish_reason":{"truncated":false,"value":"end_turn"},"last_reported_input_tokens":200,"last_response_tool_calls":0,"last_response_tool_calls_suppressed":0,"model_requests_started":2,"model_step_index":1,"permission_denial_rounds_without_progress":0,"permission_strategy_switches":0,"reason":"provider_no_tool_call","reasoning_only_reprompts":0,"route_context_window_tokens":1000000,"status":"completed","step_budget_source":"max_steps","stream_resumes":0,"transparent_stream_retries":0,"transport_retries":0},"tool_count":15,"tools":[{"allowed_callers":{"status":"known","value":{"count":1,"omitted":0,"rendered":[{"truncated":false,"value":"direct"}]}},"approval":{"status":"known","value":{"truncated":false,"value":"Required"}},"cache_control_type":{"reason":"request field absent","status":"unknown"},"capabilities":{"status":"known","value":{"count":3,"omitted":0,"rendered":[{"truncated":false,"value":"ExecutesCode"},{"truncated":false,"value":"Sandboxable"},{"truncated":false,"value":"RequiresApproval"}]}},"defer_loading":{"status":"known","value":false},"description":{"truncated":true,"value":"Execute a shell command in the workspace and return stdout and stderr (last 2000 lines or 50KB). Optional timeout is foreground seconds (default 30 seconds); a command still running then moves to the background by itself — never killed for time — returning output so far, last-output age, build phase, and a task_id. Call task_shell_wait with that task_id to read more or wait; do not sleep-poll with bash. Before a final answer, collect every still-relevant background task (wait only when genuinely blocked) an"},"input_examples":{"reason":"request field absent","status":"unknown"},"input_schema_json":{"truncated":false,"value":"{\"additionalProperties\":false,\"properties\":{\"command\":{\"description\":\"The command to execute. Actual execution shell: `/bin/bash`. Use Bash syntax: pipelines, redirections, $(command), and && / || are supported. Quote paths and variable expansions, such as \\\"$path\\\"; use single quotes for literal text. For literal multiline input, use a quoted heredoc delimiter (<<'EOF') with its closing delimiter on a separate line. Use only installed programs; do not assume GNU-specific flags on macOS/BSD. Example: printf '%s\\\\n' 'sample'.\",\"type\":\"string\"},\"description\":{\"description\":\"Optional few-word summary shown to the user beside the command.\",\"type\":\"string\"},\"justification\":{\"description\":\"Required with sandbox_permissions: one sentence explaining why this exact command needs wider access.\",\"type\":\"string\"},\"read_only\":{\"description\":\"Set true to run analysis code (including Python/SQLite) or a network fetch (curl) with mandatory native filesysteLine truncated
{"event":"turn_complete","parent_route_usage":{"input_tokens":360,"output_tokens":46},"routed_usage_dropped_records":0,"status":"completed","tool_catalog":"<pinned by the prompt family>","turn_id":"<uuid:1>","usage":{"input_tokens":360,"output_tokens":46}}
{"harness_summary":{"model_requests":2,"non_streaming_requests":0,"workspace_after":{".codewhale/state/.gitignore":"cdbcae15105d6b78",".codewhale/state/subagents.v1.json/legacy.json":"9064f16acf90984c",".codewhale/state/subagents.v1.lock":"e3b0c44298fc1c14",".codewhale/state/subagents.v3.json":"e874da2951e53d2b",".codewhale/state/subagents.v3.transaction.lock":"e3b0c44298fc1c14","NOTES.md":"f957b19529906961","README.md":"41f49bffb38de5ba"}}}
{"harness_summary":{"model_requests":2,"non_streaming_requests":0,"workspace_after":{".codewhale/state/.gitignore":"cdbcae15105d6b78",".codewhale/state/subagents.v1.json/legacy.json":"9064f16acf90984c",".codewhale/state/subagents.v3.json":"e874da2951e53d2b",".codewhale/state/subagents.v3.transaction.lock":"e3b0c44298fc1c14","NOTES.md":"f957b19529906961","README.md":"41f49bffb38de5ba"}}}
@@ -15,4 +15,4 @@
{"engine_session_id":"conformance-session","event":"session_updated","instruction_assembly":{"budgets":{"claude_fallback":false,"file_max_bytes":8388608,"global_tokens":100000,"policy":"trim","project_tokens":100000,"static_guard_tokens":667571,"usable_window_tokens":834464},"constitution_source_path":null,"constitution_tokens":0,"global_tokens":0,"notices":[{"action":"Kept","bytes_dropped":0,"bytes_kept":514,"detail":null,"fallback_selected":null,"limit":"None","origin":"Instructions","path":null,"scope":"Project","tokens_dropped":0,"tokens_kept":172}],"project_tokens":172,"retained_block_tokens":193,"source_path":null,"warnings":[]},"messages":[{"content":[{"text":"Say hello.","type":"text"},{"text":"<turn_meta>\nCurrent local date: <today>\nCurrent workspace: <WORKSPACE>\nCurrent permission posture: Ask\nCurrent sandbox posture: workspace-write (writes inside the workspace; network blocked) (local OS sandbox applied)\nEstimated conversation input: 1968 / 1000000 context tokens (0.2%). Automatic compaction is enabled.\n## Repo Working Set\nKey files: README.md\nWhen in doubt, use tools to verify and keep changes focused on the working set.\n</turn_meta>","type":"text"}],"role":"user"},{"content":[{"text":"<codewhale:runtime_event kind=\"project_instructions\" visibility=\"internal\">\n<system-reminder>\nThe following workspace instructions may be relevant to your work. Use them as guidance when applicable. More specific instructions take precedence over broader ones. They do not override system, developer, or direct user instructions. Instructions from: AGENTS.md\n\n<project_instructions source=\"project\">\n# Project Context (Auto-generated, ephemeral)\n\n> This context was generated in memory by Codewhale.\n> No .codewhale/instructions.md file was written.\n\n## Bounded Project Overview\n\n```json\n{\n \"project_name\": \"workspace\",\n \"directory_structure\": [\n \"README.md\",\n \"NOTES.md\"\n ],\n \"readme\": {\n \"path\": \"README.md\",\n \"excerpt\": \"conformance fixture\"\n },\n \"config_files\": [],\n \"key_source_files\": [],\n \"counts\": {\n \"config_files\": 0,\n \"directory_entries\": 2,\n \"key_source_files\": 0\n }\n}\n```\n</project_instructions>\n</system-reminder>\n</codewhale:runtime_event>","type":"text"},{"text":"<turn_meta>\nInput provenance: runtime (non-authoritative)\n</turn_meta>","type":"text"}],"role":"user"},{"content":[{"text":"Hello there.","type":"text"}],"role":"assistant"}],"model":"deepseek-v4-pro","system_prompt":"<pinned by the prompt family>","workspace":"<WORKSPACE>"}
{"event":"tool_request_snapshot","snapshot":{"active_tool_catalog_sha256":"9017c53ee026ae4065bed3e4b2e7d773a828556b42d6ebe2c2ebfd8e65377280","capture_source":"prepared model-client request","delivery_status":"unknown (capture does not prove provider delivery)","omitted_tool_count":0,"payload_json_bytes":17394,"payload_measurement_status":"exact (within 1048576-byte measurement bound)","provider":{"model":"deepseek-v4-pro","provider":"Deepseek","status":"available"},"registry_facts_present":true,"registry_only_tools":{"status":"known","value":{"count":40,"omitted":8,"rendered":[{"truncated":false,"value":"Git"},{"truncated":false,"value":"Run"},{"truncated":false,"value":"Web"},{"truncated":false,"value":"apply_patch"},{"truncated":false,"value":"automation"},{"truncated":false,"value":"context_archive_get"},{"truncated":false,"value":"context_archive_search"},{"truncated":false,"value":"diagnostics"},{"truncated":false,"value":"finance"},{"truncated":false,"value":"github"},{"truncated":false,"value":"handle_read"},{"truncated":false,"value":"harness"},{"truncated":false,"value":"image_ocr"},{"truncated":false,"value":"list_dir"},{"truncated":false,"value":"lsp"},{"truncated":false,"value":"note"},{"truncated":false,"value":"notify"},{"truncated":false,"value":"pandoc_convert"},{"truncated":false,"value":"project_map"},{"truncated":false,"value":"registry_sync"},{"truncated":false,"value":"request_plugin_install"},{"truncated":false,"value":"request_user_input"},{"truncated":false,"value":"retrieve_tool_result"},{"truncated":false,"value":"revert_turn"},{"truncated":false,"value":"review"},{"truncated":false,"value":"send_later"},{"truncated":false,"value":"session_get"},{"truncated":false,"value":"session_search"},{"truncated":false,"value":"start_mcp_server"},{"truncated":false,"value":"start_registry_mcp_server"},{"truncated":false,"value":"tasks"},{"truncated":false,"value":"terminal/cancel"}]}},"registry_tool_count":{"status":"known","value":65},"rendered_tool_count":15,"schema_version":1,"step":0,"terminal":{"automatic_compaction_attempts":0,"effective_max_steps":null,"emergency_compaction_attempts":0,"empty_stop_retries":0,"final_report_requested":false,"last_prepared_output_limit_tokens":65536,"last_provider_finish_reason":{"truncated":false,"value":"end_turn"},"last_reported_input_tokens":120,"last_response_tool_calls":0,"last_response_tool_calls_suppressed":0,"model_requests_started":1,"model_step_index":0,"permission_denial_rounds_without_progress":0,"permission_strategy_switches":0,"reason":"provider_no_tool_call","reasoning_only_reprompts":0,"route_context_window_tokens":1000000,"status":"completed","step_budget_source":"max_steps","stream_resumes":0,"transparent_stream_retries":0,"transport_retries":0},"tool_count":15,"tools":[{"allowed_callers":{"status":"known","value":{"count":1,"omitted":0,"rendered":[{"truncated":false,"value":"direct"}]}},"approval":{"status":"known","value":{"truncated":false,"value":"Required"}},"cache_control_type":{"reason":"request field absent","status":"unknown"},"capabilities":{"status":"known","value":{"count":3,"omitted":0,"rendered":[{"truncated":false,"value":"ExecutesCode"},{"truncated":false,"value":"Sandboxable"},{"truncated":false,"value":"RequiresApproval"}]}},"defer_loading":{"status":"known","value":false},"description":{"truncated":true,"value":"Execute a shell command in the workspace and return stdout and stderr (last 2000 lines or 50KB). Optional timeout is foreground seconds (default 30 seconds); a command still running then moves to the background by itself — never killed for time — returning output so far, last-output age, build phase, and a task_id. Call task_shell_wait with that task_id to read more or wait; do not sleep-poll with bash. Before a final answer, collect every still-relevant background task (wait only when genuinely blocked) an"},"input_examples":{"reason":"request field absent","status":"unknown"},"input_schema_json":{"truncated":false,"value":"{\"additionalProperties\":false,\"properties\":{\"command\":{\"description\":\"The command to execute. Actual execution shell: `/bin/bash`. Use Bash syntax: pipelines, redirections, $(command), and && / || are supported. Quote paths and variable expansions, such as \\\"$path\\\"; use single quotes for literal text. For literal multiline input, use a quoted heredoc delimiter (<<'EOF') with its closing delimiter on a separate line. Use only installed programs; do not assume GNU-specific flags on macOS/BSD. Example: printf '%s\\\\n' 'sample'.\",\"type\":\"string\"},\"description\":{\"description\":\"Optional few-word summary shown to the user beside the command.\",\"type\":\"string\"},\"justification\":{\"description\":\"Required with sandbox_permissions: one sentence explaining why this exact command needs wider access.\",\"type\":\"string\"},\"read_only\":{\"description\":\"Set true to run analysis code (including Python/SQLite) or a network fetch (curl) with mandatory native filesysteLine truncated
{"event":"turn_complete","parent_route_usage":{"input_tokens":120,"output_tokens":4},"routed_usage_dropped_records":0,"status":"completed","tool_catalog":"<pinned by the prompt family>","turn_id":"<uuid:1>","usage":{"input_tokens":120,"output_tokens":4}}
{"harness_summary":{"model_requests":1,"non_streaming_requests":0,"workspace_after":{".codewhale/state/.gitignore":"cdbcae15105d6b78",".codewhale/state/subagents.v1.json/legacy.json":"9064f16acf90984c",".codewhale/state/subagents.v1.lock":"e3b0c44298fc1c14",".codewhale/state/subagents.v3.json":"e874da2951e53d2b",".codewhale/state/subagents.v3.transaction.lock":"e3b0c44298fc1c14","NOTES.md":"f957b19529906961","README.md":"41f49bffb38de5ba"}}}
{"harness_summary":{"model_requests":1,"non_streaming_requests":0,"workspace_after":{".codewhale/state/.gitignore":"cdbcae15105d6b78",".codewhale/state/subagents.v1.json/legacy.json":"9064f16acf90984c",".codewhale/state/subagents.v3.json":"e874da2951e53d2b",".codewhale/state/subagents.v3.transaction.lock":"e3b0c44298fc1c14","NOTES.md":"f957b19529906961","README.md":"41f49bffb38de5ba"}}}
@@ -13,4 +13,4 @@
{"event":"tool_call_complete","result":{"content":"Not executed: the provider stream failed before the model response completed (Model not exist.).","metadata":{"error_category":"model_stream_failed","model_output_incomplete":true,"side_effect_status":"not_started"},"outcome":"ok","success":false},"tool_call_id":"<uuid:2>","tool_name":"File"}
{"event":"tool_request_snapshot","snapshot":{"active_tool_catalog_sha256":"9017c53ee026ae4065bed3e4b2e7d773a828556b42d6ebe2c2ebfd8e65377280","capture_source":"prepared model-client request","delivery_status":"unknown (capture does not prove provider delivery)","omitted_tool_count":0,"payload_json_bytes":17394,"payload_measurement_status":"exact (within 1048576-byte measurement bound)","provider":{"model":"deepseek-v4-pro","provider":"Deepseek","status":"available"},"registry_facts_present":true,"registry_only_tools":{"status":"known","value":{"count":40,"omitted":8,"rendered":[{"truncated":false,"value":"Git"},{"truncated":false,"value":"Run"},{"truncated":false,"value":"Web"},{"truncated":false,"value":"apply_patch"},{"truncated":false,"value":"automation"},{"truncated":false,"value":"context_archive_get"},{"truncated":false,"value":"context_archive_search"},{"truncated":false,"value":"diagnostics"},{"truncated":false,"value":"finance"},{"truncated":false,"value":"github"},{"truncated":false,"value":"handle_read"},{"truncated":false,"value":"harness"},{"truncated":false,"value":"image_ocr"},{"truncated":false,"value":"list_dir"},{"truncated":false,"value":"lsp"},{"truncated":false,"value":"note"},{"truncated":false,"value":"notify"},{"truncated":false,"value":"pandoc_convert"},{"truncated":false,"value":"project_map"},{"truncated":false,"value":"registry_sync"},{"truncated":false,"value":"request_plugin_install"},{"truncated":false,"value":"request_user_input"},{"truncated":false,"value":"retrieve_tool_result"},{"truncated":false,"value":"revert_turn"},{"truncated":false,"value":"review"},{"truncated":false,"value":"send_later"},{"truncated":false,"value":"session_get"},{"truncated":false,"value":"session_search"},{"truncated":false,"value":"start_mcp_server"},{"truncated":false,"value":"start_registry_mcp_server"},{"truncated":false,"value":"tasks"},{"truncated":false,"value":"terminal/cancel"}]}},"registry_tool_count":{"status":"known","value":65},"rendered_tool_count":15,"schema_version":1,"step":0,"terminal":{"automatic_compaction_attempts":0,"effective_max_steps":null,"emergency_compaction_attempts":0,"empty_stop_retries":0,"final_report_requested":false,"last_prepared_output_limit_tokens":65536,"last_provider_finish_reason":null,"last_reported_input_tokens":120,"last_response_tool_calls":1,"last_response_tool_calls_suppressed":1,"model_requests_started":1,"model_step_index":0,"permission_denial_rounds_without_progress":0,"permission_strategy_switches":0,"reason":"failed","reasoning_only_reprompts":0,"route_context_window_tokens":1000000,"status":"failed","step_budget_source":"max_steps","stream_resumes":0,"transparent_stream_retries":0,"transport_retries":0},"tool_count":15,"tools":[{"allowed_callers":{"status":"known","value":{"count":1,"omitted":0,"rendered":[{"truncated":false,"value":"direct"}]}},"approval":{"status":"known","value":{"truncated":false,"value":"Required"}},"cache_control_type":{"reason":"request field absent","status":"unknown"},"capabilities":{"status":"known","value":{"count":3,"omitted":0,"rendered":[{"truncated":false,"value":"ExecutesCode"},{"truncated":false,"value":"Sandboxable"},{"truncated":false,"value":"RequiresApproval"}]}},"defer_loading":{"status":"known","value":false},"description":{"truncated":true,"value":"Execute a shell command in the workspace and return stdout and stderr (last 2000 lines or 50KB). Optional timeout is foreground seconds (default 30 seconds); a command still running then moves to the background by itself — never killed for time — returning output so far, last-output age, build phase, and a task_id. Call task_shell_wait with that task_id to read more or wait; do not sleep-poll with bash. Before a final answer, collect every still-relevant background task (wait only when genuinely blocked) an"},"input_examples":{"reason":"request field absent","status":"unknown"},"input_schema_json":{"truncated":false,"value":"{\"additionalProperties\":false,\"properties\":{\"command\":{\"description\":\"The command to execute. Actual execution shell: `/bin/bash`. Use Bash syntax: pipelines, redirections, $(command), and && / || are supported. Quote paths and variable expansions, such as \\\"$path\\\"; use single quotes for literal text. For literal multiline input, use a quoted heredoc delimiter (<<'EOF') with its closing delimiter on a separate line. Use only installed programs; do not assume GNU-specific flags on macOS/BSD. Example: printf '%s\\\\n' 'sample'.\",\"type\":\"string\"},\"description\":{\"description\":\"Optional few-word summary shown to the user beside the command.\",\"type\":\"string\"},\"justification\":{\"description\":\"Required with sandbox_permissions: one sentence explaining why this exact command needs wider access.\",\"type\":\"string\"},\"read_only\":{\"description\":\"Set true to run analysis code (including Python/SQLite) or a network fetch (curl) with mandatory native filesystem read-only isolation. Outbound network is on only iLine truncated
{"error":"Model not exist.","event":"turn_complete","parent_route_usage":{"input_tokens":120,"output_tokens":0},"routed_usage_dropped_records":0,"status":"failed","tool_catalog":"<pinned by the prompt family>","turn_id":"<uuid:1>","usage":{"input_tokens":120,"output_tokens":0}}
{"harness_summary":{"model_requests":1,"non_streaming_requests":0,"workspace_after":{".codewhale/state/.gitignore":"cdbcae15105d6b78",".codewhale/state/subagents.v1.json/legacy.json":"9064f16acf90984c",".codewhale/state/subagents.v1.lock":"e3b0c44298fc1c14",".codewhale/state/subagents.v3.json":"e874da2951e53d2b",".codewhale/state/subagents.v3.transaction.lock":"e3b0c44298fc1c14","NOTES.md":"f957b19529906961","README.md":"41f49bffb38de5ba"}}}
{"harness_summary":{"model_requests":1,"non_streaming_requests":0,"workspace_after":{".codewhale/state/.gitignore":"cdbcae15105d6b78",".codewhale/state/subagents.v1.json/legacy.json":"9064f16acf90984c",".codewhale/state/subagents.v3.json":"e874da2951e53d2b",".codewhale/state/subagents.v3.transaction.lock":"e3b0c44298fc1c14","NOTES.md":"f957b19529906961","README.md":"41f49bffb38de5ba"}}}
+18
View File
@@ -3,6 +3,21 @@ use std::path::Path;
pub fn open_workspace_directory(
workspace: &Path,
) -> anyhow::Result<(std::path::PathBuf, std::fs::File)> {
open_directory(workspace, false)
}
pub fn open_pinned_workspace_directory(
workspace: &Path,
) -> anyhow::Result<(std::path::PathBuf, std::fs::File)> {
open_directory(workspace, true)
}
fn open_directory(
workspace: &Path,
pinned: bool,
) -> anyhow::Result<(std::path::PathBuf, std::fs::File)> {
#[cfg(not(windows))]
let _ = pinned;
let canonical = workspace.canonicalize()?;
let mut options = std::fs::OpenOptions::new();
options.read(true);
@@ -15,6 +30,9 @@ pub fn open_workspace_directory(
{
use std::os::windows::fs::OpenOptionsExt as _;
options.custom_flags(0x0200_0000 | 0x0020_0000); // BACKUP_SEMANTICS, OPEN_REPARSE_POINT
if pinned {
options.share_mode(0x1 | 0x2);
}
}
let directory = options.open(&canonical)?;
let metadata = directory.metadata()?;
@@ -68,8 +68,8 @@ ids to customers.
## Subagent state
Subagent state lives in the workspace, under `.codewhale/state/`, in
`subagents.v1.json` (the manager's `SUBAGENT_STATE_FILE`; the lock is
`subagents.v1.lock`), loaded by `load_state` and written by
`subagents.v3.json` (the manager's `SUBAGENT_STATE_FILE`), loaded by
`load_state` and written by
`persist_state*` in `crates/engine/src/tools/subagent/mod.rs`. A legacy
`.deepseek/state/` copy is still read for migration.
+30 -12
View File
@@ -29,7 +29,7 @@ resolved values are persisted in their launch manifest.
By default, delegated control-plane state remains workspace-scoped at
`<workspace>/.codewhale/state`: the worker ledger, complete transcript
artifacts, and coordination lock share that root. An embedding host may set
artifacts, and store locks share that root. An embedding host may set
`EngineConfig::subagent_state_root` to keep those files under a session-owned
root without changing child cwd, tool path authority, or the execution
workspace recorded in receipts.
@@ -124,19 +124,32 @@ cannot replace a newer one, and a terminal receipt cannot be resurrected as
Running by a checkpoint. An explicit terminal retry accepts only the same
winning outcome; authoritative newer accounting metadata is retained.
Normal interactive/exec/Fleet/background sessions continue to share the
existing admission flock. The explicit exclusive Runtime constructor retains
its host admission policy; it is not the mechanism that conserves shared
snapshots. No manager holds the transaction lock while a child executes or
while it waits for a provider or channel capacity. Conflicting lock contention
returns a bounded retry error. Unsupported locking or failed store admission
refuses durable writes rather than silently creating an empty writable ledger.
There is no workspace-wide session lock. Interactive, exec, Fleet, background
and Runtime managers in one folder are ordinary neighbours: each holds only its
own boot lease and takes the transaction lock per operation. The Runtime
constructor keeps one manager per state path inside its process. No manager
holds the transaction lock while a child executes or while it waits for a
provider or channel capacity. Conflicting lock contention returns a bounded
retry error. Unsupported locking or failed store admission refuses durable
writes rather than silently creating an empty writable ledger, and admission is
retried on the next delegated write instead of staying refused for the life of
the process.
A Runtime that admits a selected workspace other than its own state root keeps
that workspace's claims in its own store. Before it admits a shared-workspace
writer there, and each time it leases such a writer, it refuses while any
session holds a live boot lease in the selected workspace's own store, and it
refuses when that store's directory cannot be listed. Only sessions that hold
a boot lease are seen: a Codewhale 0.10.2 or older session holds none. A
session that opens in that workspace later does not see the Runtime's claims,
and its lease refuses the Runtime's next shared-workspace writer there; give
writers isolated worktrees when both are expected.
Each writer holds its own boot lease. Other managers preserve its live records
and use its active claims during admission. An existing unlocked lease can
establish that its writer ended; a missing, invalid or unreadable lease is
uncertain and fails closed. Local task handles and a failed admission flock do
not establish that another process's work stopped. Parked and headless
uncertain and fails closed. Local task handles do not establish that another
process's work stopped. Parked and headless
WaitingForUser claim rules retain their existing lifecycle meaning; they do not
transfer a still-live writer's record ownership to a different boot.
@@ -216,10 +229,15 @@ terminal receipt or claim that a remote effect was undone.
### Legacy cutover and recovery
The first current-format admission takes the legacy admission lock exclusively
only for migration, after previous holders have left. It retains the original
The first current-format admission migrates under the short transaction lock.
It does not wait for older sessions that still hold the retired
`subagents.v1.lock`. It retains the original
legacy bytes and a validated recovery copy, then leaves
`subagents.v1.json` as a private directory containing that recovery material.
An older session still open in that folder can no longer save its delegated
state once the directory replaces its file; restart it. If it publishes its
file between the two cutover renames, the cutover stops at a retained-file
refusal until a person inspects both files; nothing is deleted.
The current format3 file is published under the same short transaction lock.
Interrupted cutover states are validated and resumed without replacing a later
current-format revision with the old backup. Future or malformed envelopes
+1 -1
View File
@@ -257,7 +257,7 @@
},
"crates/engine/src/tools/subagent/mod.rs": {
"path_canonicalize": 4,
"std_fs": 3,
"std_fs": 2,
"thread_sleep": 1
},
"crates/engine/src/tools/subagent/worktree.rs": {
+2 -9
View File
@@ -9,21 +9,14 @@ GITHUB_TOKEN=
GITHUB_REPO=codewhale-hq/CodeWhale
# Optional — required to manually invoke /api/cron
# (cloudflare cron triggers don't need this; they set cf-cron). When set it must
# be 32 to 512 characters with at least 8 distinct, and a shorter value repeated
# is refused; otherwise the trigger stays disabled.
# Generate one with: openssl rand -base64 33
# (cloudflare cron triggers don't need this; they set cf-cron).
CRON_SECRET=
# Optional — defaults to deepseek-flash.
DEEPSEEK_MODEL=deepseek-flash
DEEPSEEK_BASE_URL=https://api.deepseek.com
# Admin panel auth. Set to a random secret of 32 to 512 characters with at
# least 8 distinct characters, and a shorter value repeated is refused (anything
# else leaves admin sign-in disabled); enter it in the /admin login form.
# Changing it signs out open admin sessions.
# Generate one with: openssl rand -base64 33
# Admin panel auth. Set to a random secret; enter it in the /admin login form.
MAINTAINER_TOKEN=
# GitHub PAT for posting comments via /admin. Needs issues:write scope.
+3 -5
View File
@@ -87,8 +87,8 @@ form. The form posts to `/api/admin/login`; the token never goes in the URL.
|---|---|---|
| `DEEPSEEK_API_KEY` | Yes | DeepSeek API key for the community agent |
| `GITHUB_TOKEN` | Optional | Fine-grained PAT for GitHub API (raises rate limit) |
| `CRON_SECRET` | Optional | Shared secret for manual cron invocation (32 to 512 characters, at least 8 distinct, and a shorter value repeated is refused; otherwise the trigger stays disabled); attempts are rate limited (5 per minute per location) |
| `MAINTAINER_TOKEN` | Optional | Auth token for /admin panel; 32 to 512 characters with at least 8 distinct, and a shorter value repeated is refused (otherwise sign-in stays disabled); changing it signs out open sessions |
| `CRON_SECRET` | Optional | Shared secret for manual cron invocation |
| `MAINTAINER_TOKEN` | Optional | Auth token for /admin panel |
| `MAINTAINER_GITHUB_PAT` | Optional | GitHub PAT with `issues:write` scope for posting comments |
## Initial deployment
@@ -103,9 +103,7 @@ One-time setup before the first `npm run deploy`:
Copy the returned `id` values into the matching `CURATED_KV` and
`NEXT_INC_CACHE_KV` bindings in `cloudflare.config.ts`.
2. **Set secrets:** generate `MAINTAINER_TOKEN` and `CRON_SECRET` with
`openssl rand -base64 33` (any random value of 32 to 512 characters with at
least 8 distinct and not a shorter value repeated works; `openssl rand -hex 32` is fine).
2. **Set secrets:**
```bash
npx wrangler secret put DEEPSEEK_API_KEY
npx wrangler secret put MAINTAINER_TOKEN
+2 -2
View File
@@ -20,10 +20,10 @@ Env (mirrors `.env.example`):
| `DEEPSEEK_API_KEY` | DeepSeek platform key (`sk-...`) | only for the `/api/cron` tasks (summarization + community agent) |
| `GITHUB_TOKEN` | Fine-grained PAT, public-repo read scope | optional (raises rate limit 60 → 5000 req/h) |
| `GITHUB_REPO` | Defaults to `codewhale-hq/CodeWhale` | optional |
| `CRON_SECRET` | Shared secret for manual `/api/cron` invocation (32-512 characters, 8+ distinct; a shorter value repeated is refused)| optional (Cloudflare cron triggers don't need it) |
| `CRON_SECRET` | Shared secret for manual `/api/cron` invocation | optional (Cloudflare cron triggers don't need it) |
| `DEEPSEEK_MODEL` | Defaults to `deepseek-flash` | optional |
| `DEEPSEEK_BASE_URL` | Defaults to `https://api.deepseek.com` | optional |
| `MAINTAINER_TOKEN` | Admin panel auth (32-512 characters, 8+ distinct; a shorter value repeated is refused; changing it signs out sessions); enter it in the `/admin` login form | only for `/admin` |
| `MAINTAINER_TOKEN` | Admin panel auth; enter it in the `/admin` login form | only for `/admin` |
| `MAINTAINER_GITHUB_PAT` | PAT with `issues:write`, for posting comments via `/admin` | only for `/admin` posting |
| `NEXT_PUBLIC_GITEE_ENABLED` | Set to `1` once the Gitee mirror exists; blank hides Gitee links | optional |
+2 -4
View File
@@ -4,7 +4,6 @@ import { ConnectionBanner } from "@/components/connection-banner";
import { EmptyState, ErrorState } from "@/components/surface-state";
import { WhalePose } from "@/components/whale-pose";
import { getAgentEnv, listDrafts, validateSession, type AgentDraft } from "@/lib/community-agent";
import { MAINTAINER_TOKEN_UNAVAILABLE, maintainerTokenUsable } from "@/lib/maintainer-token";
import { AdminClient } from "./admin-client";
export const dynamic = "force-dynamic";
@@ -78,8 +77,7 @@ export default async function AdminPage({
const env = await getAgentEnv();
if (!maintainerTokenUsable(env.MAINTAINER_TOKEN)) {
if (env.MAINTAINER_TOKEN) console.warn(MAINTAINER_TOKEN_UNAVAILABLE);
if (!env.MAINTAINER_TOKEN) {
return (
<div className="route-state">
<ConnectionBanner locale={locale} />
@@ -100,7 +98,7 @@ export default async function AdminPage({
const cookieStore = await cookies();
const sid = cookieStore.get("mt_sid")?.value;
const authed = await validateSession(env.CURATED_KV, sid, env.MAINTAINER_TOKEN);
const authed = await validateSession(env.CURATED_KV, sid);
if (!authed) {
return <LoginForm locale={locale} error={err === "1"} />;
+5 -5
View File
@@ -1,12 +1,12 @@
import { NextResponse } from "next/server";
import { getAgentEnv, safeEqual, createSession } from "@/lib/community-agent";
import { MAINTAINER_TOKEN_UNAVAILABLE, MAX_SECRET_CHARS, maintainerTokenUsable } from "@/lib/maintainer-token";
import { FormBodyError, readBoundedUrlEncodedForm } from "@/lib/bounded-form";
export const dynamic = "force-dynamic";
const ALLOWED_LOCALES = new Set(["en", "zh"]);
const MAX_LOGIN_BODY_BYTES = 4_096;
const MAX_TOKEN_CHARS = 512;
function pickLocale(value: string | null | undefined): string {
if (!value) return "en";
@@ -18,8 +18,8 @@ export async function POST(req: Request) {
const url = new URL(req.url);
const localeFromQuery = pickLocale(url.searchParams.get("locale"));
if (!maintainerTokenUsable(env.MAINTAINER_TOKEN)) {
return new NextResponse(MAINTAINER_TOKEN_UNAVAILABLE, {
if (!env.MAINTAINER_TOKEN) {
return new NextResponse("Not configured", {
status: 503,
headers: { "Cache-Control": "no-store" },
});
@@ -58,7 +58,7 @@ export async function POST(req: Request) {
}
const submitted = form.get("token") ?? "";
const locale = pickLocale(form.get("locale") ?? localeFromQuery);
if (submitted.length > MAX_SECRET_CHARS) {
if (submitted.length > MAX_TOKEN_CHARS) {
return new NextResponse("Token too long", {
status: 413,
headers: { "Cache-Control": "no-store" },
@@ -73,7 +73,7 @@ export async function POST(req: Request) {
});
}
const sid = await createSession(env.CURATED_KV, env.MAINTAINER_TOKEN);
const sid = await createSession(env.CURATED_KV);
if (!sid) {
return new NextResponse("Session storage unavailable", {
status: 503,
+1 -1
View File
@@ -9,7 +9,7 @@ export async function POST(request: Request) {
try {
const authEnv = await getAgentEnv();
const sid = request.headers.get("cookie")?.split(";").map(c => c.trim()).find(c => c.startsWith("mt_sid="))?.slice(7);
if (!await validateSession(authEnv.CURATED_KV, sid, authEnv.MAINTAINER_TOKEN)) throw new MerchError(401, "unauthorized", "Maintainer sign-in is required.");
if (!authEnv.MAINTAINER_TOKEN || !await validateSession(authEnv.CURATED_KV, sid)) throw new MerchError(401, "unauthorized", "Maintainer sign-in is required.");
const env = await merchEnv(), config = parseConfig(env.MERCH_CONFIG_JSON);
if (!config || request.headers.get("origin") !== new URL(config.siteOrigin).origin || !request.headers.get("content-type")?.startsWith("application/json")) throw new MerchError(403, "request_blocked", "Use the approved store origin.");
const raw = await readBoundedBody(request, 8192);
+1 -1
View File
@@ -39,7 +39,7 @@ async function checkAuth(req: Request, env: CommunityAgentEnv): Promise<{ ok: bo
}
}
if (!sid || !(await validateSession(env.CURATED_KV, sid, env.MAINTAINER_TOKEN))) {
if (!sid || !(await validateSession(env.CURATED_KV, sid))) {
return { ok: false, status: 401, error: "unauthorized" };
}
return { ok: true };
+1 -26
View File
@@ -4,7 +4,6 @@ import type { AgentEnv } from "@/lib/community-agent-tasks";
import { runFactsDrift } from "@/lib/facts-drift";
import { runLinkCheck, runSemanticDrift } from "@/lib/content-watch";
import { safeEqual } from "@/lib/community-agent";
import { CRON_SECRET_UNAVAILABLE, secretStrongEnough } from "@/lib/maintainer-token";
export const dynamic = "force-dynamic";
@@ -31,33 +30,9 @@ export async function GET(req: Request) {
);
}
if (!secretStrongEnough(env.CRON_SECRET)) {
console.warn(CRON_SECRET_UNAVAILABLE);
return NextResponse.json(
{ error: CRON_SECRET_UNAVAILABLE },
{ status: 503, headers: { "Cache-Control": "no-store" } }
);
}
try {
if (!env.ADMIN_LOGIN_LIMITER) throw new Error("Missing cron limiter");
const { success } = await env.ADMIN_LOGIN_LIMITER.limit({ key: "codewhale-web:cron-secret" });
if (!success) {
return NextResponse.json(
{ error: "too many attempts" },
{ status: 429, headers: { "Cache-Control": "no-store", "Retry-After": "60" } }
);
}
} catch {
return NextResponse.json(
{ error: "manual trigger temporarily unavailable" },
{ status: 503, headers: { "Cache-Control": "no-store", "Retry-After": "60" } }
);
}
const auth = req.headers.get("x-cron-secret") ?? "";
if (!(await safeEqual(auth, env.CRON_SECRET))) {
return NextResponse.json({ error: "unauthorized" }, { status: 401, headers: { "Cache-Control": "no-store" } });
return NextResponse.json({ error: "unauthorized" }, { status: 401 });
}
const { searchParams } = new URL(req.url);
+4 -10
View File
@@ -14,7 +14,7 @@ vi.mock("@/lib/community-agent", async (importOriginal) => {
import { POST } from "@/app/api/admin/login/route";
import { createSession, safeEqual, validateSession } from "@/lib/community-agent";
const FIXTURE_TOKEN = "local-admin-integration-fixture-0123456789";
const FIXTURE_TOKEN = "local-admin-integration-fixture";
const sessions = new Map<string, string>();
const kv = {
put: vi.fn(async (key: string, value: string) => { sessions.set(key, value); }),
@@ -57,9 +57,9 @@ describe("admin login with real credential and session helpers", () => {
const sid = response.cookies.get("mt_sid")?.value;
expect(sid).toMatch(/^[A-Za-z0-9_-]{43}$/);
expect(sessions.size).toBe(1);
expect(await validateSession(sessionKv, sid, FIXTURE_TOKEN)).toBe(true);
expect(await validateSession(sessionKv, sid)).toBe(true);
expect(safeEqual).toHaveBeenCalledExactlyOnceWith(FIXTURE_TOKEN, FIXTURE_TOKEN);
expect(createSession).toHaveBeenCalledExactlyOnceWith(sessionKv, FIXTURE_TOKEN);
expect(createSession).toHaveBeenCalledExactlyOnceWith(sessionKv);
const cookie = response.headers.get("Set-Cookie")?.toLowerCase();
expect(cookie).toContain("httponly");
expect(cookie).toContain("secure");
@@ -69,13 +69,7 @@ describe("admin login with real credential and session helpers", () => {
expect.any(String), expect.any(String), { expirationTtl: 86400 },
]);
sessions.clear();
expect(await validateSession(sessionKv, sid, FIXTURE_TOKEN)).toBe(false);
});
it("stops honouring a session after the maintainer token is rotated", async () => {
const sid = (await POST(request())).cookies.get("mt_sid")?.value;
expect(await validateSession(sessionKv, sid, FIXTURE_TOKEN)).toBe(true);
expect(await validateSession(sessionKv, sid, "rotated-integration-fixture-9876543210")).toBe(false);
expect(await validateSession(sessionKv, sid)).toBe(false);
});
it("rejects a wrong credential without creating a session", async () => {
+4 -38
View File
@@ -5,9 +5,6 @@ const mocks = vi.hoisted(() => ({
vi.mock("@/lib/community-agent", () => mocks);
import { POST } from "@/app/api/admin/login/route";
const STRONG_TOKEN = "local-fixture-token-0123456789-abcdefghij";
const LONE_SURROGATES = Array.from({ length: 16 }, (_, index) => String.fromCharCode(0xd800 + index)).join("").repeat(2);
function request(token = "wrong", ip = "127.0.0.1") {
return new Request("https://codewhale.net/api/admin/login?locale=en", {
method: "POST",
@@ -17,7 +14,7 @@ function request(token = "wrong", ip = "127.0.0.1") {
}
beforeEach(() => {
vi.resetAllMocks();
mocks.getAgentEnv.mockResolvedValue({ MAINTAINER_TOKEN: STRONG_TOKEN, ADMIN_LOGIN_LIMITER: { limit: mocks.limit }, CURATED_KV: {} });
mocks.getAgentEnv.mockResolvedValue({ MAINTAINER_TOKEN: "configured", ADMIN_LOGIN_LIMITER: { limit: mocks.limit }, CURATED_KV: {} });
mocks.limit.mockResolvedValue({ success: true });
mocks.safeEqual.mockResolvedValue(false);
mocks.createSession.mockResolvedValue("session-id");
@@ -38,7 +35,7 @@ describe("admin login attempt boundary", () => {
});
it("does not parse or compare credentials after refusal", async () => {
mocks.limit.mockResolvedValue({ success: false });
const req = request(STRONG_TOKEN);
const req = request("configured");
const read = vi.spyOn(req, "text");
expect((await POST(req)).status).toBe(429);
expect(read).not.toHaveBeenCalled();
@@ -46,47 +43,16 @@ describe("admin login attempt boundary", () => {
expect(mocks.createSession).not.toHaveBeenCalled();
});
it("fails closed if the binding is missing or unavailable", async () => {
mocks.getAgentEnv.mockResolvedValueOnce({ MAINTAINER_TOKEN: STRONG_TOKEN });
mocks.getAgentEnv.mockResolvedValueOnce({ MAINTAINER_TOKEN: "configured" });
expect((await POST(request())).status).toBe(503);
mocks.limit.mockRejectedValue(new Error("binding unavailable"));
expect((await POST(request())).status).toBe(503);
expect(mocks.safeEqual).not.toHaveBeenCalled();
expect(mocks.createSession).not.toHaveBeenCalled();
});
it("refuses to run with a configured token below the minimum strength", async () => {
const weakTokens = [
"x", "configured", "a".repeat(31), "a".repeat(32), " ".repeat(40), "password".repeat(4),
"Password1".repeat(4), "0123456".repeat(5), "\u{1F433}".repeat(16), "L".repeat(600), LONE_SURROGATES,
];
for (const weak of weakTokens) {
mocks.getAgentEnv.mockResolvedValueOnce({ MAINTAINER_TOKEN: weak, ADMIN_LOGIN_LIMITER: { limit: mocks.limit }, CURATED_KV: {} });
mocks.safeEqual.mockResolvedValue(true);
const response = await POST(request(weak));
expect(response.status).toBe(503);
expect(response.headers.get("Cache-Control")).toBe("no-store");
expect(await response.text()).toContain("at least 32 characters");
}
expect(mocks.limit).not.toHaveBeenCalled();
expect(mocks.safeEqual).not.toHaveBeenCalled();
expect(mocks.createSession).not.toHaveBeenCalled();
});
it("accepts a token of exactly the minimum length", async () => {
const exact = "abcdefghijklmnopqrstuvwxyz012345";
expect(exact).toHaveLength(32);
mocks.getAgentEnv.mockResolvedValueOnce({ MAINTAINER_TOKEN: exact, ADMIN_LOGIN_LIMITER: { limit: mocks.limit }, CURATED_KV: {} });
mocks.safeEqual.mockResolvedValue(true);
expect((await POST(request(exact))).status).toBe(303);
});
it("accepts a 32-character hex secret with fewer than 16 distinct characters", async () => {
const hex = "3f9a3f9a1c7e1c7e3f9a1c7e5b2d5b2d";
expect(new Set(hex).size).toBeLessThan(16);
mocks.getAgentEnv.mockResolvedValueOnce({ MAINTAINER_TOKEN: hex, ADMIN_LOGIN_LIMITER: { limit: mocks.limit }, CURATED_KV: {} });
mocks.safeEqual.mockResolvedValue(true);
expect((await POST(request(hex))).status).toBe(303);
});
it("retains the authenticated session and redirect after an allowed attempt", async () => {
mocks.safeEqual.mockResolvedValue(true);
const response = await POST(request(STRONG_TOKEN));
const response = await POST(request("configured"));
expect(response.status).toBe(303);
expect(response.headers.get("Location")).toBe("https://codewhale.net/en/admin");
const cookie = response.headers.get("Set-Cookie");
+1 -1
View File
@@ -144,7 +144,7 @@ function stubAdminEnv(kv: FakeKv, lock?: FakeDraftClaimLock) {
mocks.getAgentEnv.mockResolvedValue({
CURATED_KV: kv,
...(lock ? { DRAFT_CLAIM_LOCK: lock } : {}),
MAINTAINER_TOKEN: "local-fixture-token-0123456789-abcdefghij",
MAINTAINER_TOKEN: "configured",
MAINTAINER_GITHUB_PAT: "ghp_test",
GITHUB_REPO: "codewhale-hq/CodeWhale",
});
+23 -46
View File
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { createSession, logUsage, validateSession } from "./community-agent";
import { logUsage, validateSession } from "./community-agent";
describe("validateSession", () => {
let mockKV: {
@@ -20,88 +20,65 @@ describe("validateSession", () => {
const VALID_SID = "a".repeat(40);
const SESSION_PREFIX = "session:admin:";
const TOKEN = "local-fixture-token-0123456789-abcdefghij";
const ROTATED = "rotated-fixture-token-9876543210-zyxwvutsrq";
it("should return false if kv is undefined", async () => {
const result = await validateSession(undefined, VALID_SID, TOKEN);
const result = await validateSession(undefined, VALID_SID);
expect(result).toBe(false);
});
it("should return false if sid is undefined or null", async () => {
const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
expect(await validateSession(kv, undefined, TOKEN)).toBe(false);
expect(await validateSession(kv, null, TOKEN)).toBe(false);
expect(await validateSession(kv, undefined)).toBe(false);
expect(await validateSession(kv, null)).toBe(false);
});
it("should return false if sid is empty", async () => {
const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
expect(await validateSession(kv, "", TOKEN)).toBe(false);
expect(await validateSession(kv, "")).toBe(false);
});
it("should return false if sid length is less than 40", async () => {
const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
expect(await validateSession(kv, "a".repeat(39), TOKEN)).toBe(false);
expect(await validateSession(kv, "a".repeat(39))).toBe(false);
});
it("should return false if sid length is greater than 64", async () => {
const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
expect(await validateSession(kv, "a".repeat(65), TOKEN)).toBe(false);
expect(await validateSession(kv, "a".repeat(65))).toBe(false);
});
it("should return false if sid contains invalid characters", async () => {
const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
// Length 40 but contains invalid char '!'
expect(await validateSession(kv, "a".repeat(39) + "!", TOKEN)).toBe(false);
expect(await validateSession(kv, "a".repeat(39) + "!")).toBe(false);
});
it("should return false if session is not found in KV", async () => {
const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
mockKV.get.mockResolvedValue(null);
const result = await validateSession(kv, VALID_SID, TOKEN);
const result = await validateSession(kv, VALID_SID);
expect(result).toBe(false);
expect(mockKV.get).toHaveBeenCalledWith(SESSION_PREFIX + VALID_SID);
});
it("should return true for a session minted under the configured token", async () => {
const store = new Map<string, string>();
const kv = {
get: async (key: string) => store.get(key) ?? null,
put: async (key: string, value: string) => { store.set(key, value); },
} as unknown as Parameters<typeof validateSession>[0];
const sid = await createSession(kv, TOKEN);
expect(sid).toMatch(/^[A-Za-z0-9_-]{43}$/);
expect(await validateSession(kv, sid, TOKEN)).toBe(true);
});
it("should refuse the same session once the configured token changes", async () => {
const store = new Map<string, string>();
const kv = {
get: async (key: string) => store.get(key) ?? null,
put: async (key: string, value: string) => { store.set(key, value); },
} as unknown as Parameters<typeof validateSession>[0];
const sid = await createSession(kv, TOKEN);
expect(await validateSession(kv, sid, ROTATED)).toBe(false);
expect(await validateSession(kv, sid, "short")).toBe(false);
expect(await validateSession(kv, sid, undefined)).toBe(false);
expect(await validateSession(kv, sid, TOKEN)).toBe(true);
});
it("should refuse a stored record with no token fingerprint or unparseable content", async () => {
it("should return true if session is found in KV", async () => {
const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
for (const raw of [JSON.stringify({ createdAt: Date.now() }), "{}", "not json", JSON.stringify({ tokenFingerprint: 7 })]) {
mockKV.get.mockResolvedValue(raw);
expect(await validateSession(kv, VALID_SID, TOKEN)).toBe(false);
}
mockKV.get.mockResolvedValue(JSON.stringify({ createdAt: Date.now() }));
const result = await validateSession(kv, VALID_SID);
expect(result).toBe(true);
expect(mockKV.get).toHaveBeenCalledWith(SESSION_PREFIX + VALID_SID);
});
it("should not mint a session under a weak token", async () => {
const kv = mockKV as unknown as Parameters<typeof createSession>[0];
for (const weak of [undefined, "", "short", "a".repeat(32)]) {
expect(await createSession(kv, weak)).toBeNull();
}
expect(mockKV.put).not.toHaveBeenCalled();
it("should work with a 64 character sid", async () => {
const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
mockKV.get.mockResolvedValue("{}");
const sid = "b".repeat(64);
const result = await validateSession(kv, sid);
expect(result).toBe(true);
expect(mockKV.get).toHaveBeenCalledWith(SESSION_PREFIX + sid);
});
});
+6 -26
View File
@@ -12,7 +12,6 @@
import type { DraftClaimLockNamespace, DraftClaimLockStub, DraftLockAction } from "./draft-claim-lock";
import { maintainerTokenUsable } from "./maintainer-token";
import { requestChat, type ChatMessage, type DeepSeekEnv } from "./deepseek";
export type { DeepSeekEnv } from "./deepseek";
@@ -723,7 +722,6 @@ export async function deleteDraft(kv: KVNamespace | undefined, key: string): Pro
const SESSION_PREFIX = "session:admin:";
const SESSION_TTL_SEC = 60 * 60 * 24; // 24h
const SESSION_TOKEN_DOMAIN = "codewhale-web:admin-session:v1:";
function toBase64Url(bytes: Uint8Array): string {
let s = "";
@@ -740,39 +738,21 @@ export async function safeEqual(a: string, b: string): Promise<boolean> {
return diff === 0;
}
async function tokenFingerprint(token: string): Promise<string> {
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(SESSION_TOKEN_DOMAIN + token)));
let hex = "";
for (const byte of digest) hex += byte.toString(16).padStart(2, "0");
return hex;
}
export async function createSession(kv: KVNamespace | undefined, token: string | undefined): Promise<string | null> {
if (!kv || !maintainerTokenUsable(token)) return null;
export async function createSession(kv: KVNamespace | undefined): Promise<string | null> {
if (!kv) return null;
const bytes = new Uint8Array(32);
crypto.getRandomValues(bytes);
const sid = toBase64Url(bytes);
const value = JSON.stringify({ createdAt: Date.now(), tokenFingerprint: await tokenFingerprint(token) });
const value = JSON.stringify({ createdAt: Date.now() });
await kv.put(SESSION_PREFIX + sid, value, { expirationTtl: SESSION_TTL_SEC });
return sid;
}
export async function validateSession(
kv: KVNamespace | undefined,
sid: string | undefined | null,
token: string | undefined,
): Promise<boolean> {
if (!kv || !sid || !maintainerTokenUsable(token)) return false;
export async function validateSession(kv: KVNamespace | undefined, sid: string | undefined | null): Promise<boolean> {
if (!kv || !sid) return false;
if (!/^[A-Za-z0-9_-]{40,64}$/.test(sid)) return false;
const raw = await kv.get(SESSION_PREFIX + sid);
if (raw === null) return false;
let stored: unknown;
try {
stored = (JSON.parse(raw) as { tokenFingerprint?: unknown }).tokenFingerprint;
} catch {
return false;
}
return typeof stored === "string" && (await safeEqual(stored, await tokenFingerprint(token)));
return raw !== null;
}
export async function deleteSession(kv: KVNamespace | undefined, sid: string | undefined | null): Promise<void> {
-76
View File
@@ -1,76 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({ getEnv: vi.fn(), safeEqual: vi.fn(), limit: vi.fn() }));
vi.mock("@/lib/kv", () => ({ getEnv: mocks.getEnv }));
vi.mock("@/lib/community-agent", () => ({ safeEqual: mocks.safeEqual }));
vi.mock("@/lib/facts-drift", () => ({ runFactsDrift: vi.fn() }));
vi.mock("@/lib/content-watch", () => ({ runLinkCheck: vi.fn(), runSemanticDrift: vi.fn() }));
import { GET } from "@/app/api/cron/route";
function request(secret = "wrong", ip = "127.0.0.1") {
return new Request("https://codewhale.net/api/cron?task=nope", {
headers: { "x-cron-secret": secret, "CF-Connecting-IP": ip },
});
}
beforeEach(() => {
vi.resetAllMocks();
mocks.getEnv.mockResolvedValue({ CRON_SECRET: "configured-cron-secret-0123456789-abcdef", ADMIN_LOGIN_LIMITER: { limit: mocks.limit } });
mocks.limit.mockResolvedValue({ success: true });
mocks.safeEqual.mockResolvedValue(false);
});
describe("manual cron trigger attempt boundary", () => {
it("bounds repeated guesses independently of the secret and forged IP", async () => {
let attempts = 0;
mocks.limit.mockImplementation(async () => ({ success: ++attempts <= 5 }));
for (let index = 0; index < 7; index++) {
const response = await GET(request(`guess-${index}`, `192.0.2.${index}`));
expect(response.status).toBe(index < 5 ? 401 : 429);
if (index >= 5) expect(response.headers.get("Retry-After")).toBe("60");
expect(response.headers.get("Cache-Control")).toBe("no-store");
}
expect(mocks.safeEqual).toHaveBeenCalledTimes(5);
expect(mocks.limit.mock.calls.map(([options]) => options.key)).toEqual(Array(7).fill("codewhale-web:cron-secret"));
});
it("does not compare the secret after refusal", async () => {
mocks.limit.mockResolvedValue({ success: false });
expect((await GET(request("configured-cron-secret-0123456789-abcdef"))).status).toBe(429);
expect(mocks.safeEqual).not.toHaveBeenCalled();
});
it("fails closed if the binding is missing or unavailable", async () => {
mocks.getEnv.mockResolvedValueOnce({ CRON_SECRET: "configured-cron-secret-0123456789-abcdef" });
expect((await GET(request())).status).toBe(503);
mocks.limit.mockRejectedValue(new Error("binding unavailable"));
expect((await GET(request())).status).toBe(503);
expect(mocks.safeEqual).not.toHaveBeenCalled();
});
it("stays disabled without a configured secret and never consults the limiter", async () => {
mocks.getEnv.mockResolvedValue({ ADMIN_LOGIN_LIMITER: { limit: mocks.limit } });
expect((await GET(request())).status).toBe(503);
expect(mocks.limit).not.toHaveBeenCalled();
});
it("stays disabled for a secret below the minimum strength and never consults the limiter or compares", async () => {
const loneSurrogates = Array.from({ length: 16 }, (_, index) => String.fromCharCode(0xd800 + index)).join("").repeat(2);
const weak = ["x", "a".repeat(32), " ".repeat(40), "password".repeat(4), "Password1".repeat(4), "\u{1F433}".repeat(16), "0123456".repeat(5), "L".repeat(600), loneSurrogates];
for (const secret of weak) {
mocks.getEnv.mockResolvedValueOnce({ CRON_SECRET: secret, ADMIN_LOGIN_LIMITER: { limit: mocks.limit } });
const response = await GET(request());
expect(response.status).toBe(503);
expect(response.headers.get("Cache-Control")).toBe("no-store");
expect(JSON.stringify(await response.json())).toContain("at least 32 characters");
}
expect(mocks.limit).not.toHaveBeenCalled();
expect(mocks.safeEqual).not.toHaveBeenCalled();
});
it("accepts a 32-character hex secret with fewer than 16 distinct characters", async () => {
const hex = "3f9a3f9a1c7e1c7e3f9a1c7e5b2d5b2d";
mocks.getEnv.mockResolvedValueOnce({ CRON_SECRET: hex, ADMIN_LOGIN_LIMITER: { limit: mocks.limit } });
mocks.safeEqual.mockResolvedValue(true);
expect((await GET(request(hex))).status).toBe(400);
});
it("still reaches task validation after an allowed, correct attempt", async () => {
mocks.safeEqual.mockResolvedValue(true);
expect((await GET(request("configured-cron-secret-0123456789-abcdef"))).status).toBe(400);
});
});
-1
View File
@@ -32,7 +32,6 @@ export async function readBoundedKvJson(kv: KVStreamNamespace | undefined, key:
interface CloudflareEnv extends MerchEnv {
DRAFT_CLAIM_LOCK?: DraftClaimLockNamespace;
CURATED_KV?: KVNamespace & KVStreamNamespace;
ADMIN_LOGIN_LIMITER?: { limit(options: { key: string }): Promise<{ success: boolean }> };
MERCH_INTEREST_LIMITER?: { limit(options: { key: string }): Promise<{ success: boolean }> };
MERCH_INTEREST_SITE_ORIGIN?: string;
DEEPSEEK_API_KEY?: string;
-25
View File
@@ -1,25 +0,0 @@
export const MIN_SECRET_CHARS = 32;
export const MAX_SECRET_CHARS = 512;
export const MIN_SECRET_DISTINCT_CHARS = 8;
const LONE_SURROGATE = /\p{Cs}/u;
export const MAINTAINER_TOKEN_UNAVAILABLE =
`Maintainer sign-in is unavailable: MAINTAINER_TOKEN must be set to a secret of at least ${MIN_SECRET_CHARS} characters ` +
`(at most ${MAX_SECRET_CHARS}, with at least ${MIN_SECRET_DISTINCT_CHARS} distinct characters; a shorter value repeated is refused).`;
export const CRON_SECRET_UNAVAILABLE =
`manual trigger disabled: CRON_SECRET must be a secret of at least ${MIN_SECRET_CHARS} characters ` +
`(at most ${MAX_SECRET_CHARS}, with at least ${MIN_SECRET_DISTINCT_CHARS} distinct characters; a shorter value repeated is refused)`;
export function secretStrongEnough(value: string | undefined): value is string {
if (typeof value !== "string" || value.length > MAX_SECRET_CHARS || LONE_SURROGATE.test(value)) return false;
const chars = [...value];
if (chars.length < MIN_SECRET_CHARS || new Set(chars).size < MIN_SECRET_DISTINCT_CHARS) return false;
for (let period = 1; period <= value.length / 2; period++) {
if (value.slice(period) === value.slice(0, value.length - period)) return false;
}
return true;
}
export const maintainerTokenUsable = secretStrongEnough;
+2 -8
View File
@@ -155,8 +155,8 @@ describe("durable merch interest registration", () => {
describe("private merch interest list and deletion", () => {
async function signedIn(): Promise<{ auth: CommunityAgentEnv; headers: Record<string, string> }> {
const auth = { CURATED_KV: env.CURATED_KV, MAINTAINER_TOKEN: "local-fixture-token-0123456789-abcdefghij" };
const sid = await createSession(auth.CURATED_KV, auth.MAINTAINER_TOKEN);
const auth = { CURATED_KV: env.CURATED_KV, MAINTAINER_TOKEN: "local-maintainer-fixture" };
const sid = await createSession(auth.CURATED_KV);
return { auth, headers: { Cookie: "mt_sid=" + sid } };
}
it("requires a real stored maintainer session for reading or deleting contacts", async () => {
@@ -165,12 +165,6 @@ describe("private merch interest list and deletion", () => {
expect(list).not.toHaveBeenCalled();
expect(remove).not.toHaveBeenCalled();
});
it.each(["short", "rotated-fixture-token-9876543210-zyxwvutsrq"])("refuses an existing session once the configured maintainer token changes to %s", async (replacement) => {
const { auth, headers } = await signedIn();
const response = await handleAdminMerchInterest(new Request("https://codewhale.net/api/admin/merch/interest", { headers }), env, { ...auth, MAINTAINER_TOKEN: replacement });
expect(response.status).toBe(401);
expect(list).not.toHaveBeenCalled();
});
it("paginates only the private prefix and deletes an opaque id with same-origin CSRF", async () => {
await handleMerchInterest(request(), env);
await handleMerchInterest(request({ ...input(), email: "[email protected]" }), env);
+1 -1
View File
@@ -138,7 +138,7 @@ export async function handleMerchInterest(request: Request, env?: MerchInterestE
}
async function requireAdmin(request: Request, auth: CommunityAgentEnv) {
const sid = request.headers.get("cookie")?.split(";").map(cookie => cookie.trim()).find(cookie => cookie.startsWith("mt_sid="))?.slice(7);
if (!await validateSession(auth.CURATED_KV, sid, auth.MAINTAINER_TOKEN)) throw new InterestError(401, "unauthorized", "Maintainer sign-in is required.");
if (!auth.MAINTAINER_TOKEN || !await validateSession(auth.CURATED_KV, sid)) throw new InterestError(401, "unauthorized", "Maintainer sign-in is required.");
}
export async function handleAdminMerchInterest(request: Request, env?: MerchInterestEnv, authEnv?: CommunityAgentEnv): Promise<Response> {
try {
+2 -2
View File
@@ -73,7 +73,7 @@ describe("public security boundaries", () => {
kv.values.set("agent:state:latest", JSON.stringify({ state: "running" }));
securityMocks.getAgentEnv.mockResolvedValue({
CURATED_KV: kv,
MAINTAINER_TOKEN: "local-fixture-token-0123456789-abcdefghij",
MAINTAINER_TOKEN: "configured",
});
const response = await adminPost(new Request("https://codewhale.net/api/admin/post", {
@@ -121,7 +121,7 @@ describe("public security boundaries", () => {
securityMocks.getAgentEnv.mockResolvedValue({
CURATED_KV: kv,
MAINTAINER_TOKEN: "local-fixture-token-0123456789-abcdefghij",
MAINTAINER_TOKEN: "configured",
MAINTAINER_GITHUB_PAT: "ghp_test",
GITHUB_REPO: "codewhale-hq/CodeWhale",
});