Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip(#6712 PR 4b lane S): probe 51 switch tests, goldens, docs

garrytana226d5e1e42b
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.md
index eb8fe8e613..8441a697f0 100644
--- a/docs/architecture/key-files/managed-sync-bookkeeping.md
+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md
@@ -18,6 +18,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/core/wire-skew.ts` — #6712 PR 1: the one record of wire-skew windows, each a version floor plus a calendar date (`WIRE_SKEW_WINDOWS.explicitProcessing`: floor 0.60.255.0, accepted and ignored until 2026-11-14). The delegation and admin wires read the field name from here, so removing the window is one edit. #6712 PR 2: each window names the hand-offs that accept it (`wires`) and its shape (`accepts`); `retiredWireFields` / `retiredWireNotice` serve both validators. `CONFIG_ROLLBACK_WINDOWS` records the rollback config keys' windows (honored until a date, from a version floor, with the notice that named them).
- `src/core/sync-flags.ts` — #6712 PR 2: `SYNC_FLAGS`, every `gbrain sync` flag once, with its route (`forward` / `client` / `refuse`) on the serve and PGLite owner hand-offs; `syncFlagsRouted` and `syncWireFields` derive the ladder's, the IPC validator's and the owner lane's allowlists. A flag the argv parsers read must be listed (`test/sync-flag-table-6712.test.ts`). #6712 PR 3 (L7): `managed: true` marks the ten flags `gbrain sync --help` lists under "Managed brains" (`MANAGED_HELP_FLAGS`, table order; `test/sync-managed-help-l7-6712.test.ts` pins the section and runs doctor's cron recipe through the managed flag validator).
- `src/core/sync-config-keys.ts` + `src/commands/doctor/checks/sync-config-keys.ts` — #6712 PR 2: the `sync.*` keys in three kinds: `SYNC_TUNABLE_KEYS`, the rollback keys (windows in `wire-skew.ts`) and `RETIRED_SYNC_KEYS` with their `GBRAIN_SYNC_*` replacements (`retiredSyncSetting` reads one). `effectiveSyncKey` is `config get`'s value-in-effect and origin for a retired or rollback key (its resolvers mirror the readers: `resolveBulkSettings`, `waiverBatchEnabled`, `isFederatedV2Enabled`, the write switches, `planJobDrain`); `syncKeySetNotice` is `config set`'s warning (a retired key writes nothing). Doctor `sync_config_keys` reports a stored retired key as unapplied. Pinned by `test/sync-config-keys-6712.test.ts` and `test/error-registry-retired.test.ts`.
+- `src/core/persistence/sync-admission.ts` + `src/commands/config/sync-admission-value.ts` + `src/commands/doctor/checks/sync-admission.ts` — #6712 PR 4b: `sync.admission` (`normal | imports_only | classify_only`, brain-wide, a `SYNC_TUNABLE_KEYS` entry). `readSyncAdmission` parses it (junk fails closed to `classify_only`) for the pass's pin, group admission and destructive publication, and `admissionAllows` gates a write kind. `config set` refuses any other value (exit 2, `--force` included) and `writeSyncAdmission` stores the value and its `set_at` (database clock) in one transaction: config has no timestamp, so `set_at` is an `op_checkpoints` row (`op='sync-admission'`, fingerprint `brain`) that dates the stored value only while it names that value (otherwise `set_at: null`). `config get` prints the value in effect (`handleSyncKeyConfig`). `syncAdmissionStatus(engine, source, incarnation)` is `sync status`'s `admission: {value, set_at, effective}` and the helper the pass's `convergence.admission` uses: `effective` is false while an `open` pass row with `started_at` before `set_at` holds the live `gbrain-sync:<source>` lease (token match), or a `managed_sync_delete` / `canonical_reconcile` request of the incarnation admitted before it is queued, running or recovering (an unknown `set_at` counts everything as earlier). Doctor `sync_admission_restricted` (ops tier) warns on a managed brain while the value is not `normal`, with its age and the user's restore command; ok otherwise. Never settable remotely (`config` refuses on a thin client and no operation writes config). Tests: `test/sync-admission-6712.test.ts`.
- `src/core/persistence/managed-sync-flags.ts` — `managedForbiddenFlag` / `managedSyncFlagRefusal`: the `managed_sync_flag_refused` refusal for `--skip-failed` / `--include-gitignored` on a managed source (#6696), raised at `gbrain sync` parse, in `maybeDelegateManagedSyncToServe` before the socket, and by `resolveManagedSyncContext`.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 86f8250ec1..44f7856dcd 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -3392,6 +3392,14 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
|---|---|---|---|---|---|---|
| Reading or writing durable storage failed. | Usually a dropped connection or a failed statement; the same error after a rerun is not transient. `detail: persistence_mode_unknown` (#6482): the persistence_brain singleton is missing, duplicated or carries a non-boolean `enabled`, so gbrain cannot tell whether the brain is managed and refuses every write, sync, connector run and activation step that depends on it rather than route a managed brain through the unmanaged writer; only a well-formed `enabled: false` row selects the unmanaged path. | For persistence_mode_unknown: run gbrain sources writer status --probe --json on the brain host (it reports the malformed state instead of refusing), fix the persistence_brain row it names, then gbrain doctor --json. | host_admin | `gbrain doctor --json` | 1 | no |
+### sync_admission_restricted
+
+<a id="sync_admission_restricted"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| `sync.admission` is not `normal`, so managed sync admits less than it classifies: `imports_only` admits no deletes and no keep_db writes (they wait as `paused_deletes` and `paused_keep_db`), and `classify_only` writes and stamps nothing. | The owner sets the switch on the brain host (`gbrain config set`; it is never settable remotely) as the first response to a suspected sync bug. A pass reads it at pin and in every group's admission, and a destructive request re-reads it at publication, so the change applies at the next group; `sync status --json` reports `admission: {value, set_at, effective}`, where `effective` turns true once no pass pinned before `set_at` holds the lease and no delete or keep_db reconcile admitted before it is unpublished. Doctor warns, with the value's age, for as long as it stays restricted. | Tell the user how long ago the switch was set and ask whether its reason still holds. Only they restore it: gbrain config set sync.admission normal on the brain host; the next sync admits what waited. Run: gbrain config set sync.admission normal | user | `gbrain doctor --only sync_admission_restricted --json` | 1 | no |
+
### sync_cursor_replaced
<a id="sync_cursor_replaced"></a>
diff --git a/src/commands/doctor/checks/sync-admission.ts b/src/commands/doctor/checks/sync-admission.ts
index c7c0a7242b..2ebc1e5368 100644
--- a/src/commands/doctor/checks/sync-admission.ts
+++ b/src/commands/doctor/checks/sync-admission.ts
@@ -10,33 +10,38 @@ import { checkError, doctorVerify } from '../check-fix.ts';
import { readManagedMode } from '../../../core/persistence/managed-mode.ts';
import { SYNC_ADMISSION_KEY, readSyncAdmissionSetting } from '../../../core/persistence/sync-admission.ts';
-const NAME = 'sync_admission_restricted';
const DOCS = 'docs/guides/error-codes.md#sync_admission_restricted';
const PAUSED = { imports_only: 'admits no deletes and no keep_db writes (those paths wait as paused_deletes and paused_keep_db; imports continue)',
classify_only: 'reads and classifies only: it writes and stamps nothing (stop admission_paused)' } as const;
async function runSyncAdmissionCheck(ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
try {
const engine = connectedEngine(ctx);
const setting = await readSyncAdmissionSetting(engine);
const ageSeconds = setting.set_at ? Math.max(0, Math.round((Date.now() - Date.parse(setting.set_at)) / 1000)) : null;
const details = { value: setting.value, stored: setting.stored, set_at: setting.set_at, age_seconds: ageSeconds, docs: DOCS };
- if (setting.value === 'normal') return [{ name: NAME, status: 'ok', message: `${SYNC_ADMISSION_KEY} is normal: managed sync admits everything it classifies.`, details }];
+ if (setting.value === 'normal') {
+ checks.push({ name: 'sync_admission_restricted', status: 'ok', message: `${SYNC_ADMISSION_KEY} is normal: managed sync admits everything it classifies.`, details });
+ return checks;
+ }
if (!await readManagedMode(engine)) {
- return [{ name: NAME, status: 'ok', severity: 'info', readiness_state: 'not_applicable', details,
- message: `${SYNC_ADMISSION_KEY} is ${setting.value}, but this brain is not managed, so no managed sync reads it.` }];
+ checks.push({ name: 'sync_admission_restricted', status: 'ok', severity: 'info', readiness_state: 'not_applicable', details,
+ message: `${SYNC_ADMISSION_KEY} is ${setting.value}, but this brain is not managed, so no managed sync reads it.` });
+ return checks;
}
const value = setting.value as keyof typeof PAUSED;
const stored = setting.stored !== value ? ` (the stored value ${JSON.stringify((setting.stored ?? '').slice(0, 40))} is not a value and reads as ${value}, fail closed)` : '';
const age = ageSeconds === null ? 'set at an unknown time' : `set ${formatAge(ageSeconds)} ago (${setting.set_at})`;
- return [{ name: NAME, status: 'warn', details,
+ checks.push({ name: 'sync_admission_restricted', status: 'warn', details,
message: `${SYNC_ADMISSION_KEY} is ${value}${stored}, ${age}: managed sync ${PAUSED[value]}. Ask the user whether the reason for restricting it still holds; `
+ `gbrain config set ${SYNC_ADMISSION_KEY} normal restores it, and the next sync admits what waited.`,
- fix: { argv: ['gbrain', 'config', 'set', SYNC_ADMISSION_KEY, 'normal'], consent: [], actor: 'user', requires_exclusive: false, verify: doctorVerify(NAME), docs: DOCS,
- why: `Restores the default, so managed sync admits deletes and keep_db writes again. The owner chose ${value}; only they restore it, and gbrain never runs this on its own.` } }];
+ fix: { argv: ['gbrain', 'config', 'set', SYNC_ADMISSION_KEY, 'normal'], consent: [], actor: 'user', requires_exclusive: false, verify: doctorVerify('sync_admission_restricted'), docs: DOCS,
+ why: `Restores the default, so managed sync admits deletes and keep_db writes again. The owner chose ${value}; only they restore it, and gbrain never runs this on its own.` } });
} catch (error) {
- return [checkError(NAME, 'read sync.admission', error, { details: { docs: DOCS } })];
+ checks.push(checkError('sync_admission_restricted', 'read sync.admission', error, { details: { docs: DOCS } }));
}
+ return checks;
}
function formatAge(seconds: number): string {
@@ -47,4 +52,4 @@ function formatAge(seconds: number): string {
}
/** An ops section: one config read and one checkpoint row, cheap on every engine. */
-export const syncAdmissionEntry: DoctorEntry = { name: NAME, emits: [NAME], tier: 'ops', run: runSyncAdmissionCheck };
+export const syncAdmissionEntry: DoctorEntry = { name: 'sync_admission_restricted', emits: ['sync_admission_restricted'], tier: 'ops', run: runSyncAdmissionCheck };
diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.json
index 41d70c6ef8..635f7d129c 100644
--- a/test/fixtures/goldens/doctor/content-pglite-human.json
+++ b/test/fixtures/goldens/doctor/content-pglite-human.json
@@ -57,6 +57,7 @@
" [OK] persistence_terminal_failures: No terminal write failures in the last 7 d.",
" [OK] managed_sync_not_moving: No managed sync is pending.",
" [OK] managed_sync_blocked: No managed sync run is blocked.",
+ " [OK] sync_admission_restricted: sync.admission is normal: managed sync admits everything it classifies.",
" [OK] persistence_compaction: Receipt compaction last ran 0 hour(s) ago (compacted 0, freed 0 bytes).",
" [INFO] sync_soak_counters: Last 7 days: 0 managed-sync intervention(s), 0 content decision(s).",
" [OK] serve_build_drift: PGLite admits one process; no consumer heartbeat rows are kept to compare builds.",
diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.json
index 17b4906bad..06a4c9f3d8 100644
--- a/test/fixtures/goldens/doctor/content-pglite-json.json
+++ b/test/fixtures/goldens/doctor/content-pglite-json.json
@@ -656,6 +656,20 @@
"name": "managed_sync_blocked",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "age_seconds": null,
+ "docs": "docs/guides/error-codes.md#sync_admission_restricted",
+ "set_at": null,
+ "stored": null,
+ "value": "normal"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "sync.admission is normal: managed sync admits everything it classifies.",
+ "name": "sync_admission_restricted",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
index 1e7c1212bc..8d4855bc94 100644
--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
@@ -657,6 +657,20 @@
"name": "managed_sync_blocked",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "age_seconds": null,
+ "docs": "docs/guides/error-codes.md#sync_admission_restricted",
+ "set_at": null,
+ "stored": null,
+ "value": "normal"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "sync.admission is normal: managed sync admits everything it classifies.",
+ "name": "sync_admission_restricted",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
@@ -4581,6 +4595,20 @@
"name": "managed_sync_blocked",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "age_seconds": null,
+ "docs": "docs/guides/error-codes.md#sync_admission_restricted",
+ "set_at": null,
+ "stored": null,
+ "value": "normal"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "sync.admission is normal: managed sync admits everything it classifies.",
+ "name": "sync_admission_restricted",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index db59d84b64..4d14de4721 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -638,6 +638,20 @@
"name": "managed_sync_blocked",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "age_seconds": null,
+ "docs": "docs/guides/error-codes.md#sync_admission_restricted",
+ "set_at": null,
+ "stored": null,
+ "value": "normal"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "sync.admission is normal: managed sync admits everything it classifies.",
+ "name": "sync_admission_restricted",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index bc7a7ae5ec..3212582a12 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -641,6 +641,20 @@
"name": "managed_sync_blocked",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "age_seconds": null,
+ "docs": "docs/guides/error-codes.md#sync_admission_restricted",
+ "set_at": null,
+ "stored": null,
+ "value": "normal"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "sync.admission is normal: managed sync admits everything it classifies.",
+ "name": "sync_admission_restricted",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 9b80a92bc6..474eff025b 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -269,6 +269,10 @@
"category": "ops",
"name": "managed_sync_blocked"
},
+ {
+ "category": "ops",
+ "name": "sync_admission_restricted"
+ },
{
"category": "ops",
"name": "persistence_compaction"
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 531694606d..d6267bc237 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6325,7 +6325,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"page_body_segmented\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"page_body_segmented\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_drain_lease_held\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/sync-admission-6712.test.ts b/test/sync-admission-6712.test.ts
new file mode 100644
index 0000000000..6a9d1f2140
--- /dev/null
+++ b/test/sync-admission-6712.test.ts
@@ -0,0 +1,197 @@
+/**
+ * #6712 PR 4b lane S (design v3.2 §8, probe 51 switch half): the `sync.admission` switch.
+ *
+ * Protects:
+ * - `config set sync.admission` refuses any value outside `normal | imports_only | classify_only` (exit 2, nothing
+ * written, `--force` included), and `config get` prints the value in effect (`normal` when unset);
+ * - each value is stored with its `set_at` (database clock) and a transaction's `readSyncAdmission` sees it;
+ * - `effective` is false while a pass pinned before `set_at` holds the live drain lease, or a destructive request
+ * (`managed_sync_delete`, `canonical_reconcile`) admitted before it is unpublished, and true after;
+ * - doctor `sync_admission_restricted` warns on a managed brain while the value is not `normal`, with its age and the
+ * restore command for the user, and is ok on `normal` and on a brain that is not managed;
+ * - `sync status` carries `admission`.
+ */
+import { afterAll, beforeAll, beforeEach, expect, spyOn, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runConfig } from '../src/commands/config.ts';
+import { readSyncAdmission, readSyncAdmissionSetting, syncAdmissionStatus, SYNC_ADMISSION_KEY, SYNC_ADMISSION_SET_OP } from '../src/core/persistence/sync-admission.ts';
+import { writePassRow, type ManagedSyncPassValue } from '../src/core/persistence/sync-pass-row.ts';
+import { readSyncStatus } from '../src/core/persistence/sync-status.ts';
+import { syncAdmissionEntry } from '../src/commands/doctor/checks/sync-admission.ts';
+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';
+import { cliRenderContext, renderAction, type Action } from '../src/core/agent-output.ts';
+import { syncLockId } from '../src/core/db-lock.ts';
+
+let engine: PGLiteEngine;
+let incarnation: string;
+const SOURCE = 'default';
+
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ incarnation = (await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [SOURCE]))[0]!.incarnation;
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => {
+ await engine.unsetConfig(SYNC_ADMISSION_KEY);
+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=ANY($1::text[])', [[SYNC_ADMISSION_SET_OP, 'managed-sync-pass']]);
+ await engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id=$1', [syncLockId(SOURCE)]);
+ await engine.executeRaw('DELETE FROM persistence_requests WHERE source_id=$1', [SOURCE]);
+});
+
+async function config(args: string[]) {
+ const logs: string[] = [], errs: string[] = [];
+ let exit: number | null = null;
+ const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { logs.push(a.join(' ')); });
+ const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errs.push(a.join(' ')); });
+ const writeSpy = spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => { errs.push(String(chunk)); return true; }) as never);
+ const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => { exit = code ?? 0; throw new Error(`EXIT:${code}`); }) as never);
+ try { await runConfig(engine, args); }
+ catch (e) { if (!(e as Error).message.startsWith('EXIT:')) throw e; }
+ finally { logSpy.mockRestore(); errSpy.mockRestore(); writeSpy.mockRestore(); exitSpy.mockRestore(); }
+ return { out: logs.join('\n'), err: errs.join('\n'), exit: exit as number | null };
+}
+
+function passValue(token: string, startedAt: string, outcome: ManagedSyncPassValue['telemetry']['outcome'] = 'open'): ManagedSyncPassValue {
+ return { source_id: SOURCE, incarnation, lease_token: token,
+ obligations: { baseline_commit: null, mismatch: {}, not_converged_streak: 0, faults: {} },
+ telemetry: { pass_id: randomUUID(), target: 'f'.repeat(40), started_at: startedAt, ended_at: outcome === 'open' ? null : new Date().toISOString(), kind: 'full', round: 1,
+ outcome, stop_reason: null, candidates: 3, settled: 0, remaining: 3, counts: {}, duration_ms: null, timings_ms: {} } };
+}
+async function pinPass(token: string, startedAt: string, outcome: ManagedSyncPassValue['telemetry']['outcome'] = 'open') {
+ await engine.transaction(tx => writePassRow(tx, passValue(token, startedAt, outcome), { pin: true }));
+}
+async function holdLease(token: string) {
+ await engine.executeRaw(`INSERT INTO gbrain_cycle_locks(id,holder_pid,holder_host,acquired_at,ttl_expires_at,last_refreshed_at,acquisition_token)
+ VALUES($1,4242,'host-example',now(),now()+interval '2 minutes',now(),$2::uuid)
+ ON CONFLICT (id) DO UPDATE SET acquisition_token=EXCLUDED.acquisition_token, ttl_expires_at=EXCLUDED.ttl_expires_at`, [syncLockId(SOURCE), token]);
+}
+async function admitRequest(kind: string, createdAgo: string): Promise<string> {
+ const id = randomUUID();
+ await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,authority,intent_bytes,terminal_reservation,
+ state,intent,created_at,updated_at)
+ VALUES('local_cli','fixture',$1::uuid,'submit_job',$2,$3::uuid,$4,$5,'{}'::jsonb,0,0,'queued',jsonb_build_object('kind',$6::text),now()-$7::interval,now())`,
+ [id, SOURCE, incarnation, `notes/alice-example-${id.slice(0, 8)}`, randomUUID(), kind, createdAgo]);
+ return id;
+}
+const status = () => syncAdmissionStatus(engine, SOURCE, incarnation);
+async function setManaged(enabled: boolean) {
+ await engine.transaction(async tx => {
+ await declarePersistenceProtocol(tx);
+ await tx.executeRaw("SELECT set_config('gbrain.writer_quiesced','true',true)");
+ await tx.executeRaw('UPDATE persistence_brain SET enabled=$1 WHERE singleton=1', [enabled]);
+ });
+}
+
+test('config set sync.admission refuses a value outside the three and writes nothing, --force included', async () => {
+ for (const args of [['set', SYNC_ADMISSION_KEY, 'off'], ['set', SYNC_ADMISSION_KEY, 'Normal'], ['set', SYNC_ADMISSION_KEY, 'hold_destructive', '--force']]) {
+ const refused = await config(args);
+ expect(refused.exit).toBe(2);
+ expect(refused.err).toContain('sync.admission is one of normal, imports_only, classify_only');
+ expect(refused.err).toContain('Nothing was written');
+ expect(await engine.getConfig(SYNC_ADMISSION_KEY)).toBeNull();
+ }
+ const got = await config(['get', SYNC_ADMISSION_KEY]);
+ expect(got.exit).toBeNull();
+ expect(got.out).toBe('normal');
+ expect(got.err).toContain('default (unset)');
+});
+
+test('each value is stored with its set_at; a transaction reads it; config get prints the value in effect', async () => {
+ for (const value of ['imports_only', 'classify_only', 'normal'] as const) {
+ const [{ before }] = await engine.executeRaw<{ before: string }>('SELECT clock_timestamp()::text AS before');
+ const set = await config(['set', SYNC_ADMISSION_KEY, value]);
+ expect(set.exit).toBeNull();
+ expect(set.out).toContain(`Set sync.admission = ${value}`);
+ expect(await engine.transaction(tx => readSyncAdmission(tx))).toBe(value);
+ const setting = await readSyncAdmissionSetting(engine);
+ expect(setting).toMatchObject({ value, stored: value });
+ expect(Date.parse(setting.set_at!)).toBeGreaterThanOrEqual(Date.parse(before) - 1);
+ const got = await config(['get', SYNC_ADMISSION_KEY]);
+ expect(got.out).toBe(value);
+ expect(got.err).toContain(`set at ${setting.set_at}`);
+ }
+ await engine.setConfig(SYNC_ADMISSION_KEY, 'junk');
+ expect(await readSyncAdmissionSetting(engine)).toMatchObject({ value: 'classify_only', stored: 'junk', set_at: null });
+ const got = await config(['get', SYNC_ADMISSION_KEY]);
+ expect(got.out).toBe('classify_only');
+ expect(got.err).toContain('fail closed');
+});
+
+test('effective waits for a pass pinned before set_at that holds the lease, and turns true when it ends or loses the lease', async () => {
+ const token = randomUUID();
+ await pinPass(token, new Date(Date.now() - 60_000).toISOString());
+ await holdLease(token);
+ expect((await config(['set', SYNC_ADMISSION_KEY, 'imports_only'])).exit).toBeNull();
+ expect(await status()).toMatchObject({ value: 'imports_only', effective: false });
+ await pinPass(token, new Date(Date.now() - 60_000).toISOString(), 'synced');
+ expect((await status()).effective).toBe(true);
+ await pinPass(token, new Date(Date.now() - 60_000).toISOString());
+ expect((await status()).effective).toBe(false);
+ await engine.executeRaw("UPDATE gbrain_cycle_locks SET ttl_expires_at=now()-interval '1 second' WHERE id=$1", [syncLockId(SOURCE)]);
+ expect((await status()).effective).toBe(true);
+ await holdLease(randomUUID());
+ expect((await status()).effective).toBe(true);
+ const next = randomUUID();
+ await holdLease(next);
+ await pinPass(next, new Date(Date.parse((await readSyncAdmissionSetting(engine)).set_at!) + 1000).toISOString());
+ expect((await status()).effective).toBe(true);
+ await pinPass(next, new Date(Date.now() - 60_000).toISOString());
+ expect((await config(['set', SYNC_ADMISSION_KEY, 'classify_only'])).exit).toBeNull();
+ expect((await status()).effective).toBe(false);
+ expect((await config(['set', SYNC_ADMISSION_KEY, 'normal'])).exit).toBeNull();
+ expect(await status()).toMatchObject({ value: 'normal', effective: true });
+});
+
+test('effective waits for a destructive request admitted before set_at until it is published', async () => {
+ const del = await admitRequest('managed_sync_delete', '1 minute');
+ const reconcile = await admitRequest('canonical_reconcile', '1 minute');
+ await admitRequest('managed_sync_import', '1 minute');
+ expect((await config(['set', SYNC_ADMISSION_KEY, 'imports_only'])).exit).toBeNull();
+ expect((await status()).effective).toBe(false);
+ await engine.executeRaw("UPDATE persistence_requests SET state='running' WHERE request_id=$1::uuid", [del]);
+ await engine.executeRaw("UPDATE persistence_requests SET state='committed', completed_at=now() WHERE request_id=$1::uuid", [reconcile]);
+ expect((await status()).effective).toBe(false);
+ await engine.executeRaw("UPDATE persistence_requests SET state='cancelled', completed_at=now() WHERE request_id=$1::uuid", [del]);
+ expect((await status()).effective).toBe(true);
+ await admitRequest('managed_sync_delete', '0 seconds');
+ expect((await status()).effective).toBe(true);
+ await admitRequest('managed_sync_delete', '1 minute');
+ expect((await status()).effective).toBe(false);
+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1', [SYNC_ADMISSION_SET_OP]);
+ expect(await status()).toMatchObject({ value: 'imports_only', set_at: null, effective: false });
+});
+
+test('doctor sync_admission_restricted warns on a managed brain while not normal, and is ok on normal and on a brain that is not managed', async () => {
+ const ctx = { engine, progress: { heartbeat: () => {} } } as never;
+ expect(await syncAdmissionEntry.run(ctx)).toMatchObject([{ name: 'sync_admission_restricted', status: 'ok' }]);
+ expect((await config(['set', SYNC_ADMISSION_KEY, 'imports_only'])).exit).toBeNull();
+ expect(await syncAdmissionEntry.run(ctx)).toMatchObject([{ name: 'sync_admission_restricted', status: 'ok', severity: 'info', readiness_state: 'not_applicable' }]);
+ await setManaged(true);
+ try {
+ for (const value of ['imports_only', 'classify_only'] as const) {
+ expect((await config(['set', SYNC_ADMISSION_KEY, value])).exit).toBeNull();
+ const checks = await syncAdmissionEntry.run(ctx);
+ if (!Array.isArray(checks)) throw new Error('sync_admission_restricted returned no checks');
+ const [check] = checks;
+ expect(check).toMatchObject({ name: 'sync_admission_restricted', status: 'warn', details: { value, age_seconds: expect.any(Number) },
+ fix: { argv: ['gbrain', 'config', 'set', 'sync.admission', 'normal'], actor: 'user' } });
+ expect(check!.message).toContain(`sync.admission is ${value}, set `);
+ expect(check!.message).toContain(' ago (');
+ expect(check!.message).toContain('gbrain config set sync.admission normal');
+ expect(renderAction(check!.fix as Action, cliRenderContext()).next).toBe('tell_user_to_run');
+ }
+ expect((await config(['set', SYNC_ADMISSION_KEY, 'normal'])).exit).toBeNull();
+ expect(await syncAdmissionEntry.run(ctx)).toMatchObject([{ name: 'sync_admission_restricted', status: 'ok' }]);
+ } finally {
+ await setManaged(false);
+ }
+});
+
+test('sync status carries admission', async () => {
+ expect((await readSyncStatus(engine, SOURCE, { detail: false })).admission).toEqual({ value: 'normal', set_at: null, effective: true });
+ expect((await config(['set', SYNC_ADMISSION_KEY, 'classify_only'])).exit).toBeNull();
+ const { admission } = await readSyncStatus(engine, SOURCE, { detail: false });
+ expect(admission).toMatchObject({ value: 'classify_only', effective: true });
+ expect(admission.set_at).toBe((await readSyncAdmissionSetting(engine)).set_at);
+});