Skip to content

Commit 2cd3ee4

Browse files
authored
refactor: store workspace setup state in SQLite (#109147)
* refactor(state): move workspace setup state to SQLite * test(state): track workspace cleanup temp dirs * fix(state): satisfy workspace migration gates * docs(state): fix migration list indentation * fix(state): verify sibling migration claims * fix(state): remove obsolete claim probe
1 parent 2db77fb commit 2cd3ee4

39 files changed

Lines changed: 5547 additions & 735 deletions

‎docs/cli/reset.md‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,17 +27,18 @@ openclaw reset --scope full --yes --non-interactive
2727

2828
## Scopes
2929

30-
| Scope | Removes | Stops gateway first |
31-
| ----------------------- | ----------------------------------------------------------------------------------------------------- | ------------------- |
32-
| `config` | config file only | no |
33-
| `config+creds+sessions` | config file, OAuth/credentials dir, per-agent session directories | yes |
34-
| `full` | state dir (including config/creds if nested inside it) plus workspace dirs and workspace attestations | yes |
30+
| Scope | Removes | Stops gateway first |
31+
| ----------------------- | --------------------------------------------------------------------------- | ------------------- |
32+
| `config` | config file only | no |
33+
| `config+creds+sessions` | config file, OAuth/credentials dir, per-agent session directories | yes |
34+
| `full` | state dir (including the shared SQLite database) plus workspace directories | yes |
3535

3636
`config+creds+sessions` and `full` stop a running managed gateway service before deleting state.
3737

3838
## Notes
3939

4040
- Run `openclaw backup create` first for a restorable snapshot before removing local state.
41+
- Workspace setup state and attestations are rows in the shared SQLite database, so `full` removes them with the state directory; there are no current attestation sidecar files to remove separately.
4142
- Without `--scope`, `openclaw reset` prompts interactively for the scope to remove.
4243
- `--non-interactive` is only valid when both `--scope` and `--yes` are set.
4344
- `config+creds+sessions` and `full` print `Next: openclaw onboard --install-daemon` when done.

‎docs/concepts/agent-workspace.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ If a bootstrap file is missing, OpenClaw injects a "missing file" marker into th
111111
These live under `~/.openclaw/` and should NOT be committed to the workspace repo:
112112

113113
- `~/.openclaw/openclaw.json` (config)
114+
- `~/.openclaw/state/openclaw.sqlite` (shared workspace setup state and attestations)
114115
- `~/.openclaw/agents/<agentId>/agent/auth-profiles.json` (model auth profiles: OAuth + API keys)
115116
- `~/.openclaw/agents/<agentId>/agent/openclaw-agent.sqlite` (session rows, transcripts, and per-agent runtime state)
116117
- `~/.openclaw/agents/<agentId>/agent/codex-home/` (per-agent Codex runtime account, config, skills, plugins, and native thread state)
@@ -120,6 +121,12 @@ These live under `~/.openclaw/` and should NOT be committed to the workspace rep
120121

121122
If you need to migrate sessions or config, copy them separately and keep them out of version control.
122123

124+
Older OpenClaw releases wrote `openclaw-workspace-state.json`,
125+
`.openclaw/workspace-state.json`, and `.attested` workspace sidecars. Current
126+
runtime uses only the shared SQLite database for that state. If Doctor reports
127+
one of these files, run `openclaw doctor --fix`; Doctor imports valid legacy
128+
state and deletes a source only after verifying the database rows.
129+
123130
## Git backup (recommended, private)
124131

125132
Treat the workspace as private memory. Put it in a **private** git repo so it is backed up and recoverable.

‎docs/concepts/agent.md‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,16 @@ Blank files are skipped. Large files are trimmed and truncated with a marker so
4747

4848
`BOOTSTRAP.md` is only created for a **brand new workspace** (no other bootstrap files present). While it is pending, OpenClaw keeps it in Project Context and adds system-prompt bootstrap guidance for the initial ritual instead of copying it into the user message. If you delete it after completing the ritual, it is not recreated on later restarts.
4949

50-
After a workspace has been observed, OpenClaw also keeps a state-dir attestation marker for the workspace path. If a recently attested workspace disappears or is wiped, startup refuses to silently reseed `BOOTSTRAP.md`; restore the workspace or use a full onboard reset so the workspace and marker are cleared together.
50+
After a workspace has been observed, OpenClaw stores its setup state and
51+
attestation in the shared SQLite database at
52+
`~/.openclaw/state/openclaw.sqlite`. If a recently attested workspace
53+
disappears or is wiped, startup refuses to silently reseed `BOOTSTRAP.md`;
54+
restore the workspace or use a full onboard reset so the workspace and its
55+
database state are cleared together.
56+
57+
Older releases used workspace JSON and `.attested` sidecar files. Runtime does
58+
not read those files. Run `openclaw doctor --fix` to validate them, import their
59+
state into SQLite, and remove each source after the imported rows are verified.
5160

5261
To disable bootstrap file creation entirely (for pre-seeded workspaces), set:
5362

‎docs/refactor/database-first.md‎

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,10 @@ without exceptions outside doctor/import/export/debug boundaries.
146146
- Backup: `sqlite-runtime`. Backup stages compact SQLite snapshots, omits live
147147
WAL/SHM sidecars, verifies SQLite integrity, and records backup runs in the
148148
global database.
149+
- Workspace setup: `sqlite-runtime`. Setup completion, workspace attestations,
150+
and generated bootstrap hashes live in typed shared SQLite tables. Runtime
151+
does not read or write the retired workspace JSON and `.attested` sidecars;
152+
Doctor owns their validated import and verified removal.
149153
- Doctor migration: `migrating`, intentionally. Doctor imports legacy JSON,
150154
JSONL, and retired sidecar stores into SQLite, records migration runs/sources,
151155
and removes successful sources.
@@ -315,7 +319,8 @@ The branch already has a real shared SQLite base:
315319
`skill_uploads`, `capture_sessions`, `capture_events`, `capture_blobs`,
316320
`sandbox_registry_entries`, `cron_jobs`, `commitments`,
317321
`delivery_queue_entries`, `model_capability_cache`,
318-
`workspace_setup_state`, `native_hook_relay_bridges`,
322+
`workspace_setup_state`, `workspace_path_aliases`, `workspace_attestations`,
323+
`workspace_generated_bootstrap_hashes`, `native_hook_relay_bridges`,
319324
`current_conversation_bindings`, `plugin_binding_approvals`,
320325
`tui_last_sessions`, `acp_sessions`, `acp_replay_sessions`,
321326
`acp_replay_events`, `task_runs`, `task_delivery_state`, `flow_runs`,
@@ -455,11 +460,18 @@ The branch already has a real shared SQLite base:
455460
instead of scanning a whole namespace or relying on `LIKE` path matching.
456461
- `src/agents/runtime-worker.entry.ts` creates per-run SQLite VFS, tool artifact,
457462
run artifact, and scoped cache stores for workers.
458-
- Workspace bootstrap completion markers now live in typed shared
459-
`workspace_setup_state` rows keyed by resolved workspace path instead of
460-
`.openclaw/workspace-state.json`; runtime no longer reads or rewrites the
461-
legacy workspace marker, and helper APIs no longer pass around a fake
462-
`.openclaw/setup-state` path just to derive storage identity.
463+
- Workspace bootstrap completion, attestation recency, and generated bootstrap
464+
hashes now live in typed shared `workspace_setup_state`,
465+
`workspace_path_aliases`, `workspace_attestations`, and
466+
`workspace_generated_bootstrap_hashes` rows keyed by canonical workspace
467+
identity. Persisted lexical and real-path aliases keep vanished-workspace
468+
protection stable after a configured symlink disappears; repointed aliases
469+
fail closed. Runtime no longer reads or writes
470+
`openclaw-workspace-state.json`, `.openclaw/workspace-state.json`, state-dir
471+
`workspace-attestations/*.attested`, or sibling `<workspace>.attested`
472+
sidecars. `openclaw doctor --fix` validates and claims legacy sources,
473+
imports them into SQLite with migration receipts, verifies the canonical
474+
rows, and only then removes the claimed files.
463475
- The shared schema reserves an `exec_approvals_config` singleton row, but the
464476
runtime cutover remains pending. TypeScript and the macOS companion still use
465477
the state-scoped JSON file and must move to SQLite together.
@@ -1503,6 +1515,9 @@ device_identities(identity_key, device_id, public_key_pem, private_key_pem, crea
15031515
device_auth_tokens(device_id, role, token, scopes_json, updated_at_ms)
15041516
macos_port_guardian_records(pid, port, command, mode, timestamp)
15051517
workspace_setup_state(workspace_key, workspace_path, version, bootstrap_seeded_at, setup_completed_at, updated_at)
1518+
workspace_path_aliases(alias_key, alias_path, workspace_key, workspace_path, updated_at_ms)
1519+
workspace_attestations(workspace_key, attested_at_ms, updated_at_ms)
1520+
workspace_generated_bootstrap_hashes(workspace_key, filename, sha256)
15061521
native_hook_relay_bridges(relay_id, pid, hostname, port, token, expires_at_ms, updated_at_ms)
15071522
model_capability_cache(provider_id, model_id, name, input_text, input_image, reasoning, supports_tools, context_window, max_tokens, cost_input, cost_output, cost_cache_read, cost_cache_write, updated_at_ms)
15081523
agent_model_catalogs(catalog_key, agent_dir, raw_json, updated_at)
@@ -2194,7 +2209,10 @@ Add a repo check that fails new runtime writes to legacy state paths:
21942209
- `auth-profiles.json`
21952210
- `auth-state.json`
21962211
- `exec-approvals.json`
2212+
- `openclaw-workspace-state.json`
21972213
- `workspace-state.json`
2214+
- `workspace-attestations/*.attested`
2215+
- sibling `<workspace>.attested`
21982216
- Matrix `credentials*.json` and `recovery-key.json`
21992217
- `cron/runs/*.jsonl`
22002218
- `cron/jobs.json`

‎scripts/check-database-first-legacy-stores.mjs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,10 @@ const legacyStorePatterns = [
8989
/\bacp\/event-ledger\.json\b/u,
9090
/\bcache\/[^"'`]*\.json\b/u,
9191
/\bagents\/[^"'`]+\/agent\/(?:auth|models)\.json\b/u,
92-
/\b(?:credentials\/oauth|github-copilot\.token|openrouter-models|auth-profiles|auth-state|exec-approvals|workspace-state)\.json\b/u,
92+
/\b(?:credentials\/oauth|github-copilot\.token|openrouter-models|auth-profiles|auth-state|exec-approvals|(?:openclaw-)?workspace-state)\.json\b/u,
93+
// Dynamic template spans resolve to `*`, so the start alternative also
94+
// catches `${workspaceKey}.attested` and `${workspaceDir}.attested`.
95+
/(?:^|[/\\])[^/\\"'`]+\.attested\b/u,
9396
/\btui\/last-session\.json\b/u,
9497
/\bcommitments\/commitments\.json\b/u,
9598
/\bmedia\/outgoing\/records\/[^"'`]*\.json\b/u,
@@ -116,6 +119,7 @@ const allowedRuntimeMigrationPaths = [
116119
"src/infra/state-migrations.commitments.ts",
117120
"src/infra/state-migrations.managed-outgoing-images.ts",
118121
"src/infra/state-migrations.apns.ts",
122+
"src/infra/state-migrations.workspace-setup.ts",
119123
"src/infra/state-migrations.web-push.ts",
120124
"src/infra/state-migrations.node-host.ts",
121125
"src/infra/state-migrations.subagent-registry.ts",

‎src/agents/bootstrap-files.test.ts‎

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,13 @@ import {
99
registerInternalHook,
1010
type AgentBootstrapHookContext,
1111
} from "../hooks/internal-hooks.js";
12+
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
1213
import { makeTempWorkspace } from "../test-helpers/workspace.js";
1314
import { withEnvAsync } from "../test-utils/env.js";
15+
import {
16+
createOpenClawTestState,
17+
type OpenClawTestState,
18+
} from "../test-utils/openclaw-test-state.js";
1419
import {
1520
FULL_BOOTSTRAP_COMPLETED_CUSTOM_TYPE,
1621
hasCompletedBootstrapTurn,
@@ -19,8 +24,12 @@ import {
1924
resolveBootstrapFilesForRun,
2025
resolveContextInjectionMode,
2126
} from "./bootstrap-files.js";
27+
import { resetLegacyWorkspaceStateCheckForTest } from "./workspace-legacy-state.test-support.js";
28+
import { mergeWorkspaceSetupState } from "./workspace-state-store.js";
2229
import type { WorkspaceBootstrapFile } from "./workspace.js";
2330

31+
let testState: OpenClawTestState | undefined;
32+
2433
function registerExtraBootstrapFileHook() {
2534
registerInternalHook("agent:bootstrap", (event) => {
2635
const context = event.context as AgentBootstrapHookContext;
@@ -111,15 +120,10 @@ async function createHeartbeatAgentsWorkspace() {
111120
}
112121

113122
async function writeCompletedWorkspaceState(workspaceDir: string): Promise<void> {
114-
await fs.writeFile(
115-
path.join(workspaceDir, "openclaw-workspace-state.json"),
116-
`${JSON.stringify({
117-
version: 1,
118-
bootstrapSeededAt: "2026-05-16T00:00:00.000Z",
119-
setupCompletedAt: "2026-05-16T00:00:01.000Z",
120-
})}\n`,
121-
"utf8",
122-
);
123+
mergeWorkspaceSetupState(workspaceDir, {
124+
bootstrapSeededAt: "2026-05-16T00:00:00.000Z",
125+
setupCompletedAt: "2026-05-16T00:00:01.000Z",
126+
});
123127
}
124128

125129
async function writeLegacyCompletedWorkspaceState(workspaceDir: string): Promise<void> {
@@ -144,8 +148,21 @@ function expectHeartbeatExcludedAndAgentsKept(files: WorkspaceBootstrapFile[]) {
144148
}
145149

146150
describe("resolveBootstrapFilesForRun", () => {
147-
beforeEach(() => clearInternalHooks());
148-
afterEach(() => clearInternalHooks());
151+
beforeEach(async () => {
152+
clearInternalHooks();
153+
resetLegacyWorkspaceStateCheckForTest();
154+
testState = await createOpenClawTestState({
155+
layout: "state-only",
156+
prefix: "openclaw-bootstrap-state-",
157+
});
158+
});
159+
afterEach(async () => {
160+
clearInternalHooks();
161+
closeOpenClawStateDatabaseForTest();
162+
resetLegacyWorkspaceStateCheckForTest();
163+
await testState?.cleanup();
164+
testState = undefined;
165+
});
149166

150167
it("applies bootstrap hook overrides", async () => {
151168
registerExtraBootstrapFileHook();
@@ -211,7 +228,7 @@ describe("resolveBootstrapFilesForRun", () => {
211228
expect(files.map((file) => file.name)).not.toContain("BOOTSTRAP.md");
212229
});
213230

214-
it("ignores stale workspace BOOTSTRAP.md when legacy setup state is completed", async () => {
231+
it("keeps BOOTSTRAP.md until Doctor migrates legacy setup state", async () => {
215232
const workspaceDir = await makeTempWorkspace("openclaw-bootstrap-");
216233
await writeLegacyCompletedWorkspaceState(workspaceDir);
217234
await fs.writeFile(path.join(workspaceDir, "AGENTS.md"), "rules", "utf8");
@@ -220,7 +237,7 @@ describe("resolveBootstrapFilesForRun", () => {
220237
const files = await resolveBootstrapFilesForRun({ workspaceDir });
221238

222239
expect(files.map((file) => file.name)).toContain("AGENTS.md");
223-
expect(files.map((file) => file.name)).not.toContain("BOOTSTRAP.md");
240+
expect(files.map((file) => file.name)).toContain("BOOTSTRAP.md");
224241
});
225242

226243
it("keeps BOOTSTRAP.md when current setup state cannot be read", async () => {
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import "./workspace-legacy-state.js";
2+
3+
type WorkspaceLegacyStateTestApi = {
4+
resetLegacyWorkspaceStateCheckForTest(): void;
5+
};
6+
7+
function getTestApi(): WorkspaceLegacyStateTestApi {
8+
const api = (globalThis as Record<PropertyKey, unknown>)[
9+
Symbol.for("openclaw.workspaceLegacyStateTestApi")
10+
];
11+
if (!api) {
12+
throw new Error("workspace legacy state test API is unavailable");
13+
}
14+
return api as WorkspaceLegacyStateTestApi;
15+
}
16+
17+
export function resetLegacyWorkspaceStateCheckForTest(): void {
18+
getTestApi().resetLegacyWorkspaceStateCheckForTest();
19+
}

0 commit comments

Comments
 (0)