diff --git a/AGENTS.md b/AGENTS.md index 679c120472..8f9a663e37 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,397 +3,162 @@ ## What LoopX Does LoopX is a local-first, runtime-neutral control plane for long-horizon agents -and personal agent teams. The Agent host supplies models and tools; LoopX keeps -goals, decisions, work ownership and evidence durable across sessions and hosts. -The core objective is better long-horizon effectiveness and efficiency: more -independently verifiable outcome value within comparable budgets, or comparable -accepted outcomes with less total cost and human attention. Structured state, -closed-loop feedback and evidence-driven replanning provide process supervision -across sessions, recovery and collaboration; their value depends on actual -decisions, execution and outcomes. +and personal agent teams. The host supplies models and tools; LoopX keeps goals, +decisions, ownership, and evidence durable across sessions to raise verifiable +outcome value per budget (or match outcomes with less cost and human attention). 核心目标:通过结构化状态、闭环反馈和基于证据的重规划过程监督,提升 Agent 与 Agent 团队的长程效果和长程效率:在可比预算下取得更好的可验证成果,或以更低的 完整成本与人工介入交付同等验收成果。 -- **Goals and work:** durable Goals, Todos, dependencies, acceptance and recovery. -- **Governed continuation:** heartbeat, scheduling, quota and explicit stop/wait - conditions decide when authorized work can continue. -- **Peer collaboration:** claims, leases, scoped handoffs, dependent artifacts, - receiver adoption and result return; a coordinator gains no implicit authority. -- **Personal Workspace:** App/frontend, Lark and CLI expose conversations, - settings, work, decisions, artifacts and readback over the same typed owners. -- **Capabilities and extensions:** reusable engineering, research, knowledge, - content and office workflows with explicit provider and permission boundaries. - -Start with [README](README.md), the [roadmap](docs/architecture/rfcs/loopx-overall-roadmap-v0.md), -the [capabilities](loopx/capabilities/README.md) and [protocols](docs/reference/protocols/README.md). -The roadmap distinguishes shipped boundaries from acceptance still to qualify. -Core rules live in `loopx/control_plane/`; capability contracts in -`loopx/capabilities/`; extension lifecycle in `loopx/extensions/`; optional -distributions in `packages/`; product surfaces in `apps/`. - -Codex and Antigravity load this file; `CLAUDE.md` imports the same policy for -Claude Code. Read a linked procedure when its trigger applies to the current -task; do not load every reference for every turn. Keep current work, evidence -and monitor targets in their canonical task/state, not in this file or a frozen -prompt. Keep the root within both the 24,000-byte (24 KB) Antigravity per-file -rule cap and the default 32 KiB Codex discovery budget, and do not eagerly -import linked detail documents. See -[loading](docs/development/README.md#agent-instruction-loading-and-maintenance) -for host-specific checks. - -Prefer [context](docs/development/README.md#progressive-context-for-development): -current goals, constraints and acceptance criteria first; supporting evidence and -procedures on demand under their owning read/recovery contract. - -## Goal-Oriented Development - -Before selecting non-trivial work, resolve the requested outcome from user -direction, the linked issue/task, accepted contract or demonstrated bug. For -cross-cutting LoopX work, consult the [roadmap](docs/architecture/rfcs/loopx-overall-roadmap-v0.md) -and domain acceptance without making every fix wait for every RFC or inventing a -roadmap id. Check latest `main`, related PRs and canonical Todos so older task -prose cannot override corrected direction or duplicate work. - -For recurring operational or performance failures, follow the -[optimization](docs/development/testing-and-quality.md#roadmap-aligned-optimization): -bind the failure to its owning acceptance before repair, separate caller, shared -typed transport/semantics and provider costs, and reuse the common contract. A -faster lookup, timeout increase or promotion is only interim until sustained -acceptance is proven; reconcile the existing checkpoint as evidence changes. - -Carry one compact delivery brief from task to PR (goal/source, current gap, -observable result, owning boundary and decisive acceptance evidence), keeping -private Goal state out of public artifacts. Choose a complete, independently -reviewable and reversible outcome slice. Characterization, -prerequisites, research, docs and maintenance are valid when they remove an -evidenced gap or enable a named next step. - -For long-horizon improvements, trace the accepted goal and structured state -through feedback, the replan decision, subsequent work and validated outcomes. -Check whether new evidence changed the action or justified continuing it, and -preserve negative results and uncertainty. Compare -outcomes and complete costs under comparable conditions using the -[measurement contract](docs/architecture/rfcs/long-horizon-harness-benchmark-research-program-v0.md#6-measurement-model); -do not force a direction change merely to increase replan counts. - -Continue through implementation, integration, negative cases and readback while -authorized work remains feasible. Do not stop at setup, a serializer, a mock or -an isolated smoke when the useful outcome is missing, and do not expand scope -merely to enlarge a PR. When a staged boundary is necessary, name the delivered -delta, remaining gap, next owner/dependency and verification/rollback benefit. -Reuse or update an existing successor without ceremonial follow-up tasks; real -authorization, cost and operational stop gates remain. - -When adding or extending state/protocol vocabulary (Enum, `Literal`, named -closed set or TypeScript `as const`), answer whether it reuses an owner, extends -a registered vocabulary, remains local or creates a shared contract, and follow -the [diff advisory](CONTRIBUTING.md#check-new-semantic-vocabulary-while-developing) -before the full-tree check (including intentional untracked sources). For -multi-Agent changes, qualify dependency artifacts, receiver adoption, claim/lease -handling, independent acceptance and result return; missing frontend/Lark/CLI -companion work makes a product journey partial. - -Before delivery, reconcile the result with the original/current goal, update its -task and RFC checkpoint when the boundary changes, and preserve passed, failed -and untested distinctions. If user feedback exposes the same missing outcome, -repair the owning rule, active task or projection through self-repair rather -than appending stronger prose. PR review must execute the capability-owned -`problem_context` delivery judgment. - -## Commit And PR Hygiene - -### Worktree And PR Gate - -For any tracked repository change beyond a trivial typo fix, create or use a -dedicated clean `git worktree` on a `codex/` branch based on the verified target -remote's latest `main` (or the user-named integration/release branch), verifying -merge base and actual PR base before pushing so unrelated history cannot leak. -Do not implement changes directly in a dirty primary worktree; if a dirty tree -holds valuable work, classify it read-only, copy the valuable subset into the -clean worktree, and clean the original only after merge or explicit obsolescence -(leaving unrelated untracked local artifacts alone). Every tracked change must -go through a branch PR before reaching `main` unless explicitly marked local-only. +- **Codebase map:** `loopx/control_plane/` (core rules), `loopx/capabilities/` + (capability contracts), `loopx/extensions/` (extension lifecycle), + `packages/` (optional distributions), `apps/` (product surfaces). +- **Entry docs:** [README](README.md), [roadmap](docs/architecture/rfcs/loopx-overall-roadmap-v0.md), + [capabilities](loopx/capabilities/README.md), [protocols](docs/reference/protocols/README.md). +- **Loading & maintenance:** Codex and Antigravity load this file; `CLAUDE.md` + imports `@AGENTS.md` for Claude Code. Read linked owners only when triggered—do + not eagerly inline or duplicate owner prose here. Keep this root compact so + `AGENTS.md` plus any nested `**/AGENTS.md` and host rules fit comfortably + inside both the 24,000-byte Antigravity cap and the 32 KiB Codex budget + ([loading](docs/development/README.md#agent-instruction-loading-and-maintenance)). + +## Precedence & Always-On Invariants + +**Precedence:** `Public/Private & Safety Boundary > Explicit Authority Gate > Exact-Head Evidence & Verification > Right-Sized Scope > Autonomous Continuation` + +1. **Clean worktree & PR gate:** For any tracked change beyond a trivial typo, + use a clean `git worktree` on a `codex/` branch from verified latest `main` + (or named target), checking merge base and PR base before pushing. Never edit + a dirty primary tree directly (copy valuable subsets read-only into a clean + worktree; leave unrelated untracked files alone); tracked changes reach + `main` only via PR unless marked local-only. +2. **DCO sign-off (`git commit -s`):** Every PR commit requires `Signed-off-by`; + repair missing trailers with `git commit --amend -s` or rebase before pushing + ([DCO](CONTRIBUTING.md#license-and-dco-sign-off)). +3. **Explicit staging & public/private boundary:** Before staging non-trivial + changes, read `git status --short --branch`, `git diff --stat`, + `git diff --name-only`, and `git ls-files --others --exclude-standard`; + classify every candidate path (product code, core docs, durable smoke, + local/private state, or obsolete artifact) and scan candidate contents for + credentials, private state, local absolute paths, raw logs, benchmark + trajectories/verifier output, and internal links before staging. Stage + explicit pathspecs only (**never `git add .`**), split by reviewer logic + (runtime/API, public docs/protocols, validation/cleanup). Never publish + private team/customer/meeting/reporting/strategy context, credentials, local + paths, raw logs, benchmark trajectories/verifier output, or internal links; + keep private evidence in ignored `.local/`. On public leak, stop normal + delivery, self-repair current heads, and flag remaining PR-ref/cache cleanup + as a user/support gate. +4. **Local-first CI (`wait_for_ci=false`):** Never wait on or poll remote CI + during development, review, or readiness once local deterministic gates pass + ([local-first CI](docs/development/testing-and-quality.md#local-first-premerge-gate-vs-asynchronous-ci--本地优先门禁与异步-ci), + [two-tier CI](docs/development/ci-impact-selection.md)). +5. **Merge authority boundary:** Protected surfaces (`loopx/**`, `apps/**`, + `packages/**`, permissions/authority, persisted state/receipts, + quota/scheduler/todo, CLI/API contracts) require explicit maintainer merge + authorization regardless of diff size, green CI, or published reviews. +6. **TypeScript-first single authority:** Prefer TypeScript and the existing + typed owner for domain-neutral control-plane/orchestration/projection logic + ([migration RFC](docs/architecture/rfcs/typescript-control-plane-migration-v0.md)); + never create a parallel Python decision owner or unrelated language rewrites + (stable domain providers and transport adapters may stay Python with a + placement rationale). +7. **Source-checkout Python:** From the worktree root, prepare with + `uv sync --extra test` and run `uv run --extra test python|loopx ...` + ([environment](docs/development/testing-and-quality.md#local-validation-environment--本地验证环境)). + Keep subprocesses on `sys.executable` (not nested `uv run`), verify + `sys.executable`/`loopx.__file__` when uncertain, never rewrite historical + receipts, and never commit an unrelated `uv.lock`. +8. **Complete, right-sized delivery:** Resolve the real outcome against latest + `main`, open PRs, and canonical Todos without inventing roadmap ids or making + every fix wait for every RFC; carry one compact public-safe delivery brief + (goal/source, gap, observable result, owning boundary, decisive evidence). + Continue authorized work through implementation, integration, negative cases, + and readback without inflating scope (if staged, name delta, gap, next owner, + and rollback benefit; reuse existing successors without ceremonial tasks, and + honor real authorization/cost/stop gates). Before delivery, reconcile against + the current goal, update task/RFC checkpoints when boundaries change, and + preserve passed/failed/untested and proposed/packaged/installed distinctions. +9. **Multi-Agent & companion surfaces:** Qualify dependency artifacts, receiver + adoption, claim/lease handling, independent acceptance, and result return; + inspect frontend, Lark, and CLI entrypoints before calling a change + backend-only. +10. **Self-repair recurring failures:** When behavior is surprising, too small, + contradictory, or user-flagged as wrong, use + [loopx-self-repair](skills/loopx-self-repair/SKILL.md) to fix the owning + rule, skill, projection, or smoke—never lower gates, guess around + contradictory payloads, or commit private state. + +## Task-Triggered Owner Routing + +Read linked owners **only when their trigger applies**: + +| When your task touches... | Read owner first | Non-negotiable gate | +|---|---|---| +| Goal context, long-horizon work, or measurement | [context](docs/development/README.md#progressive-context-for-development), [measurement contract](docs/architecture/rfcs/long-horizon-harness-benchmark-research-program-v0.md#6-measurement-model) | Keep live work/evidence in canonical state; trace feedback → replan → outcome; preserve negative results and uncertainty; never force replans for counts. | +| Recurring ops or perf failures | [optimization](docs/development/testing-and-quality.md#roadmap-aligned-optimization) | Bind to owning acceptance before repair; separate caller, typed transport/semantics, and provider costs; interim speedups do not prove sustained acceptance. | +| New/extended Enum, `Literal`, closed set, or TS `as const` | [diff advisory](CONTRIBUTING.md#check-new-semantic-vocabulary-while-developing) | Declare owner reuse, registered extension, local scope, or new contract before full-tree checks (include intentional untracked sources). | +| Existing EN/ZH RFC pair (`docs/architecture/rfcs/`) | `scripts/check_rfc_bilingual.py` | Both files must change in the same PR (unstaged translations do not satisfy it; paired diffs do not certify semantic equivalence). Require a verified target ref first: `: "${PR_BASE_REF:?set the verified PR target ref}" && uv run --extra test python scripts/check_rfc_bilingual.py --base "$PR_BASE_REF" --staged` pre-commit and `--head HEAD` pre-merge (also enforced by `loopx canary premerge --from-git-diff --git-diff-base "$PR_BASE_REF"`). Fails closed even with admin bypass or `wait_for_ci=false`. | +| GitHub PR review | [review workflow](skills/loopx-pr-review/SKILL.md) | Execute `pull_request_review_execution_contract_v2` (`problem_context`, typed-state, domain-neutrality, default-off parity, authority); flag substring/prose-classification risks; publish validated actionable findings + URL readback by default unless the user requested local-only/dry-run output or the finding is private or security-sensitive. | +| Named public releases | [Personal Feishu guide](docs/product/release-readiness.md#personal-feishu-release-guide), [Attribution](docs/product/release-readiness.md#release-note-checklist), [Release body](docs/product/release-readiness.md#final-release-body-usage-gate) | Verify personal ownership, tag/PR-derived bilingual attribution (omit if none), and full bilingual activation/validation/rollback/boundary release body with remote readback. | +| All product changes, including frontend, Lark, CLI journeys, new/extended caller-facing capabilities, or media captures | [frontend delivery](docs/development/frontend-delivery.md#task-first-delivery--从用户任务开始), [design system](docs/development/design.md), [viewport attention](docs/development/design.md#earn-the-users-attention), [populated-page review](docs/development/design.md#populated-page-review), [capture retention](docs/development/documentation-layout.md#visual-evidence-retention) | Read the delivery guide before implementation. Inspect existing settings and capability editors before declaring a change backend-only. **Let layout do the explaining:** remove secondary label/slogan/agent-prose clutter while keeping accessible names, constraints, errors, and recovery. Ship full journeys over typed owners; validate packaged builds on populated/narrow views with the real backend (artifact outputs like HTML/games/video use existing conversation preview/download/revision unless a workflow requires an editor). | +| Size/structure/latency budget failure or prose edits | [budget decisions](docs/development/testing-and-quality.md#budget-failure-decisions) | Compare same base/head workload and info value vs redundancy; never relabel failures. Agent-consumed prose is behavior: audit clauses via `observable_semantics.decision_text_assessment` and route detail instead of silently truncating. | +| Refactors or storage/authority backends | [real-path gate](docs/development/testing-and-quality.md#refactor-real-path-gate--重构真实路径门), [default provider](docs/development/testing-and-quality.md#default-provider-performance-qualification--默认-provider-性能资格) | Validate production entrypoint + real backend beyond mocks; PostgreSQL requires isolated real server (unavailable = evidence gap, not pass); never mutate active Goal/registry/Todo state. SQLite qualifies default local perf; correctness/durability apply to every affected backend. | +| New module, capability, extension, field, flag, fixture, or abstraction | [placement](docs/reference/extensions.md#placement-decision-for-agents), [scope fit](docs/development/README.md#scope-fit-review) | Name capabilities after caller outcomes; record capability/provider/origin and owner gap first; require active caller/contract; characterize before moving; derive tests from independent semantics; keep contracts typed and domain-neutral; disclose default changes. | +| Automation & recurring watch Todos | [prompt layers](docs/heartbeat-automation-prompt.md#two-prompt-layers) | Keep generic heartbeat prompts free of one-off monitor policy; store watches in canonical `continuous_monitor` Todos (`claimed_by`, `unblocks_todo_id`, evidence); edit saved prompts only for lifecycle contract changes or explicit scheduler requests. | +| Display / projection sinks | [projection contract](docs/product/core-control-plane/state-machine.md#7-projection-sink-machine) | Project bounded public-safe state with lineage; redact multi-user sinks; require explicit user auth for owner-only boards. A sink displays state; it never becomes authority. | +| Smokes & benchmarks | [good smokes](docs/development/good-smokes.md), [benchmark boundaries](docs/development/good-smokes.md#benchmark-boundaries), [archives](benchmark/README.md#archive-placement) | Protect shipped contracts with independent semantic oracles and public-safe fixtures; review smokes over ~500 lines; keep raw tasks/trajectories/logs/credentials/private paths and archives out of CI. | + +## Pinned Root Contracts ### Author Submission And Review Entry -Open a completed, independently reviewable proposal as a normal PR. Missing -review, pending/failed CI, change-quality holds and unavailable merge readiness -are not reasons to keep it Draft; record those limits in the PR and reserve -Draft for unfinished author work with a concrete remaining step. For an -authorized author delivery, mark a completed Draft ready, read back its state -and unchanged head, and refresh the review packet (Drafts are excluded from the -review queue). A reviewer must obey the packet's action authority and may not +Open a completed, independently reviewable proposal as a normal PR. Reserve +Draft strictly for unfinished author work with a concrete remaining step—never +for missing review, pending/failed CI, change-quality holds, or unavailable +merge readiness (disclose those limits in the PR). For authorized author +delivery, mark a completed Draft ready, read back its state and unchanged head, +and refresh the review packet. Reviewers must obey packet authority and never mark another author's Draft ready without authorization. Keep exact-head review, -required validation, first-screen evidence and merge authorization separate. -Agents/subagents must not wait on or poll remote CI during development, review or -readiness when local gates pass (`wait_for_ci=false`); see -[local-first CI](docs/development/testing-and-quality.md#local-first-premerge-gate-vs-asynchronous-ci--本地优先门禁与异步-ci) -and [two-tier CI](docs/development/ci-impact-selection.md). - -### DCO Sign-Off - -Every PR commit needs a `Signed-off-by` trailer: always use `git commit -s`. -Repair a missing trailer with `git commit --amend -s` or rebase before pushing -(see [DCO](CONTRIBUTING.md#license-and-dco-sign-off)). - -### Bilingual RFC Diff Gate - -For an existing English/Chinese RFC pair under `docs/architecture/rfcs/`, -including ledger entries, both files must change in the same PR. Check staged -files before committing against the verified PR target ref (`PR_BASE_REF`): - -```bash -: "${PR_BASE_REF:?set the verified PR target ref}" -uv run --extra test python scripts/check_rfc_bilingual.py --base "$PR_BASE_REF" --staged -``` - -Before merge, run `uv run --extra test python scripts/check_rfc_bilingual.py --base "$PR_BASE_REF" --head HEAD` -against the PR's target branch and exact reviewed head (`uv run --extra test loopx canary premerge --from-git-diff --git-diff-base "$PR_BASE_REF"` -runs this as a direct blocking check, including in the quick tier). A failure holds merge even when CI waiting is -disabled or admin bypass is authorized; unstaged translations cannot satisfy it, -and paired diffs do not certify semantic equivalence. - -### Staging And Public Boundary - -Before staging non-trivial changes: - -1. Read `git status --short --branch`, `git diff --stat`, `git diff --name-only` - and `git ls-files --others --exclude-standard`. -2. Classify every path (product code, core docs, durable smoke, local/private - state, or obsolete artifact) and scan for credentials, private state, local - absolute paths, raw benchmark logs/trajectories/verifier output and internal links. -3. Stage explicit pathspecs only (`never git add .`), split by reviewer logic - (runtime/API, public docs/protocols, validation/cleanup), and follow - [capture retention](docs/development/documentation-layout.md#visual-evidence-retention) - before staging media or capture manifests. +required validation, first-screen evidence, and merge authorization separate. ### Merge Authority And Validation -Before approval or merge, read the repository-kept -[merge workflow](skills/loopx-pr-merge/SKILL.md) and its -[self-merge rules](skills/loopx-pr-merge/SKILL.md#self-merge-eligibility-and-benchmark-exceptions); -installing it is optional and does not replace repository policy or the current -capability-owned review. - -Control-plane, runtime and product surfaces (`loopx/**`, `apps/**`, `packages/**`, -permissions/authority, persisted state/receipts, quota/scheduler/todo rules, and -CLI/API contracts) require explicit maintainer merge authorization. Propose and -review the exact head, pass required validation, and run merge-readiness -(`uv run --extra test loopx pr-review --check-merge-readiness NUMBER@HEAD_OID`, -plus `--goal-id GOAL` for Goal-managed work) for that unchanged head. -Normal merge requires `ready=true` and `admin_bypass_required=false`. -With explicit maintainer authorization, admin bypass may override a -`ready=false` readiness or GitHub policy hold, but never missing exact-head -review, required validation, unresolved findings or threads, a changed head, -an unmergeable conflict, or absent merge authority. Without authorization, defer to the maintainer regardless of diff size, -CI, or published reviews. - -For author-owned PRs, GitHub blocks formal self-approval: publish a `COMMENTED` -review on the exact head carrying the approval conclusion and an English verdict. -Maintainers may self-merge single-purpose, low-risk public-doc, contributor -metadata, test, example or narrow-cleanup PRs (and the bounded benchmark -seam/helper exceptions) only when all conditions in -[self-merge rules](skills/loopx-pr-merge/SKILL.md#self-merge-eligibility-and-benchmark-exceptions) -hold and `uv run --extra test loopx canary premerge --from-git-diff --git-diff-base "$PR_BASE_REF"` -(or equivalent risk-based validation) passes. After merging, sync local `main`, preserve unrelated untracked artifacts -and continue the next safe project batch. - -### Named Public Releases - -Before completing a named public release, follow the existing release owners: - -- [Personal Feishu guide](docs/product/release-readiness.md#personal-feishu-release-guide): - verified personal user ownership, illustrated released UI, upgrade/use guidance - and ownership/text/image readback; no corporate/bot substitution, implied - announcement authority, or private account/draft/raw evidence exposure. -- [Attribution](docs/product/release-readiness.md#release-note-checklist): - derive eligible non-founder community contributions from the tag range and - merged PR metadata with concrete bilingual attribution and product-first - ordering; omit both sections when none qualifies. -- [Release body](docs/product/release-readiness.md#final-release-body-usage-gate): - teach each changed optional surface's activation, validation, disable/rollback, - authority/privacy boundary and versioned docs in both languages; validate the - complete body before publishing and after remote readback. - -## First-Screen Review Evidence - -Treat public first screens as reviewable product presentation. Within the -requested outcome, existing design contract and scoped authorization, do not -add a confirmation round before commit, push or PR submission merely because -the viewport, hero, primary CTA or opening navigation changes; reuse prior -approval across routine refinements. - -Before submitting/updating the PR, inspect the actual first viewport and put a -public-safe screenshot/browser capture directly in the PR description's visual -evidence (with useful before/after and desktop/narrow views, preview link when -available, tested revision, and synthetic/prototype/packaged/installed boundary). -Chat, PR comments, Todos or final reports alone do not satisfy this rule. Ask -only for a missing consequential decision, work outside accepted scope, or an -explicit user reservation of presentation approval; this rule grants no merge, -install, release, paid-execution or sensitive-publication authority. - -## Product Delivery Completeness - -For product changes, read [frontend delivery](docs/development/frontend-delivery.md#task-first-delivery--从用户任务开始) -before implementation. Identify affected frontend/Lark/CLI entrypoints and -inspect existing settings/capability editors before declaring a change backend-only. -Every new or materially extended caller-facing capability needs a shipped -frontend journey: discover purpose, perform the authorized operation, see -unavailable/error states and read back the result. Reuse the typed owner without -duplicate configuration or automatic execution of privileged tools. For -artifact-producing capabilities (HTML, games, mini-worlds, video), the requested -work, conversation preview/download and revision feedback satisfy the journey -without a dedicated editor unless an accepted workflow requires one. Before PR -handoff, validate the packaged journey with its real owning backend and a -failure/recovery case, distinguishing proposed, packaged and installed behavior. - -## UI Design Standard - -**Avoid unnecessary secondary labels and descriptions. Let the layout do the explaining.** -Use hierarchy, grouping, spacing and clear control names to make the interface -understandable. Remove slogans, heading restatements and implementation or Agent -instructions from product UI. Preserve accessible control names, input -constraints, permission/activation consequences, errors, recovery and action -outcomes; place optional help on demand. - -Before changing or reproducing any UI, read [design system](docs/development/design.md), -especially [viewport attention](docs/development/design.md#earn-the-users-attention), -and carry the primary user question, default-versus-detail choices and the -[populated-page review](docs/development/design.md#populated-page-review) -in the task/PR evidence. Inspect the affected page with long, repeated content -and mixed states rather than quiet fixtures alone, and name the observed -composition and any remaining failure. - -## Public And Private Boundary - -Never publish private department/team/customer/meeting/reporting/strategy or -local operating context in repository changes, PR descriptions or review -artifacts (notes, fixtures, screenshots, examples, catalog rows). Keep private -planning/incident evidence in ignored `.local/` or another owner-approved -ignored location, and generalize public material by removing internal actors, -timelines, reporting needs, local paths, raw logs, private links and decisions. -Scan candidates before staging; if already pushed, stop normal delivery, use -self-repair, clean current public heads and report remaining PR-ref/cached-view -cleanup as an explicit user/support gate. - -## PR Review Comments - -For a requested GitHub PR review, publish validated actionable findings on the -PR by default (unless local-only or private/security-sensitive), returning the -published URL and compact summary. Use [review workflow](skills/loopx-pr-review/SKILL.md) -and execute the current capability-owned `pull_request_review_execution_contract_v2`. -Apply its typed-state, domain-neutrality, behavior-change, guidance-vs-obligation, -default-off-isolation and authority lenses; flag substring/prose-classification -risks, domain-specific generic contracts and silent default changes, and prove -feature-off parity on every changed shared surface. - -## Engineering Quality And Right-Sized Scope - -### TypeScript-First Implementation - -Prefer TypeScript and the existing typed owner for new/refactored domain-neutral -capabilities, control plane, orchestration, capability/context/memory composition -and shared projections. Follow the accepted [migration RFC](docs/architecture/rfcs/typescript-control-plane-migration-v0.md); -do not create a parallel Python decision owner. Stable domain providers, -specialized computation and transport adapters may remain Python with a placement -rationale. Do not expand into unrelated language rewrites or make full migration -a prerequisite for a bounded outcome. - -### Source-Checkout Python Entry Points - -From the intended worktree root, prepare with `uv sync --extra test` and use -`uv run --extra test python ...` / `uv run --extra test loopx ...` (or an -activated compatible environment with that checkout installed), following the -[environment](docs/development/testing-and-quality.md#local-validation-environment--本地验证环境). -Verify `sys.executable` and `loopx.__file__` when provenance is uncertain, keep -subprocesses on `sys.executable` (not nested `uv run`), preserve version coverage -and fixtures, and never rewrite historical receipts or commit an unrelated `uv.lock`. - -### Evidence-Based Budget Decisions - -When a size, structure or latency budget fails, follow the -[budget decisions](docs/development/testing-and-quality.md#budget-failure-decisions): -measure the same base/head workload, identify what the limit protects and -compare information value and real redundancy before compaction, retention or -an evidence-backed increase. Hard limits and frozen experiment/promotion criteria -retain their authority; never relabel an earlier failure or add an approval flow. -Agent-consumed prose is behavior: before shortening it, compare obligations -clause by clause (actor, ordering, modality, evidence provenance, scope, -continuation and stop conditions) using `observable_semantics.decision_text_assessment` -and deliver host-capped detail through reachable task-specific instructions -rather than silent truncation. - -### Refactor Real-Path Validation - -Before claiming refactor delivery, follow the [real-path gate](docs/development/testing-and-quality.md#refactor-real-path-gate--重构真实路径门) -and the [default provider](docs/development/testing-and-quality.md#default-provider-performance-qualification--默认-provider-性能资格): -validate the affected production entrypoint and real backend beyond mocks/unit -tests. PostgreSQL authority-store changes require its integration suite on an -isolated real server/tenant (unavailable environment is an evidence gap, not a -pass); never test by promoting, rewriting or corrupting active Goal/registry/ -writer-fence/Todo/lease state. SQLite real-path performance gates qualify default -local delivery (a File-only performance miss must be disclosed but does not block -SQLite qualification), while correctness, durability, authority and recovery -checks remain required for every affected backend. +Before approval or merge, read [merge workflow](skills/loopx-pr-merge/SKILL.md) +and its [self-merge rules](skills/loopx-pr-merge/SKILL.md#self-merge-eligibility-and-benchmark-exceptions). +Propose and review the exact head, pass required validation, and run +`uv run --extra test loopx pr-review --check-merge-readiness NUMBER@HEAD_OID` +(`--goal-id GOAL` if Goal-managed) for that unchanged head. Normal merge +requires `ready=true` and `admin_bypass_required=false`. Author-owned PRs +publish a `COMMENTED` review carrying the approval conclusion and an English +verdict. Low-risk self-merge requires all self-merge conditions plus +`uv run --extra test loopx canary premerge --from-git-diff --git-diff-base "$PR_BASE_REF"` +(or equivalent risk-based validation). Admin bypass requires explicit maintainer +authority and never overrides missing exact-head review, required validation, +unresolved findings or threads, a changed head, merge conflicts, or absent merge +authority. After merging, sync local `main` and preserve unrelated untracked +artifacts. ### Bounded Future-Facing Refactoring -During development and before approving or merging, apply the +During development and before approving or merging, apply [scope and refactoring](docs/development/README.md#engineering-scope-and-refactoring) -to the touched behavior and adjacent owner. Include a same-domain, reversible, -behavior-preserving improvement when locally reviewable and covered by parity; -report applied/deferred/unnecessary with the concrete boundary. - -## Capability And Extension Placement - -Before adding an ability, read [placement](docs/reference/extensions.md#placement-decision-for-agents). -Name public capabilities after caller outcomes; reuse the nearest capability -and typed owner. Record capability id, provider id, builtin/extension origin -and why that owner is or is not sufficient before editing. Before adding a -module, builder, protocol field, CLI option, fixture, smoke section or -abstraction, apply [scope fit](docs/development/README.md#scope-fit-review): -require an active caller, shipped behavior or explicit compatibility contract, -characterize before moving code, derive tests from independent semantics, keep -state/delivery classifications typed and generic obligations domain-neutral, and -disclose default-behavior changes. +to the touched behavior and adjacent owner. Prefer removing duplicate authority, +narrowing ownership, and deleting redundant layers over adding abstractions; +include a same-domain, reversible, behavior-preserving improvement when locally +reviewable and covered by parity, and report applied, deferred, or unnecessary +with the concrete boundary. -## Automation And Monitor Todos - -Keep generic heartbeat prompts free of one-off project/PR monitor policy. -Recurring watches belong in canonical `continuous_monitor` Todos with compact -`claimed_by`, `unblocks_todo_id` and evidence metadata; discover them through -status/quota/Todo projections. Change the saved prompt only for heartbeat -lifecycle contract changes or an explicit user scheduler request; see -[prompt layers](docs/heartbeat-automation-prompt.md#two-prompt-layers). - -## Projection Sink Design - -When adding a display sink (Lark Base, dashboard, chat summary or report), follow -[projection contract](docs/product/core-control-plane/state-machine.md#7-projection-sink-machine). -Use bounded public-safe state projections rather than project-private raw files, -retain source/evidence/gates and row lineage, redact public/multi-user sinks, -and require explicit user authorization for owner-only private planning boards. -A sink displays state; it does not become its authority. - -## Smoke Retention Policy - -Before adding, retaining or consolidating a smoke, read -[good smokes](docs/development/good-smokes.md). Keep shipped behavior, reusable -contracts, boundary checks, automation regressions and representative public-safe -fixtures with independent semantic oracles; do not freeze dated prose or -temporary builders (~500 lines triggers review). For benchmark changes, follow -[benchmark boundaries](docs/development/good-smokes.md#benchmark-boundaries) -and [archives](benchmark/README.md#archive-placement): active smokes -protect stable toolkit contracts without entering archives into CI or requiring -raw tasks, trajectories, logs, verifier tails, credentials, uploads, -leaderboard submissions or private local paths. - -## LoopX Self-Repair +## First-Screen Review Evidence -When LoopX behavior is surprising, too small, contradictory, or called out by -the user as likely wrong, use `skills/loopx-self-repair/SKILL.md`. Treat -recurring mistakes as product or process gaps: update the skill, interaction -docs, active-state projection, or focused smoke so the lesson is durable, -without lowering gates, guessing around contradictory payloads, or committing -private logs and local state. +Treat public first screens as reviewable product presentation. Before submitting +or updating a UI-affecting PR, inspect the actual first viewport and embed +public-safe visual evidence directly in the PR description (before/after and +desktop/narrow views, preview link when available, tested revision, and +synthetic/prototype/packaged/installed boundary); chat, comments, Todos, or +final reports alone do not satisfy this rule. Within the requested outcome, +design contract, and scoped authorization, do not add confirmation rounds for +routine viewport/CTA/navigation refinements—ask only for a missing consequential +decision, out-of-scope work, or an explicit user reservation of presentation +approval. This rule grants no merge, install, release, paid-execution, or +sensitive-publication authority. diff --git a/docs/development/README.md b/docs/development/README.md index 91e217c5b0..fada6c280a 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -215,19 +215,22 @@ import the detailed procedures: read their linked owner when its task applies. Codex's default `project_doc_max_bytes` is 32 KiB across discovered instructions, and Antigravity caps individual rule files (`AGENTS.md`) at 24,000 bytes (24 KB). -The root regression checks that `AGENTS.md` fits within the stricter 24,000-byte -per-file host cap as well as the 32 KiB discovery budget, while ancestor -instructions, nested files and user overrides still require a host-specific -loading check. Claude's import/discovery settings have different semantics; -neither cap is a universal Claude limit. Inspect actual startup context after -changing the entry or its alias, and distinguish assembled text from model -compliance and live effects. Existing sessions may retain an older copy. +The delivery test verifies that every tracked `AGENTS.md` / `AGENTS.override.md` +fits within the 24,000-byte per-file cap, and that every root-to-nested +instruction chain leaves at least 4 KiB of headroom inside Codex's 32 KiB +discovery budget for host/user instructions. Ancestor instructions outside +the repository and user overrides still require a host-specific loading check. +Claude's import/discovery settings have different semantics; neither cap is a +universal Claude limit. Inspect actual startup context after changing the entry +or its alias, and distinguish assembled text from model compliance and live +effects. Existing sessions may retain an older copy. Run `uv run --extra test python -m pytest -q tests/test_repository_instruction_delivery.py` -for root size, shared import, local routes and existing inbound anchors. Review -a moved obligation clause by clause: owner, modality, scope, order, exceptions, -evidence provenance, continuation and stop conditions. Keep operational rules in their existing -owners rather than adding another parallel policy collection. +for per-file and combined budgets, shared import, duplicate-free local routes, +whole-repository inbound anchors, and always-on obligation retention. Review a +moved obligation clause by clause: owner, modality, scope, order, exceptions, +evidence provenance, continuation and stop conditions. Keep operational rules in +their existing owners rather than adding another parallel policy collection. Design sources and the disposition of the earlier proposal are recorded in [the instruction/skill/prompt study](../research/2026-10-17-agent-instruction-skill-prompt-guidance.md). diff --git a/pyproject.toml b/pyproject.toml index cdf9bbc4c3..a8ee10d81d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,6 +48,7 @@ test-core = [ "pytest>=9.0.3,<10", ] test = [ + "markdown-it-py>=3,<5", "hypothesis==6.142.4", "tiktoken==0.12.0", "distlib>=0.3.9,<1; sys_platform == 'win32'", diff --git a/tests/test_repository_instruction_delivery.py b/tests/test_repository_instruction_delivery.py index 20a988323e..e81a6ed6b2 100644 --- a/tests/test_repository_instruction_delivery.py +++ b/tests/test_repository_instruction_delivery.py @@ -1,93 +1,537 @@ -"""Check instruction delivery, not whether an agent obeys the delivered prose.""" +"""Check instruction delivery, combined budgets, anchor integrity, and obligation retention.""" from __future__ import annotations import re +import subprocess from pathlib import Path from urllib.parse import unquote, urlsplit import pytest - +from markdown_it import MarkdownIt ROOT = Path(__file__).resolve().parents[1] INSTRUCTIONS = ROOT / "AGENTS.md" -# The default Codex project-doc budget is 32 KiB across discovered files, while -# Antigravity caps individual rule files (AGENTS.md) at 24,000 bytes (24 KB). -# This root must fit within both host limits by itself; host overrides and -# ancestor files need their own delivery checks. +INSTRUCTION_FILENAMES = ("AGENTS.override.md", "AGENTS.md") +# Codex defaults to 32 KiB across discovered instruction files; Antigravity caps +# individual rule files at 24,000 bytes (24 KB). Combined chains reserve 4 KiB +# inside Codex's 32 KiB budget for host/user-level instructions. DEFAULT_PROJECT_DOC_MAX_BYTES = 32 * 1024 ANTIGRAVITY_RULE_FILE_MAX_BYTES = 24_000 +HOST_GLOBAL_INSTRUCTION_HEADROOM_BYTES = 4 * 1024 +IGNORED_SCAN_PARTS = frozenset({".git", "node_modules", ".venv", ".pytest_cache", "__pycache__"}) + +# CommonMark §2.4 allows backslash escapes only before ASCII punctuation (never +# letters), so any link resolving to AGENTS.md must contain "agents.md", +# "agents\.md", a percent-encoded char of "agents.md", or a tracked symlink name. +_AGENTS_PREFILTER_TOKENS = ( + "agents.md", "agents\\.md", + "&#", ".", + "%41", "%61", "%47", "%67", "%45", "%65", "%4e", "%6e", + "%54", "%74", "%53", "%73", "%2e", "%4d", "%6d", "%44", "%64", +) +_BLOCKQUOTE_RE = re.compile(r"^(?:[ ]{0,3}>[ ]?)+") +_LIST_ITEM_RE = re.compile(r"^([ ]{0,3}(?:[-+*]|\d{1,9}[.)])[ \t]+)") +_FENCE_OPEN_RE = re.compile(r"^(`{3,}|~{3,})(.*)$") +_MARKDOWN = MarkdownIt("commonmark").enable("table") + + +def _strip_markdown_code_blocks(text: str) -> str: + """Strip CommonMark fenced and 4-space indented code blocks.""" + kept: list[str] = [] + open_fence: tuple[str, int, int] | None = None + in_indented, prev_blank = False, True + list_indent: int | None = None + + for raw_line in text.splitlines(): + line = _BLOCKQUOTE_RE.sub("", raw_line) + if not line.strip(): + prev_blank = True + if open_fence is None: + kept.append("") + continue + expanded = line.expandtabs(4) + rest = expanded.lstrip(" ") + indent = len(expanded) - len(rest) + + if open_fence is not None: + f_char, f_len, base = open_fence + stripped = rest.rstrip(" ") + if indent < base + 4 and len(stripped) >= f_len and stripped == f_char * len(stripped): + open_fence, prev_blank = None, False + continue + + base = list_indent or 0 + if in_indented: + if indent >= base + 4: + continue + in_indented = False + if prev_blank and indent >= base + 4: + in_indented = True + continue + if list_indent is not None and indent < list_indent: + list_indent, base = None, 0 + if match := _LIST_ITEM_RE.match(line): + list_indent = base = len(match.group(1).expandtabs(4)) + if ( + indent < base + 4 + and (fm := _FENCE_OPEN_RE.match(rest)) + and not (fm.group(1)[0] == "`" and "`" in fm.group(2)) + ): + open_fence, prev_blank = (fm.group(1)[0], len(fm.group(1)), base), False + continue + + prev_blank = False + kept.append(line) + return "\n".join(kept) + + +def _extract_markdown_link_targets(text: str) -> list[str]: + targets: list[str] = [] + for block in _MARKDOWN.parse(text): + for token in block.children or (): + if token.type == "link_open": + href = token.attrGet("href") + if isinstance(href, str): + targets.append(href) + return targets def _heading_anchors(path: Path) -> set[str]: anchors: set[str] = set() counts: dict[str, int] = {} - in_fence = False - for line in path.read_text(encoding="utf-8").splitlines(): - if line.startswith(("```", "~~~")): - in_fence = not in_fence - if in_fence: - continue - match = re.match(r"^#{1,6}\s+(.+?)\s*#*\s*$", line) - if not match: - continue - heading = re.sub(r"[^\w\- ]", "", match[1].lower()).replace(" ", "-") - suffix = counts.get(heading, 0) - counts[heading] = suffix + 1 - anchors.add(f"{heading}-{suffix}" if suffix else heading) + for line in _strip_markdown_code_blocks(path.read_text(encoding="utf-8")).splitlines(): + if match := re.match(r"^#{1,6}\s+(.+?)\s*#*\s*$", line): + raw = re.sub(r"!?\[([^\]]+)\]\([^)]*\)", r"\1", match[1]) + heading = re.sub(r"[^\w\- ]", "", raw.lower()).replace(" ", "-") + suffix = counts.get(heading, 0) + counts[heading] = suffix + 1 + anchors.add(f"{heading}-{suffix}" if suffix else heading) return anchors -def _local_links(path: Path) -> list[tuple[Path, str]]: - links = [] - for target in re.findall(r"\]\(([^\s)]+)\)", path.read_text(encoding="utf-8")): +def _local_links(path: Path, *, root: Path = ROOT, anchors_only: bool = False) -> list[tuple[Path, str]]: + links: list[tuple[Path, str]] = [] + parent_res, path_res, root_res = path.parent.resolve(), path.resolve(), root.resolve() + for target in _extract_markdown_link_targets(path.read_text(encoding="utf-8")): + if anchors_only and "#" not in target: + continue parts = urlsplit(target) - if parts.scheme or parts.netloc or parts.path.startswith("/"): + if parts.scheme or parts.netloc: continue - resolved = (path.parent / unquote(parts.path)).resolve() if parts.path else path - links.append((resolved, unquote(parts.fragment))) + fragment = unquote(parts.fragment) + if anchors_only and not fragment: + continue + if not parts.path: + resolved = path_res + elif parts.path.startswith("/"): + resolved = (root_res / unquote(parts.path.lstrip("/"))).resolve() + else: + resolved = (parent_res / unquote(parts.path)).resolve() + links.append((resolved, fragment)) return links -def test_root_instructions_fit_default_project_doc_loading() -> None: - contents = INSTRUCTIONS.read_bytes() - for host_name, limit in ( - ("Antigravity per-file rule cap", ANTIGRAVITY_RULE_FILE_MAX_BYTES), - ("Codex default project_doc_max_bytes", DEFAULT_PROJECT_DOC_MAX_BYTES), +def _tracked_files(*patterns: str, root: Path = ROOT) -> list[Path]: + if (root / ".git").exists(): + res = subprocess.run(["git", "ls-files", "-z", "--", *patterns], cwd=root, capture_output=True, check=False) + if res.returncode == 0: + # Preserve checkout paths (do not .resolve()) so symlinks keep their discovery location. + paths = [root / raw.decode("utf-8", errors="surrogateescape") for raw in res.stdout.split(b"\0") if raw] + return sorted(p for p in paths if p.is_file() or p.is_symlink()) + return sorted( + { + p + for pat in patterns + for p in root.rglob(Path(pat).name) + if (p.is_file() or p.is_symlink()) and not any(part in IGNORED_SCAN_PARTS for part in p.parts) + } + ) + + +def _tracked_instruction_files(root: Path = ROOT) -> list[Path]: + patterns = [pat for name in INSTRUCTION_FILENAMES for pat in (name, f"**/{name}")] + return sorted({p for p in _tracked_files(*patterns, root=root) if p.name in INSTRUCTION_FILENAMES}) + + +def _agents_discovery_chain(leaf: Path, *, tracked_set: set[Path], root: Path = ROOT) -> list[Path]: + chain: list[Path] = [] + current = leaf.parent + while True: + for name in INSTRUCTION_FILENAMES: + cand = current / name + if cand in tracked_set and cand.is_file() and (name == "AGENTS.md" or cand.stat().st_size > 0): + chain.append(cand) + break + if current == root or current.parent == current: + break + current = current.parent + chain.reverse() + return chain + + +def _check_instruction_budgets(root: Path = ROOT) -> list[str]: + instruction_files = _tracked_instruction_files(root=root) + if not instruction_files: + return ["No tracked AGENTS.md or AGENTS.override.md files found."] + tracked_set, errors = set(instruction_files), [] + + for file_path in instruction_files: + rel = file_path.relative_to(root) + if not file_path.is_file(): + errors.append(f"{rel} is a broken symlink or unreadable instruction file.") + continue + size = len(file_path.read_bytes()) + for host_name, limit in ( + ("Antigravity per-file rule cap", ANTIGRAVITY_RULE_FILE_MAX_BYTES), + ("Codex default project_doc_max_bytes", DEFAULT_PROJECT_DOC_MAX_BYTES), + ): + if size > limit: + errors.append( + f"{rel} loses {size - limit} bytes at the {host_name} ({limit} bytes) boundary; " + "route applicable detail to its existing owner." + ) + + combined_limit = DEFAULT_PROJECT_DOC_MAX_BYTES - HOST_GLOBAL_INSTRUCTION_HEADROOM_BYTES + seen_chains: set[tuple[Path, ...]] = set() + for file_path in instruction_files: + if not file_path.is_file(): + continue + chain = tuple(_agents_discovery_chain(file_path, tracked_set=tracked_set, root=root)) + if not chain or chain in seen_chains: + continue + seen_chains.add(chain) + chain_bytes = sum(item.stat().st_size for item in chain) + if chain_bytes > combined_limit: + names = " + ".join(str(item.relative_to(root)) for item in chain) + errors.append( + f"Combined instruction chain ({names}) uses {chain_bytes} bytes, exceeding " + f"{combined_limit} bytes ({DEFAULT_PROJECT_DOC_MAX_BYTES} minus " + f"{HOST_GLOBAL_INSTRUCTION_HEADROOM_BYTES} host headroom)." + ) + return errors + + +def _candidate_markdown_files_for_root_links(root: Path) -> list[Path]: + root_resolved = (root / "AGENTS.md").resolve() + extra_tokens: list[str] = [] + symlink_mds: list[Path] = [] + if (root / ".git").exists(): + ls = subprocess.run(["git", "ls-files", "-s", "-z"], cwd=root, capture_output=True, check=False) + if ls.returncode == 0: + for entry in ls.stdout.split(b"\0"): + if entry.startswith(b"120000 ") and b"\t" in entry: + p = root / entry.split(b"\t", 1)[1].decode("utf-8", errors="surrogateescape") + if p.suffix.lower() == ".md" and p.is_file(): + symlink_mds.append(p) + if p.is_file() and p.resolve() == root_resolved: + extra_tokens.append(p.name) + + grep_cmd = ["git", "grep", "-z", "-l", "-i", "-F"] + for tok in (*_AGENTS_PREFILTER_TOKENS, *extra_tokens): + grep_cmd.extend(["-e", tok]) + grep_cmd.extend(["--", "*.md"]) + res = subprocess.run(grep_cmd, cwd=root, capture_output=True, check=False) + if res.returncode in (0, 1): + hits = {root / raw.decode("utf-8", errors="surrogateescape") for raw in res.stdout.split(b"\0") if raw} + return sorted(p for p in (hits | set(symlink_mds)) if p.is_file()) + + byte_tokens = tuple(t.encode("ascii") for t in _AGENTS_PREFILTER_TOKENS) + return [ + p + for p in _tracked_files("*.md", root=root) + if p.is_file() and any(tok in p.read_bytes().lower() for tok in byte_tokens) + ] + + +def _find_broken_inbound_anchors(root: Path = ROOT) -> list[str]: + instructions = root / "AGENTS.md" + root_resolved, root_anchors = instructions.resolve(), _heading_anchors(instructions) + broken: list[str] = [] + for md_path in _candidate_markdown_files_for_root_links(root): + if md_path.resolve() == root_resolved: + continue + for target, anchor in _local_links(md_path, root=root, anchors_only=True): + if target == root_resolved and anchor not in root_anchors: + broken.append(f"{md_path.relative_to(root)} -> AGENTS.md#{anchor}") + return broken + + +def _markdown_h2_sections(text: str) -> dict[str, str]: + sections: dict[str, list[str]] = {"": []} + current = "" + for line in _strip_markdown_code_blocks(text).splitlines(): + if match := re.match(r"^##\s+(.+?)\s*#*\s*$", line): + current = match.group(1).strip() + sections.setdefault(current, []) + continue + sections[current].append(line) + return {heading: "\n".join(lines) for heading, lines in sections.items()} + + +def _missing_always_on_obligations(text: str) -> list[str]: + sections = _markdown_h2_sections(text) + invariants = sections.get("Precedence & Always-On Invariants", "") + if not invariants: + return ["section: Precedence & Always-On Invariants"] + + checks = { + "precedence order": lambda s: "Precedence:" in s, + "clean git worktree rule": lambda s: "git worktree" in s and "`codex/`" in s, + "DCO sign-off": lambda s: "git commit -s" in s and "Signed-off-by" in s, + "pre-staging scan and raw logs boundary": lambda s: ( + bool(re.search(r"\bclassify\b", s, re.IGNORECASE)) + and bool(re.search(r"\bscan\b", s, re.IGNORECASE)) + and len(re.findall(r"\braw logs\b", s, re.IGNORECASE)) >= 2 + and "`.local/`" in s + ), + "ban on git add .": lambda s: bool(re.search(r"\bnever\b[^.\n]*git add \.", s, re.IGNORECASE)), + "local-first CI policy": lambda s: ( + "wait_for_ci=false" in s and bool(re.search(r"never wait on or poll remote ci", s, re.IGNORECASE)) + ), + "protected-surface merge authority": lambda s: ( + bool(re.search(r"protected surfaces", s, re.IGNORECASE)) + and bool(re.search(r"explicit maintainer merge\s+authorization", s, re.IGNORECASE)) + ), + "TypeScript-first single authority": lambda s: "TypeScript" in s and "parallel Python decision owner" in s, + "source-checkout Python": lambda s: "uv run --extra test" in s and "sys.executable" in s, + "complete right-sized delivery": lambda s: "Complete, right-sized delivery" in s and "readback" in s, + "multi-agent and companion surfaces": lambda s: all(tok in s for tok in ("frontend", "Lark", "CLI")), + "self-repair route": lambda s: "skills/loopx-self-repair/SKILL.md" in s, + } + missing = [label for label, pred in checks.items() if not pred(invariants)] + + routing_lines = sections.get("Task-Triggered Owner Routing", "").splitlines() + if not any("PR_BASE_REF:?" in r for r in routing_lines if "scripts/check_rfc_bilingual.py" in r): + missing.append("verified base-ref guard for bilingual RFC gate") + if not any( + all(t in r.lower() for t in ("unless", "local-only", "dry-run", "private", "security-sensitive")) + for r in routing_lines + if "skills/loopx-pr-review/SKILL.md" in r + ): + missing.append("review publication exemptions (local-only/dry-run/private/security-sensitive)") + if not any( + "caller-facing capabilities" in r.split("|")[1].lower() + for r in routing_lines + if "docs/development/frontend-delivery.md#" in r and len(r.split("|")) > 2 + ): + missing.append("caller-facing capabilities trigger in frontend delivery row") + if not any( + "all product changes" in row.partition("|")[2].split("|")[0].lower() + and "read the delivery guide before implementation" in row.lower() + and "inspect existing settings and capability editors before declaring a change backend-only" in row.lower() + for row in routing_lines if "docs/development/frontend-delivery.md#" in row ): - loaded = contents[:limit] - assert loaded == contents, ( - f"Root instructions lose {len(contents) - len(loaded)} bytes at the " - f"{host_name} ({limit} bytes) boundary; route applicable detail to its existing owner." - ) + missing.append("pre-implementation product delivery and backend-only inspection") + if not any( + "fixture" in r.split("|")[1].lower() + for r in routing_lines + if "docs/development/README.md#scope-fit-review" in r and len(r.split("|")) > 2 + ): + missing.append("fixture trigger in scope-fit routing row") + if "--check-merge-readiness" not in sections.get("Pinned Root Contracts", ""): + missing.append("merge readiness check") + return missing + + +def test_root_instructions_fit_default_project_doc_loading() -> None: + assert INSTRUCTIONS in _tracked_instruction_files() + errors = _check_instruction_budgets(ROOT) + assert not errors, "\n".join(errors) def test_root_instruction_routes_resolve_to_existing_files_and_sections() -> None: links = _local_links(INSTRUCTIONS) assert links, "Root instructions need reachable task-specific procedures." + seen: set[tuple[Path, str]] = set() + duplicates: list[str] = [] for target, anchor in links: - assert target.is_file(), f"Missing instruction route: {target.relative_to(ROOT)}" + assert target.is_relative_to(ROOT), f"Instruction route escapes repository: {target}" + rel = target.relative_to(ROOT) + assert target.is_file(), f"Missing instruction route: {rel}" if anchor: - assert anchor in _heading_anchors(target), ( - f"Missing instruction section: {target.relative_to(ROOT)}#{anchor}" - ) + assert anchor in _heading_anchors(target), f"Missing instruction section: {rel}#{anchor}" + if (target, anchor) in seen: + duplicates.append(f"{rel}#{anchor}" if anchor else str(rel)) + seen.add((target, anchor)) + assert not duplicates, f"Duplicate routes in AGENTS.md bloat startup context: {duplicates}" @pytest.mark.parametrize( "consumer", [ + ".github/GOVERNANCE.md", "loopx/capabilities/pr_review_queue/README.md", "docs/development/design.md", "docs/development/frontend-delivery.md", ], ) def test_existing_consumers_can_follow_root_instruction_anchors(consumer: str) -> None: - anchors = [anchor for target, anchor in _local_links(ROOT / consumer) if target == INSTRUCTIONS] + anchors = [anchor for target, anchor in _local_links(ROOT / consumer) if target == INSTRUCTIONS.resolve()] assert anchors, f"{consumer} must retain its repository-policy route." + root_anchors = _heading_anchors(INSTRUCTIONS) for anchor in anchors: - assert anchor in _heading_anchors(INSTRUCTIONS), f"Broken root-policy anchor: {anchor}" + assert anchor in root_anchors, f"Broken root-policy anchor: {anchor}" + + +def test_pinned_external_html_blog_anchor_resolves() -> None: + assert "bounded-future-facing-refactoring" in _heading_anchors(INSTRUCTIONS) + for blog_rel in ( + "apps/presentation/site/public/blog/semantic-software-development/index.html", + "apps/presentation/site/public/blog/zh/semantic-software-development/index.html", + ): + blog_path = ROOT / blog_rel + if blog_path.is_file(): + assert "AGENTS.md#bounded-future-facing-refactoring" in blog_path.read_text(encoding="utf-8") + + +def test_all_repository_markdown_inbound_links_to_root_instructions_resolve() -> None: + broken = _find_broken_inbound_anchors(ROOT) + assert not broken, f"Broken inbound AGENTS.md anchors across repository: {broken}" + + +def test_root_instructions_retain_always_on_obligations() -> None: + missing = _missing_always_on_obligations(INSTRUCTIONS.read_text(encoding="utf-8")) + assert not missing, f"AGENTS.md dropped required always-on obligations: {missing}" def test_claude_imports_one_shared_policy_without_eager_detail_imports() -> None: assert (ROOT / "CLAUDE.md").read_text(encoding="utf-8").strip() == "@AGENTS.md" assert not re.search(r"^\s*@\S+", INSTRUCTIONS.read_text(encoding="utf-8"), re.MULTILINE) + + +def test_markdown_parser_handles_code_blocks_escapes_references_and_root_links(tmp_path: Path) -> None: + doc = tmp_path / "docs" / "sample.md" + doc.parent.mkdir(parents=True) + (tmp_path / "AGENTS.md").write_text("# Root\n\n## See [Design](design.md) & `code`\n", encoding="utf-8") + doc.write_text( + 'Inline [titled](../AGENTS.md#missing-title "Title"), [angle](<../AGENTS.md#missing-angle> \'T\'), ' + "and [root-rel](/AGENTS.md#missing-root).\n" + "Ref [full][ref-a], collapsed [ref-b][], shortcut [ref-c].\n" + "Inline code `[ignored](../AGENTS.md#in-code)` skipped.\n\n" + "Escaped \\` tick in paragraph one.\n\n" + "Unclosed ` tick in paragraph two.\n\n" + "Real link [between](../AGENTS.md#between-escaped) paragraphs.\n\n" + "Second escaped \\` tick and unclosed ` tick.\n\n" + " ```\n" + " [indented](../AGENTS.md#in-indented-code)\n\n" + "````markdown\n```\n[fenced](../AGENTS.md#in-fence)\n```\n````\n" + "After blocks [real](../AGENTS.md#after-blocks).\n\n" + '[ref-a]: ../AGENTS.md#missing-ref-a "Title"\n' + "[ref-b]: <../AGENTS.md#missing-ref-b>\n" + "[ref-c]: /AGENTS.md#missing-ref-c\n", + encoding="utf-8", + ) + assert _heading_anchors(tmp_path / "AGENTS.md") == {"root", "see-design--code"} + anchors = [a for target, a in _local_links(doc, root=tmp_path) if target == (tmp_path / "AGENTS.md").resolve()] + assert anchors == [ + "missing-title", "missing-angle", "missing-root", "missing-ref-a", "missing-ref-b", + "missing-ref-c", "between-escaped", "after-blocks", + ] + + +def test_tracked_files_handles_non_ascii_and_root_relative_links(tmp_path: Path) -> None: + subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True) + subprocess.run(["git", "config", "core.quotePath", "true"], cwd=tmp_path, check=True) + (tmp_path / "AGENTS.md").write_text("# Agent Instructions\n\n## Valid Section\n", encoding="utf-8") + doc = tmp_path / "docs" / "政策.md" + doc.parent.mkdir(parents=True) + doc.write_text( + 'See [rel](../AGENTS.md#bad-rel "P"), [root](/AGENTS.md#bad-root), ' + "[bs](../AGENTS\\.md#bad-bs), and [pct](../%41GENTS.md#bad-pct).\n", + encoding="utf-8", + ) + subprocess.run(["git", "add", "AGENTS.md", "docs/政策.md"], cwd=tmp_path, check=True) + + assert _find_broken_inbound_anchors(tmp_path) == [ + "docs/政策.md -> AGENTS.md#bad-rel", + "docs/政策.md -> AGENTS.md#bad-root", + "docs/政策.md -> AGENTS.md#bad-bs", + "docs/政策.md -> AGENTS.md#bad-pct", + ] + + +def test_inbound_guard_reads_rendered_links_and_decodes_entity_destinations(tmp_path: Path) -> None: + subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True) + (tmp_path / "AGENTS.md").write_text("# Root\n", encoding="utf-8") + (tmp_path / "plain.md").write_text("Unmatched ](AGENTS.md#plain)\n", encoding="utf-8") + (tmp_path / "entity.md").write_text("[Runbook](AGENTS.md#missing)\n", encoding="utf-8") + subprocess.run(["git", "add", "AGENTS.md", "plain.md", "entity.md"], cwd=tmp_path, check=True) + assert _find_broken_inbound_anchors(tmp_path) == ["entity.md -> AGENTS.md#missing"] + + +def test_instruction_budgets_enforce_chain_override_and_ignore_untracked_overrides(tmp_path: Path) -> None: + subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True) + (tmp_path / "AGENTS.md").write_bytes(b"r" * 16_000) + (tmp_path / "sub").mkdir() + (tmp_path / "sub" / "AGENTS.md").write_bytes(b"s" * 16_000) + (tmp_path / "override_dir").mkdir() + (tmp_path / "override_dir" / "AGENTS.override.md").write_bytes(b"y" * (DEFAULT_PROJECT_DOC_MAX_BYTES + 1024)) + subprocess.run( + ["git", "add", "AGENTS.md", "sub/AGENTS.md", "override_dir/AGENTS.override.md"], cwd=tmp_path, check=True + ) + (tmp_path / "sub" / "AGENTS.override.md").write_bytes(b"x") # untracked override must not mask tracked overflow + + errors = _check_instruction_budgets(tmp_path) + assert any("AGENTS.md + sub/AGENTS.md" in err for err in errors), errors + assert any("override_dir/AGENTS.override.md" in err for err in errors), errors + + +def test_instruction_budgets_measure_symlinked_file_at_checkout_location(tmp_path: Path) -> None: + subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True) + (tmp_path / "AGENTS.md").write_bytes(b"r" * 10_000) + (tmp_path / "a").mkdir() + (tmp_path / "a" / "AGENTS.md").write_bytes(b"m" * 10_000) + (tmp_path / "policy.md").write_bytes(b"l" * 10_000) + (tmp_path / "a" / "b").mkdir() + try: + (tmp_path / "a" / "b" / "AGENTS.md").symlink_to(Path("../../policy.md")) + except OSError as exc: + pytest.skip(f"symlink creation unavailable: {exc}") + subprocess.run( + ["git", "add", "AGENTS.md", "a/AGENTS.md", "policy.md", "a/b/AGENTS.md"], cwd=tmp_path, check=True + ) + + errors = _check_instruction_budgets(tmp_path) + assert any("AGENTS.md + a/AGENTS.md + a/b/AGENTS.md" in err for err in errors), errors + + +@pytest.mark.parametrize( + ("pattern", "replacement", "count_limit", "expected_missing"), + [ + (r"(?ms)^\d+\.\s+\*\*Local-first CI\b.*?(?=^\d+\.\s+\*\*|\Z)", "", 1, "local-first CI policy"), + ( + r"(?ms)^\d+\.\s+\*\*Merge authority boundary:.*?(?=^\d+\.\s+\*\*|\Z)", + "", + 1, + "protected-surface merge authority", + ), + (r"\*\*never `git add \.`\*\*", "**always `git add .`**", 1, "ban on git add ."), + (r"\braw logs,\s*", "", 1, "pre-staging scan and raw logs boundary"), + (r"dry-run", "normal", 1, "review publication exemptions (local-only/dry-run/private/security-sensitive)"), + ( + r"security-sensitive", + "routine", + 1, + "review publication exemptions (local-only/dry-run/private/security-sensitive)", + ), + ( + r",\s*new/extended caller-facing capabilities", + "", + 1, + "caller-facing capabilities trigger in frontend delivery row", + ), + (r"All product changes", "UI changes", 1, "pre-implementation product delivery and backend-only inspection"), + (r"guide before implementation", "guide after implementation", 1, "pre-implementation product delivery and backend-only inspection"), + (r"Inspect existing settings and capability editors", "Skip existing editors", 1, "pre-implementation product delivery and backend-only inspection"), + (r",\s*fixture", "", 1, "fixture trigger in scope-fit routing row"), + (r': "\$\{PR_BASE_REF:\?[^"]+\}" && ', "", 1, "verified base-ref guard for bilingual RFC gate"), + ], +) +def test_obligation_check_detects_clause_deletions_and_modality_inversions( + pattern: str, replacement: str, count_limit: int, expected_missing: str +) -> None: + original = INSTRUCTIONS.read_text(encoding="utf-8") + mutated, count = re.subn(pattern, replacement, original, count=count_limit) + assert count >= 1, f"Mutation pattern did not match AGENTS.md: {pattern}" + assert expected_missing in _missing_always_on_obligations(mutated)