리뷰에서 확인된 Milestone 식별자와 컴파일 바이너리 상태 검증의 빈틈을 보완하고, 활성 agent-task에서는 dispatcher만 실행 경로로 사용하도록 고정한다.
176 lines
45 KiB
Markdown
176 lines
45 KiB
Markdown
# IOP Agent CLI Runtime Contract
|
|
|
|
## Contract metadata
|
|
|
|
- id: `iop.agent-cli-runtime`
|
|
- boundary: `inner`
|
|
- status: active
|
|
- shared contract dependency: `iop.agent-runtime`
|
|
- implemented S05 source: `packages/go/agentconfig/runtime_config.go`, `packages/go/agentconfig/watcher.go`.
|
|
- implemented S07 source: `packages/go/agentprovider/cli/status/quota.go`, `packages/go/agentpolicy/quota.go`, `packages/go/agentpolicy/failure_policy.go`, `packages/go/agenttask/ports.go`, and `packages/go/agenttask/dispatch.go`.
|
|
- implemented S09 source: `packages/go/agentstate/store.go`, `packages/go/agenttask/ports.go`, `packages/go/agenttask/intent.go`, and `packages/go/agenttask/reconcile.go`.
|
|
- implemented S11 source/tests: `proto/iop/agent.proto`, generated `proto/gen/iop/agent.pb.go`, `apps/agent/internal/localcontrol/protocol.go`, `apps/agent/internal/localcontrol/ledger.go`, `apps/agent/internal/localcontrol/service.go`, `apps/agent/internal/localcontrol/server.go`, `apps/agent/internal/localcontrol/peercred.go`, `apps/agent/internal/localcontrol/peercred_linux.go`, `apps/agent/internal/localcontrol/peercred_darwin.go`, `apps/agent/internal/localcontrol/peercred_unsupported.go`, and the focused `apps/agent/internal/localcontrol/*_test.go` matrix.
|
|
- implemented S12 source/tests: `packages/go/agenttask/types.go`, `packages/go/agenttask/state_machine.go`, `packages/go/agenttask/manager.go`, `packages/go/agenttask/reconcile.go`, `packages/go/agenttask/review.go`, `packages/go/agenttask/state_machine_test.go`, `packages/go/agenttask/manager_integration_test.go`, `apps/agent/internal/projectlog/sink.go`, `apps/agent/internal/projectlog/store.go`, `apps/agent/internal/projectlog/record.go`, `apps/agent/internal/projectlog/sink_test.go`, `apps/agent/internal/projectlog/store_test.go`, and `apps/agent/internal/projectlog/record_test.go`.
|
|
- implemented S13 source/tests: `apps/agent/internal/taskloop/testdata/parity.yaml`, `apps/agent/internal/taskloop/parity.go`, `apps/agent/internal/taskloop/parity_test.go`, `apps/agent/internal/taskloop/cutover_test.go`, `apps/agent/internal/command/task_loop.go`, `apps/agent/internal/command/task_loop_test.go`, and `apps/agent/cmd/agent/main.go`. The bounded `task-loop` command delegates to the existing `taskloop.Runtime`; `task-loop validate-plan` is the Go-owned active workflow validator, and the manifest discovers every retained Python source/test fixture below its reference root, checksum-binds the exact inventory, and proves zero production callers without claiming shared runtime ownership.
|
|
- implemented S15 source/tests: user-local client schema and validation in `packages/go/agentconfig/runtime_config.go` and `runtime_config_test.go`; daemon process ownership and durable reconciliation in `apps/agent/internal/clientprocess/types.go`, `process.go`, `store.go`, `manager.go`, `manager_test.go`, and `store_test.go`; authenticated/idempotent client command adaptation in `apps/agent/internal/localcontrol/client_operations.go` and `client_operations_test.go`.
|
|
- implemented S18 source: `packages/go/agentworkspace/snapshot.go`, `packages/go/agentworkspace/overlay.go`, and `packages/go/agentworkspace/confinement*.go`.
|
|
- implemented S10 source/tests: `apps/agent/cmd/agent/main.go`, `apps/agent/cmd/agent/main_test.go`, `apps/agent/internal/command/root.go`, `apps/agent/internal/command/service.go`, `apps/agent/internal/command/root_test.go`, `apps/agent/internal/command/config_test.go`, `apps/agent/internal/bootstrap/module.go`, `apps/agent/internal/bootstrap/module_test.go`, `apps/agent/internal/taskloop/workflow.go`, `apps/agent/internal/taskloop/workflow_test.go`, `apps/agent/internal/taskloop/module.go`, `apps/agent/internal/taskloop/recovery.go`, and their focused tests. CLI reads and mutations reconstruct the same checksum-protected manager state, while `serve` owns sustained reconciliation and exposes that runtime through local control. Deterministic fake-provider composition tests drive the real persisted manager through canonical review, validation rollback, sibling continuation, restart, project logs, and terminal archive evidence without launching a real provider CLI.
|
|
- implemented standalone S06/S08/S19 host bindings: `apps/agent/internal/taskloop/workflow.go`, `provider.go`, `recovery.go`, `evidence.go`, `review.go`, `integration.go`, `module.go`, and their focused tests. These adapters normalize host artifacts and locators; shared selection, lifecycle, admission, review sequencing, and integration state transitions remain owned by `iop.agent-runtime`. Closure coverage includes canonical verdict parsing, retained-confinement official review, same-native-session Pi repair, active-artifact preservation, common ordered policy composition, mandatory validation, rollback, and independent queue continuation.
|
|
- implemented S14 harness/schema: `scripts/e2e-iop-agent-logged-smoke.sh`, `scripts/fixtures/iop-agent-smoke-manifest.schema.json`, and the `test-iop-agent-logged-smoke-preflight` / `test-iop-agent-logged-smoke` Make targets. Local evidence covers syntax, an actual 13-file safe bundle, deletion/symlink/tamper/digest/schema/path/duplicate/terminal/restart rejection cases, exact-PID cleanup, deterministic fixture seeding, and the pre-login Darwin gate. Completion evidence is the 6,757-byte redacted manifest plus its exact 13 bounded JSON evidence files at `agent-task/m-iop-agent-cli-runtime/25+19,21,22,23,24_logged_smoke_closure/`, produced on Darwin arm64 from source/build/clone commit `8e55719a928a01f88f7f5e3d2574e3ea810035e8` and tree `ed741ffa781c6b52eea59175b1cb5a4891e1b0e8`; the manifest SHA-256 is `77b351792ceb235b0eaf80ef66feb48d4387b49b84517cb916ab4412ca8d906b`.
|
|
- design input: `agent-roadmap/sdd/automation-runtime-bridge/iop-agent-cli-runtime/SDD.md`
|
|
|
|
## Read when
|
|
|
|
- changing standalone `iop-agent` process lifecycle, repo-global/user-local configuration precedence, device singleton ownership, or host-local checkpoint and recovery records;
|
|
- checking standalone S07 quota/failure evidence ownership or its delegated shared-runtime continuation boundary;
|
|
- changing the host extension points for workspace isolation or change-set persistence while preserving the shared runtime ports owned by `iop.agent-runtime`;
|
|
- changing `AgentLocalEnvelope`, `AgentLocalRequest`, `AgentLocalResponse`, `AgentLocalEvent`, or `AgentLocalError`, including peer authorization, command idempotency, replay, or failure behavior;
|
|
- changing Flutter or Unity client-process start, stop, focus, reconnect, crash recovery, or Unity-to-Flutter detail routing.
|
|
|
|
## Scope and non-scope
|
|
|
|
This contract defines the standalone host boundary for one device-local `iop-agent` daemon. It owns host configuration composition, daemon and client-process ownership, the local control protocol, and host-local durable records that reference shared-runtime identities.
|
|
|
|
`iop.agent-runtime` is the sole authoritative contract for common provider execution, `agenttask.Manager` lifecycle and state transitions, `agentguard` admission and Permit validation, review, integration ports, and their source paths. This contract may require the host to call those shared boundaries, but it does not restate their rules or claim their implementation sources.
|
|
|
|
The Edge-Node wire and Edge configuration contracts remain owned by `iop.edge-node-runtime-wire` and `iop.edge-config-runtime-refresh`. The local-control schema remains client-neutral, while S11 concretely carries `AgentLocalEnvelope` from `proto/iop/agent.proto` over an owner-only Unix proto-socket. Linux authorizes peers with kernel `SO_PEERCRED`; Darwin uses kernel `LOCAL_PEERCRED`, the non-cgo `getpeereid`-equivalent credential primitive. Unsupported platforms fail before listening.
|
|
|
|
## Evidence map
|
|
|
|
| Scenario | Required evidence | Completion evidence expectation |
|
|
|----------|-------------------|---------------------------------|
|
|
| S05 | Repo-global/user-local precedence, invalid configuration, immutable repo input, and revision-change tests | `config-registry` evidence records both revisions and confirms the repo is not mutated. |
|
|
| S06 | Ordered selection persistence and tamper rejection tests | `target-policy` evidence records the selected rule, reason, and retained route history. |
|
|
| S07 | Snapshot tamper/reason/not-applicable tests, sealed safe observation projection, strict durable projection round trips, common-policy manager integration, unused-target history, and failure-budget tests | `quota-failure` evidence records content-bound immutable snapshots, canonical corrupt blockers, exact attempt/target transitions, sealed disk round trips, and no reused candidate. Shared semantics are authoritative in `iop.agent-runtime`. |
|
|
| S08 | `TestReadReviewVerdictAcceptsCanonicalOverallVerdict`, `TestCatalogReviewExecutorRequiresExactRetainedConfinement`, `TestPiEvidenceRepairResumesExactNativeSession`, `TestWorkerPromptPreservesActiveArtifactsForOfficialReview`, and `TestOfficialReviewPromptPreservesRetainedArtifacts` | `workflow-evidence` proves canonical review parsing, exact retained executable confinement, same-native-session repair followed by fresh evidence, zero direct provider launch in deterministic tests, and active PLAN/review preservation until manager-owned integration. |
|
|
| S09 | Device singleton, workspace lease, checkpoint, restart, and archive fault tests | `state-recovery` proves no duplicate owner and exact retained state. |
|
|
| S10 | Binary entry point, split configuration, validation, discovery, selection, lifecycle, and status commands; exact failure-context selector coverage; and `TestWorkflowMilestonesListsSelectableTaskGroups`, `TestWorkflowArchiveOnlyMilestoneRemainsSelectable`, `TestInspectTaskGroupArchiveOnly`, `TestRunMilestoneListAndSelectionShareCatalog`, `TestAdapterStatusPreservesAllWork`, `TestRunFullHeadlessS10Transcript`, `TestBuiltBinaryHeadlessS10Transcript`, `TestRuntimeFakeProviderPersistedLifecycleRollbackAndRestart`, `TestCommandAdapterFakeProviderPersistedLifecycleRollbackAndRestart`, and `TestDaemonFakeProviderPersistedLifecycleRollbackAndRestart` | `cli-surface` is implemented by one authoritative `taskloop.Runtime` composition in CLI and daemon paths. The tests prove Milestone catalog discovery/selection parity, per-work status DTOs with durable dispatch ordinals, archive-only completion semantics, full ordered failure predicates, canonical review, mandatory validation rollback, independent sibling completion, persisted command/local-control projections, restart convergence, exact dispatch counts, ordered project logs, terminal archives, and compiled binary transcript evidence with proof-owned no-op child processes and no real provider CLI. |
|
|
| S11 | `TestServerSameUserProtoSocket`, `TestPeerUIDMismatchDeniedBeforeDispatch`, `TestServerBroadcastsCommittedEventToConcurrentClients`, `TestServerRejectsUnsafePaths`, `TestServerStopPreservesReplacedSocketPath`, `TestProtocolValidationMatrix`, `TestCommandIdempotencySurvivesRestart`, `TestCommandIDConflictHasZeroMutation`, `TestReplayGapRequiresSnapshot`, `TestServiceRejectedFramesHaveZeroCalls`, and the fresh package/race plus Darwin arm64 cross-build commands in the active code-review artifact | `local-control` proves an owner-only Unix socket, kernel same-user authorization with no app-token fallback, zero dispatch for denied or malformed peers, durable command-id convergence, ordered live and retained events, explicit replay-gap recovery, and a coherent snapshot cursor. |
|
|
| S12 | `TestManagerEventDeliveryUsesCommittedEvidence` and `TestManagerEventDeliveryRecoversSinkFailure` in `packages/go/agenttask/manager_integration_test.go`; `TestSinkPendingDeliveryUsesExactCommittedEvidence`, `TestSinkReplayShortCircuitsEvidenceAfterClockAndStateAdvance`, `TestSinkRejectsLogicalEventIDReuseAcrossScopesBeforeEvidenceResolution`, `TestStoreEventReplayFingerprintSurvivesPruneAndRestart`, `TestStoreRejectsLogicalEventIDReuseAcrossScopes`, `TestStoreEventReplayIndexRecoversLegacyScopedEntry`, `TestStoreEventReplayIndexSerializesCrossScopeCAS`, and `TestS12LoopParallelArchiveMatrix` in `apps/agent/internal/projectlog/*_test.go`; atomic state-store coverage in `TestStoreIntegrationRecordBatchCAS`; fresh race verification: `go test -count=1 -race ./packages/go/agentstate ./apps/agent/internal/projectlog -run 'TestStoreIntegrationRecordBatchCAS|TestStoreEventReplayIndexSerializesCrossScopeCAS|TestS12LoopParallelArchiveMatrix'` | `project-logs` proves commit-before-observe manager ordering, returned-but-recoverable sink failure, exact pending-delivery evidence, project-wide replay identity before volatile projection or caller scope, atomic index/journal persistence, fail-closed legacy recovery and scope drift, 11 explicit review-failure/follow-up pairs, independent same-project task completion, complete redacted WORK_LOG JSONL, and exactly-once task-scoped terminal archive reconciliation for every crash phase. |
|
|
| S13 | `parity.yaml` disposition and disposal inventory, `ValidateParityManifest`, `TestParityEmbeddedManifestIsCompleteAndCurrent`, `TestParityManifestRejectsUnrecordedRetainedFixture`, `TestCutoverProductionOwnershipHasNoReferenceCallerOrStaticRouteTable`, `TestCutoverProductionOwnershipRejectsInjectedPythonCaller`, `task-loop validate-plan`, and the `task-loop parity --disposal-manifest` command | The manifest permits `absorb`, `replace`, or `not-applicable` exactly once per behavior, requires concrete Go source/test evidence, discovers and verifies every retained Python source/test fixture checksum, and rejects stale, unclassified, or unrecorded rows. Production callers and static routing ownership are rejected by deterministic repository guards, while active plan/review workflows use the Go validator. Physical disposal remains prohibited until the Milestone-completion transition: verify `retained` hashes and cutover, delete only the recorded fixtures, change the manifest to `disposed`, then rerun parity/cutover. A disposed manifest requires the exact inventory to be absent and retained-fixture discovery to be empty, so partial or mixed states fail. |
|
|
| S14 | Exact-source logged-in macOS run through discovery, two-project preview/start, cancellation isolation, new invocation, live daemon crash recovery, and terminal completion; strict redacted manifest and evidence-file validation | The executable harness fails before provider login or process launch on non-Darwin hosts, validates one exact clean commit/tree across source and two distinct clean clones, and owns only its exact daemon PID/start identity. The Darwin arm64 run at commit `8e55719a928a01f88f7f5e3d2574e3ea810035e8` proves a durable review while the selected invocation is live, then derives no-duplicate recovery from increasing state revision and identical attempt, process-locator revision, PID/start identity. Both projects completed with absorbing terminal traces and terminal archives. The promoted 6,757-byte manifest and all 13 referenced files pass in-place digest, schema, shape, regular-file, redaction, and same-directory validation; manifest SHA-256 is `77b351792ceb235b0eaf80ef66feb48d4387b49b84517cb916ab4412ca8d906b`. |
|
|
| S15 | `TestManagerOwnsSingletonAndReapsClient`, `TestDuplicateLaunchConvergesAfterManagerRestart`, `TestDaemonSurvivesCrashAndBoundedRestart`, `TestS15ClientLifecycleTrace`, `TestReconcileBlocksAmbiguousIdentityWithoutLaunch`, `TestClientOperationMatrix`, `TestUnityDetailStartsOrFocusesFlutter`, `TestRejectedClientCommandHasZeroProcessCalls`, `TestAcceptedIncompleteClientCommandReusesExactManagerReceiptAfterStateChange`, `TestCommandReceiptCapacityMatchesLedger`, `TestStartConfiguredLaunchesAfterDaemonRestart`, `TestCloseStopsCurrentGenerationAfterPriorLifecycleReceipts`, `TestConcurrentCloseCancelsInFlightFocus`, `TestConcurrentCloseCancelsInFlightDetail`, `TestConcurrentCloseFencesConnectionMutation`, `TestCommandReceiptCompletionSaveFailureStaysPending`, `TestRecordRejectsInvalidCommandReceiptProjection`, `TestClosePreservesAmbiguousIdentityBeforeAdoption`, and `TestClosePreservesAmbiguousAdoptedIdentity`; fresh focused/race suites and Darwin arm64 cross-build | `client-process-manager` proves one PID/start identity per kind, exact reaping, live adoption without duplicate launch, bounded crash restart, disconnect/reconnect without daemon cancellation, fail-closed ambiguous recovery, and Unity detail routing only to daemon-owned Flutter start/focus. Completed external client receipts replay only an immutable accepted result for the matching command action and strict action-specific lifecycle projection; a completion save failure leaves the durable pending receipt in place and never replays an aborted or non-durable success. Ambiguous close preserves the retained identity, returns bounded error evidence, and permits durable reaping only after a proven exit; daemon lifecycle generations do not create or reuse external command receipts, and close cancels admitted mutations before reaping the current identity. |
|
|
| S18 | `packages/go/agentworkspace/overlay_test.go` and `confinement_test.go` cover dirty/untracked/mode/symlink fingerprinting, identical concurrent bases, same-file and disjoint writes, a real confined child that can change content and metadata only in its view/temp/cache roots, protected `chmod`/`utime`/`chown`/`setxattr` denial, canonical/sibling/snapshot/overlay-record/shared-Git denial, exact root/config/grant replay rejection, idempotency, and failure retention. | `overlay-workspace` proves the executable child boundary and retained records preserve one exact immutable base and isolated writable layers. |
|
|
| S19 | `TestIntegrationDelegatesCleanConflictRetentionAndQueueContinuation`, `TestIntegrationRequiresPostApplyValidator`, and `TestIntegrationValidationFailureRollsBackAndAllowsIndependentQueue` | `change-set-integration` proves retained host records identify the exact immutable change set, a missing validator fails construction, post-apply validation failure rolls back the canonical root, the blocker is retained, and an independent sibling continues in queue order. |
|
|
|
|
## Standalone host schemas and durable records
|
|
|
|
The following are contract-first records owned by the standalone host. They define host inputs, durable backend state, and host-facing projections; they do not define shared runtime lifecycle, admission, review, or integration algorithms.
|
|
|
|
| Schema | Host-owned contract |
|
|
|---|---|
|
|
| `RuntimeConfig` | A versioned composition of read-only repo-global defaults and user-local configuration. It records both immutable input revisions, applies user-local values after repo-global values, replaces ordered arrays rather than appending them, and owns local roots without writing device state or credentials to the repo. |
|
|
| `ProjectRegistration` | A user-local, revisioned registration of one project identity and canonical workspace reference, including the applicable configuration revision and host recovery metadata. It does not mutate the repo-global configuration or create a shared runtime lease by itself. |
|
|
| `SelectionPolicy` | The versioned policy input supplied to the shared selector: ordered rules, local overrides, and retained route-history references. The host preserves the resolved policy revision and route evidence, while `iop.agent-runtime` remains the owner of selection and failover algorithms. |
|
|
| `PreviewRequest` | An immutable request identifying the project, workspace, configuration and policy revisions to evaluate. Preview uses the same delegated decision boundary without dispatching a provider, creating an isolation layer, changing persisted state, or otherwise causing a side effect. |
|
|
| `WorkspaceSnapshot` | A versioned immutable base fingerprint that records and hashes the normalized canonical root, exact configuration and grant revisions, Git revision/index identity, tracked and untracked content, dirty state, file modes, and symlink identity. A snapshot may be reused only when this complete identity matches. |
|
|
| `OverlayWorkspace` | A durable isolation record for one task identity that records the same canonical/configuration/grant identity, exact base snapshot, writable layer, merged read view, task-local temporary/cache roots, isolated Git metadata reference, executable confinement revision, and retention/recovery state. An idempotent replay with a different root or revision is rejected without changing the retained record. |
|
|
| `ChangeSet` | A frozen, content-addressed host persistence record with the exact base fingerprint and change-set revision, additions/modifications/deletions, mode or symlink operations, write set, and validation evidence. It remains immutable after review acceptance and is retained for recovery and later integration attempts. |
|
|
| `IntegrationRecord` | A revisioned record of one exact change set and integration attempt: dispatch and attempt ordinals, expected and observed before fingerprints, predecessor references, apply/validation outcome, rollback or blocker evidence, after fingerprint, cleanup state, and retention identity. It records delegated integration results but does not decide integration order or outcome. |
|
|
| `ProjectLogRecord` | An append-only host presentation and recovery projection that connects project/work-unit and attempt identities with route/quota observations, process or session references, overlay/change-set/integration locators, failures, retries, review evidence, and completion state. |
|
|
| `IntegrationStatus` | A current host-facing recovery projection for a task/change-set and ordinal, including queued/integrating/integrated/blocked state, conflict or blocker reference, retained overlay reference, and available recovery action. It reports shared runtime results without owning integration decisions. |
|
|
|
|
- The host owns one device-local daemon identity and the client-process records associated with that daemon. A live owner prevents a second daemon from taking over until the prior owner is conclusively released or expired.
|
|
- `taskloop.Runtime` is the single standalone application owner around the shared `agenttask.Manager`. One immutable runtime snapshot, provider catalog, `agentstate.Store`, workflow adapter, workspace backend, provider/recovery/evidence/review/integration ports, and project-log sink are composed once for `serve`. CLI commands reconstruct only bounded read or mutation ownership over the same durable state; they never run the sustained reconciliation loop.
|
|
- Explicit milestone selection is stored as a checksum-protected integration record. Workflow discovery reads only registered project roots and requires exactly one active PLAN/review pair per active task directory, bounded literal write-set rows, stable task aliases, and exact completed predecessor evidence. Unknown, disabled, unselected, malformed, escaping, or identity-drifted inputs fail closed.
|
|
- The host-local state file uses a versioned JSON envelope containing a monotonically increasing CAS revision, the manager snapshot, and a SHA-256 checksum over the schema/revision/state tuple. Writes use a same-directory temporary file, file sync, atomic rename, directory sync, and an advisory lock shared by all store instances. A checksum failure, malformed envelope, or unsupported schema is returned without overwriting the original evidence.
|
|
- The manager claims the durable device singleton before reconciliation and retains it via an immutable fencing token (scope/owner/token/subject handle) for the daemon owner. A background supervisor renews device, project, workspace, and integration leases by CAS at a bounded fraction of `LeaseDuration`. The guarded reconciliation context is cancelled the moment any renewal cannot prove its token still matches current state. Project and workspace invocation leases plus the workspace integration lease are acquired with the same CAS state; a foreign unexpired lease prevents execution, while an expired lease is eligible for an identity-checked takeover. Every external result is followed by an atomic fence check against all live tokens before entering durable state; on loss the guarded context is cancelled, the external call is cancelled, and only exact tokens are released—never overwriting a successor lease.
|
|
- Provider invocation is checkpoint-first. `Start` returns opaque process/session locators, the manager persists them before `Wait`, and restart reconciliation delegates those locators to `RecoveryInspector`. Proven-live work is retained, an exact recovered submission advances to review, and stale, exited-without-result, partial-completion, or ambiguous observations become typed blockers with zero provider invocation. Recovery copies only process and optional session locators into a reconstructed provider submission; overlay and other host locators remain host-owned.
|
|
- Process, session, overlay, change-set, and completion locators carry the exact project, workspace, work-unit, attempt, kind, and revision identity. Failure budgets are persisted per stage and become a non-retryable `failure_budget_exhausted` blocker at their configured limit.
|
|
- Shared `agenttask.Manager` durably enqueues an exact pending delivery only after its project/work evidence commits. `StartProject`, `StopProject`, and `Reconcile` return sink failures without deleting the envelope; restart replays the same `EventID`, timestamp, evidence revision, project, and work snapshot and acknowledges it only after sink success.
|
|
- The standalone event sink prefers the matching pending delivery over current manager state. It does not derive state from event type, reinterpret workflow revision as manager state revision, or fabricate route-selection identities. Project-only events may omit work evidence.
|
|
- Work records are journaled under deterministic project/workspace/work-unit scopes, while one project-wide replay index owns each manager `EventID` projection across all those scopes. The retained entry includes the exact project-only or work-unit scope, assigned task-local sequence, and stable logical event fingerprint. The sink checks this entry before evidence resolution and before trusting caller scope; `Timestamp` and projection `StateRevision` changes retain the original sequence across restart/archive/prune, while changed logical content or scope drift under one manager `EventID` fails closed for work-to-work, project-to-work, and work-to-project reuse.
|
|
- A new manager event uses one atomic integration-record batch to commit the project-wide replay index and exactly one target journal. Stale shared-index writers cannot leave a partial journal record. When an index entry is absent, the host scans checksum-covered legacy scoped journals for the same project/workspace, rejects conflicting duplicate ownership, and persists a recovered entry before replay. Generic records without an event fingerprint remain scope-local and require normal evidence resolution.
|
|
- The archived timeline remains the full redacted `WorkLogEntry` JSONL projection rather than a reduced legacy timeline.
|
|
- S07 host records persist only the safe shared-runtime `AttemptObservationRecord`, exact attempted target identity, and manager-owned failure budget. Valid/stale quota projections retain the shared runtime's private integrity seal over every policy-visible field; strict durable decoding rejects seal drift before state use. Quota normalization, `not_applicable` semantics, policy ordering, used-target exclusion, and the final `DecideContinuation` result remain owned by `iop.agent-runtime`; the standalone host does not duplicate or override them.
|
|
- Every host record carries an explicit schema version and preserves referenced configuration, shared-runtime, workspace, isolation, base, change-set, and integration revisions exactly. Retention and cleanup must leave enough identity to recover or report a retained blocker.
|
|
- Corrupt state, an unsupported schema version, or a mismatched referenced identity is a typed host failure or blocker. The host must not silently reset a record, rebind it to current inputs, fabricate a replacement identity, or treat it as a successful recovery.
|
|
- Host isolation and change-set implementations are extension points. Their preparation, admission, review, and integration semantics remain delegated to `iop.agent-runtime`; the host preserves returned immutable identities when persisting or presenting state.
|
|
|
|
## Workspace overlay and executable confinement
|
|
|
|
- The default overlay backend materializes an immutable snapshot tree and isolated Git metadata, confirms that the canonical fingerprint did not drift during capture, and installs one private task view plus task-local temp and cache roots. The canonical root and device-local runtime root must not overlap.
|
|
- The overlay record revision covers project/work/attempt identity, canonical/configuration/grant/profile/base identity, exact locators, and retention policy. A separate confinement revision covers that overlay revision, the platform policy revision, canonical root, protected runtime and snapshot roots, task root, view/temp/cache roots, and profile/configuration/grant revisions.
|
|
- `Prepare` fails closed before returning an admissible descriptor when the platform cannot install executable confinement. Linux admits only a probed unprivileged user/mount namespace with a recursively read-only filesystem and explicit writable task mounts; its probe requires protected content writes and `chmod`, `utime`, `chown`, and `setxattr` mutations to fail without changing metadata. macOS uses a verified `sandbox-exec` child policy. Other platforms are unsupported.
|
|
- `ConfinementProof.Start` accepts only executable name, arguments, and environment. It creates anonymous stdin/stdout/stderr pipes, installs the OS policy, starts the wrapped provider child, and returns the exact child plus parent-side pipe endpoints as one proof-owned started handle. Provider launch plans cannot supply files, readers, writers, raw descriptors, or any other inheritable I/O capability.
|
|
- The child may mutate only its view, temp, and cache roots. Canonical files, sibling task layers, immutable snapshots, the overlay record, and shared Git metadata remain non-writable even when addressed by absolute path or when the host opened a writable descriptor before launch. The descriptor cannot enter the child because child I/O is created exclusively by the confinement owner.
|
|
- Provider binding receives only the exact started handle returned by the proof. Before a successful ownership transfer, an incomplete handle or bind failure closes every pipe endpoint, terminates the child, and reaps it. Provider authentication and command binaries may be read outside the task roots, but the child receives no writable exception for them; temporary and cache output must be routed into task-local roots.
|
|
|
|
## Runtime configuration composition and revisions
|
|
|
|
- `RepoGlobalRuntimeConfig` is the strict, versioned repository input. It may contain the secret-free provider catalog, runtime defaults, ordered selection policy, isolation modes, and retention limits. The registry reads this source with no repository write API and never opens it for writing.
|
|
- `UserLocalRuntimeConfig` is the strict, versioned device input. It contains device-local state, overlay, log, optional temporary/cache roots, Flutter/Unity argv-only process policies, scalar and map overrides, and project registrations with project-specific overrides. Client policies contain absolute executable and working-directory paths, argument arrays, launch/restart bounds, and Flutter focus arguments; credential values and arbitrary environment values are not fields in this schema and are rejected as unknown fields.
|
|
- Each source must contain exactly one YAML document at the supported schema version. Unknown fields, malformed values, invalid catalog references, non-absolute required device/workspace paths, unsupported isolation modes, duplicate selection rule identities, and negative retention limits fail the load.
|
|
- Composition is deterministic: an explicitly present user-local scalar replaces the repo-global scalar, profile-alias maps merge by key with the local value winning, and ordered selection-rule and isolation-fallback arrays replace the complete preceding array instead of appending. The same rules apply again for each project override.
|
|
- A `RuntimeSnapshot` records SHA-256 revisions of the exact repo-global and user-local inputs plus a derived runtime revision. Its merged value is private; config and project accessors return defensive deep copies. Each effective `ProjectRegistration` carries the applicable runtime revision, and each effective `SelectionPolicy` carries a derived policy revision.
|
|
- `RuntimeConfigWatcher` keeps the last valid snapshot when either input is invalid and publishes only a valid changed revision. An invocation that already captured revision A remains pinned to A; a later invocation obtains revision B after B has loaded and validated successfully.
|
|
|
|
## Local control protocol version and envelope
|
|
|
|
- The daemon owns exactly one local proto-socket endpoint per device-local daemon identity. It publishes client-neutral state and accepts local control only through this boundary.
|
|
- The canonical schema is `proto/iop/agent.proto`; Go bindings are generated at `proto/gen/iop/agent.pb.go` through `make proto`. `proto/iop/control.proto` remains the Control Plane wire and is not reused.
|
|
- `apps/agent/internal/localcontrol/server.go` provides bounded proto-socket framing over a Unix listener. The state root must be an owned `0700` directory and the socket must remain the originally created owned socket at mode `0600`; symlinks, pre-existing paths, unsupported platforms, and replacement identities fail closed.
|
|
- Peer authorization runs before a protocol session or service dispatch. `peercred_linux.go` reads `SO_PEERCRED`; `peercred_darwin.go` reads `LOCAL_PEERCRED` through `getpeereidUID`; both must equal the daemon effective UID. There is no app-token field or fallback.
|
|
- `AgentLocalEnvelope` is the outer schema for every frame. It contains `protocol_version`, `kind`, `message_id`, `correlation_id`, optional `event_sequence`, optional `operation`, and a typed payload. `kind` is exactly `request`, `response`, `event`, or `error`.
|
|
- `AgentLocalRequest` carries a request envelope, operation arguments, and an optional replay cursor. Every mutating request also carries a stable, caller-generated `command_id`.
|
|
- `AgentLocalResponse` carries the correlated operation result, current state revision or snapshot marker when applicable, and the accepted `command_id` for a mutation.
|
|
- `AgentLocalEvent` carries an ordered `event_sequence`, event type, subject identity, state revision, and a payload that is sufficient to update a current snapshot.
|
|
- `AgentLocalError` carries a stable error code, safe message, retryability, correlation identifier, and recovery metadata such as the current replay floor or snapshot marker.
|
|
- Protocol versions are explicit. A peer must not assume that an unknown envelope field, version, operation, or event type is safe to ignore when doing so could alter command meaning.
|
|
|
|
## Operations, authorization, and idempotency
|
|
|
|
| Operation class | Operations | Required behavior |
|
|
|-----------------|------------|-------------------|
|
|
| Read | `runtime.status`, `project.status`, `overlay.status`, `integration.status`, `blocker.list`, `process.status` | Return a coherent host snapshot or a typed absence/error response without mutation. |
|
|
| Project mutation | `project.start`, `project.stop`, `project.resume` | Require `command_id`; delegate shared lifecycle actions to `iop.agent-runtime`; persist only host-owned command presentation and recovery state. |
|
|
| Client mutation | `client.start`, `client.stop`, `client.focus`, `client.detail` | Require `command_id`; execute only through daemon-owned client-process records. `client.detail` routes a supported Unity detail request to Flutter start/focus through the daemon. |
|
|
|
|
- The daemon authorizes a peer from local socket ownership and peer credential evidence. It accepts only a peer with the same effective OS user as the daemon; all other peers receive `permission_denied` before command dispatch.
|
|
- A client uses no app token for this boundary, and no app-token fallback may bypass peer credential or same OS user authorization.
|
|
- Repeating a mutation with the same `command_id`, operation, and immutable arguments returns the original accepted result without a second mutation. Reusing that `command_id` with different operation or arguments returns `command_id_conflict` and performs no mutation.
|
|
- A rejected frame, failed authorization, unsupported operation, invalid state, or idempotency conflict performs no mutation and does not create a substitute command record.
|
|
- S11 implements every read and project-mutation operation through the narrow `StateReader` and `ProjectController` host ports. S15 implements the typed `client.*` mutation adapter in `client_operations.go`; it applies the same peer-authorization input, strict request validation, replay, durable command acceptance, immutable-argument conflict check, final response, and retained-event ledger before invoking the daemon-owned process controller. The standalone S11 `Service` continues to fail closed for client mutations until the host composition supplies this S15 adapter.
|
|
|
|
## Replay, delivery, and failures
|
|
|
|
- Events are ordered by a monotonically increasing `event_sequence` within one daemon identity. Clients may reconnect with a replay cursor and must tolerate duplicate retained events by deduplicating their sequence.
|
|
- The daemon replays retained events after the requested cursor when the cursor is within retention. If the cursor predates the retention floor, belongs to another daemon identity, or cannot form a contiguous replay, it returns `replay_unavailable` with `snapshot_required` recovery metadata instead of silently omitting state changes.
|
|
- A snapshot response establishes the current state revision and replay cursor from which later events may resume. The daemon may coalesce non-essential progress events, but it must not claim a replay that hides a state transition represented by the current snapshot.
|
|
- Command acceptance, the original response, state revision, retained event envelopes, replay floor, and next sequence are one versioned JSON ledger stored under a checksum-covered `agentstate.Store` integration record. Mutation events are appended only after durable command acceptance; identical replay after restart returns the stored response without a second host mutation.
|
|
- Connected same-user sessions receive committed event envelopes live. The retained ledger remains authoritative: a client reconnects with its last contiguous daemon/sequence cursor, and any daemon mismatch, stale floor, future cursor, or discontinuity requires a fresh snapshot.
|
|
- `AgentLocalError` uses typed codes at minimum: `malformed_frame`, `unsupported_version`, `unsupported_operation`, `invalid_state`, `permission_denied`, `command_id_conflict`, `replay_unavailable`, and `internal`.
|
|
- Error payloads exclude credentials, tokens, raw private paths, and unbounded subprocess output. Internal failures are correlated and surfaced as safe diagnostics without changing command state unless the command had already been accepted and recorded.
|
|
|
|
## Client-process lifecycle
|
|
|
|
- `ClientProcessSpec` identifies a Flutter or Unity absolute executable and working directory, argv arrays, launch and bounded crash-restart policy, and Flutter focus arguments. It is accepted only in user-local configuration; repo-global client fields, unknown kinds, environment maps, credentials, relative paths, negative or unbounded restart policy, and Unity focus arguments are rejected.
|
|
- For each client kind, `clientprocess.Manager` is the only process owner and tracks `stopped`, `starting`, `connected`, and `crashed` in a checksum-covered `client-process/<kind>` integration record. Each live record binds the PID to an OS-observed start token, retains the prior identity for evidence, and has exactly one child waiter or adopted-process watcher. A duplicate start inspects and converges on that live identity instead of creating a second subprocess.
|
|
- Reconciliation distinguishes proven live, exited, stale PID reuse, and ambiguous identity. Proven live work is adopted, exited/stale work becomes `crashed`, and ambiguous or in-flight state without a persisted identity blocks replacement launch. A conclusively reaped daemon-owned crash may consume the configured backoff/attempt budget; CAS conflict prevents process start or state overwrite.
|
|
- Disconnect changes only the connected projection while the daemon retains process ownership; reconnect restores `connected`. Client exit and crash never cancel the manager/daemon context. Stop verifies the exact identity, sends termination, bounds the wait, kills only that identity when needed, and completes after the direct child is reaped or an adopted identity is proven exited. An ambiguous identity is close error evidence, not exit evidence: close preserves its durable identity and blocker, joins adopted watcher ownership after cancellation, and never fabricates a stopped or crashed reaping transition.
|
|
- A caller receipt first persists as pending. A completed receipt persists only with its action-specific state, connection, and changed-result projection; if that completion save fails, the exact prior durable pending projection and revision are restored in memory. A later command replay therefore remains pending until a durable completion exists.
|
|
- Unity never starts, stops, focuses, or directly communicates with Flutter. A validated Unity `client.detail` request is translated by `ClientOperations` into one atomic `StartOrFocusFlutter` call; absent Flutter starts, while live Flutter executes the configured focus argv as a daemon-owned, reaped command.
|
|
- Stopping or exiting a client never stops the daemon or transfers runtime, project, provider, scheduling, retry, or integration ownership to a client.
|
|
|
|
## Prohibitions
|
|
|
|
- Do not duplicate `agenttask` or `agentguard` source-path ownership, lifecycle rules, admission rules, Permit validation, review rules, or integration-port semantics in this contract.
|
|
- Do not implement a direct client-to-client control path, an app-token authorization fallback, or a cross-user local control path.
|
|
- Do not dispatch a mutating operation before peer authorization and `command_id` validation, or make rejected frames mutate host state.
|
|
- Do not silently discard a replay gap, fabricate a contiguous event sequence, or treat a stale cursor as a current snapshot.
|
|
- Do not let a client own daemon lifecycle or shared-runtime execution decisions.
|
|
- Do not store device paths, checkpoint state, client process records, or credentials in repo-global configuration or project task artifacts.
|
|
|
|
## Change checklist
|
|
|
|
- Read `agent-contract/inner/agent-runtime.md` before changing any shared runtime dependency; update that contract rather than this one when the common owner changes.
|
|
- For local-control changes, update the operation matrix, authorization, idempotency, replay, failure, and client lifecycle rules together.
|
|
- For a concrete transport implementation, add its actual host source paths and focused tests in the implementing S11 or S15 task; do not backfill speculative paths here.
|
|
- For durable-state changes, run the `agentstate` checksum/atomic-CAS suite and the `agenttask` restart, duplicate-owner, cancel, corruption, partial-completion, and failure-budget matrices under the race detector.
|
|
- For S07 changes, run the status snapshot integrity matrix, `agentpolicy` continuation matrix, `agenttask` multi-failure history and malformed-evidence matrix, and the shared `agentpolicy`/`agenttask` race suites.
|
|
- For S12 changes, run `go test -count=1 -race ./packages/go/agenttask ./apps/agent/internal/projectlog -run 'TestManagerEventDelivery|TestS12LoopParallelArchiveMatrix'`, `go test -count=1 -race ./packages/go/agentstate ./apps/agent/internal/projectlog -run 'TestStoreIntegrationRecordBatchCAS|TestStoreEventReplayIndexSerializesCrossScopeCAS'`, and the full fresh `agenttask`, `projectlog`, and `agentstate` race suites.
|
|
- For S15 changes, run `go test -count=1 ./packages/go/agentconfig ./apps/agent/internal/clientprocess ./apps/agent/internal/localcontrol`, `go test -count=1 -race ./apps/agent/internal/clientprocess ./apps/agent/internal/localcontrol ./packages/go/agentstate`, and `GOOS=darwin GOARCH=arm64 go test -c -o /tmp/clientprocess-darwin.test ./apps/agent/internal/clientprocess`.
|
|
- For workspace isolation changes, verify `packages/go/agentworkspace/*_test.go` together with the shared `agentguard` and `agenttask` suites.
|
|
- For S10 changes, run `gofmt -w apps/agent/internal/taskloop/*.go apps/agent/cmd/agent/*.go apps/agent/internal/bootstrap/*.go`, the fresh focused and race suites for `taskloop`, CLI, bootstrap, `agenttask`, and `agentstate`, `go vet ./apps/agent/internal/taskloop ./apps/agent/cmd/agent ./apps/agent/internal/bootstrap ./packages/go/...`, `make build-agent`, the Darwin arm64 cross-build, `make test-iop-agent-logged-smoke-preflight`, and `git diff --check`.
|
|
- For S14 closure, run the exact `test-iop-agent-logged-smoke` Make target on a clean logged-in macOS runner with every explicit path/revision variable. Validate the resulting `manifest.json` again with `--validate-manifest`; do not promote raw provider logs, paths, credentials, or unbounded subprocess output into review evidence.
|
|
- Verify standalone contract changes with index ownership searches, S11/S15 anchor searches, the relevant future host tests when they exist, and `git diff --check`.
|