# Objective Guard capabilities and flows

Each capability distinguishes observed behavior `[Fact]`, inferences `[Inference]`, and gaps `[Ambiguity]`. CAP-02, CAP-10, and CAP-11 have partial or complete executable implementation; the rest describe the planned product.

### CAP-01 — Receive immediate feedback after an edit

- Actor: programming agent.
- Surface: edit-triggered hook.
- Objective: know a local violation before building new steps on top of it.
- Preconditions: hook installed; file inside a supported repository.
- Trigger: write or edit completed by the agent.
- Main flow:
  1. The hook receives the modified file.
  2. Objective Guard obtains relevant content and diff.
  3. Executes universal detectors with timeout.
  4. Compares fingerprints with previous state.
  5. Emits only new findings and logs the event.
- Variants / observable errors: [Inference] no findings emits no noise; [Inference] timeout logs `error` and does not block; [Ambiguity] exact hook format depends on first harness.
- Expected result: the agent receives a compact delta within latency budget.
- Rules / permissions involved: level 0 requires no contract; maximum five lines; `error` is not equivalent to `pass`.
- Data / entities touched: file, diff, fingerprint, event, local state.
- Evidence: `docs/product/02-product-contract.md` RF-01 to RF-04; `docs/product/04-technical-architecture.md` Level 0.
- Open gaps: choose initial harness and measure real latency.

### CAP-02 — Detect universal drift without configuration

- Actor: programming agent.
- Surface: hook and local CLI.
- Objective: detect objectively risky patterns even if no task contract exists.
- Preconditions: diff available; language or manifest supported by detector.
- Trigger: execution of level 0.
- Main flow:
  1. Analyzes file syntax.
  2. Compares tests before and after.
  3. Searches for new stubs in production.
  4. Inspects manifests for new dependencies.
  5. Produces facts separated by rule.
- Variants / observable errors: [Inference] unsupported files are reported as out of scope; [Inference] a new dependency starts as warning; [Ambiguity] initial heuristic for assertion drop.
- Expected result: each fact includes rule, file, location, and reproduction.
- Rules / permissions involved: a disabled test can block; a stub or dependency only warns by default.
- Data / entities touched: AST, manifests, tests, diff, findings.
- Evidence: `docs/product/06-roadmap-and-criteria.md` MVP and functional criteria.
- Open gaps: build golden corpus JS/TS and decide Java support.

### CAP-03 — Avoid repetition of known findings

- Actor: programming agent.
- Surface: hook and local storage.
- Objective: save tokens and prevent fatigue from repeated warnings.
- Preconditions: fingerprintable finding; local state accessible.
- Trigger: a detector produces a finding.
- Main flow:
  1. Normalizes rule, file, window, and message.
  2. Calculates versioned fingerprint.
  3. Compares with active fingerprints.
  4. Emits only novelties.
  5. Summarizes resolutions and updates state.
- Variants / observable errors: [Inference] deleted state can re-report; [Inference] corrupted state must not cause silence; [Ambiguity] migration policy between rule versions.
- Expected result: consecutive executions without changes do not repeat the same finding.
- Rules / permissions involved: state is discardable; delta-only mandatory.
- Data / entities touched: fingerprints, rule version, state.json.
- Evidence: `docs/product/04-technical-architecture.md` Persistence and protocol.
- Open gaps: define exact window normalization and file movements.

### CAP-04 — Formalize a task via session contract

- Actor: supervising developer and programming agent.
- Surface: CLI and session contract.
- Objective: make objective, scope, criteria, and invariants observable.
- Preconditions: original request available; repository at least partially discovered.
- Trigger: explicit session start or transition from `discovery`.
- Main flow:
  1. Preserves original objective without rewriting it.
  2. Registers task type and criteria.
  3. Declares objective set, scope, and sensitive zones.
  4. Composes global and local policies.
  5. Validates and versions the compiled contract.
- Transition variant [Fact]: `next-round` requires a clean tree and matching baseline, archives the previous contract/baseline, and records `round-transition` before activating the new contract.
- Migration variant [Fact]: `adopt-baseline` allows a single adoption of a historical typed contract with a clean tree; it preserves the contract and records `baseline-adopted`.
- Variants / observable errors: [Inference] ambiguity produces `discovery`; [Inference] policy conflict shows provenance; [Ambiguity] YAML or JSON format.
- Expected result: there exists a traceable contract that enables specific checks without hiding uncertainty.
- Rules / permissions involved: higher policies are not implicitly relaxed; expansions remain recorded.
- Data / entities touched: session, objective, criteria, scope, invariants, policy rules.
- Evidence: `docs/product/02-product-contract.md` Level 1 and RF-05 to RF-07.
- Open gaps: confirmation UX, remote round hierarchy, and definitive external schema.

### CAP-05 — Execute an incremental affected check

- Actor: programming agent.
- Surface: local CLI by save or turn.
- Objective: obtain relevant evidence without running the entire suite.
- Preconditions: diff available; repository adapter detects units and commands.
- Trigger: `oguard round-end --mode fast` or automatic checkpoint.
- Main flow:
  1. Calculates affected paths, static relative imports, modules, and declared public boundaries.
  2. Declares graph uncertainty.
  3. Plans inspectable checks.
  4. Executes only the checks declared for `fast` (or without mode restriction).
  5. Reuses cache and updates evidence.
- Variants / observable errors: [Inference] high uncertainty expands checks; [Inference] cache miss increases latency; [Ambiguity] initial test selection by ecosystem.
- Expected result: quick verdict with checks executed, omitted, `mode: fast`, and declared scope; an unknown required criterion remains `unknown`.
- Rules / permissions involved: cost proportional to impact; no omitted check is presented as approved.
- Data / entities touched: graph, planned checks, cache keys, evidence.
- Evidence: `docs/product/04-technical-architecture.md` Level 1.
- Open gaps: [Fact] the Node adapter propagates static relative JS/MJS/CJS imports to transitive consumers and, for public boundaries declared by path, to the exact consumer workspaces; a workspace dependency alone does not widen the impact of an internal file. Declared checks reuse local cache only with identical inputs, contract, and environment. [Ambiguity] aliases, dynamic imports, TypeScript, symbols, distributed cache, and a calibrated public propagation threshold are still missing.

### CAP-06 — Close a task with complete traceability

- Actor: programming agent and supervising developer.
- Surface: CLI final mode and CI integration.
- Objective: demonstrate which criteria were tested and which remain unknown.
- Preconditions: active session; defined criteria; changes available.
- Trigger: close request or CI verification via `oguard round-end --mode final`.
- Main flow:
  1. Iterates through each acceptance criterion.
  2. Links tests, contracts, or reproducible commands.
  3. Executes checks declared for `final` (or without mode restriction).
  4. Marks `proven`, `violated`, `unknown`, or `not_applicable`.
  5. Emits auditable artifact and verdict.
- Variants / observable errors: [Fact] any required `unknown` criterion blocks in `final`; checks outside the mode remain `skipped` and are not approved; [Inference] exception preserves the fact; [Ambiguity] CI artifact format.
- Expected result: no criterion silently disappears from closure.
- Rules / permissions involved: `not_applicable` requires justification; runner error does not count as positive evidence.
- Data / entities touched: criteria, evidence, exceptions, final report.
- Evidence: `docs/product/02-product-contract.md` RF-10 to RF-13.
- Open gaps: [Fact] feature, refactor, improvement, migration, and investigation obligations reference versioned criteria and block closure if missing; [Ambiguity] artifact retention and signing are still missing.

### CAP-07 — Request and audit an exception

- Actor: programming agent and supervising developer.
- Surface: CLI or approval mechanism.
- Objective: allow legitimate expansion without erasing observed violation.
- Preconditions: identified finding or policy; authorized actor available.
- Trigger: explicit exception request.
- Main flow:
  1. Records rule, reason, and scope.
  2. Identifies approver actor and expiration.
  3. Evaluates whether policy permits exception.
  4. Preserves original fact.
  5. Modifies only the decision and audits the result.
- Variants / observable errors: [Inference] insufficient authority rejects; [Inference] expired exception re-applies; [Ambiguity] integration with external identity.
- Expected result: work can continue only within approved scope and without losing traceability.
- Rules / permissions involved: no self-approval of sensitive changes; an exception does not convert a violation into historical `pass`.
- Data / entities touched: finding, policy decision, actor, approval, expiration.
- Evidence: `docs/product/02-product-contract.md` RF-11.
- Open gaps: [Fact] the versioned local exception requires rule, reason, actor, expiration, and paths; it preserves the warning and exempts only the decision; [Ambiguity] external identity, remote approval, and approval storage are still missing.

### CAP-08 — Measure drift without initially influencing the agent

- Actor: researcher or evaluator.
- Surface: event log and offline scientific report.
- Objective: calibrate surface and evidence before activating statistical alerts.
- Preconditions: append-only trajectories; labels or outcomes; dataset separation.
- Trigger: periodic offline analysis or benchmark.
- Main flow:
  1. Reconstructs complete trajectory.
  2. [Fact] calculates surface vector, discrete per-round AUS, scope-based distance proxy, and relative evidence using versioned formulas.
  3. [Fact] exports passive, disjoint, and deterministic `calibration` / `evaluation` partitions.
  4. [Inference] compares against simple baselines.
  5. [Inference] calibrates on training repositories and evaluates on unseen repositories.
- Variants / observable errors: [Inference] absent ground truth limits distance; [Inference] insufficient sample prevents activation; [Ambiguity] anonymization requirements across organizations.
- Expected result: reproducible dataset that can conclude the signal is not useful, without changing the round's verdict.
- Rules / permissions involved: passive statistics until validation; do not adjust thresholds on final test.
- Data / entities touched: events, features, labels, calibration set, evaluation set.
- Evidence: `synthetic/scenarios/task-trajectories-v1.mjs`; `synthetic/results/task-trajectories-v1.json`; `docs/product/05-scientific-validation.md` Evidence ladder.
- Open gaps: minimum real volume, out-of-sample evaluation, and privacy policy.

### CAP-09 — Intervene with a validated statistical signal

- Actor: programming agent and supervising developer.
- Surface: hook or CLI.
- Objective: pause anomalous expansions before they become terminal.
- Preconditions: out-of-sample calibrated detector; approved intervention trial; active policy.
- Trigger: trajectory crosses pre-registered threshold.
- Main flow:
  1. Calculates non-conformance with frozen version.
  2. Explains primary factors.
  3. Distinguishes anomaly from incorrectness.
  4. Expands checks or requests justification.
  5. Records response and outcome.
- Variants / observable errors: [Inference] moderate signal only warns; [Inference] distribution drift deactivates governance; [Ambiguity] recalibration frequency.
- Expected result: net cost reduction without diminishing correct resolution.
- Rules / permissions involved: never block on opaque score alone; versioned thresholds.
- Data / entities touched: feature vector, calibration version, alert, response, outcome.
- Evidence: `docs/product/03-signal-and-decision-model.md` Policy decision; `docs/product/05-scientific-validation.md` H5.
- Open gaps: empirical evidence still inexistent.

### CAP-10 — Validate documentation against its contract

- Actor: platform team.
- Surface: documentary guard.
- Objective: prevent documentation from losing required layers, fields, or links.
- Preconditions: Node.js available; execution from repository root.
- Trigger: `node scripts/validate-docs.mjs`.
- Main flow:
  1. Verifies canonical and historical files.
  2. Checks contractual headings.
  3. Validates fields of each capability.
  4. Validates matrix and relative links.
  5. Returns `PASS` or `BLOCK` with causes.
- Variants / observable errors: [Fact] missing files produce exit code 1; [Fact] a broken relative link blocks; [Ambiguity] does not yet validate complete semantics.
- Expected result: only a documentary topology satisfying the encoded contract is accepted.
- Rules / permissions involved: does not modify documents; result reproducible locally.
- Data / entities touched: Markdown files and contract embedded in the script.
- Evidence: `scripts/validate-docs.mjs` functions for required files, capabilities, matrix, and links.
- Open gaps: add external schema if contract grows.

### CAP-11 — Assess a round's contribution to hierarchical objectives

- Actor: programming agent and supervising developer.
- Surface: `oguard align`, `npm run round:end`, the `oguard.contract.json` contract, and versioned evidence.
- Objective: warn about material local progress that contributes no evidence to the target KRs and also crosses a declared scope or non-goal boundary.
- Preconditions: [Fact] Git repository; valid schema v1 contract; diff against `HEAD`; KRs with evidence patterns; `goal_substitution` policy configured.
- Trigger: early `oguard align` query after a patch, or round closure via `npm run round:end`.
- Main flow:
  1. [Fact] loads the parent objective, round objective, KRs, scope, non-goals, and thresholds.
  2. [Fact] measures files, lines added/removed, churn, modules, entropy, and out-of-scope files.
  3. [Fact] attributes modified files as evidence candidates for each target KR.
  4. [Fact] prints a compact reminder of objective, round, surface, and evidence per KR.
  5. [Fact] emits a single `goal-substitution` warning if material surface, zero evidence for target KRs, and observable scope/non-goal deviation coincide.
  6. [Fact] records contract hash, surface, and alignment; the export strips sensitive text and paths.
- Variants / observable errors: [Fact] invalid contract ends with error; [Fact] absent contract keeps existing checks without evaluating alignment; [Fact] incremental in-scope work without evidence does not alert; [Fact] evidence for the target KR suppresses the alert; [Fact] a change below both thresholds does not alert.
- Expected result: the agent receives an explainable, non-blocking warning when the change reproduces goal substitution; an aligned round reports contribution without noise.
- Rules / permissions involved: warning with exit 0; modified paths are candidates, not semantic proof of the KR; the statistical signal remains passive; invalid IDs and hierarchy are not accepted.
- Data / entities touched: versioned contract, hash, diff, surface vector, per-KR contributions, warnings, and event log.
- Evidence: `src/contract.mjs` `validateContract`; `src/surface.mjs` `measureSurface`; `src/alignment.mjs` `evaluateAlignment`; `test/alignment.test.mjs`; `synthetic/scenarios/e001-goal-substitution.json`.
- Open gaps: [Ambiguity] `proven` evidence is not yet distinguished from a path-based candidate; [Ambiguity] semantic distance and imports are left for a later phase; [Ambiguity] statistical thresholds do not activate until pre-registered volume is reached.
