Contract for unidirectional monorepo-path → GitHub infrastructure
(plan-20260916). This file is created by GS-14 and extended by later cards.
Three scripts share one exit-code contract: 0 pass, 1 decision failure
(out of allowlist / dangling doc ref), 2 command or input error. Guard
output prints paths and verdicts only — never file contents (ER-11).
Saves a content-plus-metadata baseline for every dirty path reported by
libra status --short (XY path). Only a status column containing R
splits old -> new into two paths; a literal -> in any other status
is one path. C-quoted paths ("…\nnn…", including \") are decoded
before fingerprinting. A decoded path that contains a tab or newline is
unrepresentable in the line format and exits 2. Output is sorted by
the decoded path. Each line is:
<kind>|<mode>|<fingerprint> <path>
| kind | mode | fingerprint |
|---|---|---|
file |
octal permission (stat -c '%a') |
SHA-256 of file bytes |
symlink |
- |
readlink target |
absent |
- |
- |
unsupported |
- |
- (directory, FIFO, device, …) |
libra status, sha256sum, stat, readlink, sort, or writing
<out> failing makes the script exit 2. Isolated fixtures:
tests/fixtures/guard/run_baseline_shape_cases.sh and
run_baseline_failure_cases.sh.
Compares the union of baseline paths and current dirty paths. Allowed
paths may change. Any other path whose current fingerprint differs from
the baseline exits 1. Rename source and destination are judged
separately. kind=unsupported is always out of allowlist, even when the
path was passed as allowed. Missing baseline, empty allowlist, usage
error, or tool failure (libra / sha256sum / stat / readlink /
grep / sort) exits 2. Isolated fixtures:
tests/fixtures/guard/run_allowlist_cases.sh and
run_allowlist_failure_cases.sh.
A baseline or live symlink record whose target contains two consecutive
spaces is ambiguous in the line format and exits 2.
Callers must pass that card’s exact product paths — never a wide
directory such as docs.
Extracts references matching docs/ plus ASCII letters, digits, _,
., /, -, then .md, using rg -o --no-filename (no multi-file
prefixes; globs, placeholders, and CJK punctuation are not path
characters). Dangling refs exit 1. Empty match set is success (0).
rg exit >1, sort failure, missing input, or no arguments exit
2. Isolated fixtures:
tests/fixtures/guard/run_docrefs_cases.sh and
run_docrefs_failure_cases.sh.
[github_sync] is a first-class Config field (GS-03). The section is
optional: omitting it loads GithubSyncConfig::default(), which has
enabled = false and empty strings / no bindings. ssh_key_ref is a
string path only — this card does not resolve secrets.
| Type | Fields |
|---|---|
GithubSyncConfig |
enabled, ssh_host, ssh_user, ssh_host_key, ssh_key_ref, bindings |
GithubSyncBinding |
id, path, remote |
Whitelist (github_sync / github_sync.bindings), restart-required
reload classification, commented config/config.toml plus config init
template, and bilingual README links are GS-23. Binding-entry checks
remain GS-13. No runtime sync runs from this schema.
Startup Config::validate rejects combinations that cannot run
(plan-20260916 GS-04). enabled=false still parses and namespace-checks
a non-empty ssh_key_ref; vault values are not resolved (GS-05).
| When | Rejected if |
|---|---|
enabled=true |
git.push_auth is unset |
enabled=true |
bindings is empty |
enabled=true |
monorepo.object_format is not sha1 |
enabled=true |
ssh_host_key is empty |
enabled=true |
ssh_key_ref fails validate_config_secret_ref under config/<profile>/github_sync/ssh_key |
enabled=false |
non-empty ssh_key_ref fails SecretRef parse or the same namespace |
Error text names the field or gate; it never echoes the ssh_key_ref URI.
Startup Config::validate checks every [github_sync.bindings] row
(plan-20260916 GS-13). Duplicate diagnostics name both 1-based indexes.
| Field | Rejected if |
|---|---|
id |
not 1..32 characters of [A-Za-z0-9_-], or not unique |
path |
not a canonical absolute path (., .., //, trailing /) |
path |
not under /project by component boundary (/projectX fails) |
path |
equal to monorepo.import_dir or under it (import_dir compared after normalizing . / ..) |
path |
not unique |
remote |
not <owner>/<repo> with each side ^[A-Za-z0-9_-][A-Za-z0-9_.-]*$ and not . / .. |
remote |
not unique |
Startup AppContext loads or generates one Ed25519 SSH key when
[github_sync] enabled=true (plan-20260916 GS-05). The private key is
stored in OpenSSH format at ssh_key_ref and held in process memory.
| When | Behavior |
|---|---|
enabled=true, vault has no key |
generate Ed25519, write OpenSSH private key, hold |
enabled=true, vault already has a key |
load it, do not overwrite, hold |
enabled=false |
do not generate, do not write vault |
Algorithm is Ed25519 only. Deleting the vault entry and restarting generates a new key (public key differs).
When [github_sync] enabled=true and the vault entry is missing, startup
takes a Redis RedLock (mega2:github_sync:ssh_key:init, same mechanism
as ensure_server_signing_key) before generating. The vault value is
re-read inside the lock so concurrent replicas converge on one key.
| When | Behavior |
|---|---|
| vault already has a valid key | load it on the fast path; no lock |
| vault has no key | acquire RedLock, re-read, generate only if still missing |
| vault read or write error | fail closed; do not install a process hold |
| vault value is present but not a valid OpenSSH Ed25519 key | fail closed; do not overwrite |
If the lock is lost (TTL expiry or Redis partition) while a replica is still generating, a second replica may also generate. The last writer wins; a process hold may then diverge from vault until restart. This window is not closed here (vault has no compare-and-set). The close is the GS-28 「原子写入冻结(Q8)」 scheme. The operator repair is: stop every replica, delete the vault entry, restart one replica to bootstrap, start the rest, replace the GitHub machine-account key with the new public key.
When [github_sync] enabled=true, startup logs the OpenSSH public key
as a paste-ready line. The private key is not written to logs, error
text, or Debug.
| Branch | Log |
|---|---|
| generated | machine-readable github_sync_ssh_key_generated / 「生成」; full ssh-ed25519 … mega2-github-sync line; hint to add the key to the GitHub machine account |
| loaded | machine-readable github_sync_ssh_key_loaded / 「载入」; the same public-key line as generation |
- Set
enabled=trueand start one replica. - Copy the
ssh-ed25519 AAAA… mega2-github-syncline from the startup log. - Add that public key to the GitHub machine account.
- Further replicas load the same vault key and log the same public line.
Outbound SSH reads the process hold from GS-05, connects to
[github_sync].ssh_host / ssh_user, and authenticates with that
Ed25519 key. ssh_host is host or host:port (default port 22).
The server host key is compared to ssh_host_key as OpenSSH public-key
bytes (exact trimmed encoding, or the parsed key-material bytes when the
configured line carries a comment). A mismatch, an unparseable pin, or a
certificate host key aborts before public-key authentication.
Non-Ed25519 client keys are rejected with an actionable auth error.
Failures carry stage=ssh_connect|host_key|auth. The TCP plus handshake
plus public-key authentication budget is 15 seconds; a timeout is
ssh_connect, not an unbounded wait. The russh session also has a 15
second inactivity bound so a cancelled or stalled handshake cannot leak
a background task or socket.
Loopback evidence is tests/integration_github_sync.rs
(ssh_connect_authenticates). Production GitHub live is covered by
plan-20260920 OX-06 (was DEFER-GS-08, now in-scope; layer A′).
After the SSH session is authenticated, github_sync runs
git-receive-pack '<owner>/<repo>.git' (single-quoted; a remote that
contains ' is rejected). The advertisement is parsed as pkt-lines
until flush. refs/heads/main becomes the remote tip; if that ref is
absent the tip is 40 zero hex digits. Capabilities are taken from the
NUL-terminated first ref line.
report-status is required. If it is missing, the client aborts with an
error that names report-status and writes no command or pack bytes.
Loopback evidence is loopback_advertise. Command construction and pack
write are GS-24. Production GitHub live is covered by
plan-20260920 OX-06 (was DEFER-GS-08, now in-scope; layer A′).
After the advertisement is accepted, the client writes one receive-pack command pkt-line and a flush, then streams the packfile.
The command payload is
<old> <new> refs/heads/main\0 <capabilities> — NUL, then a leading
space before the capability list, and no trailing LF. The pkt-line
is followed immediately by 0000.
report-status is always requested (GS-08 already required it).
side-band-64k is requested only when the advertisement declared it;
otherwise the write result sets missing_sideband. Pack bytes are
written in at most 16 KiB windows; a larger caller chunk is split. Live
residency is the command frame plus one window, not the full pack.
Loopback evidence is loopback_receive_pack. Report-status termination
is GS-15.
Success requires all three of unpack ok, ok refs/heads/main, and a
terminating flush. ng refs/heads/main <reason> is a ref rejection and
keeps the reason string. unpack <error> that is not ok is
report_unpack and keeps the server error text. A missing or
half-finished report is report_incomplete. A closed connection before
flush is report_disconnect. Side-band channel 3 is report_fatal and
stops without waiting for later report lines.
When side-band-64k is negotiated, channel 1 carries the inner
pkt-line report-status stream and may split a pkt-line across
packets. Channel 2 is collected into the diagnostic budget. Channel 3
is fatal immediately and also counts toward that budget. An outer
multiplex flush without a complete inner report is
report_incomplete, not a disconnect.
SSH transport termination is below. Deadlines are GS-20. Diagnostic byte budgets are in 「诊断容量边界」.
SSH stderr (SSH_EXTENDED_DATA_STDERR, RFC 4254 type code 1) is
collected into diagnostics as ssh_stderr. Any exit-signal is
ssh_exit_signal. A non-zero exit-status is ssh_exit_status. Both
of those failures outrank a complete successful report-status.
Report-layer failure (including side-band channel 3 fatal) returns
immediately. Exit events are recorded and the reader keeps draining
stdout until EOF/close, because OpenSSH may send exit-status before
the last report bytes.
Final success is report-layer success plus an explicit exit-status = 0.
EOF or close without exit-status is ssh_exit_missing and is never
success; the wait is bounded by the exit deadline below.
Four independent receive-pack deadlines live on [github_sync]:
| Field | Default | Stage on expiry |
|---|---|---|
advertise_timeout_seconds |
30 | advertise |
send_timeout_seconds |
300 | send |
report_timeout_seconds |
60 | report |
exit_timeout_seconds |
15 | report |
Each expiry cancels the in-flight future, marks the receive-pack
aborted, and shuts down the SSH TCP socket (SO_LINGER 0 + close/RST)
so queued writes cannot resume when the peer reads again. The SSH
session inactivity bound is at least the max of these four fields
(and the 15s connect timeout); connect itself is still cancelled at
15s and aborts the TCP fd so a failed handshake cannot leak.
exit_timeout_seconds starts when report-status parses successfully
or stdout closes, then covers the SSH exit-status/exit-signal wait
and any remaining stdout drain. Zero is rejected at config validate.
Diagnostic byte budgets are in 「诊断容量边界」.
[github_sync].diagnostic_budget_bytes (default 4096) is the single
cap for receive-pack diagnostic output: side-band channel 2, side-band
channel 3, and SSH stderr. Values below 9 (the complete truncated
marker) are rejected at validate. The field is restart-required.
Side-band channel 2/3 payloads are counted and discarded after the
sink; they are not retained on the report buffer. Channel 3 and SSH
stderr take priority over channel 2 when the cap is full.
Collection stops at the cap. Overflow truncates on a UTF-8 character
boundary (no illegal fragment) and appends the truncated marker
(计划 AC-5「已截断」). Non-UTF-8 remote bytes are shown with U+FFFD
so ASCII around them survives (GS-15 / GS-25). Rendered diagnostic
bytes stay within the configured cap.
Spike GS-09. Freezes outbound sync semantics only. No production
code in this card. Pack error channels (Q6a), pack budget / have
hardening (Q6b), operator authorization (Q7), and atomic storage
primitives (Q8) stay on later spikes. DEP-03 (full outbound draft)
was not found as a file in this tree; the schemes below are derived
from the plan-20260916 fact baseline and the cited code.
A trunk B3 push is one transaction that already mutates more than the pushed path:
| Kind | What B3 writes | Evidence |
|---|---|---|
| Path upsert | main@P → landed_at_p |
apply_push_in_txn (mono_api_service.rs:3741–:3750) |
| Ancestor roll-up | each ancestor whose tree hash changed gets a new synthesized commit; unchanged ancestors are skipped | :3756–:3788 |
| Root CAS | / advances or does a net-zero same-value write |
:3791–:3836 |
| Descendant continuation | already-materialized descendant main refs |
push_queue_service.rs:2115–:2126; advance_descendant_refs (mono_storage.rs:631) |
| Descendant delete | a descendant main ref is tombstoned and removed when its relative path is gone from the new tree |
DescendantResolve::Delete → tombstone_and_delete_main_ref_in_txn (mono_storage.rs:735–:737, :763–:769; called from push_queue_service.rs:2115–:2126) |
| Failure / bypass | apply is rolled back; BypassDetected commits the Failed queue row and notify_mono_write_queue, not the apply |
push_queue_service.rs:2087–:2102; authz precedent notify.rs:164–:174 |
Scheme. After those writes, still inside the same B3 transaction
and only if the apply succeeded, enumerate a change set of
(path, old_oid, new_oid, kind):
upsert—Pand every ancestor that received a new commit.advance— every descendant whosemainref moved.delete— every descendant that B3 resolved asDescendantResolve::Delete(the pathmainref was tombstoned and removed in this transaction). The pushed pathPitself is not deleted by B3 apply; a client receive-pack delete ofrefs/heads/mainis refused (monorepo.rs:913–:925,MEGA_BRANCH_NAME). Tombstone repair / reaper deletes outside a successful B3 apply are not sync-outbox events (Q1 only fires after a successful apply in that same transaction).- Skip net-zero rows (ancestor tree hash unchanged; root CAS same-value write).
Intersect the change set with [github_sync].bindings by exact
binding.path (ADR-GS-01: one path ↔ one remote; no implicit
prefix fan-out). Each hit inserts one sync-outbox row
(binding_id, remote, kind, local_oid, queue_id) in that same
transaction — the same shape as insert_authz_outbox
(push_queue_storage.rs:1278–:1286). BypassDetected and apply
failure must not insert sync rows. Root / is not a binding path.
local_oid is always the new ref commit at that binding's exact
path, not a single queue-wide id:
upsert/advance: the newmaincommit written for that path. When the binding path is the pushed pathPandN=1, that equals the clientnew_id(docs/refactoring/trunk-push.md:429;api_tip_lander.rs:119–:120). WhenN>1onP, it isP's squash / synthesized commit (push_queue.landed_commit_idnames onlyP). Ancestor and descendant rows use their own synthesized commits fromother_updates/advance_descendant_refs.delete: there is no landed commit.local_oidis the all-zero object id of the repository hash kind (40 hex zeros for sha1; 64 for sha256/blake3).old_oidon the change-set row is the pathmaincommit that was just removed. Outbound receive-pack isold=last_pushed(must equal advertise),new=zeros,refs/heads/main— a Git delete ofmain. If GitHubngs deleting the default branch, the binding parks with that reason (GS-15); an empty-tree replacement is a GS-10 alternative, not this freeze. First-create in Q5 is the inverse (old=zeros,new=local_oid).
Implementation note (plan-20260920 OX-67, OX-68, OX-182, OX-229, OX-11): Forward-only
migration m20261129_000200_github_sync_outbox creates
github_sync_outbox (row_id BIGSERIAL PRIMARY KEY, queue_id BIGINT NOT NULL, binding_id TEXT NOT NULL, payload BYTEA NOT NULL, completed_at TIMESTAMPTZ NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), UNIQUE (queue_id, binding_id))
and SeaORM entity src/callisto/github_sync_outbox.rs. Monotonic
row_id commit ordering relies on B3 MONO_WRITE_LOCK serializing
the emitting transactions. BindingIdentitySnapshot freezes the
creation-time binding.path, binding.remote, and canonical SHA-256
config_identity inside the serialized payload, so restart/retry
never recomputes old row identity from reloaded configuration.
OutboxRowCandidate and closed OutboxEventKind (upsert /
advance / delete) pair that frozen identity with old_oid and
new_oid, and OutboxRowCandidate::validate(hash_kind) enforces
hash-kind width, lowercase hex encoding, and create/delete zero-OID
boundaries before producing a ValidatedOutboxRow for SQL insert
via GithubSyncOutboxStorage::insert_in_txn (src/jupiter/storage/github_sync_outbox.rs),
which deduplicates only on full frozen payload equality and returns
OutboxStorageError::IdentityConflict on any field mismatch.
Additive migration m20261129_000300_github_sync_outbox_fifo_lease
(OX-179) appends nullable lease_owner TEXT, nullable
lease_expires_at TIMESTAMPTZ, and FIFO index
idx_github_sync_outbox_binding_fifo ON github_sync_outbox (binding_id, row_id).
GithubSyncOutboxStorage::claim_next_fifo (OX-34) claims the oldest
uncompleted row per binding (ORDER BY row_id ASC LIMIT 1 FOR UPDATE SKIP LOCKED),
commits before returning ClaimedOutboxRow so no SQL lock is held across
network I/O, never leapfrogs an active head lease, and preserves each row's
frozen remote and config_identity. GithubSyncOutboxStorage::complete_if_token
(OX-186) performs a single-statement SQL compare-and-set
(WHERE row_id = $1 AND lease_owner = $2 AND completed_at IS NULL) so an
expired holder cannot mark a row completed or alter the new holder's lease
after takeover. Inside B3 b3_execute_push_inner, OX-10 freezes the exact
configured [github_sync].bindings set once per round (FrozenGithubSyncBindings)
and samples each path's pre-apply native refs/heads/main (is_cl = false) via
get_native_main_ref_in_txn inside the MONO_WRITE_LOCK transaction prior to
apply_push_in_txn. OX-183 reuses that exact frozen binding set inside
the same B3 transaction to sample the post-apply native refs/heads/main
snapshot immediately after advance_descendant_refs_with and before
mark_done_if_running_in_txn. OX-43 adds classify_github_sync_upserts
to classify exact-match bindings on pushed path P and changed ancestors as
OutboxEventKind::Upsert using each path's own post-snapshot OID while
skipping net-zero paths, siblings, partial prefixes, and descendants.
OX-152 adds classify_github_sync_descendant_advances to classify
already-materialized strict descendants whose native main advanced as
OutboxEventKind::Advance with each descendant's own post-snapshot OID,
excluding unmaterialized, net-zero, deleted, and non-descendant paths.
OX-184 updates MonoStorage::advance_descendant_refs_with to return a
same-transaction DescendantAdvanceReport carrying DeletedDescendantProvenance
(path, pre-delete native old_oid) populated strictly after
tombstone_and_delete_main_ref_in_txn succeeds inside the
DescendantResolve::Delete branch (excluding pushed path P, changed/unchanged
descendants, and out-of-band repair/reaper deletes). OX-69 adds
classify_github_sync_descendant_deletes and classify_github_sync_change_set:
a Delete outbox candidate is emitted only when exact binding.path has
explicit OX-184 provenance, pre-snapshot Some(old_oid) matching provenance,
and post-snapshot None, with new_oid equal to the repository hash-kind
all-zero OID. OX-185 wraps the classified rows in a read-only
EligibleChangeSet gate constructed strictly inside b3_execute_push_inner
on the n > 0 path after apply_push_in_txn and advance_descendant_refs_with
both succeed and before mark_done_if_running_in_txn. OX-35 consumes that
EligibleChangeSet inside the exact same B3 transaction via
emit_eligible_github_sync_outbox_in_txn → GithubSyncOutboxStorage::insert_in_txn
before mark_done_if_running_in_txn: any outbox insert error or IdentityConflict
aborts the transaction (rolling back ref writes, mark_done, and earlier outbox
rows), and a mark_done claim-loss rollback likewise discards the uncommitted
outbox rows.
incremental_pack stops walking parents once a parent id is in
have, then excludes every object reachable from those have
commits' trees (monorepo.rs:521–:566). That is only a correct
thin pack if the GitHub repo still holds that closure.
Scheme. have=[last_pushed] is legal for a binding if and only if
all of:
last_pushedis either thenewoid of the last receive-pack this binding recorded as success (GS-15/GS-25/GS-20/GS-26:unpack ok+ok refs/heads/main+exit-status=0) or an operator cursor-reset that Q3 already required to equal the current advertisement (so it is a proven remote tip, just not one this process created).- The current advertisement tip for
refs/heads/mainequalslast_pushed. last_pushedstill exists in local object storage.binding.remotehas not changed since that success.
Advertisement tip equality is the only SSH-visible proof that GitHub
still has the object (ADR-GS-03: no REST; DEFER-GS-02: no fetch).
Any of: tip ≠ last_pushed, missing local object, empty repo (40
zero hex), or a remote string change invalidates the cursor.
Invalid → have=[] (full pack) and do not reuse the old cursor after
success until a new tip is recorded. Pack error-channel and byte
budget remain GS-18 / GS-27.
Expected local tip = the binding path's current main commit
(local_oid from Q1). Expected remote tip for a push attempt =
last_pushed, which must equal the advertisement.
Divergence = advertised refs/heads/main ≠ last_pushed.
mega2 cannot prove that a GitHub-side merge (human or AI) contains our
content: there is no merge-base, no 2-parent commit, and no inbound
fetch (ADR-GS-04; push_chain.rs rejects merge commits;
DEFER-GS-02). A third oid on GitHub is therefore not a resume
signal.
Scheme.
- Divergence parks the binding: no receive-pack.
- Divergence clears only when the advertisement equals
last_pushedagain (they reset to our last success) or an operator cursor-reset is applied only after the advertisement already equalslocal_oid(they made GitHub match us out of band). Who may invoke that reset is GS-21 Q7; this card only freezes the cursor predicate. - Both sides' expected tips are the two oids above; validation is
advertise ==
last_pushedimmediately before send (Q4). - GitHub-side merge that produces a new tip stays parked. Automatic
resume is never a force. Operator
force/cursor_resetare Q7; implementation isplan-20260920OX-03. Inbound merge staysDEFER-GS-02.
A successful receive-pack updates GitHub before the local cursor
row. A poller that only compares advertise ≠ last_pushed would
treat our own in-flight tip as a remote edit.
Scheme. Persist an intent row before sending:
last_pushed— last proven success (immutable on the success path until CAS).in_flight—(new_oid, remote_old)written before the command/pack; cleared only after the cursor CAS.
Implementation note (plan-20260920 OX-70, OX-153): Forward-only migration
m20261129_000400_github_sync_cursor creates the base cursor table
github_sync_cursor (binding_id TEXT PRIMARY KEY, path TEXT NOT NULL, remote TEXT NOT NULL, last_pushed TEXT NULL, generation BIGINT NOT NULL DEFAULT 0, state TEXT NOT NULL DEFAULT 'idle', park_reason TEXT NULL, updated_at TIMESTAMPTZ NOT NULL DEFAULT now())
and SeaORM entity src/callisto/github_sync_cursor.rs. Forward-only additive
migration m20261129_000500_github_sync_intent (OX-153) appends nullable
config_identity, in_flight_new_oid, in_flight_remote_old, and
in_flight_outbox_row_id to github_sync_cursor while preserving existing
last_pushed and generation rows, and adds github_sync_intent (keyed by
(binding_id, remote, local_oid, remote_old)) so completed intent records
retain their original remote_old across subsequent last_pushed updates.
GithubSyncCursorStorage::prepare_in_flight_intent (OX-71,
src/jupiter/storage/github_sync_cursor.rs) compares the exact 4-tuple
(binding_id, remote, local_oid, remote_old), commits durably before returning
(never gating SSH send on uncommitted memory), replays identically on matching
4-tuples, and returns CursorStorageError::InFlightConflict without overwriting
an active differing in_flight. GithubSyncCursorStorage::issue_cas_permit_in_txn
(OX-189) performs a strictly read-only in-transaction verification of
expected_last_pushed, full 4-tuple in_flight identity, expected_generation,
and OX-186 active lease_owner token (GithubSyncOutboxStorage::verify_active_lease_in_txn),
returning a transaction-scoped CursorCasPermit<'txn> verified against the
issuing &DatabaseTransaction and Postgres (pg_backend_pid, virtualxid).
GithubSyncCursorStorage::complete_push_with_permit_in_txn / complete_push_atomic
(OX-14) consumes that same-transaction permit to atomically advance
last_pushed, clear in_flight_*, increment generation, mark the outbox row
completed via OX-186 complete_if_token, and finalize github_sync_intent
(status = 'completed') while preserving original remote_old; any failure in
cursor or outbox completion rolls back the entire transaction.
classify_cursor_recovery, park_binding, self_complete_in_flight, and
reconcile_before_send (OX-36) implement Q3/Q4/Q5 divergence & crash
recovery: advertise == in_flight.new_oid self-completes without resending,
first-create (remote_old == zeros) crash before accept retries create without
ever deleting remote main, third remote OID parks without sending, and
path/remote changes park and stay parked.
PackBridge / BoundedPackIterator (OX-49, src/ceres/github_sync/pack_bridge.rs)
bridges Q6a ReportedPackStream (async Stream<Result<Bytes, PackStreamError>>)
to a synchronous iterator over a bounded 64×16 KiB (1 MiB) channel consumed
strictly inside spawn_blocking, preserving terminal PackStreamError separately
from CleanEof and cancelling + joining upstream OX-33 tasks on early close.
ReceivePack::write_bridged_pack (OX-72, src/ceres/github_sync/send_pack.rs)
and worker::send_reported_pack / send_reported_stream (src/ceres/github_sync/worker.rs)
consume that bounded iterator inside spawn_blocking, send SSH eof and read
report-status strictly on CleanEof, abort receive-pack without reading a
report on terminal PackStreamError (returned verbatim via
ReceivePackBridgeError::PackStream), and on transport/deadline abort cancel
the bridge and bounded-join upstream OX-33 producer/encoder tasks.
worker::select_proven_have_base / resolve_proven_have_base (OX-73)
enforces the Q2 have=[C] predicate: selects incremental have=[C] only when
cursor.last_pushed == Some(C) (non-zero), cursor.remote == current_remote,
advertised_main_tip == C, and C exists locally, falling back to have=[]
otherwise. worker::evaluate_pre_send_fence (OX-74) checks generation,
path, remote, config_identity, and advertised_main_tip == in_flight.remote_old
immediately before write_pack, refusing stale preflight generations and
parking via OX-36 park_binding on any identity mismatch or third remote OID.
GithubSyncWorker (OX-01, src/ceres/github_sync/worker.rs, injected passively
into AppContext) orchestrates FIFO OX-34 claim → SSH advertise → durable
OX-71 in_flight prepare → OX-74 pre-send fence → OX-73 proven have
selection → Monorepo::incremental_pack_reported over OX-72 bridge → full
GS-15 report check → atomic OX-14/OX-186 cursor + outbox CAS. For
OutboxEventKind::Delete (OX-44), GithubSyncWorker sends a packless Git
delete (old=remote_old, new=zeros, zero pack bytes) without building a pack
and parks the binding via OX-36 if GitHub rejects deleting refs/heads/main
with report_ng (leaving cursor last_pushed and outbox uncompleted).
GithubSyncWorker::replay_once_all_bindings (OX-25) replays persisted pending
outbox rows across configured bindings after crashes (preserving first-create
remote_old = zeros without ever sending a remote main delete compensation,
and self-completing crash-after-accept intents via OX-36 with zero commands).
The background loop starts exclusively at the HTTP service startup boundary
(http_server::spawn_github_sync_worker_task, OX-47), leaving AppContext::new
passive and bounded-joining all worker/pack child tasks on graceful shutdown.
For operator aborts (OX-26), GithubSyncWorker maintains a per-binding
cancellation handle (cancel_binding / operator_abort_binding) paired with
cancellation-aware ReceivePack::write_bridged_pack_cancellable and
read_report_cancellable (boundedly aborting blocked SSH I/O, dropping
ReportedPackStream, and joining OX-33 child tasks), observes cross-replica
generation increments via GithubSyncCursorStorage::current_generation /
operator_abort_park (preventing stale-generation CAS from overwriting a newer
park), and preserves in_flight_* across operator_abort so an abort-vs-accept
race still self-completes via OX-36 when remote advertises in_flight.new_oid.
Poller classification:
| Advertised tip | Meaning |
|---|---|
last_pushed |
idle, not modified |
in_flight.new_oid |
self; complete the cursor CAS (crash after GitHub accept) |
| anything else | remote modified → Q3 park |
Order: write in_flight → advertise must still equal remote_old
(= last_pushed) → receive-pack → CAS last_pushed := new, clear
in_flight. A crash before GitHub accept leaves in_flight set and
advertise still last_pushed; retry is the same idempotent command
(Q5). A crash after accept leaves advertise == in_flight.new_oid;
the next worker finishes the CAS and does not park.
Scheme. The idempotency key is
(binding_id, remote, local_oid, remote_old). remote_old is the
advertised tip captured into in_flight before send and is
not overwritten by the success path (keep it on the completed
outbox / intent row). Retries with the same key replay the same
receive-pack command (old/new/refs/heads/main).
Compensation uses that stored remote_old, never the post-success
last_pushed:
- Failed before accept: retry the same key; do not invent a new
old. - Success then crash: Q4 self-complete; no compensate.
- First create: advertisement tip is 40 zero hex;
remote_oldis zeros; the command is a create. Compensation is not a remote delete (we do not delete GitHubmain). If advertise later showslocal_oid, treat as first-push success and CAS the cursor. If advertise is still zeros, retry the create. If advertise is some other oid, park (Q3).
| Field | Value |
|---|---|
| Branch | go |
| Timebox | 2026-09-20, single session after GS-26 v0.38.18 (9514a49) |
| Basis | Q1–Q5 each have a scheme above, consistent with ADR-GS-01…04, the B3 change-set, and the receive-pack success contract |
| Not claimed | Automatic resume across a GitHub-side merge; inbound fetch; REST; any src/ change |
N/A — this card is go. If a later review rejects Q3's park-only
resume, the alternative already named for GS-10 is an explicit
force-replace (or inbound merge) plan; do not silently treat a third
GitHub oid as fast-forward.
Spike GS-18. Freezes in-stream pack errors, completion, and
cancel for the outbound sync worker. Byte budget and have
negotiation stay on GS-27. No production code in this card.
Today RepoHandler::incremental_pack returns
Result<ReceiverStream<Vec<u8>>, GitError> (pack/mod.rs:254–:258).
The Result is only the setup failure. After the stream exists there
is no item-level error and no completion token. Both implementations
still unwrap storage lookups (monorepo.rs walk; import_repo.rs:187
–:190). Clone/fetch consume that stream at smart.rs:283 and
v2.rs:284; full_pack (monorepo.rs:248) and default
filtered_pack (pack/mod.rs:284) are the other two call sites.
Changing that return type in place would force a behavior change onto the live upload-pack path. This freeze does not do that.
Scheme. Keep incremental_pack byte-identical for clone/fetch.
Add a parallel method (name is DEP-01's; call it
incremental_pack_reported here) that is not on the live
upload-pack call sites:
async fn incremental_pack_reported(
&self,
want: Vec<String>,
have: Vec<String>,
) -> Result<ReportedPackStream, GitError>
The method has a default body that returns
GitError “unsupported” so ImportRepo (and Arc<dyn RepoHandler>)
need not implement it. Only the monorepo handler used by github_sync
overrides it.
ReportedPackStream is a Stream<Item = Result<Bytes, PackStreamError>>:
| Item | Meaning |
|---|---|
Ok(chunk) |
pack window (same 16 KiB cap the receive-pack writer already uses) |
Err(e) |
terminal in-stream failure; stream ends |
stream end (None) |
completion — trailer was written; no extra success item |
PackStreamError is a closed enum: Storage, Encode, Canceled,
Protocol. Setup failures (bad want, handler missing) still return
from the async fn as GitError, same as today. The outbound worker
is the only required consumer in DEP-01. Migrating clone/fetch onto
this method is optional and out of this plan.
| Site | Role | Impact of this freeze |
|---|---|---|
pack/mod.rs:254 |
trait declaration | unchanged |
pack/monorepo.rs:497 |
monorepo impl | unchanged; new method added beside it |
pack/import_repo.rs:175 |
import-repo impl | unchanged; default “unsupported” body (sync is monorepo-path only, ADR-GS-01) |
protocol/smart.rs:283 |
upload-pack v1 | no change |
protocol/v2.rs:284 |
upload-pack v2 | no change |
pack/monorepo.rs:249 |
full_pack → incremental_pack |
no change |
pack/mod.rs:284 |
filtered_pack default |
no change |
pack/monorepo.rs:3281 |
unit test | no change |
1 declaration / 2 implementations / 4 production call sites stay on
the existing Vec<u8> stream. That is how Q6a avoids regressing
clone/fetch. The new method's first production caller is the
github_sync worker (DEP-01).
Scheme. Today's incremental_pack walks inline before
returning the stream (monorepo.rs:497–:617); only the encoder
is a spawned task. The reported method must move the walk into a
task owned by the stream (DEP-01 structural delta). The stream
owns:
- an
mpsc(or equivalent) from that walker/encoder task, and - a
CancellationToken(orDropflag) that the consumer drop cancels.
When the outbound worker drops the stream (timeout from GS-20, park from GS-09 Q3, or process shutdown):
- The token is cancelled.
- The next
sender.sendfails or the walker sees the token and returnsErr(Canceled). - The producer task exits; it does not start a new tree walk or blob fold.
A late chunk already sitting in the channel may be lost; that is
acceptable because the worker has abandoned the receive-pack. The
producer must not unwrap a closed send (today's
map_err on send is the model, pack/mod.rs:475–:481).
Scheme. The pack encoder (the task that turns Entrys into
pack windows) is a child of the same token:
- On cancel: abort the encoder
JoinHandle(or select on the token next toentry_rx). Drop the in-flightVecfromtry_fold(pack/mod.rs:464–:470) without sending it. - On
senderclosed: same path — treat asCanceled, not asEncode. - Do not spawn an unbound encoder per blob; the existing
try_for_each_concurrent(16, …)stays the concurrency cap (budget numbers are GS-27). Cancel must stop scheduling new concurrent folds.
Completion is not defined by channel close alone (plan-20260920
OX-02 AC-8 correction): ReportedPackStream only emits a clean None
after (1) the full pack trailer has been written into the output channel,
(2) the producer completion coordinator has exited cleanly, and (3) the
encoder JoinHandle has been awaited and returned Ok with
trailer_written = true. Any sender close before trailer, producer join
failure, encoder panic (including after trailer write), or unexpected
encoder task cancellation emits a terminal PackStreamError::Encode
before ending the stream. The worker treats a clean None as success
only if it had already written that stream to receive-pack; a cancel
mid-trailer is Canceled and the GitHub attempt is not recorded as
success (GS-09 Q4/Q5).
Scheme. On the reported path only, every storage lookup
that today's impls unwrap (get_commits_by_hashes,
get_commit_by_hash, get_trees_by_hashes) maps Err to
PackStreamError::Storage and ends the stream. No unwrap /
expect / panic on that path (plan GC-11).
The live incremental_pack path is not rewritten by this
freeze (DEFER-GS-07 still owns those unwraps). Clone/fetch keep
today's panic-or-disconnect behavior until a later plan migrates
them onto incremental_pack_reported.
A storage error that happens after some windows were already
sent is still terminal: the worker must not send those bytes as
a successful pack (GS-15 incomplete report). The first Err
item is the only diagnostic; later items are not produced.
| Field | Value |
|---|---|
| Branch | go |
| Timebox | 2026-09-20, same session as GS-09 17c3905 |
| Basis | Additive reported stream; 4 live call sites untouched; cancel via token+drop; storage errors only on the new path |
| Not claimed | Rewriting clone/fetch; pack byte budget; have ACK semantics (GS-27) |
N/A — this card is go. The rejected alternative is changing
incremental_pack's return type in place (would force smart.rs /
v2.rs to handle Result items and is a live-protocol rewrite).
Spike GS-27. Freezes four byte budgets on the reported pack
path (GS-18) and the have distinction that must not change
upload-pack. Live incremental_pack / clone / fetch stay as they
are. No production code in this card. Numbers below are DEP-01
defaults, not new [github_sync] keys in this plan.
Today the real allocation is the shared walker: each blob is
try_folded into one Vec at concurrency 16 (pack/mod.rs:464–
:470). The mpsc capacity is pack.channel_message_size slots
(default 1_000_000, src/config/model.rs:711), not bytes.
Parent walk stops when a parent id is in have
(monorepo.rs:521–:538). Upload-pack ACKs only commits it
already has (smart.rs:275–:276).
Scheme. Bound the in-memory graph before any blob fold. Caps
depend on whether have is a proven tip or empty (GS-09 Q2):
| Set | What it holds | Incremental have=[last_pushed] |
Full have=[] |
|---|---|---|---|
want_commits / walk list |
commits collected from want toward have (or to root) |
pack_max_walk_commits = 4096 |
pack_max_walk_commits_full = 65536 |
want_trees |
trees for those commits | same 4096 | same 65536 |
exist_objs / counted_obj |
hex ids already seen | pack_max_object_ids = 1_000_000 |
same 1_000_000 |
have=[] is the first push and every cursor invalidation (Q2).
That walk is full history to root, not the delta between two
tips — the 4096 incremental cap must not be applied there, or a
repo with >4096 commits could never recover. Exceeding the
applicable cap is PackStreamError::Encode on the reported
stream and does not start encode. No silent truncate, no chunked
push in this plan: a binding that overflows the full cap fails
closed until the receiving plan raises the cap or splits history.
Derived id-set residency (not a second cap): 1_000_000 × ~64-byte
hex String keys ≈ 64–100 MiB for exist_objs / counted_obj.
Live incremental_pack is not rewritten (same as GS-18).
Scheme. The live default traverse (pack/mod.rs:436, fold at
:464) is shared by incremental_pack, full_pack, and import.
DEP-01 must not patch that default. The reported path gets a
fork (traverse_budgeted or a BlobBudget argument used only by
incremental_pack_reported).
On that fork: try_for_each_concurrent(16, …) is the maximum
concurrency; DEP-01 may lower it, not raise it. Each fold has a
per-blob cap pack_max_blob_bytes = 64 MiB. Crossing the cap
aborts that fold, cancels the other 15 (GS-18 AC-4), and emits
PackStreamError::Encode.
Aggregate in-flight blob bytes (AC-2 + AC-3 + encoder input hold share
this number, per plan-20260920 ADR-OX-02 / OX-27 / OX-178):
pack_max_inflight_blob_bytes = 16 * pack_max_blob_bytes (1 GiB).
Each folded blob carries an owned credit token (BlobCredit) inside
BudgetedEntry across concurrent folds, the 16-slot entry channel, and
the single input Entry currently held by BoundedPackEncoder until
that Entry is dropped — never cloning a second full raw payload and
never releasing the credit early.
This budget is independent of Git LFS (LFS payloads are not pack blobs). A blob that exceeds the per-blob cap is not chunked into the pack.
Scheme. Do not reuse channel_message_size = 1_000_000 for
sync. The reported path uses small slot channels whose byte
residency is explicit. Entry slots equal fold concurrency so
the queue cannot hold a second 64-blob pile on top of AC-2:
| Channel | Slots | Payload cap per slot | Byte residency |
|---|---|---|---|
walker → encoder (entry_tx) |
16 | one Entry ≤ pack_max_blob_bytes |
counted inside pack_max_inflight_blob_bytes (1 GiB), not additive |
encoder → worker (stream_tx) |
64 | PACK_WRITE_WINDOW (16 KiB, GS-24) |
64 × 16 KiB = 1 MiB |
The walker must not start a 17th fold while 16 entries are already in flight (folding or queued). Backpressure is “send awaits or cancel” (GS-18 AC-3). A full channel is not an error. The live pack path may keep today’s slot count until a later plan migrates it.
PACK_WRITE_WINDOW (16 KiB) is enforced directly by the in-repo
BoundedPackEncoder (src/ceres/pack/bounded_encoder.rs, OX-12 /
OX-151) before enqueueing onto stream_tx, so the 64-slot output
channel is strictly bounded to 64 × 16 KiB = 1 MiB. Live incremental_pack
remains untouched on git-internal::PackEncoder.
Scheme. (plan-20260920 ADR-OX-02 / OX-12 / OX-178 correction):
The reported path uses the in-repo sequential, no-delta streaming zlib
encoder BoundedPackEncoder (src/ceres/pack/bounded_encoder.rs) rather
than pinned git-internal::PackEncoder (which batches ≥1000 entries and
buffers full compressed objects). At any moment the encoder holds at most
one owned input Entry (up to 64 MiB), which continues to occupy the
1 GiB pack_max_inflight_blob_bytes budget (AC-2) until dropped.
pack_max_encode_bytes = 4 MiB bounds the peak residency of
encoder-owned scratch buffers, zlib compression state, and un-enqueued
output window bytes — it does not reject packs whose cumulative
streamed size exceeds 4 MiB, and it does not double-count the owned
input Entry.data (AC-2) or already-enqueued stream_tx windows (AC-3,
1 MiB). Any scratch reservation that would exceed 4 MiB fails closed
with PackStreamError::Encode before allocating. Cancel releases all
encoder-owned scratch immediately via RAII. Completion still requires
trailer write + producer join + encoder join (OX-02 AC-8).
| Kind | Who sends it | Missing oid means | Action |
|---|---|---|---|
Negotiated have |
Git client on upload-pack | client advertised a commit we do not store | do not ACK (smart.rs:275); keep walking; not an error |
| Must-traverse ancestor | our walker, parent of a want we decided to include |
local storage has no row (get_commit_by_hash None / Err) |
error on the reported path (PackStreamError::Storage); invalidate is not “treat as have” |
Sync have |
github_sync worker | last_pushed missing locally, or advertise ≠ last_pushed |
GS-09 Q2: invalidate cursor, have=[] (full pack) or park — never pass a GitHub-only oid as have |
A client-advertised unknown have is negotiation noise. A missing
parent of a want we already accepted is a broken graph.
Scheme. AC-5’s “unknown have is not an error” is exactly
today’s upload-pack behavior and is frozen as a non-goal for this
plan: smart.rs:275–:287 and v2.rs stay on
incremental_pack(want, have) with ACK-only-if-exists. DEP-01 must
not teach the live handler to fail closed on unknown client have.
The reported/sync path is a different caller and a different have
vector (Q2). Mixing those two have lists is a protocol bug.
| Field | Value |
|---|---|
| Branch | go |
| Timebox | 2026-09-20, after GS-18 fabd01f |
| Basis | Four caps on the reported path; live upload-pack have ACK rule left intact |
| Not claimed | Rewriting PackConfig.channel_message_size for clone/fetch; LFS; new config keys in this crate; patching git-internal |
N/A — this card is go. The rejected alternative is “any missing
have is an error” on incremental_pack (R2 / ADR-GS-06: that
breaks upload-pack negotiation).
DEP-01 must implement, on incremental_pack_reported only:
- Dual walk caps (AC-1): 4096 incremental / 65536 full (
have=[]); typed overflow; no silent truncate. - Forked budgeted traverse (do not patch live
traverse); concurrency ≤ 16; per-blob 64 MiB; aggregate in-flight blobs 1 GiB (AC-2). - Entry channel 16 slots (inside the 1 GiB blob cap) and stream channel 64 × 16 KiB windows (AC-3).
- Encoder residency ≤ 4 MiB (AC-4).
- Sync
haveis only[last_pushed]or[]per GS-09 Q2 (AC-5). - Live upload-pack continues to ignore unknown client
have(AC-6). - Missing local parent of an accepted
wantisPackStreamError::Storageon the reported path. Liveincremental_packtoday panics (monorepo.rs:527–:533unwrap().unwrap()); that panic is not the reported-path contract (GS-18 AC-5).
Spike GS-21. Freezes the operator identity, token scope, and
abort / force predicates for github_sync commands. This plan
still adds no HTTP routes (ADR-GS-02) and no CLI subcommand.
DEP-01 owns the surface. Atomic CAS of the cursor is GS-28 Q8; this
card only names who may request a write and when it is legal.
Trunk /api/v1 has no cedar_guard (http_server.rs:768–:771;
review mounts it at :792). push_auth=none returns the stable
name anonymous (api_write_auth.rs:34). Agent-capture already
splits identity (require_ingest_token :98) from scope
(token_covers_capture_repo :634). Q7 copies that two-check
shape onto a new token family, not git.push_tokens.
Scheme. Operator identity is a named token from
[[github_sync.operator_tokens]] (OX-03, src/config/model.rs:
GithubSyncOperatorToken with redacted Debug and closed
GithubSyncOperatorAction; empty operator_tokens or actions = [] denies all
operations without blocking startup, and bindings = ["*"] never implies any
action). Presentation is the same Basic-password / Bearer header as
authorize_trunk_api_write (api_write_auth.rs:58–:71), implemented by
authorize_operator_request (OX-37, src/api/router/github_sync.rs), which
classifies missing/unknown tokens as Unauthenticated, out-of-scope bindings or
actions as ForbiddenBinding / ForbiddenAction, and returns a named
AuthorizedOperator for downstream routes. HTTP error projection (OX-76,
src/common/errors/api.rs GithubSyncOperatorError / GithubSyncOperatorErrorDto,
registered in ApiDoc OpenAPI components) maps Unauthenticated → 401,
Forbidden → 403, UnknownBinding → 404, and Conflict → 409 using
strictly fixed { code, message } JSON with no raw context fields. The requester name is token.name.
Not an identity source: session cookies, UserStorage, Cedar
principals, the bootstrap SSH key, git.push_tokens, or the
anonymous string (OX-48, src/api/router/github_sync.rs:
resolve_operator_token_identity and GithubSyncConfig::lookup_operator_token
enforce strict credential-family isolation so operator tokens never grant Git
push or session permissions and push_auth = "none" never synthesizes an
operator identity or scope). The SSH key authenticates to GitHub
(ADR-GS-03); it never authenticates an operator to mega2.
Scheme. Each operator token carries:
| Field | Meaning |
|---|---|
name |
identity (AC-1) |
token |
secret; compared like ingest tokens |
bindings |
binding id list, or ["*"] for every configured binding |
actions |
subset of status, abort, cursor_reset, force |
A call is in scope only if both the target binding.id and the
verb are listed. status is read-only. cursor_reset is the Q3
“advertise already equals local_oid” write (no receive-pack).
force is the history-rewrite receive-pack. * in bindings does
not imply every action; omitted actions is empty (fail-closed).
Scheme.
| Caller | push_auth=none |
push_auth=token |
|---|---|---|
| monorepo git / trunk API write | anonymous (today) |
git.push_tokens + path cover |
| github_sync operator command | 401 unless an operator token is presented | same: operator token required; a push token is not enough |
Missing or unknown operator secret → 401. Known secret but
binding/action out of scope → 403 (the api_write_auth
path-cover shape, not agent-capture’s 404-on-scope). Operator
calls name a configured binding.id; hiding existence after a
valid secret is not required. enabled=true does not require
any operator token at boot (auto-park still works); commands are
simply unavailable until tokens exist. Review / Cedar stay out of
this plan (ADR-GS-02). DEP-01 must extend the GS-23 whitelist with
github_sync.operator_tokens when the table is added.
Two distinct aborts; do not mix them.
Policy abort (automatic). On Q3 divergence (advertise ≠ last_pushed and advertise is not in_flight.new_oid), the worker
parks the binding and does not send receive-pack. No operator
token. This is the only automatic NFF response (ADR-GS-04: mega2
does not merge).
Operator abort (command). Allowed when:
- Token has
aborton thatbinding.id(AC-2). - The binding exists.
- Binding state is one of the four frozen values below.
Frozen states (DEP-01 must not invent others):
| State | Meaning |
|---|---|
idle |
last_pushed equals advertise; no in_flight |
in_flight |
intent row set; receive-pack may be running or crash-pending (Q4) |
parked |
Q3 / operator abort; no automatic send |
disabled |
binding exists in config but sync is off |
running / queued are not states; they collapse into
in_flight (OX-101, src/api/router/github_sync.rs: GithubSyncBindingState
and allowlisted GithubSyncStatusCoreDto { binding_id, state, reason }
registered in ApiDoc OpenAPI components; mounted at read-only
GET /api/v1/github-sync/bindings/{id}/status by OX-15 in
http_server::storage_only_api_v1 without DB writes or SSH I/O, extended by
OX-77 (GithubSyncStatusResponseDto) with local_main_oid and persisted
last_observed_remote_tip / observed_at (non-live, null when unobserved,
404 on unknown binding ID)). Operator abort of idle is a no-op 200.
It is not a GitHub update. It cancels the local pack (GS-18
token+drop), leaves last_pushed unchanged, and does not invent a
force-push. Do not clear in_flight on operator abort — Q4
self-complete (advertise == in_flight.new_oid) must still run if
GitHub already accepted (OX-136, GithubSyncCursorStorage::operator_abort_in_flight_cas:
single-SQL generation-fenced CAS from active in_flight to parked/operator_abort
preserving last_pushed and in_flight_* with zero mutation on stale generation). After an operator abort, clear in_flight
only on a later cursor CAS (success or Q4 self-complete).
Pre-send Policy abort vs. in-flight third-OID poll park (OX-123 source-of-truth clarification):
- Pre-send Policy abort (no command sent yet): When the worker detects Q3 divergence before any receive-pack command has been sent on the wire, that policy abort may clear its corresponding pending
in_flightintent without a remote acceptance race (nothing was sent). - In-flight third-OID poll park (command already in flight): Once an
in_flightcommand has been durably prepared/sent and a Q4 poll observes a third remote OID (advertise ≠ last_pushedandadvertise ≠ in_flight.new_oid), poll must park the binding (state = 'parked',reason = remote_diverged) while preserving the originalin_flightintent andremote_old(OX-92) so Q4/Q5 idempotent retry (OX-94/OX-116) or explicit Q7 operator recovery (cursor-reset/force) can inspect or replay the exact original command identity. - State invariants:
idlemust never coexist within_flight(aparkedbinding withoutin_flightrecovers toidleonadvertise == last_pushedviaOX-63, whereas aparkedbinding retainingin_flightmay only promote back to retryablein_flightviaOX-94/OX-116, neveridle). A third remote OID — including any GitHub-side merge commit — never auto-unparks aparkedbinding. - Operator abort boundary unchanged: Operator abort authentication (
operator_tokenswithbindings/actionsscope,401/403), the four frozen states (idle/in_flight/parked/disabled), and the no-force boundary remain identical to AC-1–AC-4.
parked and disabled abort are idempotent 200 (no cursor write); pure
inactive-state classification (idle / parked / disabled) is implemented by
classify_operator_abort (OX-110, src/api/router/github_sync.rs) with zero
worker cancels, cursor writes, or receive-pack sends, and projected to the fixed
HTTP 200 DTO GithubSyncAbortResponseDto by project_abort_noop_response
(OX-135, strictly omitting tokens, vault/SSH secrets, and raw stderr).
POST /api/v1/github-sync/bindings/{id}/abort (OX-16,
src/api/router/github_sync.rs::post_binding_abort / execute_operator_abort)
orchestrates OX-37 auth → OX-110/OX-135 inactive idempotent 200 → OX-46
fail-closed named audit → OX-136 generation CAS park (409 on race) → OX-26
worker::cancel_active_binding cancellation.
| Case | Binding | Cursor | Remote | Report |
|---|---|---|---|---|
| Policy abort (pre-send divergence, nothing sent) | parked, reason remote_diverged |
last_pushed unchanged; pending in_flight may be cleared (nothing was sent) |
no receive-pack | outbox / event aborted |
In-flight third-OID poll park (OX-92 / OX-123) |
parked, reason remote_diverged |
last_pushed unchanged; original in_flight and remote_old preserved (never idle + in_flight) |
no receive-pack; Q4/Q5 idempotent retry if remote returns to last_pushed, or Q7 operator recovery; GitHub-side merge never auto-unparks |
event parked (OX-93) |
Operator abort of in_flight |
parked, reason operator_abort |
last_pushed unchanged; in_flight kept |
local pack cancelled; if advertise later equals in_flight.new_oid, Q4 self-complete still CAS-es |
aborted + token name |
Operator abort of already parked |
stays parked |
unchanged | none | 200 idempotent |
Operator abort of disabled |
stays disabled |
unchanged | none | 200 idempotent |
After either abort the next automatic attempt stays parked until
advertise equals last_pushed again (recovering to idle only when in_flight is absent, or promoting to retryable in_flight with the preserved intent/remote_old when in_flight is present — never idle + in_flight) or a legal cursor_reset /
force runs (Q3). A third OID or GitHub-side merge never auto-unparks.
Never automatic. A GitHub-side merge is not a resume signal (Q3). Two operator writes exist:
cursor_reset (preferred; no history rewrite) when all of:
- Token has
cursor_reseton the binding. - Binding is
parked. - Current advertise equals
local_oid(Q3 already required this). Request repeatsexpected_remote_tipandexpected_local_oid; mismatch → 409, no write (OX-45preflight_operator_expected_tips+OX-78revalidate_operator_expected_tips, which always re-runs live SSHadvertiseand re-reads local nativemainwithout reusing cached status). - No receive-pack. Cursor CAS
last_pushed := local_oid, unpark. The CAS primitive is GS-28 (OX-137,GithubSyncCursorStorage::operator_cursor_reset_cas: single-SQL CAS requiringstate = 'parked', exactgeneration, and equal non-zero remote/local OIDs; advanceslast_pushed, clearsin_flight_*, unparks toidle, incrementsgeneration, with zero mutation on any precondition failure). The HTTP orchestration is mounted atPOST /api/v1/github-sync/bindings/{id}/cursor-reset(OX-17,src/api/router/github_sync.rs::post_binding_cursor_reset/execute_operator_cursor_reset), chainingOX-37(cursor_resetscope) →OX-45preflight →OX-78live two-tip revalidation (requiring equal non-zero tips) →OX-46fail-closed named audit →OX-137CAS (mapping contention to HTTP409 cursor_cas_conflict).
force (history rewrite) when all of:
- Token has
forceon the binding (cursor_resetis not enough). - Binding is
parkedfor Q3 divergence. - Request repeats
expected_remote_tip(= current advertise) andexpected_local_oid(= pathmain). Mismatch → 409. - Advertise is not
last_pushedand notlocal_oid(those are idle / cursor_reset, not force). - Worker sends receive-pack
old=expected_remote_tip new=expected_local_oid refs/heads/main. GitHub maynga protected default branch (GS-15). The external HTTP endpoint is mounted atPOST /api/v1/github-sync/bindings/{id}/force(OX-18,src/api/router/github_sync.rs::post_binding_force/execute_operator_force), requiring explicitforcescope (cursor_resetnever grantsforce), third-OIDValidatedForceproof fromOX-45/OX-78, and fail-closedOX-46named audit prior to callingOX-79.
| Outcome | Binding | Cursor | Remote |
|---|---|---|---|
cursor_reset 200 |
idle |
last_pushed = local_oid; in_flight empty |
unchanged (already local_oid) |
force unpack+ok refs/heads/main+exit 0 |
idle |
last_pushed = local_oid after CAS |
GitHub main is local_oid (history of the previous tip discarded) |
force ng / unpack fail / timeout |
stays parked |
last_pushed unchanged |
GitHub tip unchanged |
| 401 / 403 / 409 | unchanged | unchanged | none |
Report and process-exit classification for force is implemented as pure
strongly-typed values in src/ceres/github_sync/send_pack.rs (OX-106,
ForceReportOutcome / ForceReportFailureKind / classify_force_report_bytes
/ classify_force_report_result): Success strictly requires unpack ok,
ok refs/heads/main (flushed), and process exit 0; ng, unpack failure,
timeout, non-zero/missing exit, or truncated/fatal streams map to distinct
Failure variants and never produce false success. Cursor convergence is
implemented in src/ceres/github_sync/worker.rs::converge_force_report_outcome
and src/jupiter/storage/github_sync_cursor.rs::complete_force_push_cas
(OX-102): ForceReportOutcome::Success runs a generation CAS advancing
last_pushed, clearing in_flight_*, unparking to idle, and completing the
matching Q5 compensation intent; any ForceReportOutcome::Failure performs
zero cursor writes, preserving parked state and original last_pushed.
A successful force is a new compensation key
(binding_id, remote, local_oid, expected_remote_tip) (Q5). It is
not a replay of the parked attempt. The internal send primitive is implemented
in src/ceres/github_sync/worker.rs::GithubSyncWorker::execute_force_push
(OX-79): it accepts ONLY an immutable ValidatedForce derived from OX-45/
OX-78 (enforcing third-OID divergence), persists/reuses the Q5 compensation
key in github_sync_intent, sends old=expected_remote_tip,
new=expected_local_oid to refs/heads/main via
ReceivePack::write_bridged_pack_with_old, classifies GS-15 report/timeout via
OX-106, and delegates cursor convergence exclusively to OX-102
converge_force_report_outcome.
| Field | Value |
|---|---|
| Branch | go |
| Timebox | 2026-09-20, after GS-27 9da75a3 |
| Basis | Dedicated operator token family; push_auth=none never authorizes commands; automatic NFF is park-only; force is explicit + CAS |
| Not claimed | HTTP routes or CLI in this crate; Cedar on trunk; implementing the CAS primitive (GS-28); REST to GitHub |
N/A — this card is go. Rejected alternatives: reuse anonymous /
git.push_tokens for force; auto-force on a third GitHub oid;
mount cedar_guard on trunk as a hidden dep of this plan.
Spike GS-28. Freezes the conditional-write primitive that closes the RedLock drop-lock window (GS-16 residual). No production code in this card.
Today VaultStorage::save is an upsert that always overwrites
value on key conflict (vault_storage.rs:57–:61). The vault
row is (id, key, value) with no version column (callisto/vault.rs:8–
:14). After lock loss, RedLock only stops the renew task
(lock.rs:323); unlock (:359) does not fence a writer already
inside the critical section. ensure_server_signing_key
(server_signing.rs:250–:255) and github_sync::key::ensure
(key.rs:228–:237) share that window.
VaultCore::write_secret does not call VaultStorage::save. It
calls rvault.write (vault_core.rs:1231–:1233) → libvault
barrier → Backend::put (jupiter_backend.rs:116) → save.
libvault put is blind. Physical value bytes are barrier
ciphertext, so UPDATE vault SET value=new WHERE value=expected
is not a logical CAS (callers never see those bytes; a new
nonce would miss even an uncontended write). That path is
rejected. Do not add write_secret_cas. Do not patch
libvault in this freeze.
Scheme. A SQL create-once fence, in-repo, beside vault — not
inside vault.value.
table vault_create_once (
logical_name TEXT PRIMARY KEY,
created_at TIMESTAMPTZ NOT NULL
)
enum Fence {
Applied, -- this replica won; it may write_secret
Conflict, -- another replica already won; do not write
}
fn claim_create_once(logical_name) -> Result<Fence, MegaError>
-- INSERT … ON CONFLICT DO NOTHING
-- 1 row inserted → Applied; 0 → Conflict
logical_name is a fixed string (not a generated key_id).
Only the winner of claim_create_once may call write_secret for
that init. The loser only read_secret. VaultStorage::save and
write_secret stay last-writer-wins for everyone else.
A fence row with empty secrets (winner crashed after INSERT) is the GS-16 repair: delete the fence row and the vault secrets, bootstrap one replica.
github_sync cursor CAS (Q4 / Q7) is a third table:
UPDATE … WHERE last_pushed = $expected. Not vault, not this
fence.
Scheme. persist_new_key_generation writes three secrets
(key entry at {KEYS_PREFIX}/{key_id}, KEY_INDEX,
ACTIVE_POINTER — server_signing.rs:456 / :468 / :473).
key_id is a fingerprint, so two racers write different key
rows; create-once on the key entry never conflicts.
Authoritative fence: logical_name = ACTIVE_POINTER (the one
fixed, contended name).
Order for first init only:
claim_create_once(ACTIVE_POINTER).Applied→ write key entry, thenKEY_INDEX, thenACTIVE_POINTER(today’swrite_secret). Losers never enter this step, so they cannot orphan-overwrite the index.Conflict→read_secret(ACTIVE_POINTER)and load that key. Do not write key entry, index, or pointer. If the pointer secret is still missing, fail closed (winner crashed); operator repair is GS-16 (also delete the fence row).
Outer ensure_server_signing_key signature unchanged.
Rotation (rotate_server_signing_key :289) is
operator-driven and out of this fence. It keeps RedLock +
write_secret. This card does not add a rotation HTTP route
(ADR-GS-02).
Scheme.
| Writer | Path | Change |
|---|---|---|
VaultStorage::save / JupiterBackend::put |
generic KV / barrier | unchanged |
github_sync::key::generate_and_store (key.rs:206) |
one config-derived secret name | claim_create_once(ssh_key_ref name) then write_secret; Conflict → read_secret only |
Token / barrier / other write_secret |
existing secrets, including other create-once identities (ssh_server_key, nostr, PGP) that this card does not fence |
no fence |
Do not fence every vault put. Only create-once identity material (active signing pointer, github_sync SSH secret name).
| Field | Value |
|---|---|
| Branch | go |
| Timebox | 2026-09-20, after GS-21 9adfd31 |
| Basis | SQL INSERT … ON CONFLICT DO NOTHING is expressible in-repo; it fences writes before blind write_secret; no libvault / ciphertext CAS |
| Not claimed | write_secret_cas; comparing vault.value bytes; patching libvault; implementing the table in this crate; rotation CAS |
AC-4 / AC-5 apply only on no-go; this card is go, so they are N/A.
N/A — this card is go. Rejected alternatives: WHERE value = expected on ciphertext; extending libvault::Backend in this
plan; accepting the residual window forever; Redis fencing without
a SQL claim (still last-writer-wins on save).
AC-7 — receiving-plan handoff & Q8 targeted repair runbook (OX-64 / OX-04 / OX-31 / OX-13 / OX-236 / OX-32 / OX-08 / OX-07)
Track 1 of plan-20260920 has landed Q8:
vault_create_once(logical_name TEXT PRIMARY KEY,created_at TIMESTAMPTZ NOT NULL) added by forward-only migrationm20261129_000100_vault_create_once, plusVaultStorage::claim_create_once(INSERT … ON CONFLICT (logical_name) DO NOTHING, returningCreateOnceFence::Applied | Conflictand propagating SQL errors verbatim) andVaultCore::claim_create_once. GenericVaultStorage::saveandVaultCore::write_secretstay last-writer-wins.ensure_server_signing_keyfirst-init claimsACTIVE_POINTERbefore writing key entry,KEY_INDEX, andACTIVE_POINTER;ConflictreadsACTIVE_POINTERonly and fails closed if missing. Rotation (rotate_server_signing_key) remains operator-driven outside the fence.github_sync::key::ensurefirst-init claims the resolved physicalSecretRef::secret_name()(shared across#fieldaliases);Conflictreads only and fails closed if missing.- Full
config vault reset --forcecallsVaultStorage::reset_all_with_claimsto clearvaultandvault_create_oncein a single SQL transaction and backs upcore_key.jsonto a non-collidingjson.bak.<timestamp>[.<seq>]path.
当赢家在写入 vault_create_once 后、写入目标 secret 前崩溃(例如 ACTIVE_POINTER 或某个 github_sync SecretRef::secret_name() 的 fence 已存在但对应 secret 缺失),启动期会 fail-closed 拒绝启动。严禁将全量 config vault reset --force 用作局部修复——全量 reset 会删除全库 vault secret 以及所有历史 server-signing keys/* 与 KEY_INDEX,导致既有签名无法验证。
按以下可执行步骤做定向修复:
-
停所有副本(
service http/service ssh/service multi全部停止)。 -
备份现场:备份目标数据库
vault与vault_create_once表(以及对应core_key.json),核对报错中指出的精确logical_name(ACTIVE_POINTER对应server-signing/active,GitHub 同步私钥对应解析后的物理SecretRef::secret_name(),不含#field)。 -
只读确认目标行(绝不触碰其它命名空间或历史 server-signing 密钥):
SELECT logical_name, created_at FROM vault_create_once WHERE logical_name = '<logical_name>'; SELECT id, key FROM vault WHERE key LIKE '%<logical_name>%';
-
受控事务仅删除该
logical_name的 fence 与未完成 secret(若历史server-signing的keys/*与index仍用于验证旧提交签名,必须保留,不得删除):BEGIN; DELETE FROM vault_create_once WHERE logical_name = '<logical_name>'; -- 仅当存在对应未完成/损坏的目标 secret 时,再按精确路径删除该条: -- DELETE FROM vault WHERE key = 'logical/<mount-uuid>/<logical_name>'; COMMIT;
-
单副本重启与复核:仅启动单副本触发重新自举并核对启动成功与日志输出;若是
github_syncSSH 私钥,须把新公钥重新登记到 GitHub 机器账号后再恢复多副本。若涉及server-signing,核对历史公钥列表(list_server_signing_public_keys)仍包含所有既有历史密钥。 -
Implement github_sync cursor CAS as SQL
UPDATE … WHERE, not vault and not this fence.
Mirrors plan-20260916 「开工前凭证与密钥清单」并由 plan-20260920 ADR-OX-01(OX-96 事实源兼容订正)限定覆盖历史 60916 测试禁令。Three layers. Do not mix. Product path never uses a GitHub PAT,
deploy key, or gh auth token (ADR-GS-03 / ADR-OX-01). This crate’s gh release
is publisher-layer only.
Postgres / Redis from .env.test, in-process vault, fixture SSH host
keys. No GitHub token. All normal full-gate receive-pack tests remain loopback
(DEFER-GS-08 → 现由 plan-20260920 OX-24 / OX-06 承接隔离 live 验收).
对 plan-20260916 历史测试禁令的限定覆盖(ADR-OX-01 /
OX-96): 60916 曾禁止在测试侧使用任何 GitHub PAT 或 deploy key;plan-20260920ADR-OX-01 对该历史禁令作出严格限定覆盖——仅允许在显式MEGA_TEST_GITHUB_LIVE=1opt-in 的独立隔离测试夹具内,使用测试侧 PAT(MEGA_TEST_GITHUB_TOKEN)与一次性可写 deploy key 完成受控私有空仓验收;产品读写路径仍绝对禁止 PAT、deploy key 或 REST 客户端(ADR-GS-03)。
- 显式 opt-in 与零伪通过门(AC-1): 只有在显式设置
MEGA_TEST_GITHUB_LIVE=1且提供有效MEGA_TEST_GITHUB_TOKEN与MEGA_TEST_GITHUB_NAMESPACE(以及 namespace kind 预检通过)后才执行 live 夹具。以下任一情形一律不算 live PASS:- 远端返回
ng(含分支保护或权限拒绝ng诊断); - 环境变量缺失导致的
not-run / env-not-set; - 未显式设置
MEGA_TEST_GITHUB_LIVE=1opt-in; - 用例被跳过或未执行;
- 测试后清理失败(含人工补偿未关闭)或 held-open 原 case 提前退出。
- 远端返回
- 同 run 双推正回执门(AC-2): 必须在同一 run 隔离私有空仓内先后完成一次首推(空仓 → C1)与一次增量推送(C1 → C2),且两次推送均获得完整 GS-15 正回执(
unpack ok+ok refs/heads/main)、SSHexit-status=0以及远端refs/heads/mainOID 与预期提交精确对齐,方可关闭 live 验收(OX-24/OX-06)。 - 测试夹具 vs 产品配置边界(AC-3 / AC-4): 一次性可写 deploy key 与测试侧 PAT(
MEGA_TEST_GITHUB_TOKEN)仅属于本隔离测试夹具,绝不进入产品代码路径或生产配置;产品配置始终是专用 GitHub 机器用户(machine user)SSH 身份、有写权限的仓库绑定与官方钉住的ssh_host_key(见下方「层 C」与「上线检查清单」)。
Publisher gh on gitmono-dev/mega2 plus Libra push to origin.
Docs / spike / handoff cards do not need gh.
Dedicated GitHub 机器用户(machine user) SSH public key + writable repository bindings + pinned ssh_host_key. Product path never uses PAT or deploy key. Implementation
of the push worker is plan-20260920. Normal loopback tests must not require layer C.
Operator checklist before the first real GitHub push
(plan-20260920, 引用 ADR-OX-01 测试/产品边界及对 60916 历史测试禁令的限定覆盖). Not a 60916 test gate. Before this list, run the
plan-20260920 OX-24 / OX-06 isolated live acceptance (层 A′) with explicit MEGA_TEST_GITHUB_LIVE=1, MEGA_TEST_GITHUB_TOKEN, and MEGA_TEST_GITHUB_NAMESPACE: both the initial empty-repo push and the subsequent incremental push must receive GS-15 unpack ok + ok refs/heads/main, exit-status=0, and exact remote OID alignment (ng, env-not-set, missing opt-in, skipped runs, cleanup failures, or premature held-open exit are never PASS).
- Use a dedicated GitHub 机器用户(machine user), not a human account. A human token/key would couple personal access to every binding and break ADR-GS-03’s single-credential model.
- Paste the startup
ssh-ed25519 … mega2-github-syncline onto that machine user (Settings → SSH keys). Not a deploy key (one-shot writable deploy keys belong solely to ADR-OX-01 isolated test fixtures, never production). - Pin
ssh_host_keyfrom GitHub’s published host-key document. Accept-any is forbidden. - Confirm the 机器用户(machine user)has write permission on each configured
binding.remote. - Manually confirm
mainbranch protection will not block a direct push. There is no automatic preflight: the bootstrap SSH key cannot call GitHub REST (ADR-GS-03). First-pushngis a failure diagnostic, never a live PASS. - Do not introduce a PAT /
gh/ REST client or deploy key on the product path (ADR-OX-01 product boundary).
任何消费方 AI operator 客户端均必须复用具名 Q7 [[github_sync.operator_tokens]] 身份,不得新开隐式、匿名、Git push token 或浏览器会话通道:
| 维度 | 契约字段 | 语义与拒绝码 |
|---|---|---|
| 具名身份 | operator_tokens[].name / token |
缺失或未知凭据一律返回 401(unauthenticated);git.push_tokens、session 与 push_auth = "none" 均不可认证为 operator(OX-48)。 |
| Binding 范围 | operator_tokens[].bindings |
显式绑定 ID 列表或 ["*"];越绑定范围返回 403(forbidden),bindings = ["*"] 绝不隐含任何动作授权(OX-03/OX-37)。 |
| Action 范围 | operator_tokens[].actions |
显式动作白名单:status、abort、cursor_reset、force;越动作范围返回 403(forbidden)。 |
| 非破坏恢复 vs 历史重写 | cursor_reset vs force |
cursor_reset 与 force 为完全独立的两个 action scope;持有 cursor_reset 绝不授予 force(请求 /force 返回 403),反之亦然(OX-17/OX-18)。 |
裁决结论(GO): 现有 Q7 operator_tokens 配置与 OX-37/OX-48 鉴权模型已完整表达具名身份、独立 bindings/actions 范围以及 cursor_reset 与 force 的权限隔离,允许推进 OX-80。
具 status action scope 的 AI operator 客户端经只读 GET /api/v1/github-sync/bindings/{id}/status 观察核心状态字段表(本节仅冻结本地身份/状态/本地 tip 契约,不指定未知外部接收者;远端观察与游标恢复字段见 OX-107):
| 字段 | 类型 / 枚举 | 冻结语义 |
|---|---|---|
binding_id |
string |
目标配置 binding ID;要求客户端具备该 binding(或 "*")与 status action 权限。 |
state |
idle | in_flight | parked | disabled |
冻结四态枚举;不新增 running 或 queued 变体,在途推送统一归入 in_flight(OX-101)。 |
reason |
string | null |
脱敏后的受控状态原因(如 remote_diverged、operator_abort、disabled);绝不透传原始凭据或未经脱敏 stderr。 |
local_main_oid(本地 local_oid) |
string | null |
对应 binding.path 当前本地原生 refs/heads/main 提交 OID(40 位 SHA-1 十六进制,未初始化或已删除时为 null)(OX-77)。 |
裁决结论(GO): 现有 OX-101/OX-15/OX-77 只读 status 模型完整覆盖 binding ID、四态、reason 与本地原生 main local_oid,放行 OX-107。
为支撑具名 operator 客户端(含 AI operator)在只读 GET /api/v1/github-sync/bindings/{id}/status 响应中判断后续恢复动作而不触发实时 SSH 拨号,本节冻结远端观察与持久游标字段语义(由 OX-109/OX-53 落地为封闭安全 DTO):
| 字段 | 类型 | 冻结语义与空值规则 |
|---|---|---|
last_observed_remote_tip 与 observed_at |
(string | null, string | null) |
成对表示最近一次持久化游标观察到的远端 refs/heads/main OID 及其观察时间戳;从未观察到时双双为 null。status 绝不为远端 tip 声称实时 SSH 新鲜度(实时核验只发生在 cursor-reset/force 写命令的 OX-78 阶段)。 |
last_pushed |
string | null |
持久 github_sync_cursor.last_pushed OID;从未完成推送时为 null。 |
in_flight_new_oid(即 in_flight.new_oid) |
string | null |
存在活跃在途 intent(含 operator_abort 保留的待 Q4 自完成 intent)时暴露该 40-hex OID;无 in-flight intent 时必须为 null。 |
generation |
integer |
持久 github_sync_cursor.generation,与写命令 CAS(OX-45/OX-136/OX-137/OX-102)读取同一 cursor 快照,用于防陈旧写竞争。 |
裁决结论(GO): 现有 github_sync_cursor 模型(OX-70/OX-153)已持久化全部所需字段(last_pushed、in_flight_new_oid、generation、updated_at),无需新增 schema 迁移即可由 OX-109/OX-53 投影,放行 OX-81。OX-109 已在 src/api/router/github_sync.rs 落地封闭白名单 DTO GithubSyncCursorStatusDto { last_pushed, in_flight_new_oid, generation } 与纯投影函数 project_binding_cursor_status(并注册至 ApiDoc OpenAPI components,不序列化原始 github_sync_cursor::Model);OX-53 已将该具名 schema 接入 GET /api/v1/github-sync/bindings/{id}/status(GithubSyncStatusResponseDto.cursor),复用既有 OX-37 鉴权与单次持久快照读取(零额外 SSH 拨号或游标写入)。
当远端出现第三 OID 分歧导致 binding 进入 parked(reason = remote_diverged)后,自动同步永不擅自解除 park,亦不把 GitHub 侧合并视为自动恢复信号(Q3)。任何人类或 AI operator 必须严格按下列显式顺序恢复:
- 观察阶段(只读): 经
GET /api/v1/github-sync/bindings/{id}/status确认state = parked、reason = remote_diverged,获取local_main_oid、last_pushed、in_flight_new_oid与generation。 - 带外核对与对齐: 外部人员或系统先在 GitHub 侧带外核对分歧提交并对齐远端
refs/heads/maintip(首选无历史重写路径,使远端main等于本地local_main_oid)。 - 显式授权恢复命令(首选
cursor_reset): 持cursor_resetscope 的具名 token 调用POST /api/v1/github-sync/bindings/{id}/cursor-reset,请求体显式携带expected_remote_tip与expected_local_oid(及可选expected_generation)。 - 失败态与冲突保护: 服务端实时重新执行 SSH
advertise并重读本地原生main(OX-78);若两端不相等、任一端与请求值漂移或并发generation变化,一律 fail-closed 返回409且零游标写入、零 receive-pack;仅当确实需覆写第三 OID 且持有独立forcescope 时,才可显式调用POST .../force(同样携带expected_remote_tip与expected_local_oid)。
裁决结论(GO): 现有 Q7 status / cursor-reset / force 命令及 409 双端 expected-tip 预条件已完整表达第三 OID 后的显式恢复顺序,放行 OX-108。
为防止将本仓本地协议测试误记为真实外部 AI 已接管生产恢复,本节冻结以下不可逾越的证据与交接边界(ADR-OX-05、DEP-OX-06、DEFER-OX-03):
- 本地 fake 客户端证据范围:
OX-82/OX-117的本地 fake Q7 operator 客户端测试仅验证本仓 Q7 HTTP 状态、权限、冲突与恢复时序契约,绝不作为真实外部 AI operator 已上线或已接管的运行证据。 storage_eventsbest-effort 语义: Track 6 的github_sync.state_changed属于storage_eventsbest-effort 出站通知,不构成外部 AI 接收/处理成功回执;本仓不为外部 AI 新增专用 webhook 目标、新通知协议或回执 wire。- 跨计划移交与延后保持 open:
DEFER-OX-03(真实外部 AI operator 消费者实现与联调)在本计划全生命周期保持open;DEP-OX-06指向的PT-16仅为待外部接收的契约移交条目,不记为已完成。
裁决结论(GO): 上述本地契约与外部交接边界清晰可表达,无需新增 target、webhook 或回执 wire,放行 OX-109。
GitHub 出站同步状态变更复用既有 storage_events version-1 envelope(schema_version: 1、source: "git"、scope: { tenant_id: null, repo_path: "<canonical path>", oci_repository: null }),冻结唯一事件类型名称 github_sync.state_changed:
data.transition闭合枚举(仅四态):pushed— 普通 worker 或具名 operatorforce成功提交 cursor CAS 推进last_pushed。parked— 远端第三 OID 分歧或受控 park CAS 提交。aborted— worker 发送前 policy abort 或 operatorabort提交 park CAS。self_completed— Q4 远端已接受in_flight.new_oid经零重发自完成 CAS 提交。
data封闭字段白名单(绝不携带私钥、token、带凭证 URL、原始 stderr 或 pack 字节):binding_id:string(配置 binding ID)path:string(canonical monorepo path,与scope.repo_path一致)outbox_row_id:integer | null(可选关联 outbox 行 ID;poll-only / operator 命令无 outbox 时为null)transition:"pushed" | "parked" | "aborted" | "self_completed"reason:string | null(脱敏受控标签,无原因时为null)old_oid:string | null(旧last_pushed/remote_old40-hex OID)new_oid:string | null(目标/新last_pushed/in_flight.new_oid40-hex OID)observed_remote_oid:string | null(观察到的远端refs/heads/main40-hex OID)occurred_at:integer(Unix 秒级时间戳,与外层 envelopeoccurred_at一致)
- Golden JSON(
github_sync.state_changedversion-1 envelope):{ "schema_version": 1, "event_id": "0195a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b", "event_type": "github_sync.state_changed", "occurred_at": 1764400000, "source": "git", "scope": { "tenant_id": null, "repo_path": "/project/core", "oci_repository": null }, "data": { "binding_id": "core", "path": "/project/core", "outbox_row_id": 42, "transition": "pushed", "reason": null, "old_oid": "1111111111111111111111111111111111111111", "new_oid": "2222222222222222222222222222222222222222", "observed_remote_oid": "2222222222222222222222222222222222222222", "occurred_at": 1764400000 } }
裁决结论(GO): 既有 storage_events version-1 envelope 与 EventScope::Git 完全承载 github_sync.state_changed wire 与 golden,放行 OX-84。OX-51 已在 src/jupiter/service/storage_event.rs 落地 EventType::GithubSyncStateChanged、GithubSyncStateTransition(pushed/parked/aborted/self_completed 闭合枚举,未知值拒绝)与 EventData::GithubSyncStateChanged 投影及 golden 测试(生产发射接线前不可达);OX-87 补齐 EventSource::Git/EventScope::Git 强匹配、canonical path 与 scope.repo_path == data.path 校验、16 KiB 无截断 ProjectionDrop::Size 边界及既有事件兼容回归。
每次已提交的 github_sync_cursor CAS 均单调递增持久 generation(OX-14/OX-36/OX-136/OX-102)。github_sync.state_changed 的确定性 UUIDv5 event_id 必须以该已提交后的持久 cursor generation 与 transition 作为核心身份输入(installation/binding 命名空间与数量边界见 OX-103):
- 重试稳定向量: 同一已提交转换
(generation = 7, transition = "pushed")的重复构造/重试生成完全相同的event_id。 - 代数变化隔离向量:
generation递增(如generation = 7vsgeneration = 8,即使transition均为"pushed")必须生成不同event_id,绝不复用。 - 结果变化隔离向量:
transition不同(如"parked"vs"aborted"或"self_completed")必须生成不同event_id,绝不复用。
裁决结论(GO): 现有 github_sync_cursor.generation 已在每次状态 CAS 成功时持久递增,足以稳定唯一区分已提交转换,放行 OX-103。
在 OX-84 基础上补齐确定性 event_id 的完整四元组作用域与每轮数量契约:
- 完整命名空间键:
event_id = UUIDv5(NAMESPACE, "github_sync.state_changed:{installation_id}:{binding_id}:{generation}:{transition}");installation或binding任一变化均产生不同event_id,绝不跨安装实例或跨 binding 复用 ID。 - 无 outbox/intent 的 poll-only 身份: 无 outbox 行与无
in_flightintent 的 poll-only park(例如空仓或空闲 binding 经 Q4 轮询发现第三 OID 后提交 park CAS)依然通过该次已提交的 cursorgeneration(叠加installation、binding、transition = "parked")获得完全确定的稳定event_id。 - 单次转换数量边界: 同一 binding 的同一次已提交转换至多发起一次通知尝试(best-effort
try_emit)。 - B3 多 binding 无静默截断: 单次 B3 推送影响多个 binding 时,各 binding 拥有独立的
binding_id与独立generation,各自生成独立event_id,绝不按单轮固定件数静默截断(受限于下游 emitter 容量时仅走显式可观测的capacitydrop)。
裁决结论(GO): 四元组命名空间完整覆盖 poll-only 稳定身份且对 B3 多 binding 零静默截断,放行 OX-85。OX-60 已在 src/jupiter/service/storage_event_emitter.rs 实现确定性 github_sync_event_id(installation_id, binding_id, committed_generation, transition)(SHA-256 + UUIDv5 布局,无 outbox/intent 的 poll-only park 同样由已提交 generation 派生稳定 ID);OX-138 实现不可变快照安全字段投影 project_safe_sync_event_fields → SafeSyncEventFields(不生成 ID/JSON/日志,缺失或非法 canonical path 返回具名 SyncEventFieldProjectionError);OX-88 实现最小 typed payload builder build_github_sync_event_payload(及四态构造器 GithubSyncEventPayload,仅接受 SafeSyncEventFields、使用 github_sync_event_id 与已提交时间戳且不调用 try_emit);OX-139 实现安全 JSON wire 序列化器 project_github_sync_event_json(&GithubSyncEventPayload) 与 storage_event.rs 纵深敏感标记守卫,确保私钥、token、带凭证 URL、stderr 与原始 pack 不进入 JSON wire;OX-140 实现只读脱敏诊断投影 SafeSyncEventDiagnostic(project_github_sync_event_diagnostic / log_github_sync_event_diagnostic),确保同步事件诊断日志不格式化原始输入且不含五类敏感原文;OX-57 在 src/config/validate.rs 允许 [[storage_events.targets]].events 订阅 github_sync.state_changed 并将单 target 上限扩展至 7 项(拒绝未知字面量、重复项与第 8 项,保持既有活跃存储事件有效且维持 MTR-57 退场边界);OX-89 在 StorageEventEmitter 新增 try_emit_github_sync(GithubSyncEventPayload),仅向匹配 Git canonical path 且订阅 github_sync.state_changed 的 HTTPS HMAC target 投递,提供 disabled/filter/capacity 可观测 drop disposition 且不触碰 cursor/outbox;OX-52 在 src/ceres/github_sync/worker.rs 将 emit_committed_pushed_event 接入 complete_push_atomic 提交后分支(完整 GS-15 + cursor CAS 提交后发一件 pushed,回滚/CAS 失败/空闲无事件,同次转换重试沿用 OX-60 event_id,任意 drop disposition 不改变已提交 push 结果);OX-112 在 worker.rs 将 emit_committed_policy_abort_event 接入已提交的发送前 policy abort park CAS 分支(身份不符/远端分歧/拒删默认分支新提交 parked 时由 worker 发一件 aborted,已 parked 幂等无变更/CAS 失败零发射,同次转换重试沿用 OX-60 event_id,任意 drop 不改变已提交 parked 状态);OX-113 在 src/api/router/github_sync.rs 提供纯值分类器 classify_operator_abort_event_eligibility(&AbortCommitResult) -> Option<CommittedAbortTransition>(仅 Committed { generation } 返回 Some,已 parked/disabled/idle 幂等、陈旧 generation CAS 失败与回滚均返回 None,不持 emitter/cursor/outbox 句柄);OX-62 在 execute_operator_abort 接入 OX-113 与 emit_committed_operator_abort_event(仅在 operator_abort_in_flight_cas 提交返回 Some 后发一件 aborted,None 分支绝不调用 OX-89 admission,同次转换重试沿用 OX-60 event_id,任意 drop 不改变 HTTP 200 响应或游标);OX-114 在 src/api/router/github_sync.rs 提供纯 route 资格分类器 classify_operator_force_or_reset_event_eligibility(&OperatorForceOrResetOutcome) -> Option<CommittedOperatorPushTransition>(仅 OX-106 Success 且 cursor CAS 提交映射为 Some,陈旧 generation CAS 失败、旧 expected tips 409、无 force scope 403、cursor-reset 成功及全部 OX-106 失败变体统一映射为 None,不调用 emitter 且不重复解析 wire);OX-90 在 execute_operator_force_with_hooks 接入 OX-114 与 emit_committed_operator_force_event 作为 operator force 成功 pushed 事件的唯一 owner(None 分支含拒绝/远端失败/CAS 冲突与 cursor-reset 绝不调用 emitter,重试沿用 OX-60 event_id,普通 worker 不重复发射)。
为杜绝同一已提交转换被双路重复发射,本节冻结 worker 与 operator 路径的唯一事件 owner 归属表(poll 归属与无事件转换见 OX-104):
| 已提交状态转换 | data.transition |
唯一发射 Owner | 禁止重复发射方 |
|---|---|---|---|
| 发送前 policy abort(第三 OID 分歧 / binding identity 不符 / 拒删默认分支) | aborted |
提交该 abort park CAS 的 worker(OX-112) |
operator 路由 / poller |
具名 operator abort(活跃 in_flight → parked/operator_abort) |
aborted |
提交该 abort CAS 的 operator 路由(OX-62) |
worker / poller |
| 普通 worker 成功推送(GS-15 完整成功 + cursor/outbox 原子 CAS 提交) | pushed |
提交该成功 CAS 的 worker(OX-52) |
operator 路由 / poller |
具名 operator force 成功(GS-15 完整成功 + cursor CAS 提交) |
pushed |
提交该成功 CAS 的 operator 路由(OX-90) |
普通 worker / poller |
裁决结论(GO): 四类 worker/operator 已提交转换均存在无歧义的单一提交方作为唯一事件 owner,无归属冲突,放行 OX-104。
补齐 Q4 周期轮询提交转换的唯一 owner,以及明确不发射 github_sync.state_changed 的无事件转换:
| 状态变化 | 是否发射 github_sync.state_changed |
唯一发射 Owner / 无事件理由 |
|---|---|---|
poll 观测到第三 OID(无论有或无 in_flight intent)并提交 park CAS |
发 parked |
提交该 park CAS 的 poller(OX-93)唯一发射,worker/operator 不重复发。 |
Q4 远端已接受 in_flight.new_oid 并经自完成 CAS 收敛 |
发 self_completed |
提交该自完成 CAS 的 poller(或对应唯一自完成 CAS 提交者)唯一发射,无双 owner。 |
具名 operator cursor-reset 成功(无推送游标复位) |
不发射 | cursor-reset 不属于 pushed/parked/aborted/self_completed 四种结果转换(OX-114)。 |
无 intent 且远端恢复为 last_pushed 的 parked -> idle 自动恢复 |
不发射 | 无新推送/无自完成/无 park/无 abort,不属于四种结果转换(OX-59)。 |
裁决结论(GO): poll 提交转换均具备唯一 owner 且无事件边界清晰,无双 owner 冲突,放行 OX-86。
github_sync.state_changed 沿用既有 storage_events 的事务外 best-effort 投递边界,绝不要求事务内可靠投递或新增出站通知持久化队列:
- 已提交前置资格: 仅在对应
github_sync_cursorCAS 事务已经成功提交之后,调用方才具备调用try_emit的资格;CAS 竞争失败、前置校验拒绝或数据库事务回滚绝不产生任何通知。 - 提交后崩溃丢失窗口: 在游标 CAS 提交完成之后、调用
try_emit之前(或进程异步发送完成之前)发生进程崩溃,该条通知可能永久丢失;本契约明确不承诺状态提交与事件投递的原子性,下游系统必须通过只读GET /api/v1/github-sync/bindings/{id}/status轮询获取权威状态。
裁决结论(GO): 既有事务外非原子 try_emit 边界满足本计划通知语义,放行 OX-105。
github_sync.state_changed 严格复用既有 storage_events bounded transport 语义,不引入新的可靠投递队列或重试机制:
- 单次 POST 无后台重试: 沿用
StorageEventEmitter::try_emit的单次 HTTPS HMAC POST 语义,不新增后台重试队列或退避循环。 - 三类可观测 Drop Disposition:
disabled(storage_events未启用)、filter(目标未订阅该事件或路径过滤不匹配)与capacity(有界并发/队列满)分别沿用既有可观测 drop disposition 与计数,不静默吞错。 - Drop 与 Git 同步结果隔离: 任意 drop 或投递失败绝不回滚或改写已经提交的 Git 同步 cursor/outbox 事务结果或 operator HTTP 响应。
- 外部 AI 不可推断边界: 本事件仅为 best-effort 通知,不是外部 AI operator 接收、理解或执行恢复动作的可靠回执;本移交(
DEFER-OX-03/DEP-OX-06PT-16)不要求必达回执,权威状态始终以 Q7GET /status为准。
裁决结论(GO): 既有 bounded try_emit 与 drop disposition 完全满足本计划非必达通知边界,放行 OX-51。
OX-126(Q4 poll 纯分类接口): 在src/ceres/github_sync/poller.rs定义无 I/O 能力的不可变输入PollSnapshot(含只读PollInFlightSnapshot)与AdvertisedOid、封闭四变体枚举PollClassification::{RemoteUnchanged { has_in_flight }, SelfComplete, RemoteDiverged, FirstCreate}以及纯 traitPollClassifier::classify(&PollSnapshot, &AdvertisedOid) -> PollClassification,签名不持有任何 SSH/DB/Git 写句柄,具体 tip 判定由OX-54/OX-91/OX-122承接。OX-54(轮询 Q4 三 tip 分类): 在src/ceres/github_sync/poller.rs实现ExistingCursorPollClassifier/classify_existing_cursor:advertised == last_pushed返回RemoteUnchanged { has_in_flight }(有 intent 时不视为idle),advertised == in_flight.new_oid返回SelfComplete,第三 OID 或远端分支消失返回RemoteDiverged(绝不推断 GitHub 侧 merge 完成)。OX-91(空仓首建的 Q4 纯分类): 在src/ceres/github_sync/poller.rs新增AdvertisedOid::from_raw_tip与EmptyWithoutIntentPollClassifier/classify_empty_without_intent:无last_pushed且无in_flight时,远端缺失/零 OID 返回FirstCreate,遇任意非零远端 OID 返回RemoteDiverged(不推断远端已接受本地首推),纯判定零网络/DB I/O。OX-122(持久首建 intent 的 Q4 分类): 在src/ceres/github_sync/poller.rs新增完整纯分类器Q4PollClassifier/classify_poll_snapshot:空last_pushed且已持久化首建in_flightintent 时,远端缺失/零 OID 返回RemoteUnchanged { has_in_flight: true }(保留原 intent 供 Q5 幂等重试),等于in_flight.new_oid返回SelfComplete,其余非零远端 OID 返回RemoteDiverged(绝不推断 GitHub 侧 merge),严格走OX-126纯接口。OX-115(poll SSH advertise 与取消边界): 在src/ceres/github_sync/poller.rs新增只读PollAdvertisertrait、SshPollAdvertiser与PollAdvertiseError(仅通过配置钉住主机钥的ssh::connect+send_pack::begin_with_deadlines读取refs/heads/maintip,零 cursor/intent 写句柄;认证失败、主机钥不匹配、超时与取消均返回具名错误,取消或错误时立即abort_transport()关闭底层 TCP 连接,保证在 deadline 内退出且不遗留后台 SSH 任务)。OX-61(单轮 poll 的快照分类): 在src/ceres/github_sync/poller.rs新增只读PollOnceVerdict、PollOnceError、poll_snapshot_from_cursor与poll_once_classify(先走OX-115读远端 tip,失败即返回PollOnceError::Advertise不产出分类;再只读抓取 cursor 快照并脱离 DB/网络锁调用OX-54/OX-91/OX-122纯分类器,返回不带写句柄的只读判定 DTO 供OX-100/OX-92/OX-127独立 CAS 消费)。OX-100(poll self-complete 的 cursor CAS): 在src/jupiter/storage/github_sync_cursor.rs新增单事务 identity/generation CASpoll_self_complete_cas,并在src/ceres/github_sync/poller.rs新增PollSelfCompleteOutcome与apply_poll_self_complete(仅当OX-61判定为SelfComplete且advertised == in_flight.new_oid时原子推进last_pushed、清除in_flight_*、置idle、递增generation并完成关联 intent/outbox 且保留remote_old;失败 CAS 或重复观测已完成 OID 不改游标,零 Git 写/重发 pack)。OX-92(poll 第三 OID 的保守 park): 在src/jupiter/storage/github_sync_cursor.rs新增单 SQL cursor-only CASpoll_park_diverged_with_intent_cas(及format_poll_diverged_park_reason/extract_parked_observed_oid),在src/ceres/github_sync/poller.rs新增封闭 DTODivergedWithIntent(仅由非 parked 且有in_flight的RemoteDiverged快照构造)、cursor-only writer traitPollParkCursorWriter与apply_poll_park_diverged_with_intent(保留原in_flight/remote_old,记录观察到的第三 OID,陈旧 generation CAS 失败不覆盖新游标,重复 poll 不二次 park,类型零 SSH/Git 写句柄)。OX-127(无 intent poll-only 第三 OID park): 在src/jupiter/storage/github_sync_cursor.rs新增单 SQL cursor-only CASpoll_park_diverged_without_intent_cas(既有游标要求in_flight IS NULL、state <> 'parked'与last_pushed/generation精确匹配;尚无游标行的新绑定按ON CONFLICT (binding_id) DO NOTHING原子插入generation = 1的parked行),在src/ceres/github_sync/poller.rs新增封闭 DTODivergedWithoutIntent、cursor-only writer traitPollParkWithoutIntentCursorWriter与apply_poll_park_diverged_without_intent(保留原last_pushed,零github_sync_intent/github_sync_outbox创建入口,陈旧 CAS 或重复 poll 零二次状态转换)。OX-93(poll 已提交转换事件): 在src/ceres/github_sync/poller.rs新增封闭证明类型CommittedPollTransition(仅由已提交的OX-100PollSelfCompleteOutcome::Completed或OX-92/OX-127PollParkOutcome::Parked构造,NotApplicable/CasConflict/错误无法构造)与emit_committed_poll_transition(自完成发一件self_completed、park 发一件parked,事件身份完全经OX-60/OX-88基于已提交generation生成——OX-127无 outbox ID 同样得稳定event_id;投递经OX-89try_emit_github_sync且 drop 绝不改写已提交游标)。OX-63(轮询parked -> idle自动恢复): 在src/jupiter/storage/github_sync_cursor.rs新增单 SQL generation CASpoll_recover_parked_without_intent_cas(严格要求state = 'parked'、in_flight_new_oid IS NULL、in_flight_remote_old IS NULL、last_pushed = expected_last_pushed与generation = expected_generation),在src/ceres/github_sync/poller.rs新增PollRecoverIdleOutcome与apply_poll_recover_parked_to_idle(有in_flight时返回NotApplicable绝不形成idle + in_flight,陈旧 generation 不覆盖新状态,重复 poll 无二次转换;按OX-104不接收 emitter 从而零github_sync.state_changed事件)。OX-94(parked intent 重试资格判定): 在src/ceres/github_sync/poller.rs新增封闭类型RetryCandidate(不含idle态变体,杜绝idle + in_flight)与纯判定函数classify_parked_intent_retry(&PollSnapshot, &AdvertisedOid) -> Option<RetryCandidate>(及错误包装classify_parked_intent_retry_from_result):仅当is_parked == true、保留in_flight且advertised == last_pushed(或首建空远端AbsentOrZero)时返回Some(RetryCandidate),其余 tip 与 advertise/cursor 错误返回None,严格沿用OX-126纯接口且不修改parked状态。OX-116(parked intent 原命令重试 CAS): 在src/jupiter/storage/github_sync_cursor.rs新增单 SQL identity/generation CASpoll_promote_parked_intent_cas(严格要求state = 'parked'、精确generation与原in_flight4-tuple 且存在匹配github_sync_intent行,原子提升为in_flight、清除park_reason、递增generation并保留原in_flight_*tuple),在src/ceres/github_sync/poller.rs新增PollRetryPromoteOutcome与apply_poll_parked_intent_retry(&RetryCandidate, &GithubSyncCursorStorage)(仅接受OX-94封闭候选,陈旧 CAS 返回CasConflict不覆盖并发更新,重复 poll 不新建 intent 行,零 Git/SSH 写句柄)。OX-121(Q4 单轮结果分派): 在src/ceres/github_sync/poller.rs新增PollRoundError、PollRoundDispatchOutcome、穷尽式单轮分派器dispatch_poll_verdict与组合入口run_poll_round(单次穷尽match至多执行一条状态转换:SelfComplete→OX-100+OX-93,RemoteDiverged { has_in_flight: true }→OX-92+OX-93,RemoteDiverged { has_in_flight: false }→OX-127+OX-93,其余分类暂返NoTransition待OX-132扩展,零 Git 写句柄)。OX-132(Q4 unchanged 恢复分派): 在src/ceres/github_sync/poller.rs扩展PollRoundDispatchOutcome与dispatch_poll_verdict的RemoteUnchanged两条已 parked 分支:无in_flight→OX-63(RecoveredToIdle,无事件),有in_flight→ 先OX-94资格判定再OX-116(PromotedParkedIntent,保留原 intent tuple);其余非 parkedRemoteUnchanged与FirstCreate保持NoTransition,advertise 错误或 CAS 冲突即终态返回、不在同轮改选另一分支且零 Git 写。OX-55(轮询频率配置): 在src/config/{model,validate,reload,template}.rs、config/config.toml与中英文配置指南新增github_sync.poll_interval_seconds(默认60,有效范围10..=3600,超界 fail-closed 拒载,热加载记录为restart_required_fields保持快照不变,旧配置省略该字段自动按默认60加载)。OX-95(poll 选择与有界节奏): 在src/ceres/github_sync/poller.rs新增只读标识PollBindingIdentity与有界选择器PollTickSelector(仅在config.enabled时从当前配置 binding 产出 tick,相邻 tick 遵循OX-55的poll_interval_seconds,同 binding 活跃 poll 数经active_bindings/mark_finished严格限制<= 1,返回类型仅含只读身份且零 GitHub/SSH/cursor 写句柄)。OX-59(轮询服务生命周期 — Track 7 收官 19/19): 在src/ceres/github_sync/poller.rs新增PollClock/TokioPollClock与GithubSyncPollerService(消费OX-95PollTickSelectortick、将每个 eligible binding 分派至OX-121/OX-132run_poll_round,自带实例与服务级单例守卫、关停时向全部活跃子任务传播CancellationToken并等待全部 join,阻塞中的 SSH advertise 通过abort_transport()在既定 deadline 内退出),并在src/server/http_server.rs挂载spawn_github_sync_poller_task与优雅关停shutdown_and_join(禁用时零启动、重复启动不产生第二个 poller、关停后零后台 SSH 任务)。
OX-21(live runner 显式 opt-in): 新增独立 runnerscripts/github-sync-live.sh(默认不随普通cargo test触发):缺少显式MEGA_TEST_GITHUB_LIVE=1时立即以非零退出并输出guard_stage=opt_in guard_reason=missing_explicit_opt_in,零 REST/SSH 网络请求且零凭据回显。OX-38(官方 SSH 主机钥钉住): 在scripts/github-sync-live.sh新增纯离线守卫guard_official_ssh_host_pin_from_stdin(--guard-official-host-pin),强制钉住ssh_host=ssh.github.com:443、ssh_user=git(禁止默认端口 22)及官方 Ed25519 OpenSSH 公钥(严格核验官方指纹SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU,并由russh::keys::PublicKey::from_openssh解析验证);拒绝空 pin、known_hosts整行、非官方指纹与ssh-keyscan/TOFU 来源(VER-1live_official_host_pin)。OX-05(实现契约与索引收口 — Q1–Q8 / ADR-OX-01 / ADR-OX-02 实现锚点核对):- Q1–Q8 产品实现锚点: Q1/Q2/Q3/Q5 推送引擎与三态/游标 CAS(
src/ceres/github_sync/、src/jupiter/storage/github_sync_{outbox,cursor}.rs)、Q4 周期轮询与parked -> idle自动恢复(Track 7OX-126..OX-59)、Q6a/Q6b 有界 pack 编码器与峰值 4 MiB 驻留预算(ADR-OX-02OX-27/OX-12/OX-178,不限制累计流大小,不保留累计 4 MiB 口径)、Q7 具名 operator HTTP API / 鉴权 / 审计 / AI 协议(Track 5OX-37..OX-117)、Q8 配置/Vault/主机钥(Track 1),以及ADR-OX-04github_sync.state_changed通知(Track 6)均已本地验收。 - ADR-OX-01 测试/产品隔离边界: 产品路径严禁任何 GitHub PAT、deploy key 或 REST 客户端;仅
scripts/github-sync-live.sh在显式MEGA_TEST_GITHUB_LIVE=1+OX-375同 UUID durable accepted receipt 放行下于隔离私仓使用测试 PAT(仅 REST 建仓/登记 deploy key,runner 零 DELETE 路径)与一次性0600deploy 私钥(仅 SSH 推送)。 - Live dispatch、脱敏归档与安全退出归属:
OX-238唯一拥有真实 REST/SSH dispatch(--worker-first-push/--worker-two-push),OX-376拥有 UUID-scoped 脱敏 bundle/index 归档(--write-evidence-archive/--verify-archive),OX-379拥有唯一安全退出门(--terminal-archive-exit-gate)。 - Live 验收与发布状态:
OX-24(独立新仓真实首推)与OX-06(新 UUID 同仓真实双推与终态清理)两张有界 live spike 仍待真网验收;唯一末尾 patch 发布与 tag D 由OX-284承接,OX-283/OX-20在 D 后关闭DEFER-GS-08。
- Q1–Q8 产品实现锚点: Q1/Q2/Q3/Q5 推送引擎与三态/游标 CAS(
Closed 2026-09-20. docs/plan/plan-template.md GC-12 / ER-01 /
ER-07 now match AGENTS.md「Task card release」: this repo is
Libra-managed (.libra present, .git absent). Workflow is
libra add / libra commit -s -m / libra push origin main.
DEP-02 is closed. README.md Contributing lists the three
cargo gates and defers VCS commands to AGENTS.md.