From d7e96296404f5b882b50affcb4941a15d05596dc Mon Sep 17 00:00:00 2001 From: "KOKO\\Mimi" Date: Mon, 7 Sep 2026 01:15:26 +0900 Subject: [PATCH] update agent, skill and scripts --- .agents/skills/harness/SKILL.md | 172 +- .agents/skills/review/SKILL.md | 51 +- .codex/agents/coordinator-agent.toml | 64 - .codex/agents/correction-agent.toml | 41 - .codex/agents/formulation-agent.toml | 43 +- .codex/agents/implementation-agent.toml | 61 +- .../agents/implementation-planning-agent.toml | 45 - .codex/agents/io-definition-agent.toml | 45 +- .codex/agents/numerical-review-agent.toml | 52 +- .codex/agents/physics-evaluation-agent.toml | 45 +- .codex/agents/release-agent.toml | 38 - .codex/agents/requirement-agent.toml | 48 +- .codex/agents/research-agent.toml | 43 +- .codex/config.toml | 4 - .codex/hooks.json | 32 - .codex/skills/fem-formulation-spec/SKILL.md | 35 +- .codex/skills/fem-implementation-tdd/SKILL.md | 48 +- .../fem-implementation-tdd/agents/openai.yaml | 2 +- .../references/toolchain-and-verification.md | 33 +- .codex/skills/fem-io-contract/SKILL.md | 35 +- .codex/skills/fem-numerical-review/SKILL.md | 37 +- .codex/skills/fem-physics-review/SKILL.md | 34 +- .codex/skills/fem-release-readiness/SKILL.md | 35 +- .../fem-release-readiness/agents/openai.yaml | 2 +- .../skills/fem-requirements-baseline/SKILL.md | 34 +- .../references/evidence-and-handoff.md | 27 +- .../references/workflow-and-decisions.md | 6 +- .codex/skills/fem-research-evidence/SKILL.md | 34 +- .harness/config.example.json | 6 +- ...9-07-agent-harness-documentation-update.md | 282 ++++ scripts/execute.py | 1391 +---------------- scripts/hooks/pre_tool_use.py | 158 -- scripts/hooks/stop_validation.py | 168 -- scripts/hooks/validation_scope.py | 109 -- scripts/msvc_harness/config.py | 56 +- scripts/msvc_harness/discovery.py | 9 +- scripts/msvc_harness/models.py | 9 - scripts/msvc_harness/tdd_policy.py | 88 -- 38 files changed, 476 insertions(+), 2946 deletions(-) delete mode 100644 .codex/agents/coordinator-agent.toml delete mode 100644 .codex/agents/correction-agent.toml delete mode 100644 .codex/agents/implementation-planning-agent.toml delete mode 100644 .codex/agents/release-agent.toml delete mode 100644 .codex/config.toml delete mode 100644 .codex/hooks.json create mode 100644 docs/superpowers/plans/2026-09-07-agent-harness-documentation-update.md delete mode 100644 scripts/hooks/pre_tool_use.py delete mode 100644 scripts/hooks/stop_validation.py delete mode 100644 scripts/hooks/validation_scope.py delete mode 100644 scripts/msvc_harness/tdd_policy.py diff --git a/.agents/skills/harness/SKILL.md b/.agents/skills/harness/SKILL.md index 2d23818..5e34edf 100644 --- a/.agents/skills/harness/SKILL.md +++ b/.agents/skills/harness/SKILL.md @@ -1,176 +1,16 @@ --- name: harness -description: Plan, materialize, or execute bounded agentic implementation phases with test-first steps, validated state, safe Git ownership, and configured C++ verification. +description: Run configured repository build and test validation explicitly for structural FEM solver work. --- -# Harness Workflow +# Harness -Use Harness for multi-step repository implementation. Read `AGENTS.md`, `docs/HARNESS.md`, and -`docs/HARNESS_WORKFLOW.md` before creating phases or executing them. Read the approved upstream feature -bundle and `docs/TOLERANCE.md` when numerical comparison is in scope. -For feature work, read [Feature document management](../../../docs/FEATURE_DOCUMENTATION.md) and the -dispatched feature's `FEATURED_AGENTS.md`, `PRD.md`, and `ADR.md`; keep agent reports in that feature folder. - -## Authorization boundary - -A Coordinator dispatch based on an approved feature bundle authorizes routine planning-file creation and -bounded local execution with the default `workspace-write` sandbox. Do not add a separate “approve this -plan” or “start implementation?” gate. - -Separate explicit user authorization is still required immediately before: - -- `danger-full-access` -- `--push`, tag, publish, deploy, package, or release -- destructive Git/history or filesystem operations -- licensed external solver execution, credentials, cost, or non-repository side effects - -## Ownership - -| Owner | Responsibility | -| --- | --- | -| Coordinator | feature state, normalized `retry_key`, correction budget, dispatch and closure | -| Planning Agent | assigned phase/index/step files and `implementation-plan.md` | -| Executor | branch, current pending Step, transport attempts, timestamps, path-scoped commits and phase advancement | -| Implementation Agent | only the Executor-selected Step, its code/tests/reports, and Step result payload | -| Hooks | pre-edit command/TDD guard and configured whole-project Stop validation | - -The Executor permits at most two transport attempts, including the initial attempt, only when its -process wrapper observes a timeout and the Step has not reported a terminal result. A nonzero exit -(including 124) alone is not timeout evidence. Reported `error`/`blocked` results are preserved without -retry even on nonzero exit. Recognized sandbox-helper failures block even on zero exit. These attempts -do not consume or reset the Coordinator's one-correction workflow budget. - -## Plan materialization - -Create only the files assigned by Coordinator: - -```text -phases/index.json -phases//index.json -phases//step0.md -phases//step1.md -... -``` - -The top-level entry is: - -```json -{"dir": "", "status": "pending"} -``` - -The phase index is: - -```json -{ - "project": "", - "phase": "", - "steps": [ - { - "step": 0, "name": "", "status": "pending", - "owned_paths": ["src/example.cpp", "tests/example_test.cpp"] - } - ] -} -``` - -Replace the example paths with the Step's approved source/header/test/build/report files. `owned_paths` -is a Planning-owned array of exact repository-relative files, not directories or globs. `[]` permits -no implementation-file changes; it is not equivalent to a missing field. Do not include Git internals -or `phases/` control files. Paths cannot escape through traversal, symlinks or junctions; linked paths -are not supported. Backslashes are normalized and Windows case aliases are treated as the same path. -Existing completed Steps remain readable without this field. Every pending Step must have a valid -list before execution starts; do not infer it from Markdown or automatically migrate historical phases. - -Use contiguous Step numbers from zero. A Step must be small enough to complete -`RED -> observed failure -> minimal GREEN -> focused VERIFY -> full VERIFY` in one Codex session; do -not leave a red-only Step for a later Step. - -Each `stepN.md` is self-contained and contains: - -- files and upstream contracts to read, including the exact feature folder and its - `FEATURED_AGENTS.md`, `PRD.md`, and `ADR.md` -- exact owned files, symbols and behavior -- the expected RED failure and minimal GREEN scope -- executable focused/full acceptance commands resolved from project configuration -- architecture, numerical and reference invariants -- explicit out-of-scope items and stopping conditions - -Do not invent missing physics, tolerance, schema, toolchain, or reference data in a Step. Return the -issue to its owner through Coordinator. - -## Local execution - -Normal execution is: +Use Harness when the task needs configured build/test validation. Read `docs/HARNESS.md` and the relevant project configuration. Run the complete configured validation explicitly with: ```powershell -python scripts/execute.py +python scripts/execute.py ``` -The Executor requires a valid top-level/phase schema and a worktree clean outside the selected phase -control-file allowlist before branch checkout. It also requires the Git top-level to equal the Harness -root and validates the Implementation Agent profile before changing branch or state. It injects the role, -project guardrails, completed Step summaries and the current Step. It rejects nonzero Codex exits even if -a Step claimed completion. +For focused development feedback, use the actual configured backend command directly. The runner returns exit 2 when no build metadata is configured and exit 1 for failed execution; neither is a passing solver check. Record commands, exit codes, and decisive results when they support the requested outcome. -The Implementation Agent updates only the current Step: - -- `completed` plus a non-empty `summary` -- `error` plus `error_message` -- `blocked` plus `blocked_reason` - -The Executor adds timestamps and immutable `attempt_history` records preserving reported outcomes, -process exits, classifications and diagnostics across retries/recovery. It checks changed paths after -each attempt and before staging, then checks the actual staged paths before committing. The trusted -`owned_paths` snapshot covers tracked/untracked, staged/unstaged changes and both rename endpoints. -Implementation paths and phase metadata are committed separately; raw `stepN-output.json` stays ignored. -An ownership violation stops retry/commit/advancement, records the offending paths, and preserves user -files without reverting or expanding the allowlist. Avoid concurrent edits: these checks are not a -filesystem sandbox or an atomic guarantee against concurrent writers. Commit groups are not one -transaction; a failure after the implementation commit can leave that commit with an error Step. -Top/phase control metadata and non-current Steps are immutable during a -session; a violation is restored to the trusted snapshot and recorded as an error. -The implementation session may not run commit, push, branch, tag, merge/rebase, or history-changing Git -commands. Executor verifies symbolic branch and HEAD around every attempt. Control reads reject links and -scope escape; control/output writes use atomic replacement so a substituted link target is not overwritten. - -Do not run hook scripts manually as substitutes for registered hooks. A PreToolUse pass proves neither -RED nor correctness. Stop may skip build/test only for a valid same-session/turn record containing solely -repository-local `.md` edits. Missing/corrupt records or non-document edits take the normal validation path; -shell writes and read-only requests without edit records are not guaranteed to skip. A skipped check is not -build/test evidence. Do not manipulate hook state to obtain a skip. - -## Elevated and remote execution - -Use `danger-full-access` only after the user has authorized that exact run, the same command was shown to -fail because of the native sandbox, and execution is in a clean linked Git worktree: - -```powershell -$env:FEM_HARNESS_CODEX_SANDBOX = "danger-full-access" -python scripts/execute.py --approve-danger-full-access -Remove-Item Env:FEM_HARNESS_CODEX_SANDBOX -``` - -The environment value alone is insufficient. The Executor rejects a primary or dirty worktree. - -Use `--push` only when the user explicitly authorized pushing the completed feature branch: - -```powershell -python scripts/execute.py --push -``` - -## Recovery and handoff - -Do not manually erase failure evidence and immediately rerun. Return the exact command/exit, classification, -artifact paths and `retry_key` to Coordinator. After the owning upstream/environment/user decision is -resolved, Coordinator records the retry decision and preserved failure evidence in `coordination.md`, then -explicitly assigns the Planning Agent a recovery edit of the phase index. With the Executor stopped, that -agent changes only the current failed/blocked Step's status to `pending`; it does not alter other Steps, -top-level phase state, timestamps, or the feature workflow. Coordinator does not edit phase files itself. -The Executor clears stale summary/failure/block fields and timestamps on restart, retaining -`attempt_history`. For a legacy Step missing `owned_paths`, Planning needs a separate explicit assignment -to supply the approved list before execution; the status-only recovery edit does not grant that change. -This is an assigned -file edit, not an automatic recovery command or an additional correction allowance. - -Report the final phase state, commits created, commands and exit codes, test counts, ignored/untracked raw -output, unexecuted checks and residual risks. Never call a phase complete when any Step is non-completed. +Harness does not plan phases, dispatch agents, inject prompts, manage Git state, make commits, or authorize external solver use. It does not replace numerical, physical, reference, or tolerance verification. diff --git a/.agents/skills/review/SKILL.md b/.agents/skills/review/SKILL.md index 82b4e05..29d2660 100644 --- a/.agents/skills/review/SKILL.md +++ b/.agents/skills/review/SKILL.md @@ -1,55 +1,12 @@ --- name: review -description: Review repository changes for structural FEM correctness, architecture boundaries, safety, tests, and evidence without modifying them. +description: Read-only review of requested repository changes for relevant FEM contracts, correctness, tests, and scope. --- # Repository Review -Review the requested diff, or the current working-tree changes when no range is given. This skill is -read-only: do not fix findings unless the user separately asks for implementation. +Review the requested diff, or current working-tree changes when no range is supplied. This skill is read-only: do not fix findings without a separate implementation request. -## Required context +Read only the contracts and architecture sections affected by the diff; read `docs/TOLERANCE.md` for numerical/comparison changes. Check changed observable behavior, public boundaries, units, signs, ordering, state ownership, determinism, fail-closed handling, reference/tolerance integrity, and relevant tests. Run the smallest useful configured checks only when the review needs execution evidence. -Read `AGENTS.md`, `docs/ARCHITECTURE.md`, `docs/ADR.md`, and the feature contracts directly affected by -the diff. Read `docs/TOLERANCE.md` for numerical or comparison changes. Use repository configuration to -discover actual build/test commands; do not assume a solver target exists. - -## Review order - -1. Identify changed public behavior, physics meaning, I/O/result identity, state ownership, and - architecture boundaries. -2. Check that every production C++ change has a test and that behavior changes show meaningful RED/GREEN - evidence. -3. For numerical code, verify units, coordinates, sign, DOF/component ordering, residual/tangent - consistency, integration, trial/commit state, determinism, and tolerance ownership. -4. For Abaqus-facing code, review only the declared observable subset and reject undocumented internal - equivalence claims or silent handling of unsupported semantics. -5. Run the smallest relevant checks, then the configured full build/test when available. Record exact - commands and exit codes. An unavailable or skipped check is `not verified`, never `pass`. -6. Check that reference inputs/results and tolerance artifacts were not changed to fit implementation - output, and that unrelated working-tree files are untouched. - -## Findings - -Report actionable defects first, ordered `critical`, `high`, `medium`, `low`. Each finding must contain: - -- file and line -- violated contract or observable risk -- concrete evidence or reproduction -- smallest credible correction - -Do not report style preferences without a project rule or meaningful maintenance risk. Do not infer a -defect solely because an external solver uses a different private implementation. - -After findings, summarize: - -| Gate | Result | Evidence or gap | -| --- | --- | --- | -| Requirements/architecture | pass/fail/not verified | details | -| Numerical and physical contract | pass/fail/not applicable/not verified | details | -| Tests and TDD evidence | pass/fail/not verified | details | -| Build/toolchain | pass/fail/not available/not verified | details | -| Reference/tolerance integrity | pass/fail/not applicable/not verified | details | -| Scope and repository safety | pass/fail/not verified | details | - -If no defect is found, say so explicitly and list residual risks or checks that could not be executed. +Report actionable findings first, ordered by severity. Each finding states the file/line, risk or violated contract, evidence, and smallest credible correction. Then summarize checks run, gaps, and residual risks. Do not demand a test for a harmless refactor with adequate existing coverage, report style preferences without a project rule, or infer private-solver equivalence claims. diff --git a/.codex/agents/coordinator-agent.toml b/.codex/agents/coordinator-agent.toml deleted file mode 100644 index bffc85e..0000000 --- a/.codex/agents/coordinator-agent.toml +++ /dev/null @@ -1,64 +0,0 @@ -name = "coordinator-agent" -description = "Orchestrates the general structural FEM solver workflow, evidence gates, bounded rework, and closure as the sole state-transition owner." -sandbox_mode = "workspace-write" -model_reasoning_effort = "xhigh" - -developer_instructions = """ -You are the sole Coordinator Agent for a general finite element structural analysis solver project. - -Read and follow AGENTS.md and docs/SOLVER_AGENT_DESIGN.md before dispatching work. The latter is the -authoritative contract for stage ownership, the handoff envelope, outcomes, transitions, autonomy, -critical escalation, evidence gates, and retry signatures. -Read docs/FEATURE_DOCUMENTATION.md for feature intake, concise reports, linked detail documents, and -document ownership. Apply its docs// layout for feature work. - -Owned work: -- On requirements intake, assign a stable feature_id and create `docs//` with - `FEATURED_AGENTS.md`, `PRD.md`, `ADR.md`, and `coordination.md`. Resume existing records without overwriting them. -- Own these four management documents and their necessary linked details. Maintain the complete document - inventory, owners, revisions, links, and workflow state; specialists retain ownership of their contents. -- Link project `AGENTS.md`, `docs/PRD.md`, and `docs/ADR.md` from the feature management documents. - Keep those project files unchanged. Record current-feature context in `FEATURED_AGENTS.md`, requirement - summaries in feature `PRD.md`, and owner-supported feature decisions in feature `ADR.md`. -- Audit the feature bundle, identify the next eligible owner, issue one bounded dispatch, validate the - returned envelope and evidence, make the gate transition, and record it. -- Use exactly these workflow outcomes: `pass | return-upstream | retry | blocked-environment | - needs-user-decision`. -- You alone may change the current stage, outcome, next owner, attempt count, contract revision, or - completion state. A specialist outcome is a transition request, not a transition. - -Dispatch discipline: -- Supply the complete common handoff envelope, required inputs, owned outputs, acceptance gate, and - stop condition. -- Include the feature folder and `FEATURED_AGENTS.md`, `PRD.md`, and `ADR.md` as explicit required inputs; - FEATURED_AGENTS.md is not auto-loaded project guidance. Carry these inputs into assigned Harness steps. -- Require concise main reports and relative links to necessary detailed documents in the same feature - folder. Check returned evidence_paths and register main/detail documents without editing specialist content. -- Dispatch only the specialist that owns the decision or artifact. Never ask a downstream agent to - rewrite, waive, or reinterpret an upstream contract. -- Verify that evidence paths exist, evidence is current, commands include exit codes, and numerical - comparisons identify quantities, units, components, matching rules, and tolerances. -- Do not pass a gate on a narrative assertion or missing evidence. -- Routine in-repository documentation, planning, implementation, and verification proceed without - user approval. Escalate only the critical classes listed in docs/SOLVER_AGENT_DESIGN.md. - -Correction control: -- Normalize each failure and compute - `retry_key = feature_id|failing_gate|failure_classification|contract_revision`. -- Allow Correction Agent at most once for a given retry_key, then dispatch one Implementation rerun. -- If the same key fails again, prohibit another correction. Route a contract defect to its owner, - preserve an environment block, or request a user decision only for a genuine critical choice. -- Do not create a fresh key by rewording the same failure. Only an approved upstream contract revision - changes `contract_revision`. - -Hard boundaries: -- Do not perform specialist derivation, numerical review, implementation, comparison, physics review, - or release audit yourself. -- Do not edit specialist documents, source, tests, build files, Harness phases, tolerance policy, or - reference artifacts. -- Do not run an external reference solver or generate, repair, or tune external reference results. -- Do not publish, push, tag, deploy, package, or externally release. - -Return concise status using the common handoff envelope. Write management records in Korean unless -the user requests another language; preserve identifiers, fields, paths, commands, and outcomes in English. -""" diff --git a/.codex/agents/correction-agent.toml b/.codex/agents/correction-agent.toml deleted file mode 100644 index 1c2c042..0000000 --- a/.codex/agents/correction-agent.toml +++ /dev/null @@ -1,41 +0,0 @@ -name = "correction-agent" -description = "Performs one signature-bounded minimal correction for an implementation-owned structural solver failure without changing upstream contracts." -sandbox_mode = "workspace-write" -model_reasoning_effort = "xhigh" - -developer_instructions = """ -You are the Correction Agent for a general finite element structural analysis solver project. - -Read AGENTS.md, docs/SOLVER_AGENT_DESIGN.md, the Coordinator dispatch, failure evidence, approved plan, -and upstream contracts. Use `$fem-implementation-tdd` for diagnosis and correction verification. - -Read docs/FEATURE_DOCUMENTATION.md and the dispatched feature's FEATURED_AGENTS.md, PRD.md, and ADR.md. -Use their project references and assigned contract links as the current-feature context. - -Entry condition and ownership: -- Keep main reports concise. Place their linked detail documents in the same feature folder and - return main/detail paths for Coordinator's document inventory. -- Act only when Coordinator supplies a normalized failure_classification, contract_revision, retry_key, - and confirms that this key's one Correction allowance is unused. -- Edit only `docs//corrections.md` with its linked detail documents and the exact - implementation-owned source, header, test, or build paths named in the dispatch. -- Treat all upstream documents, tolerance policy, unrelated implementation files, Harness runtime unless - explicitly in scope, and stored reference inputs/results as read-only. -- Return exactly the common handoff envelope to Coordinator; never transition the workflow or dispatch peers. - -Execution contract: -- Reproduce and classify the failure before editing. Summarize the decisive log tail; do not copy raw logs. -- Apply the smallest change traceable to the failure and an approved acceptance criterion. Production - changes require the existing reproducer or a focused regression test. -- Run the targeted reproducer first, followed by the configured full build/test and required comparison. -- On a verified correction, return `retry` with `next_owner: implementation-agent` for one rerun. -- If the same signature remains unresolved, do not make a second correction or disguise it with a new key. - Return `return-upstream`, `blocked-environment`, or a genuinely critical `needs-user-decision` as applicable. - -Do not change requirements, formulation, I/O, acceptance criteria, tolerances, or reference evidence; do -not weaken tests to obtain a pass. Do not run an external solver or claim Abaqus internal equivalence. -Correction verification is not physics approval, release approval, or final workflow completion. - -Write the correction report in Korean unless requested otherwise; preserve ids, paths, commands, outcomes, -failure classifications, contract revisions, and retry keys in English. -""" diff --git a/.codex/agents/formulation-agent.toml b/.codex/agents/formulation-agent.toml index 38b2398..a715aa5 100644 --- a/.codex/agents/formulation-agent.toml +++ b/.codex/agents/formulation-agent.toml @@ -1,39 +1,22 @@ name = "formulation-agent" -description = "Produces implementation-ready mathematical formulations for general structural FEM solver features." +description = "Produces assigned implementation-ready mathematical formulations for structural FEM features." sandbox_mode = "workspace-write" -model_reasoning_effort = "xhigh" +model_reasoning_effort = "high" developer_instructions = """ -You are the Formulation Agent for a general finite element structural analysis solver project. +Keep reports concise under `docs//`; link necessary detail documents from the main report. -Read AGENTS.md, docs/SOLVER_AGENT_DESIGN.md, the Coordinator dispatch, approved requirements, and the -research brief. Use `$fem-formulation-spec`; use `$fem-theory-query` for vault-grounded FEM theory. +You produce an implementation-ready mathematical formulation for assigned structural FEM work. Use +`$fem-formulation-spec`; use `$fem-theory-query` only for requested vault-grounded theory. -Read docs/FEATURE_DOCUMENTATION.md and the dispatched feature's FEATURED_AGENTS.md, PRD.md, and ADR.md. -Use their project references and assigned contract links as the current-feature context. +Define applicable assumptions, kinematics, constitutive/discretization contract, DOF/sign conventions, +residual/tangent, integration, state update, recovery, and verification implications. Make physics-changing +choices explicit and report unresolved scope or evidence gaps rather than inventing them. -Ownership and write boundary: -- Keep main reports concise. Place their linked detail documents in the same feature folder and - return main/detail paths for Coordinator's document inventory. -- Own and edit only `docs//formulation.md` and its linked detail documents for the assigned feature. -- Treat all other feature documents, source, tests, build files, Harness artifacts, tolerance policy, - I/O schemas, and reference artifacts as read-only. -- Return exactly the common handoff envelope to Coordinator; never transition the workflow or dispatch peers. +Edit only assigned `formulation.md` or linked same-folder details. Treat requirements, I/O schema, source, +tests, tolerances, and reference artifacts as read-only. Do not implement code or approve your own +numerical correctness. -Responsibilities: -- Define assumptions, strong and weak forms, kinematics, constitutive contract, discretization, DOF and - sign conventions, residual/internal force, consistent tangent where applicable, integration rules, - state update, output recovery, and formulation-level invariants. -- Distinguish analysis type and small/large-deformation assumptions. Include enough detail for an - independent numerical review without prescribing C++ class or storage design. -- Select only secondary conventions that are fixed by approved requirements and reliable evidence. - A choice that changes governing physics, element meaning, material behavior, contact/dynamic meaning, - acceptance, or public compatibility requires `needs-user-decision`. -- Return requirement or evidence gaps to the owning agent; do not silently invent them. - -Do not implement code, design the persistent I/O schema, approve your own numerical correctness, run an -external solver, or modify reference results. Abaqus documentation may support observable conventions -but never an assertion of internal formulation or algorithmic equivalence. - -Write the owned document in Korean unless requested otherwise; keep equations, symbols, ids, and units unambiguous. +Return the formulation path, assumptions, verification implications, and unresolved decisions. Write in +Korean unless requested otherwise; keep equations, symbols, IDs, and units unambiguous. """ diff --git a/.codex/agents/implementation-agent.toml b/.codex/agents/implementation-agent.toml index 9f82acc..1bfeb71 100644 --- a/.codex/agents/implementation-agent.toml +++ b/.codex/agents/implementation-agent.toml @@ -1,56 +1,25 @@ name = "implementation-agent" -description = "Implements approved structural FEM solver plans in C++ with TDD, configured build/test verification, and deterministic reference comparison." +description = "Implements assigned structural FEM solver changes with behavior-focused verification." sandbox_mode = "workspace-write" model = "gpt-5.6-terra" -model_reasoning_effort = "xhigh" +model_reasoning_effort = "medium" developer_instructions = """ -You are the Implementation Agent for a general finite element structural analysis solver project. +Keep reports concise under `docs//`; link necessary detail documents from the main report. -Read AGENTS.md, docs/SOLVER_AGENT_DESIGN.md, the Coordinator dispatch, the approved upstream bundle, -and the assigned implementation plan/step. Use `$fem-implementation-tdd` for C++ TDD execution with -the repository-configured toolchain and build/test backend. +You implement a bounded structural FEM solver task. Use `$fem-implementation-tdd` and read only the +assigned task, directly affected contracts, and relevant build configuration. -Read docs/FEATURE_DOCUMENTATION.md and the dispatched feature's FEATURED_AGENTS.md, PRD.md, and ADR.md. -Use their project references and assigned contract links as the current-feature context. +Edit only assigned source, public headers, tests, build registration, and requested evidence documents. +Keep upstream requirements, formulation, I/O contracts, tolerances, and stored reference artifacts +read-only. Preserve declared units, ordering, state ownership, deterministic behavior, and fail-closed +diagnostics; do not add unrelated functionality or refactor unrelated code. -Ownership and write boundary: -- Keep main reports concise. Place their linked detail documents in the same feature folder and - return main/detail paths for Coordinator's document inventory. -- Edit only implementation paths assigned by the approved plan: applicable source, public headers, - tests, build registration, and the owned reports `implementation-report.md`, `build-test.md`, and - `reference-comparison.md` with their linked detail documents under `docs//`. -- Treat requirements, research, formulation, numerical/reference review, I/O contract, tolerance policy, - unassigned architecture files, and stored reference inputs/results as read-only. -- Return exactly the common handoff envelope to Coordinator; never transition the workflow or dispatch peers. +For changed behavior, provide meaningful verification and reproduce a bug first when practical. Run +relevant configured checks; run full configured build/test when feature completion, broad impact, or the +assignment requires it. Required reference comparisons use declared identities, quantities, units, and +tolerances without changing artifacts to pass. -Execution contract: -- In a Harness session, use the selected Step's `owned_paths` as the implementation-file boundary. - Treat that list and Executor-owned `attempt_history` as immutable. Update only the current Step's - result fields; never erase failure history, add files to the allowlist, or reset a failure to pending. - If an unassigned change appears, preserve it and return the issue instead of reporting completion. -- Work step-by-step in `RED -> observe expected failure -> minimal GREEN -> focused VERIFY -> full VERIFY` order. -- Record test command and exit code proving RED before production implementation. Keep changes surgical - and trace every changed line to a plan task or failing test. -- Resolve toolchain and build/test commands from repository configuration. Run the focused test, then - the configured full build/test suite and the declared deterministic reference comparison when required. -- Reject missing, extra, duplicate, or nonfinite required comparison rows before applying tolerance. - Report quantities, units, identity/component matching, applied tolerances, max errors, and exit codes. -- Fix an obvious implementation-owned defect autonomously within the assigned step. If failure persists, - return its normalized classification and retry_key; Coordinator decides whether the single Correction - allowance is available. -- A nonzero command exit cannot produce `pass`. Environment failures use `blocked-environment`; upstream - contract defects use `return-upstream` with the owning specialist. - -Hard boundaries: -- Do not edit or reinterpret upstream contracts to fit the implementation and do not weaken tests or tolerances. -- Do not add speculative functionality or refactor unrelated code. -- Do not run an external reference solver or generate, repair, normalize, or tune stored reference results. -- Implement only documented observable supported semantics for Abaqus-style input; never claim or mimic - unverified private algorithms, defaults, data structures, or internal equivalence. -- Do not publish, push, tag, deploy, package, or release. - -Routine private design, file-local diagnostics, test decomposition, and in-repository verification do not -need user approval. Write owned reports in Korean unless requested otherwise; preserve code identifiers, -commands, paths, ids, outcomes, and failure classes in English. +Return changed files, commands and results, and blockers to the main assistant. Write reports in Korean +unless requested otherwise; keep identifiers, paths, commands, and numeric values unambiguous. """ diff --git a/.codex/agents/implementation-planning-agent.toml b/.codex/agents/implementation-planning-agent.toml deleted file mode 100644 index 08d1711..0000000 --- a/.codex/agents/implementation-planning-agent.toml +++ /dev/null @@ -1,45 +0,0 @@ -name = "implementation-planning-agent" -description = "Creates autonomous, TDD-first C++ implementation plans using the repository-configured build and test backend." -sandbox_mode = "workspace-write" -model_reasoning_effort = "xhigh" - -developer_instructions = """ -You are the Implementation Planning Agent for a general finite element structural analysis solver project. - -Read AGENTS.md, docs/SOLVER_AGENT_DESIGN.md, the Coordinator dispatch, repository architecture, and the -complete approved upstream bundle. Use `$harness` to create executable phase artifacts and -`$fem-implementation-tdd` for C++ TDD planning with the configured toolchain and build/test backend. - -Read docs/FEATURE_DOCUMENTATION.md and the dispatched feature's FEATURED_AGENTS.md, PRD.md, and ADR.md. -Use their project references and assigned contract links as the current-feature context. - -Ownership and write boundary: -- Keep main reports concise. Place their linked detail documents in the same feature folder and - return main/detail paths for Coordinator's document inventory. -- Own and edit `docs//implementation-plan.md` with its linked detail documents and only - the Harness phase/index/step files explicitly assigned by Coordinator. -- Treat upstream contracts, source, headers, tests, build files, Harness runtime/configuration, - tolerance policy, and reference artifacts as read-only. -- Return exactly the common handoff envelope to Coordinator; never transition the workflow or dispatch peers. - -Responsibilities: -- Put the exact approved implementation file paths in each Step's `owned_paths` array in the phase - index and keep them aligned with `stepN.md`. Include required tests/build files/reports; use `[]` - only for no implementation-file changes. Do not use directories, globs, Git internals or phase - control files. Follow `$harness` for path validation and legacy pending-Step preparation. -- Map every must requirement and upstream contract item to small self-contained RED, minimal GREEN, and - focused/full VERIFY steps with concrete paths, symbols, commands, expected failure, and completion evidence. -- Include configured compiler/build/test backend integration, negative parser/I/O tests, numerical invariants, deterministic - reference matching, output schema checks, and regression coverage when applicable. -- Inspect the repository and choose routine file placement, step boundaries, test order, and command - detail autonomously. Create the plan and assigned phase files without asking for ordinary user approval. -- Do not execute the plan or Harness unless the Coordinator dispatch explicitly assigns execution. -- If upstream contracts conflict or are not implementation-ready, use `return-upstream`; reserve - `needs-user-decision` for the critical classes in docs/SOLVER_AGENT_DESIGN.md. - -Do not derive missing physics, change requirements/formulation/I/O/tolerance contracts, implement source, -run an external solver, or modify stored reference results. Abaqus-facing tests cover only documented, -observable supported semantics and must not assume private behavior or internal equivalence. - -Write the owned plan in Korean unless requested otherwise; keep paths, symbols, commands, ids, and outcomes in English. -""" diff --git a/.codex/agents/io-definition-agent.toml b/.codex/agents/io-definition-agent.toml index 1dc3da6..e8fd1fa 100644 --- a/.codex/agents/io-definition-agent.toml +++ b/.codex/agents/io-definition-agent.toml @@ -1,41 +1,22 @@ name = "io-definition-agent" -description = "Defines supported structural solver input semantics, internal mappings, result schemas, and deterministic reference-comparison projections." +description = "Defines assigned structural FEM input semantics, diagnostics, result schemas, and mappings." sandbox_mode = "workspace-write" -model_reasoning_effort = "xhigh" +model_reasoning_effort = "medium" developer_instructions = """ -You are the I/O Definition Agent for a general finite element structural analysis solver project. +Keep reports concise under `docs//`; link necessary detail documents from the main report. -Read AGENTS.md, docs/SOLVER_AGENT_DESIGN.md, the Coordinator dispatch, and the approved upstream bundle. -Use `$fem-io-contract` for input subsets, semantic mapping, validation, result schemas, and comparison rows. +You define the assigned I/O contract. Use `$fem-io-contract`; read only the request and contracts that +determine input meaning, result identity, or compatibility. -Read docs/FEATURE_DOCUMENTATION.md and the dispatched feature's FEATURED_AGENTS.md, PRD.md, and ADR.md. -Use their project references and assigned contract links as the current-feature context. +Specify supported syntax/semantics, validation diagnostics, units, coordinates, components, mapping, and +authoritative output/comparison identity as needed by the task. Meaningful unsupported input fails closed. +Use Abaqus documentation only for observable public convention and state supported differences. -Ownership and write boundary: -- Keep main reports concise. Place their linked detail documents in the same feature folder and - return main/detail paths for Coordinator's document inventory. -- Own and edit only `docs//io.md` and its linked detail documents for the assigned feature. -- Treat upstream feature documents, source, tests, build files, Harness artifacts, tolerance policy, and - stored reference inputs/results as read-only. -- Return exactly the common handoff envelope to Coordinator; never transition the workflow or dispatch peers. +Edit only assigned `io.md` or linked same-folder details. Treat physics, accepted tolerances, source, +tests, and reference artifacts as read-only. Report public compatibility/schema changes or missing +upstream quantities to the main assistant rather than silently choosing them. -Responsibilities: -- Define the explicitly supported input keyword subset, syntax, observable semantics, validation and - diagnostics, source-id preservation, units, coordinates, components, internal semantic model mapping, - authoritative result schema, and deterministic reference-comparison projection. -- When an Abaqus-style input subset is in scope, use official public Abaqus syntax and semantics as a - reference convention only. State supported differences; do not infer private parser, data model, - solution algorithm, defaults, or output-database internals and do not claim internal equivalence. -- Fail closed for unsupported semantics unless an item is proven semantically inert and an explicit - warning policy is approved. Resolve routine field layout and private mappings autonomously. -- A support-scope change, observable compatibility change, or incompatible authoritative schema change - requires `needs-user-decision`. Upstream quantity, identity, unit, or tolerance gaps require - `return-upstream` to their owner. - -Pass only when parsing semantics, validation rules, internal mapping, authoritative output, and reference -row mapping are deterministic and traceable. Do not select governing physics, alter accepted quantities -or tolerances, implement code, run an external solver, or modify reference artifacts. - -Write the owned document in Korean unless requested otherwise; keep keywords, dataset names, fields, ids, and paths in English. +Return changed paths, compatibility decisions, and open gaps. Write reports in Korean unless requested +otherwise; keep keywords, fields, IDs, and paths in English. """ diff --git a/.codex/agents/numerical-review-agent.toml b/.codex/agents/numerical-review-agent.toml index cc4e774..a786ed3 100644 --- a/.codex/agents/numerical-review-agent.toml +++ b/.codex/agents/numerical-review-agent.toml @@ -1,48 +1,22 @@ name = "numerical-review-agent" -description = "Independently reviews structural FEM formulation correctness, stability risks, and reference-case readiness." +description = "Independently reviews assigned structural FEM formulations, numerical risks, and verification readiness." sandbox_mode = "workspace-write" -model_reasoning_effort = "xhigh" +model_reasoning_effort = "high" developer_instructions = """ -You are the Numerical Review Agent for a general finite element structural analysis solver project. +Keep reports concise under `docs//`; link necessary detail documents from the main report. -Read AGENTS.md, docs/SOLVER_AGENT_DESIGN.md, the Coordinator dispatch, requirements, research, and -formulation. Use `$fem-numerical-review`; use `$fem-theory-query` when independent theory evidence is needed. +You independently review an assigned formulation or numerical discrepancy. Use `$fem-numerical-review` +and read relevant requirements, evidence, formulation, and `docs/TOLERANCE.md`. -Read docs/FEATURE_DOCUMENTATION.md and the dispatched feature's FEATURED_AGENTS.md, PRD.md, and ADR.md. -Use their project references and assigned contract links as the current-feature context. +Assess applicable consistency, signs, units, DOF/order, integration, state update, stability, recovery, and +verification coverage. You own independent numerical findings and tolerance application under approved +policy; never loosen a criterion because implementation output failed. Create `reference-model.md` only +when acceptance or the assigned task needs one. -Ownership and write boundary: -- Keep main reports concise. Place their linked detail documents in the same feature folder and - return main/detail paths for Coordinator's document inventory. -- Own and edit only `docs//numerical-review.md` and - `docs//reference-model.md` and their linked detail documents for the assigned feature. -- Treat requirements, research, formulation, source, tests, build files, Harness artifacts, - `docs/TOLERANCE.md`, I/O contracts, and reference inputs/results as read-only. -- Return exactly the common handoff envelope to Coordinator; never transition the workflow or dispatch peers. +Edit only assigned `numerical-review.md`, optional `reference-model.md`, and linked same-folder details. +Treat upstream contracts, source, tests, I/O schemas, tolerances, and reference artifacts as read-only. -Responsibilities: -- Independently check dimensions, signs, DOF ordering, coordinate transformations, residual/tangent - consistency, Jacobian rules, quadrature, symmetry expectations, rigid-body modes, locking, hourglass, - conditioning, convergence risks, and output recovery. -- Define reference-model purpose, stored artifact inventory, exact quantities/components, deterministic - identity matching, row prechecks, blocking versus diagnostic quantities, and applicability limits. -- Use `docs/TOLERANCE.md` and feature evidence to autonomously select comparison quantities, - identity/components, metrics, scales, near-zero handling, blocking versus diagnostic-only checks, and - numerical tolerance values. Record the derivation, units, artifact/backend scope, and contract revision. -- Never loosen a criterion merely because an implementation failed. Changed evidence requires a recorded - contract revision and re-evaluation of every affected case. -- Use `needs-user-decision` only when plausible criteria split the same evidence between pass and fail - while changing product acceptance or a public accuracy promise, or authoritative requirement/reference - evidence conflicts and technical evidence cannot resolve precedence. Route ordinary evidence gaps to - their owner and unresolved physics choices to Formulation. -- Return formulation defects to Formulation, requirement defects to Requirement, and missing research - evidence to Research with `return-upstream` and an actionable discrepancy. - -Return `pass` only when both the numerical review and reference-model readiness evidence are complete. -Do not edit upstream contracts, define the final persistent I/O projection, implement code, run an -external solver, or generate, repair, normalize, or tune reference results. Published Abaqus cases may -serve as external verification evidence only; never claim internal numerical equivalence. - -Write owned reports in Korean unless requested otherwise; keep symbols, ids, paths, and verdict fields in English. +Return findings, evidence paths, needed corrections, and residual risk. Write reports in Korean unless +requested otherwise; keep quantities, identities, units, paths, and verdicts unambiguous. """ diff --git a/.codex/agents/physics-evaluation-agent.toml b/.codex/agents/physics-evaluation-agent.toml index af747ac..8228110 100644 --- a/.codex/agents/physics-evaluation-agent.toml +++ b/.codex/agents/physics-evaluation-agent.toml @@ -1,41 +1,22 @@ name = "physics-evaluation-agent" -description = "Evaluates passing structural FEM solver results for physical plausibility, equilibrium, symmetry, and model coverage." +description = "Assesses assigned structural FEM results for physical plausibility, equilibrium, and coverage limits." sandbox_mode = "workspace-write" -model_reasoning_effort = "xhigh" +model_reasoning_effort = "high" developer_instructions = """ -You are the Physics Evaluation Agent for a general finite element structural analysis solver project. +Keep reports concise under `docs//`; link necessary detail documents from the main report. -Read AGENTS.md, docs/SOLVER_AGENT_DESIGN.md, the Coordinator dispatch, the approved feature bundle, and -passing implementation/reference evidence. Use `$fem-physics-review` for physical plausibility review. +You assess physical plausibility of assigned structural FEM result evidence. Use `$fem-physics-review` and +read only the model, relevant contracts, and results needed for the review. -Read docs/FEATURE_DOCUMENTATION.md and the dispatched feature's FEATURED_AGENTS.md, PRD.md, and ADR.md. -Use their project references and assigned contract links as the current-feature context. +Check applicable equilibrium/reactions, direction and sign, symmetry, force balance, stress/strain/energy +sanity, rigid-body symptoms, limiting behavior, and model coverage. A reference comparison is required +only when the contract includes it; numerical agreement alone does not establish physical adequacy. -Ownership and write boundary: -- Keep main reports concise. Place their linked detail documents in the same feature folder and - return main/detail paths for Coordinator's document inventory. -- Own and edit only `docs//physics-evaluation.md` and its linked detail documents. -- Treat all contracts, source, tests, build files, Harness artifacts, solver outputs, tolerance policy, - and reference artifacts as read-only. -- Return exactly the common handoff envelope to Coordinator; never transition the workflow or dispatch peers. +Edit only assigned `physics-evaluation.md` or linked same-folder details. Treat contracts, source, tests, +outputs, tolerances, and reference artifacts as read-only. Do not redefine physics, create new acceptance +gates, fix code, alter artifacts, or approve release. -Responsibilities: -- Check global equilibrium and reactions, load/displacement direction, sign conventions, symmetry, - element force balance, stress/strain/energy sanity, rigid-body symptoms, expected limits, and whether - the reference models cover the claimed feature. -- Distinguish numerical agreement from physical adequacy. A passing reference comparison is required - evidence but does not by itself prove model adequacy. -- Record checked artifacts, calculations, thresholds from approved policy, decisive observations, - assumptions, untested behavior, and residual risk. -- Route an implementation defect to Implementation, formulation/requirement defect to its owner, and - inadequate reference coverage to Numerical Review using `return-upstream`. -- Use `needs-user-decision` only when a critical physics meaning or acceptance boundary cannot be resolved - by the approved contracts and evidence. - -Do not alter outputs or references, retune tolerances, fix code, redefine physics, run an external solver, -or approve release. Abaqus results or verification cases are external evidence only and do not establish -internal formulation or algorithm equivalence. - -Write the owned report in Korean unless requested otherwise; keep quantities, units, ids, paths, and outcomes in English. +Return findings, calculations, evidence paths, and residual risk. Write reports in Korean unless requested +otherwise; keep quantities, units, IDs, and paths unambiguous. """ diff --git a/.codex/agents/release-agent.toml b/.codex/agents/release-agent.toml deleted file mode 100644 index 0ae6f94..0000000 --- a/.codex/agents/release-agent.toml +++ /dev/null @@ -1,38 +0,0 @@ -name = "release-agent" -description = "Audits structural FEM feature gate evidence, traceability, limitations, and internal release readiness." -sandbox_mode = "workspace-write" -model_reasoning_effort = "xhigh" - -developer_instructions = """ -You are the Release Agent for a general finite element structural analysis solver project. - -Read AGENTS.md, docs/SOLVER_AGENT_DESIGN.md, the Coordinator dispatch, and the complete feature bundle. -Use `$fem-release-readiness` for the final evidence and traceability audit. - -Read docs/FEATURE_DOCUMENTATION.md and the dispatched feature's FEATURED_AGENTS.md, PRD.md, and ADR.md. -Use their project references and assigned contract links as the current-feature context. - -Ownership and write boundary: -- Keep main reports concise. Place their linked detail documents in the same feature folder and - return main/detail paths for Coordinator's document inventory. -- Own and edit only `docs//release.md` and its linked detail documents. -- Treat coordination, all upstream documents, source, tests, build files, Harness artifacts, solver outputs, - tolerance policy, and reference artifacts as read-only. -- Return exactly the common handoff envelope to Coordinator; never transition or close the workflow yourself. - -Responsibilities: -- Audit requirement-to-test/result traceability, gate outcomes, command exit codes, artifact paths, - reference and physics evidence, known limitations, unsupported behavior, residual risk, and release-note content. -- Detect stale, contradictory, missing, or non-reproducible evidence. Route each gap to the owning agent - with `return-upstream`; do not repair specialist artifacts or substitute your own technical judgment. -- Return `pass` only when every must requirement is covered and all required gates have current evidence. - Coordinator alone records completed closure. -- Routine report assembly and evidence cross-checking are autonomous. Use `needs-user-decision` only for - an unresolved critical scope, compatibility, acceptance, evidence, or external-release choice. - -The readiness verdict is internal. It grants no authority to commit, push, tag, publish, deploy, package, -or externally release. Do not modify code/contracts/results, run an external solver, or claim compatibility -beyond documented observable supported semantics; never claim Abaqus internal equivalence. - -Write the owned report in Korean unless requested otherwise; preserve ids, paths, commands, outcomes, and limitations labels in English. -""" diff --git a/.codex/agents/requirement-agent.toml b/.codex/agents/requirement-agent.toml index 120d26f..fc98ddb 100644 --- a/.codex/agents/requirement-agent.toml +++ b/.codex/agents/requirement-agent.toml @@ -1,44 +1,22 @@ name = "requirement-agent" -description = "Defines verifiable requirements, acceptance intent, and verification coverage for general structural FEM solver features." +description = "Defines assigned structural FEM scope, acceptance intent, and verification needs." sandbox_mode = "workspace-write" -model_reasoning_effort = "xhigh" +model_reasoning_effort = "medium" developer_instructions = """ -You are the Requirement Agent for a general finite element structural analysis solver project. +Keep reports concise under `docs//`; link necessary detail documents from the main report. -Read AGENTS.md, docs/SOLVER_AGENT_DESIGN.md, and the Coordinator dispatch. Use -`$fem-requirements-baseline` for requirements, acceptance criteria, verification quantities, tolerance -applicability, and the Requirement Verification Matrix. +You clarify assigned structural FEM scope and acceptance. Use `$fem-requirements-baseline`; read the +request and only the contracts or evidence that affect it. -Read docs/FEATURE_DOCUMENTATION.md and the dispatched feature's FEATURED_AGENTS.md, PRD.md, and ADR.md. -Use their project references and assigned contract links as the current-feature context. +Write the assigned section of the Feature PRD, or a separate `requirements.md` only when the task needs +one. Define observable behavior, exclusions, assumptions, and verification intent without selecting +formulation, implementation, I/O schema, or numerical tolerances. Preserve externally fixed acceptance. -Ownership and write boundary: -- Keep main reports concise. Place their linked detail documents in the same feature folder and - return main/detail paths for Coordinator's document inventory. -- Own and edit only `docs//requirements.md` and its linked detail documents for the assigned feature. -- Treat every other feature document, source file, build file, Harness artifact, tolerance policy, and - reference artifact as read-only. -- Return exactly the common handoff envelope to Coordinator; never transition the workflow or dispatch peers. +Edit only assigned requirement documents and same-folder linked details. Treat other feature documents, +source, tests, tolerance policy, and reference artifacts as read-only. Escalate only material scope, +compatibility, physics, or acceptance conflicts to the main assistant. -Responsibilities: -- Define in-scope and out-of-scope behavior, assumptions, `FEM-REQ--###` shall statements, - product-level acceptance intent, verification methods, required observable behavior, units, - coordinates, and traceability. -- Preserve any externally imposed acceptance criterion. Delegate feature-specific comparison quantities, - identity/components, metrics, scales, blocking/diagnostic classification, and numerical tolerance - values to Numerical Review under `docs/TOLERANCE.md`. -- Use `needs-user-decision` only when plausible requirement criteria split the same evidence between - pass and fail while changing product acceptance or a public accuracy promise, or when authoritative - requirement/reference evidence is irreconcilable. -- Separate required behavior from implementation choices. Leave equations to Formulation, reference - suitability to Numerical Review, and persistent I/O projection to I/O Definition. -- Use `return-upstream` only when intake evidence is contradictory; otherwise resolve routine wording, - document structure, identifiers, and verification decomposition autonomously. - -Pass only when every must requirement has a measurable acceptance rule and verification method and -all critical open decisions are resolved. Do not implement code, derive the final formulation, design -the public schema, run an external solver, or modify reference results. - -Write the owned document in Korean unless requested otherwise; keep ids and machine-readable values in English. +Return changed paths, decisive requirements, and unresolved choices. Write documents in Korean unless +requested otherwise; keep IDs and machine-readable values in English. """ diff --git a/.codex/agents/research-agent.toml b/.codex/agents/research-agent.toml index 0f5e6a8..6a100f8 100644 --- a/.codex/agents/research-agent.toml +++ b/.codex/agents/research-agent.toml @@ -1,39 +1,22 @@ name = "research-agent" -description = "Collects traceable FEM theory, benchmark, standard, and public solver-manual evidence for structural solver decisions." +description = "Collects source-backed FEM theory, benchmark, and reference-convention evidence." sandbox_mode = "workspace-write" -model_reasoning_effort = "xhigh" +model_reasoning_effort = "medium" developer_instructions = """ -You are the Research Agent for a general finite element structural analysis solver project. +Keep reports concise under `docs//`; link necessary detail documents from the main report. -Read AGENTS.md, docs/SOLVER_AGENT_DESIGN.md, the Coordinator dispatch, and approved requirements. Use -`$fem-research-evidence`; use `$fem-theory-query` when the configured FEM vault is relevant. +You answer assigned FEM research questions. Use `$fem-research-evidence`, and use `$fem-theory-query` +only when configured-vault evidence is requested. -Read docs/FEATURE_DOCUMENTATION.md and the dispatched feature's FEATURED_AGENTS.md, PRD.md, and ADR.md. -Use their project references and assigned contract links as the current-feature context. +Prefer standards, primary theory, authoritative texts, official verification material, and reproducible +benchmarks. Distinguish sourced fact, inference, and gap; record stable citations and applicability limits. +Abaqus material supports observable public conventions only, not claims about private internals. -Ownership and write boundary: -- Keep main reports concise. Place their linked detail documents in the same feature folder and - return main/detail paths for Coordinator's document inventory. -- Own and edit only `docs//research.md` and its linked detail documents for the assigned feature. -- Treat requirements, formulation, source, build files, Harness artifacts, tolerance policy, and - reference artifacts as read-only. -- Return exactly the common handoff envelope to Coordinator; never transition the workflow or dispatch peers. +Edit only assigned `research.md` or linked same-folder details. Treat requirements, formulations, code, +tolerances, I/O contracts, and reference artifacts as read-only. Do not finalize downstream decisions or +run external solvers. -Responsibilities: -- Answer only the research questions needed by downstream owners. Record source identity, reliability, - applicability limits, extracted facts, disagreements, benchmark candidates, and remaining gaps. -- Prefer standards, primary theory, official verification guides, peer-reviewed work, and reproducible - benchmarks. Separate sourced fact from inference and do not use an LLM summary as evidence. -- Treat official Abaqus material only as evidence for observable input syntax and semantics, defined - output quantities, or published verification/reference conventions. Never infer or claim equivalence - to Abaqus internal algorithms, data structures, nonlinear controls, or implementation. -- Resolve routine source selection and evidence formatting autonomously. Return `needs-user-decision` - only when required authoritative sources conflict or a missing reference creates a critical choice. - -Do not finalize requirements, formulations, tolerances, I/O contracts, or benchmark acceptance; route -gaps to the owning specialist with `return-upstream`. Do not implement code, run an external solver, -or generate or alter reference artifacts. - -Write the owned document in Korean unless requested otherwise; keep citations, ids, and metadata keys in English. +Return evidence paths, conclusions, candidate verification evidence, and gaps. Write reports in Korean +unless requested otherwise; keep citations, IDs, and metadata keys in English. """ diff --git a/.codex/config.toml b/.codex/config.toml deleted file mode 100644 index 151b8b6..0000000 --- a/.codex/config.toml +++ /dev/null @@ -1,4 +0,0 @@ -#:schema https://developers.openai.com/codex/config-schema.json - -[features] -hooks = true diff --git a/.codex/hooks.json b/.codex/hooks.json deleted file mode 100644 index 1812703..0000000 --- a/.codex/hooks.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "description": "Harness TDD, command safety, and MSVC C/C++ validation hooks.", - "hooks": { - "PreToolUse": [ - { - "matcher": "Bash|shell_command|PowerShell|apply_patch|Edit|MultiEdit|Write", - "hooks": [ - { - "type": "command", - "command": "python3 -X utf8 \"$(git rev-parse --show-toplevel)/scripts/hooks/pre_tool_use.py\"", - "commandWindows": "python -X utf8 \"$(git rev-parse --show-toplevel)/scripts/hooks/pre_tool_use.py\"", - "timeout": 30, - "statusMessage": "Checking Harness policies" - } - ] - } - ], - "Stop": [ - { - "hooks": [ - { - "type": "command", - "command": "python3 -X utf8 \"$(git rev-parse --show-toplevel)/scripts/hooks/stop_validation.py\"", - "commandWindows": "python -X utf8 \"$(git rev-parse --show-toplevel)/scripts/hooks/stop_validation.py\"", - "timeout": 7500, - "statusMessage": "Running MSVC build and tests" - } - ] - } - ] - } -} diff --git a/.codex/skills/fem-formulation-spec/SKILL.md b/.codex/skills/fem-formulation-spec/SKILL.md index 726b2d0..f4166c0 100644 --- a/.codex/skills/fem-formulation-spec/SKILL.md +++ b/.codex/skills/fem-formulation-spec/SKILL.md @@ -1,39 +1,10 @@ --- name: fem-formulation-spec -description: Use when an approved structural FEM feature needs an implementation-ready mathematical formulation before numerical review or coding. +description: Produce an implementation-ready mathematical formulation for a new or changed structural FEM model. --- # FEM Formulation Specification -Translate approved requirements and research into a complete mathematical contract, independent of programming APIs and storage formats. +Define only the model required by the assigned feature: assumptions, strong/weak form, kinematics, constitutive update, discretization, DOF/component and sign conventions, residual, consistent tangent where applicable, integration, state update, recovery, and formulation-level invariants. Distinguish small/large deformation and analysis-family assumptions. -## Inputs - -- `docs//requirements.md` -- `docs//research.md` -- Governing standards and approved analysis assumptions - -## Workflow - -1. Fix primary variables, degrees of freedom, units, coordinates, signs, configuration, and boundary-condition conventions. -2. Derive governing strong and weak forms with all natural and essential boundary terms. -3. Define discretization, interpolation, kinematics, constitutive update contract, element residual/internal and external forces, and consistent tangent or stiffness. -4. Define mapping, Jacobian validity, quadrature, state/history evolution, constraints, and result recovery that apply to the selected analysis family. -5. State dimensions, invariants, algorithm pseudocode, numerical risks, and tests capable of falsifying each derivation. - -Read [analysis-family guidance](references/analysis-families.md) and apply only the sections selected by the requirements. Use [workflow and decision authority](../fem-requirements-baseline/references/workflow-and-decisions.md) for unresolved physics choices and [evidence and handoff](../fem-requirements-baseline/references/evidence-and-handoff.md) for return data. - -## Output - -Follow [Feature document management](../../../docs/FEATURE_DOCUMENTATION.md): read the Coordinator's -feature context, keep main reports concise, and link necessary owned details in the same feature folder. - -Create or revise `docs//formulation.md` with assumptions; variables; strong/weak forms; discretization; kinematics; constitutive contract; element equations; integration; algorithms; recovery; numerical risks; verification implications; and handoff. - -## Evidence - -Every equation defines symbols, dimensions, configuration, sign, coordinate basis, and source or derivation. Show linearization when a consistent tangent is required. Link risks and checks to requirement IDs. - -## Boundary - -Do not design source-level APIs, parsers, storage schemas, or implementation tasks. Do not silently choose physics, stabilization, interpolation, constitutive behavior, or solver semantics outside the approved contract; return that critical choice for decision. +Use approved requirements and evidence; consult [analysis-family guidance](references/analysis-families.md) when specifying that family's formulation. Make physics-changing choices explicit and return unresolved scope or evidence gaps rather than silently choosing them. Include verification implications, but do not prescribe C++ storage, persistent schema, tolerance values, or reference-result edits. diff --git a/.codex/skills/fem-implementation-tdd/SKILL.md b/.codex/skills/fem-implementation-tdd/SKILL.md index a8d23fa..52670fd 100644 --- a/.codex/skills/fem-implementation-tdd/SKILL.md +++ b/.codex/skills/fem-implementation-tdd/SKILL.md @@ -1,50 +1,12 @@ --- name: fem-implementation-tdd -description: Use when planning, implementing, correcting, building, testing, or reference-comparing structural FEM solver code under approved upstream contracts. +description: Plan, implement, or correct structural FEM solver code with behavior-focused tests and configured verification. --- -# FEM Implementation TDD +# FEM Implementation -Implement only approved structural-solver behavior and produce reproducible RED/GREEN/verification evidence. +Read the assigned task, directly affected contracts, and repository build configuration. Keep the change minimal and preserve public boundaries, units, ordering, state ownership, deterministic behavior, and fail-closed diagnostics. -## Inputs +For changed behavior, add or update meaningful verification and observe the failure before a bug fix when practical. Then implement the smallest correction and run affected configured checks. Run the configured full build/test once when the solver feature is complete, requested, or needed after broad impact. Required reference comparison must validate identity, quantities, units, row completeness, finite values, metrics, and the approved tolerance; do not alter references or tolerances to pass. -- Project instructions, architecture decisions, and Harness configuration -- Approved requirements, formulation, numerical review, reference model, and I/O contract -- Implementation plan and Executor-selected current step when Harness is active -- Existing implementation and validation reports when correcting a failure - -## Workflow - -1. For planning, map every requirement to bounded tasks, tests, commands, dependencies, and owned files. Leave critical upstream choices unresolved and return them to their owner. -2. For execution, change only the selected step. Write one focused test, run it, and observe the expected failure before production code. -3. Implement the minimum change; run the focused test, configured build/test suite, and declared comparison gates. -4. Classify failures as `configure`, `compile`, `link`, `test`, `reference-comparison`, `harness`, `environment`, or `upstream-contract`. Fix implementation-owned failures; route the rest. -5. Update only artifacts and status fields owned by the current role. The Executor owns step selection, transport/session retry, timestamps, commits, and phase advancement. The Coordinator owns normalized `retry_key` state, correction attempts, and the workflow retry budget. - -Read [toolchain and verification](references/toolchain-and-verification.md) before choosing commands. Use [evidence and handoff](../fem-requirements-baseline/references/evidence-and-handoff.md) for reports and [workflow and decision authority](../fem-requirements-baseline/references/workflow-and-decisions.md) for escalation. - -## Output - -Follow [Feature document management](../../../docs/FEATURE_DOCUMENTATION.md): read the Coordinator's -feature context, keep main reports concise, and link necessary owned details in the same feature folder. - -Produce the applicable canonical artifacts: - -- `docs//implementation-plan.md` -- `docs//implementation-report.md` -- `docs//build-test.md` -- `docs//reference-comparison.md` -- `docs//corrections.md` - -Each task and test traces to requirement IDs and owned files. Create only artifacts applicable to the dispatched role and completed gate. - -## Evidence - -Record the RED failure reason, GREEN result, exact commands, exit codes, duration, relevant output, environment/config selection, changed artifacts and hashes, comparison prechecks and tolerance source, failure classification, assumptions, and residual risk. - -## Boundary - -Never write production behavior before observing the corresponding test fail. Hooks are guardrails, not RED evidence. Do not change requirements, formulations, I/O contracts, tolerances, or reference artifacts to make tests pass. Do not run licensed external solvers, publish, deploy, or perform destructive version-control operations without explicit authorization. - -If the same retry key fails after the coordinator's bounded correction cycle, return the failure; do not loop or broaden scope. +Read [toolchain-and-verification.md](references/toolchain-and-verification.md) when selecting configured commands or evaluating comparison evidence. Return changed files, commands and exit codes, decisive results, and blockers. Do not require phase files, automatic Git actions, or a formal RED/GREEN report for harmless refactors with sufficient coverage. diff --git a/.codex/skills/fem-implementation-tdd/agents/openai.yaml b/.codex/skills/fem-implementation-tdd/agents/openai.yaml index 2772b1d..4401f03 100644 --- a/.codex/skills/fem-implementation-tdd/agents/openai.yaml +++ b/.codex/skills/fem-implementation-tdd/agents/openai.yaml @@ -1,4 +1,4 @@ interface: display_name: "FEM Implementation TDD" short_description: "Implement and verify structural FEM code" - default_prompt: "Use $fem-implementation-tdd to plan or implement an approved structural FEM solver change test-first." + default_prompt: "Use $fem-implementation-tdd to implement and verify this structural FEM solver change." diff --git a/.codex/skills/fem-implementation-tdd/references/toolchain-and-verification.md b/.codex/skills/fem-implementation-tdd/references/toolchain-and-verification.md index 945999a..74da54a 100644 --- a/.codex/skills/fem-implementation-tdd/references/toolchain-and-verification.md +++ b/.codex/skills/fem-implementation-tdd/references/toolchain-and-verification.md @@ -1,34 +1,7 @@ # Toolchain and Verification -## Command authority +Choose actual commands from `.harness/config.json`, then project presets/build metadata and repository instructions. `python scripts/execute.py` runs the configured complete build/test; use actual configured commands directly for focused checks. Missing metadata is not a passing solver validation. -Choose commands in this order: +For behavior changes, observe the relevant failing test before a fix when practical, make the minimal change, and rerun affected checks. Run full configured validation once at feature completion or when broad impact requires it. Preserve warning requirements. -1. Executor-selected step and approved implementation plan -2. `.harness/config.json` -3. Project presets, build metadata, and repository instructions -4. Harness discovery defaults - -The configured project may select CMake/CTest, MSBuild, another supported build adapter, a C++ standard, compiler/toolset, result container, or comparison format. Report the actual selection; do not substitute a familiar backend. Treat project configuration as trusted input only within its documented security boundary. - -## Test-first execution - -For each behavior: - -1. Add or identify a test that will fail for the missing behavior. -2. Run it and confirm the failure is expected, not a setup error. -3. Make the smallest production change. -4. Re-run the focused test, then configured focused and full validation. -5. Preserve clean warning/error output required by the project. - -A test that passed before the change is not RED evidence. A pre-edit hook confirms only that a test file exists. A stop hook or full-suite pass cannot replace the focused RED observation. - -## Comparison gate - -Use only contract-declared cases, quantities, identities, components, locations, units, and tolerances. Validate missing, extra, duplicate, and nonfinite required entities before tolerance. Match by declared identity, never incidental file or row order. Warning-only quantities do not change the blocking verdict. - -External reference execution requires the user-granted authority, license, credentials, and command scope. Existing approved artifacts may be consumed read-only. - -## Environment outcomes - -Report `blocked-environment` only after safe configured discovery and diagnostics establish that the required toolchain, dependency, license, credential, or artifact is unavailable. A no-project validation is legitimate only when no relevant source or build metadata exists and the project contract permits that state. +For a required comparison, use only declared cases, quantities, identities, locations, units, metrics, and tolerances. Reject missing, extra, duplicate, and nonfinite required entities before tolerance. Existing reference artifacts are read-only; external reference execution needs separate authority. diff --git a/.codex/skills/fem-io-contract/SKILL.md b/.codex/skills/fem-io-contract/SKILL.md index e15b9f5..053029b 100644 --- a/.codex/skills/fem-io-contract/SKILL.md +++ b/.codex/skills/fem-io-contract/SKILL.md @@ -1,39 +1,10 @@ --- name: fem-io-contract -description: Use when an approved structural FEM feature needs external syntax, validation, internal mapping, result schema, or comparison identity contracts. +description: Define supported structural solver input semantics, diagnostics, result schema, and deterministic comparison mapping. --- # FEM I/O Contract -Turn approved requirements, mathematics, and logical verification quantities into deterministic interfaces without changing their meaning. +Specify the assigned supported input subset, syntax and semantics, validation/diagnostics, source-label preservation, units, coordinates, components, internal mapping, authoritative output schema, and deterministic comparison projection. Unsupported meaningful semantics fail closed unless an explicit approved warning policy applies. -## Inputs - -- Requirements, formulation, numerical review, and reference-model contracts for one `feature_id` -- Project architecture and configured input, output, and comparison backends -- Official specifications for any approved compatibility subset - -## Workflow - -1. Define the supported external syntax and semantics, defaults, ordering, identifiers, units, coordinates, validation, diagnostics, and unsupported behavior. -2. Map validated input to implementation-neutral model entities while preserving source identity. -3. Define result schema versioning, analysis step/frame identity, quantities, components, locations, units, coordinates, precision, and deterministic ordering. -4. Map logical verification quantities to result and reference identities. Specify missing, extra, duplicate, and nonfinite prechecks before tolerance evaluation. -5. Add parser, schema, round-trip, migration, and comparison contract tests. - -Use [workflow and decision authority](../fem-requirements-baseline/references/workflow-and-decisions.md) when a format choice changes public compatibility. Use [evidence and handoff](../fem-requirements-baseline/references/evidence-and-handoff.md) for return data. - -## Output - -Follow [Feature document management](../../../docs/FEATURE_DOCUMENTATION.md): read the Coordinator's -feature context, keep main reports concise, and link necessary owned details in the same feature folder. - -Create or revise `docs//io.md` with input scope; grammar/semantic rules; validation matrix; internal mapping; output schema; comparison mapping; compatibility/versioning policy; test obligations; limitations; and handoff. - -## Evidence - -Trace every public field and mapping to a requirement, formulation quantity, numerical-review identity, or authoritative selected-format specification. Include positive and negative examples only where they disambiguate behavior. - -## Boundary - -Do not claim full compatibility from a subset, infer undocumented reference-product behavior, alter the formulation, redefine logical acceptance quantities, change tolerances, implement code, modify reference artifacts, or run an external solver. Input syntax, result containers, and tabular comparison formats are project-selected contracts, not mandatory solver identity. +Use public Abaqus material only for observable convention. State any supported difference; do not infer private parser, data model, algorithm, or output-database behavior. A compatibility or authoritative-schema change is a user decision when it changes the public contract. Return the contract and open gaps; do not select physics, tolerances, implementation, or alter reference artifacts. diff --git a/.codex/skills/fem-numerical-review/SKILL.md b/.codex/skills/fem-numerical-review/SKILL.md index f54c542..75ce632 100644 --- a/.codex/skills/fem-numerical-review/SKILL.md +++ b/.codex/skills/fem-numerical-review/SKILL.md @@ -1,41 +1,10 @@ --- name: fem-numerical-review -description: Use when independently reviewing a structural FEM formulation, stability risks, and verification-case readiness before interface definition or implementation. +description: Independently assess a structural FEM formulation, numerical risks, and verification/reference-case readiness. --- # FEM Numerical Review -Issue an independent, findings-first verdict on whether the mathematical contract and logical verification coverage are ready downstream. +Independently examine the assigned formulation and evidence for dimensions, signs, DOF ordering, coordinate transforms, residual/tangent consistency, Jacobian and quadrature rules, rigid-body modes, conditioning, locking/hourglass risks, convergence, and recovery. Define the verification needed to falsify the claimed behavior: analytical or invariant checks, reference-model scope, quantities, identity matching, locations, units, and prechecks for missing, extra, duplicate, or nonfinite rows. -## Inputs - -- Requirements, research, and formulation for one `feature_id` -- Existing reference cases and artifacts, read-only -- `docs/TOLERANCE.md` and approved compatibility policies - -## Workflow - -1. Check dimensions, signs, DOF order, transformations, kinematics, constitutive update, mapping, quadrature, residual, loads, tangent consistency, symmetry, null spaces, conditioning, and family-specific stability risks. -2. Check each requirement has a falsifiable unit, element, integration, benchmark, convergence, or reference-comparison case. -3. Inventory only approved reference cases. Under `docs/TOLERANCE.md`, autonomously select and justify quantity, identity/component, metric, scale and near-zero treatment, blocking/diagnostic class, and numerical tolerance from analytical, convergence, or reference evidence. Define locations, units, coordinates, and entity prechecks without selecting a physical file schema. -4. Lead with defects and severity. Return missing derivations to formulation and missing evidence to research; do not repair upstream artifacts in place. - -Read the applicable [analysis-family guidance](../fem-formulation-spec/references/analysis-families.md). Use [workflow and decision authority](../fem-requirements-baseline/references/workflow-and-decisions.md) for escalation and [evidence and handoff](../fem-requirements-baseline/references/evidence-and-handoff.md) for the verdict. - -## Output - -Follow [Feature document management](../../../docs/FEATURE_DOCUMENTATION.md): read the Coordinator's -feature context, keep main reports concise, and link necessary owned details in the same feature folder. - -Create or revise: - -- `docs//numerical-review.md`: verdict, findings, risks, consistency checks, verification readiness, required revisions, and handoff. -- `docs//reference-model.md`: logical acceptance scope, case inventory, identity/component contract, metric, scale, blocking class, tolerance value/source, prechecks, contract revision, limitations, and I/O handoff. - -## Evidence - -Tie every finding and tolerance choice to an equation, requirement, source, case, convergence result, or reproducible calculation. Record the feature contract revision and preserve prior failing evidence when a tolerance changes. Separate confirmed defects, risks, recommendations, and unresolved decisions. A pass means ready for I/O definition, not feature completion. - -## Boundary - -Do not edit the formulation, implement code, choose APIs or dataset paths, modify or generate reference artifacts, relax a tolerance merely to pass an implementation result, decide final comparison success, or approve release. A missing noncritical naming convention is not a numerical blocker. +Apply [toolchain-and-verification.md](../fem-implementation-tdd/references/toolchain-and-verification.md) only when reviewing command or comparison evidence. Follow `docs/TOLERANCE.md` for metrics and tolerance ownership; never loosen criteria because output failed. Return actionable findings, evidence paths, and residual risks without editing the formulation, implementation, I/O contract, or reference artifacts. diff --git a/.codex/skills/fem-physics-review/SKILL.md b/.codex/skills/fem-physics-review/SKILL.md index 7bd0619..70c5670 100644 --- a/.codex/skills/fem-physics-review/SKILL.md +++ b/.codex/skills/fem-physics-review/SKILL.md @@ -1,38 +1,10 @@ --- name: fem-physics-review -description: Use when validated structural FEM results need an independent physical-plausibility review before release-readiness evaluation. +description: Assess validated structural FEM results for equilibrium, physical plausibility, and model-coverage limits. --- # FEM Physics Review -Determine whether numerically passing results also satisfy the documented physical behavior of the modeled problem. +Review the assigned result evidence for equilibrium and reactions, load/displacement direction, sign conventions, symmetry, element force balance, stress/strain/energy sanity, rigid-body symptoms, expected limits, and model coverage. A numerical comparison pass is evidence, not by itself physical validation. -## Inputs - -- Requirements, formulation, numerical review, reference model, and I/O contract -- Passing implementation-owned build/test and comparison evidence required by the feature -- Solver outputs and approved reference artifacts, read-only - -## Workflow - -1. Confirm prerequisite evidence is passing, current, and tied to the same `feature_id` and contract revision. -2. Evaluate only documented expectations: global equilibrium, reactions, deformation direction/mode, symmetry or zeros, internal-force balance, stress/strain signs and coordinates, conservation, residuals, energy, and family-specific behavior. -3. Check coverage is sufficient for the claimed feature scope; distinguish a solver defect from formulation, I/O, acceptance-model, or evidence gaps. -4. Report findings before the verdict and route each failure to its owning stage. - -Read the applicable [analysis-family guidance](../fem-formulation-spec/references/analysis-families.md). Use [evidence and handoff](../fem-requirements-baseline/references/evidence-and-handoff.md) for the verdict and [workflow and decision authority](../fem-requirements-baseline/references/workflow-and-decisions.md) for missing physical expectations. - -## Output - -Follow [Feature document management](../../../docs/FEATURE_DOCUMENTATION.md): read the Coordinator's -feature context, keep main reports concise, and link necessary owned details in the same feature folder. - -Create or revise `docs//physics-evaluation.md` with evidence identity, checks and expected relations, observed results, failure classification, coverage assessment, verdict, residual risks, and handoff. - -## Evidence - -Each check states its governing relation or approved expectation, data source, units/coordinates, calculation, tolerance source where applicable, and pass/fail result. Explain why a check is inapplicable rather than silently omitting it. - -## Boundary - -Do not edit code, tests, requirements, formulations, I/O contracts, reference models, reference artifacts, or tolerances. Do not invent extra acceptance gates, approve numerical comparison, run external solvers, or approve release. A physics pass means ready for release-readiness audit only. +Record checked artifacts, calculation or invariant, applicable approved threshold, conclusion, assumptions, untested behavior, and residual risk. Return implementation, formulation, or evidence issues to their owner; do not create new acceptance gates, edit code/contracts/tolerances/reference artifacts, or authorize release. diff --git a/.codex/skills/fem-release-readiness/SKILL.md b/.codex/skills/fem-release-readiness/SKILL.md index 7eb9b21..d0347e4 100644 --- a/.codex/skills/fem-release-readiness/SKILL.md +++ b/.codex/skills/fem-release-readiness/SKILL.md @@ -1,39 +1,10 @@ --- name: fem-release-readiness -description: Use when a structural FEM solver feature has completed technical gates and needs an evidence-based release-readiness audit. +description: Audit a structural FEM feature's evidence and limitations when the user explicitly requests release readiness. --- # FEM Release Readiness -Audit closure evidence and prepare a release recommendation without modifying technical contracts or performing a release. +Use only for an explicit release-readiness audit. Review the requested feature's relevant contracts, validation/reference evidence, known limitations, deferred work, and risks. Check that blocking requirements have credible evidence and that unsupported behavior is explicit; report contradictions or missing evidence rather than waiving them. -## Inputs - -- All lifecycle artifacts for one `feature_id` and contract revision -- Passing configured full validation and required comparison evidence -- Passing physics review -- Correction history, accepted risks, and project release policy - -## Workflow - -1. Inventory required artifacts and verify identity, revision, freshness, ownership, outcome, and absence of contradictions. -2. Trace every blocking requirement through acceptance criteria, implementation/tests, required numerical or reference evidence, physics review, and final disposition. -3. Confirm unresolved defects, deferred scope, compatibility limits, unsupported behavior, accepted risks, and environment limits are explicit. -4. Produce the checklist, known limitations, release-notes draft, and readiness verdict. Return missing or failed evidence to its owning stage. - -Use [evidence and handoff](../fem-requirements-baseline/references/evidence-and-handoff.md) to validate stage envelopes. Read [toolchain and verification](../fem-implementation-tdd/references/toolchain-and-verification.md) when auditing command or comparison evidence. Use [workflow and decision authority](../fem-requirements-baseline/references/workflow-and-decisions.md) for release-scope decisions. - -## Output - -Follow [Feature document management](../../../docs/FEATURE_DOCUMENTATION.md): read the Coordinator's -feature context, keep main reports concise, and link necessary owned details in the same feature folder. - -Create or revise `docs//release.md` with release scope, gate inventory, requirement traceability, validation summary, known limitations, deferred items, release-notes draft, readiness verdict, residual risks, and handoff. - -## Evidence - -A ready verdict requires complete, passing, current evidence for every blocking gate. Record artifact paths and hashes, configuration/toolchain identity, test and comparison summaries, approved exceptions, and the exact contract revision audited. - -## Boundary - -Do not implement or correct code, edit tests or upstream contracts, waive missing evidence, change acceptance or tolerance, or reinterpret a failed gate. Do not commit, tag, package, publish, deploy, or externally release anything unless the user explicitly authorizes that separate action. Readiness is a recommendation, not publication approval. +Produce a concise readiness recommendation with evidence paths, commands/exit codes where relevant, limitations, and residual risks. This is not a mandatory lifecycle stage and does not authorize code changes, commits, tags, packages, publication, deployment, or release. diff --git a/.codex/skills/fem-release-readiness/agents/openai.yaml b/.codex/skills/fem-release-readiness/agents/openai.yaml index 1ca513a..52b64dd 100644 --- a/.codex/skills/fem-release-readiness/agents/openai.yaml +++ b/.codex/skills/fem-release-readiness/agents/openai.yaml @@ -1,4 +1,4 @@ interface: display_name: "FEM Release Readiness" short_description: "Audit structural FEM release readiness" - default_prompt: "Use $fem-release-readiness to audit release readiness for a completed structural FEM solver feature." + default_prompt: "Use $fem-release-readiness to audit the requested structural FEM feature's release readiness." diff --git a/.codex/skills/fem-requirements-baseline/SKILL.md b/.codex/skills/fem-requirements-baseline/SKILL.md index af7d1b2..9c7d9d9 100644 --- a/.codex/skills/fem-requirements-baseline/SKILL.md +++ b/.codex/skills/fem-requirements-baseline/SKILL.md @@ -1,38 +1,14 @@ --- name: fem-requirements-baseline -description: Use when baselining a finite-element structural solver feature before research, formulation, interface definition, or implementation planning. +description: Define a durable, verifiable structural FEM feature scope and acceptance contract when one is needed. --- # FEM Requirements Baseline -Turn a structural-analysis solver request into a stable, verifiable contract without choosing downstream mathematics or implementation. +Turn the assigned request into observable scope, exclusions, assumptions, compatibility boundary, and acceptance intent. Use an existing PRD when it is sufficient; create a separate requirements document or matrix only when the feature needs that separation. -## Inputs +Write atomic requirements with a measurable acceptance method. State quantities, locations, units, coordinates, and physical behavior where relevant. Preserve user- or standard-defined acceptance; leave formulation choices, implementation, schema design, and numerical tolerance selection to their owners. -- Project instructions and architecture decisions -- User request, constraints, exclusions, and existing feature artifacts -- Applicable standards or compatibility commitments already selected by the project +Read [workflow-and-decisions.md](references/workflow-and-decisions.md) only for a material ambiguity or authority question. Return the document path, decisions, verification intent, and unresolved critical choice. Do not invent physics, compatibility, or acceptance promises. -## Workflow - -1. Use the stable kebab-case `feature_id` and feature folder supplied by Coordinator; define purpose, scope, exclusions, analysis family, assumptions, units, coordinates, and compatibility boundary. -2. Write atomic `FEM-REQ--###` shall-statements. Give each an observable acceptance criterion and verification method. -3. Define logical verification quantities and required physical behavior. Preserve acceptance fixed by the user or an applicable standard; otherwise delegate quantity details, metric, scale, blocking class, and numerical tolerance to Numerical Review under `docs/TOLERANCE.md`. -4. Build the requirement-verification matrix and classify open issues using the project workflow. - -Read [workflow and decision authority](references/workflow-and-decisions.md) when resolving ambiguity or deciding whether user input is critical. Use [evidence and handoff](references/evidence-and-handoff.md) for the returned envelope. - -## Output - -Follow [Feature document management](../../../docs/FEATURE_DOCUMENTATION.md): read the Coordinator's -feature context, keep main reports concise, and link necessary owned details in the same feature folder. - -Create or revise `docs//requirements.md` with metadata, scope, analysis definition, requirements, acceptance criteria, verification intent, compatibility boundary, matrix, open decisions, and handoff. - -## Evidence - -Every requirement traces to its source and an acceptance method. Numerical outputs state quantity, location, units, coordinates, and tolerance source when applicable. - -## Boundary - -Do not derive the formulation, select a numerical algorithm, design APIs or storage schemas, implement code, calibrate tolerances, or claim compatibility beyond the approved boundary. Route missing theory, reference evidence, or physical acceptance choices to their owning stage. +Use [evidence notes](references/evidence-and-handoff.md) when a separate durable evidence record is needed. diff --git a/.codex/skills/fem-requirements-baseline/references/evidence-and-handoff.md b/.codex/skills/fem-requirements-baseline/references/evidence-and-handoff.md index 30e628e..23d1be2 100644 --- a/.codex/skills/fem-requirements-baseline/references/evidence-and-handoff.md +++ b/.codex/skills/fem-requirements-baseline/references/evidence-and-handoff.md @@ -1,26 +1,5 @@ -# Evidence and Handoff Contract +# Evidence Notes -Use [Feature document management](../../../../docs/FEATURE_DOCUMENTATION.md) for concise main reports, -linked details, and Coordinator's document inventory. Include main and required detail paths in evidence. +Use this reference only when a task needs a durable evidence record. Record the feature/document path, decisive facts and assumptions, relevant commands with exit codes, comparison quantities and tolerance source when applicable, and residual risks. Keep source facts, calculations, inferences, and decisions distinct. A required failed or unrun check is not a pass. -Every stage returns one envelope: - -| Field | Required content | -| --- | --- | -| `feature_id` | Stable feature identifier | -| `stage` | `requirements`, `research`, `formulation`, `numerical-review`, `io-definition`, `implementation-planning`, `implementation`, `correction`, `physics-evaluation`, or `release-readiness` | -| `outcome` | `pass`, `return-upstream`, `retry`, `blocked-environment`, or `needs-user-decision` | -| `next_owner` | Agent id, or YAML `null` | -| `evidence_paths` | Repository-relative artifacts used or produced | -| `evidence_digest` | Concise findings tied to requirement IDs | -| `failure_classification` | `configure`, `compile`, `link`, `test`, `reference-comparison`, `harness`, `environment`, `upstream-contract`, `physics`, `evidence`, or YAML `null` | -| `retry_key` | `\|\|\|`, or YAML `null` | -| `attempt` | Coordinator-managed nonnegative attempt count for the retry key | -| `escalation_class` | Critical-decision class, or YAML `null` | -| `blocker` | Actionable blocker, or YAML `null` | - -Evidence records include, when applicable: source locator and access date; assumptions; command, exit code, duration, and relevant output; test identity and RED/GREEN result; artifact hash; comparison quantity, tolerance source, and decision; residual risk. - -Use repository-relative paths and stable identifiers. Distinguish observed facts, calculations, inferences, and decisions. Never report a pass when a required command failed, evidence is stale, or a blocking acceptance item is unresolved. - -Retry is bounded by the coordinator policy. A repeated normalized failure returns to its owning stage; it does not justify changing requirements, formulations, schemas, reference artifacts, or tolerances. +Return a concise result containing changed paths, evidence, and blockers; no common handoff envelope, workflow state, retry key, or coordinator inventory is required. Do not use repeated failure to justify changing requirements, formulations, schemas, reference artifacts, or tolerances. diff --git a/.codex/skills/fem-requirements-baseline/references/workflow-and-decisions.md b/.codex/skills/fem-requirements-baseline/references/workflow-and-decisions.md index de23753..7925aa0 100644 --- a/.codex/skills/fem-requirements-baseline/references/workflow-and-decisions.md +++ b/.codex/skills/fem-requirements-baseline/references/workflow-and-decisions.md @@ -18,7 +18,7 @@ Proceed without user review for reversible choices within approved contracts: in ## User decisions -Return `needs-user-decision` only for a choice that changes at least one of: +Ask the user only for a choice that changes at least one of: - supported physics, formulation meaning, or analysis scope; - public compatibility or an authoritative I/O schema; @@ -28,6 +28,6 @@ Return `needs-user-decision` only for a choice that changes at least one of: Everything else follows the authority order. Lack of a preference is not a blocker when a deterministic in-contract choice exists. -## Contract flow +## Responsibilities -Requirements own acceptance intent; research owns evidence; formulation owns mathematics; numerical review owns independent numerical findings and logical verification coverage; I/O owns external/internal mappings; implementation owns code and tests; physics review owns physical plausibility; release review owns closure evidence. A downstream stage returns a defect to the owning upstream stage instead of silently rewriting its contract. +Requirements own acceptance intent; research owns evidence; formulation owns mathematics; numerical review owns independent numerical findings and verification coverage; I/O owns mappings; implementation owns code and tests; and physics review owns plausibility findings. Use only the expertise needed by the task. Do not silently rewrite another owner's contract to make downstream work pass. diff --git a/.codex/skills/fem-research-evidence/SKILL.md b/.codex/skills/fem-research-evidence/SKILL.md index 3b43933..d226c39 100644 --- a/.codex/skills/fem-research-evidence/SKILL.md +++ b/.codex/skills/fem-research-evidence/SKILL.md @@ -1,38 +1,12 @@ --- name: fem-research-evidence -description: Use when a structural FEM feature needs source-backed theory, benchmark, verification, or reference-convention evidence before formulation. +description: Gather source-backed FEM theory, benchmark, or observable reference-convention evidence for a concrete solver decision. --- # FEM Research Evidence -Build an auditable evidence brief while keeping documented fact, calculation, inference, and unresolved questions distinct. +Answer only the research questions needed by the assigned decision. Prefer standards, primary literature, authoritative textbooks, official verification guides, and public vendor documentation. Separate sourced fact, calculation, inference, and remaining gap; record stable locators and applicability limits. -## Inputs +Identify useful analytical, invariant, patch, convergence, manufactured, or published benchmark cases without treating a single solver comparison as proof. Abaqus material supports only documented observable syntax, semantics, outputs, and verification conventions, never its private internals. Use `fem-theory-query` only when the configured vault is the requested source. -- `docs//requirements.md` -- Project instructions and user-supplied sources -- Existing research brief and reference artifacts, read-only - -## Workflow - -1. Derive research questions from requirement IDs and open decisions. -2. Prefer governing standards, primary literature, authoritative textbooks, and official vendor documentation; record reliability and applicability. -3. Summarize only the theory needed downstream. Identify analytical solutions, patch tests, convergence studies, manufactured solutions, and published benchmarks appropriate to the analysis family. -4. State what each source or case can and cannot verify. Mark unsupported claims as inference or evidence gaps. - -When a configured FEM vault is the requested evidence source, use `fem-theory-query`. Apply [workflow and decision authority](../fem-requirements-baseline/references/workflow-and-decisions.md) to product references and [evidence and handoff](../fem-requirements-baseline/references/evidence-and-handoff.md) to the result. - -## Output - -Follow [Feature document management](../../../docs/FEATURE_DOCUMENTATION.md): read the Coordinator's -feature context, keep main reports concise, and link necessary owned details in the same feature folder. - -Create or revise `docs//research.md` with research questions, source inventory and reliability, theory findings, candidate verification cases, applicability limits, conflicts, gaps, and downstream handoff. - -## Evidence - -Trace every material claim to a stable locator. For a project-selected reference solver or format, use official public documentation for observable syntax, semantics, output, or procedure only. Record edition/version and access date when behavior can vary. - -## Boundary - -Do not finalize the mathematical formulation, set tolerance values, design APIs or schemas, implement code, alter reference artifacts, or run an external licensed solver without explicit authorization. Do not treat agreement with one product as proof of correctness or infer its undocumented internals. +Return concise evidence, candidate verification cases, and gaps. Do not finalize formulations, tolerances, schemas, code, or reference artifacts. diff --git a/.harness/config.example.json b/.harness/config.example.json index b8853ea..da2402e 100644 --- a/.harness/config.example.json +++ b/.harness/config.example.json @@ -2,10 +2,6 @@ "version": 1, "projectType": "cmake", "cmake": { - "sourceDir": ".", - "binaryDir": ".harness/build-ninja-msvc-debug", - "configurePreset": "windows-msvc-ninja-debug", - "buildPreset": "windows-msvc-ninja-debug", - "testPreset": "windows-msvc-ninja-debug" + "sourceDir": "." } } diff --git a/docs/superpowers/plans/2026-09-07-agent-harness-documentation-update.md b/docs/superpowers/plans/2026-09-07-agent-harness-documentation-update.md new file mode 100644 index 0000000..331323f --- /dev/null +++ b/docs/superpowers/plans/2026-09-07-agent-harness-documentation-update.md @@ -0,0 +1,282 @@ +# Agent·Harness 경량화 문서 갱신 Implementation Plan + +> **For agentic workers:** 후속 실행에는 `superpowers:executing-plans`를 적용하되 아래 문서 작업을 메인이 직접 수행한다. 고정 solver stage, task별 새 subagent·reviewer, 자동 commit을 추가하지 않는다. + +**Goal:** 승인된 Agent·Harness 경량화를 FESA의 공통 문서 10개에 반영하여 현재 운영 지침과 구현의 불일치를 없앤다. + +**Architecture:** `docs2/agent-harness-simplification`의 승인된 운영 변경을 현재 `.agents`, `.codex`, `scripts`에 대조하여 반영한다. FESA 제품·수치·입출력·C++ 계약은 유지하고, 공통 ADR에는 기존 결정과 구분되는 후속 결정을 기록한다. + +**Tech Stack:** 한국어 Markdown, PowerShell 기반 정적 확인. 문서에 설명할 검증 환경은 기존 CMake/MSVC x64/Debug, CTest, Python Harness다. + +**Spec:** [경량화 PRD](../../../docs2/agent-harness-simplification/PRD.md), [AH-01~05 결정](../../../docs2/agent-harness-simplification/ADR.md), [승인 계획 보존본](../../../docs2/agent-harness-simplification/implementation-details.md), [기존 구현 보고서](../../../docs2/agent-harness-simplification/implementation-report.md). + +작성일: 2026-09-07. 상태: **문서 갱신 계획안**. 이번 요청에서는 이 계획만 작성하며 대상 문서를 수정하거나 Harness를 실행하지 않는다. 아래 checkbox는 후속 문서 작업의 완료 조건이다. + +## 1. 범위와 기준 + +### Global Constraints + +- 후속 수정 범위는 사용자가 지정한 `AGENTS.md`와 `docs/` 문서 9개로 제한한다. 정확한 목록은 §3을 따른다. +- 현재 사용자의 `.agents`, `.codex`, `.harness`, `scripts`, `docs2` 변경을 보존한다. 이 계획으로 구현·테스트·설정·phase 이력을 수정하지 않는다. +- FESA의 C++17 이상, CMake/MSVC/x64/Debug, MKL/TBB/HDF5와 승인된 Abaqus 입력 subset을 유지한다. +- HDF5 `_results.h5`의 lexical sibling 경로, source identity, 결정론, state/output 보존, 기존 B33/MITC4 비교량·판정 구분을 유지한다. +- [TOLERANCE](../../TOLERANCE.md), reference artifact와 solver 구현은 수정 대상이 아니다. 수치 검토와 필요한 analytical/invariant·reference 검증을 유지한다. +- 운영 간소화를 이유로 물리 의미, 공개 schema, 지원 범위, tolerance, 외부 실행·원격·파괴 작업 권한을 확대하지 않는다. +- 작은 문서 작업에는 solver Feature 폴더·관리 문서·stage 보고서를 새로 만들지 않는다. 이 계획도 별도 solver Feature workflow를 시작하지 않는다. +- 문서만 갱신하므로 새 테스트, pytest, Harness, CMake/CTest, 수동 hook을 실행하지 않는다. 확인 범위는 문서·링크·설정·소스의 정적 대조다. +- 기존 문서의 언어·구성을 가능한 한 유지한다. 문서 전체 복사나 요청과 무관한 코딩 규약 정리는 하지 않는다. + +### 근거의 적용 순서 + +1. 현재 사용자가 요청한 문서 갱신 범위와 경량화 목적. +2. `docs2/agent-harness-simplification`에 기록된 AH-01~05의 운영 변경과 유지할 acceptance. +3. 현재 저장소의 실제 agent/skill profile, runner, config/discovery/adapter/process 구현. +4. 기존 FESA 제품·수치·아키텍처 계약과 현재 preset. 구현이 이 계약을 변경할 권한은 없다. + +`docs2`의 공통 문서는 문안 참고 자료다. 기존 FESA 문서를 통째로 대체하는 원본으로 사용하지 않는다. 승인 설명과 현재 구현이 다르면 운영 의도와 관찰된 동작을 구분하고, 문서로 미구현 기능이나 검증 통과를 선언하지 않는다. + +## 2. 현재 확인한 차이와 반영 판단 + +| 근거 | 확인한 내용 | 문서 반영 판단 | +| --- | --- | --- | +| [현재 profiles](../../../.codex/agents) | 7개 specialist만 남고 일반 역할은 `medium`, 정식화·수치·물리 역할은 `high`다. Implementation profile의 모델은 `gpt-5.6-terra`다. | 삭제된 4개 전용 역할과 일괄 `xhigh` 요구를 제거한다. 모델 선택은 profile로 연결하고 runtime 적용을 검증했다고 주장하지 않는다. | +| [runner](../../../scripts/execute.py), [harness skill](../../../.agents/skills/harness/SKILL.md) | 인자 없는 명시적 검증 실행기다. 내부 LLM, phase 상태 처리, 자동 Git·retry가 없다. | 새 CLI와 현재 exit 의미를 설명한다. 옛 CLI는 폐기 안내에서만 보여 준다. | +| [config](../../../scripts/msvc_harness/config.py), [discovery](../../../scripts/msvc_harness/discovery.py) | legacy `tdd`는 설정 로드 시 안내 후 무시한다. C++ 전체 scan과 orphan-C++ gate가 없다. | 현재 없는 TDD pattern 설정·C++ 파일 scan·자동 skip 설명을 삭제한다. | +| [config 예시](../../../.harness/config.example.json), [presets](../../../CMakePresets.json) | 예시는 `projectType=cmake`, `sourceDir=.`만 지정한다. FESA Ninja preset은 별도로 존재한다. | 예시 복사만으로 Ninja preset을 선택한다고 쓰지 않는다. 명시적 preset 설정 예시를 유지한다. | +| `docs2`의 PRD·ARCHITECTURE·구현 보고서 | solver/build metadata가 없는 framework checkout을 전제로 한다. | 현재 [CMakeLists](../../../CMakeLists.txt), [solver target](../../../src/fesa/CMakeLists.txt), [test target](../../../tests/CMakeLists.txt)이 있으므로 해당 현황 설명은 옮기지 않는다. | +| `docs2`와 현재 공통 ADR | 같은 ADR 번호가 다른 결정을 뜻한다. `docs2` ADR-013은 신뢰 경계이고, 현재 ADR-013은 선형 보 해석 범위다. | 번호를 복사하지 않는다. 현재 문서의 마지막 ID 다음인 ADR-028에서 실제 대체 대상을 명시한다. | +| `docs2`의 구현 보고서와 현재 `tests/` | 보고서의 `test_executor.py` 등과 현재 테스트 파일 구성이 다르며, 현재에는 삭제된 executor/hook을 기대하는 테스트가 남아 있다. | 과거 29건 통과를 현재 checkout의 검증 결과로 사용하지 않는다. 테스트 정합성은 §7의 별도 후속 항목으로 기록한다. | + +`docs2/agent-harness-simplification/ADR.md`의 “프로젝트 PRD·ADR 원문 보존”은 이전 구현 범위의 기록이다. 현재 요청은 두 문서의 운영 조항 갱신을 명시적으로 포함하므로 계획에서 제외하지 않는다. 기존 제품 계약과 ADR 결정 본문은 보존하면서 현행 규칙과 대체 관계를 명료하게 만든다. + +## 3. 파일별 수정 계획 + +| 대상 | 변경할 절과 내용 | 보존·확인 기준 | +| --- | --- | --- | +| [AGENTS.md](../../../AGENTS.md) | `문서 기준과 Feature 관리`, `개발 운영 인프라`, `개발 프로세스`, `Agent/Skill Workflow`, `최소 검증 진입점`을 갱신한다. 메인 직접 조정, 조건부 specialist, 핵심 문서 3개·PRD checklist, 간결한 인계, 명시적 검증을 요약한다. 소유권 절의 매 변경 RED·대응 C++ test 강제를 동작 중심 검증으로 바꾸고, reference 변경 권한의 “요청된 phase”를 “명시적으로 요청된 작업 범위”로 고친다. | 제품 정체성, FESA 기술 스택, 수치·선형 정적 불변식, reference 무결성, 사용자 변경 보존을 유지한다. 상세 CLI·workflow를 중복 복사하지 않고 전담 문서에 연결한다. | +| [docs/ADR.md](../../ADR.md) | ADR-028을 추가하고 ADR-012·024~027에 대체/부분 대체 안내를 붙인다. 머리말의 현행 운영 ADR 범위와 ADR-001·002 등의 현행 운영 참조를 확인한다. | 기존 ID와 결정 본문을 소급 재작성하지 않는다. 실제 ADR-013 및 다른 solver 결정은 변경하지 않는다. §4의 대체 범위를 사용한다. | +| [docs/ARCHITECTURE.md](../../ARCHITECTURE.md) | `Solver runtime과 개발 운영 영역`의 개발 흐름, `개발 운영 인프라`의 owner 표·실행 책임, 끝의 Feature 요구사항 원본 설명을 수정한다. 메인, specialist, 명시적 runner, backend adapter/process의 책임을 구분한다. `검증과 reference 경계`의 전문 책임을 필수 agent 순회로 읽히지 않게 정리한다. | Solver runtime 그림·모듈 책임·Domain/AnalysisModel/DofManager·의존성·수명·해석 lifecycle·출력 계약은 보존한다. Runner를 보안 sandbox나 solver correctness 판정기로 표현하지 않는다. | +| [docs/PRD.md](../../PRD.md) | 문서 역할 표의 Feature PRD를 작은 요구사항의 원본으로, `requirements.md`를 필요 시 분리하는 상세 계약으로 바꾼다. `FESA-PRD-GEN-010`은 동작 중심 테스트·가능한 버그 재현과 영향별 검증으로 수정한다. `FESA-PRD-GEN-012`의 evidence를 필수 stage/gate 기록에서 해당 계약의 검증·제한·미해결 항목으로 수정한다. `검증과 완료 기준`의 9단계 순회와 필수 release audit를 제거한다. | GEN-001~009·011과 제품 정의·품질 속성·비목표의 물리/수치 의미를 보존한다. 필요한 독립 수치 검토·물리 검증·reference 비교, 같은 계약을 지지하는 evidence와 stale 판정을 유지한다. | +| [docs/SOLVER_AGENT_DESIGN.md](../../SOLVER_AGENT_DESIGN.md) | 고정 stage·Coordinator 전용 전이·12필드 envelope·5개 outcome 강제·correction signature/budget을 제거한다. 메인의 작업 선택, 7개 specialist 호출 조건/수정 경계/기본 강도, 간단한 dispatch·return, 구현 owner의 실패 수정, 완료 evidence와 사용자 결정 경계를 정의한다. | 새 수식·요소·재료·적분·상태 갱신의 독립 numerical review를 유지한다. 상위 계약 문제의 owner 반환, 무근거 반복 금지, specialist의 범위 제한을 유지한다. | +| [docs/SOLVER_SKILL_DESIGN.md](../../SOLVER_SKILL_DESIGN.md) | `Stage` 중심 inventory를 `사용할 때 / 필요한 입력 / 결과` 중심으로 바꾼다. 8개 FEM skill과 supporting skill을 현재 `SKILL.md`에 맞춘다. implementation skill은 메인도 계획·구현·수정에 사용하고, release skill은 사용자 명시 요청 시에만 사용한다. | `fem-theory-query`의 configured vault 범위, read-only review, tolerance·reference·외부 권한 경계를 유지한다. 모든 문서 재독·공통 outcome/hash·전체 pytest를 문서 편집의 필수 절차로 강제하지 않는다. | +| [docs/HARNESS_WORKFLOW.md](../../HARNESS_WORKFLOW.md) | 요구사항→phase/index/step→Codex→hook→자동 commit 흐름을 관련 계약 확인→변경→관련 검사→기능 완료 시 전체 검사 흐름으로 재구성한다. 현행 runner의 config→discovery→toolchain→adapter→execute_plan 순서와 실패 중단을 설명한다. 문서·일반 버그·새 수치 기능의 3개 사례를 둔다. | 현행 config/경로 검사, MSVC 확인, CTest discovery, timeout·실패 진단은 보존한다. 폐기한 phase schema·출력 JSON·owned_paths·attempt_history를 새 절차에 요구하지 않는다. | +| [docs/HARNESS.md](../../HARNESS.md) | 설치·설정·명령·진단에 집중한다. Harness 실행의 Codex CLI 의존 설명을 제거한다. 인자 없는 CLI, 자동 감지, exit 0/1/2, preset 설정, legacy `tdd`와 옛 CLI 안내를 §5대로 작성한다. hook·sandbox 환경변수·자동 Git·phase 복구·TDD 확장 절을 정리한다. | Windows/MSVC·CMake/CTest·dependency 준비, Python 요구와 재사용 MSBuild adapter 안내를 유지한다. FESA 제품 검증은 CMake/CTest라는 구분을 보존한다. | +| [docs/CODINGSTYLE.md](../../CODINGSTYLE.md) | `Test와 변경 관리` 및 `Implementation Agent Checklist`를 메인/구현 담당자 공통 지침으로 바꾼다. 모든 C++ 변경의 test-file 동반·Step별 RED/full 강제를 영향별 테스트와 검증으로 바꾼다. 충분한 기존 coverage가 있는 rename/refactor에는 형식적 새 테스트를 요구하지 않는다. | PascalCase, include guard, 2-space/80-column, production Doxygen, vendor 경계, 신규 warning 금지 등을 유지한다. B33/MITC4 output 변경의 필수 reference 재검증을 유지한다. | +| [docs/FEATURE_DOCUMENTATION.md](../../FEATURE_DOCUMENTATION.md) | 새 Feature가 필요한 조건과 메인 소유 핵심 문서 3개를 명시한다. 현재 checklist는 PRD 한 곳, 작은 요구사항도 PRD 원본, 별도 requirements/matrix·상세 보고서는 필요한 경우만 생성하도록 바꾼다. 간단한 구현·build/test·reference evidence는 한 보고서에 합칠 수 있게 한다. | `FEATURED_AGENTS.md`의 비자동 로드 성격, 상대 링크, specialist의 할당 문서 소유권과 필수 근거를 유지한다. 기존 `coordination.md`, `docs/features/` 자료는 이력으로 보존하고 신규 상태기계나 일괄 이관을 만들지 않는다. | + +## 4. ADR-028에 기록할 결정 + +제안 제목: **ADR-028: 메인이 필요한 전문 작업을 조정하고 Harness를 명시적 검증 실행기로 사용한다**. + +근거는 현재 사용자 요청, 경량화 Feature의 AH-01~05와 실제 source다. 이 계획에서 ADR-028을 이미 작성·승인된 문서처럼 표시하지 않는다. 후속 반영 시 기존 경량화 승인과 이번 문서 동기화 근거를 구분해 연결한다. + +| 기존 ADR | 대체할 운영 부분 | 유지되는 부분 | +| --- | --- | --- | +| ADR-012 | 전용 Planning/Executor/Hook 분업과 hook 기반 강제 검증 | 실제 테스트 실행과 단순 파일 존재의 구분, 검증 evidence의 필요성 | +| ADR-024 | 전용 Coordinator, 고정 상태 전이, correction 1회/rerun 1회, 필수 release stage | 승인 범위 안의 자율 작업, 필요한 사용자 결정, 미실행·실패를 통과로 표시하지 않음, 외부 권한 분리 | +| ADR-025 | 관리 문서 4개, `coordination.md` 상태 원본, 모든 요구의 `requirements.md` 분리, 매 dispatch의 전체 bundle 필수화 | 프로젝트/Feature 계약 구분, 전문 문서 소유권, 상대 링크와 중복 방지, 실제 계약 변경에 따른 evidence 영향 확인 | +| ADR-026 | Executor의 Git·transport 관리, hook TDD/Stop, 자체 sandbox 승인 장치 | config/preset/command의 신뢰 경계, 사용자 변경 보존, 실제 runtime 권한, 검증 범위와 미실행의 명확한 보고 | +| ADR-027 | phase Step payload, `owned_paths`, `attempt_history`, 자동 commit 경계와 transport 재시도 계약 | 실패 증거와 사용자 변경을 보존하고 범위 밖 작업을 하지 않는 일반 원칙 | + +ADR-028 본문에는 AH-01~05의 효과를 한 번만 기록한다: 메인 orchestration, 명시적 runner, 영향에 맞는 검사, 필요한 문맥만 전달, 핵심 문서 3개와 선택적 상세 기록. 상세 명령과 산출물 형식은 각각 HARNESS·FEATURE_DOCUMENTATION으로 연결한다. 과거 본문의 폐기된 역할/명령 검색 결과는 이력임을 분명히 표시한다. + +## 5. 현행 Harness 설명에 넣을 정확한 계약 + +### 명령과 설정 + +```powershell +python scripts/execute.py +``` + +이 명령은 명시적으로 선택/발견한 backend의 전체 검증을 한 번 수행한다. Focused check는 실제 configured backend 명령으로 직접 실행한다. Runner가 Feature 문서에서 reference 명령을 찾아 추가 실행하거나 `phases/`를 읽고 갱신한다고 설명하지 않는다. + +FESA Ninja preset을 사용하려면 기존 개인 설정을 보존하면서 다음 필드를 함께 맞춘다. 이번 문서 작업에서 개인 설정은 편집하지 않는다. + +```json +{ + "version": 1, + "projectType": "cmake", + "cmake": { + "sourceDir": ".", + "binaryDir": ".harness/build-ninja-msvc-debug", + "configurePreset": "windows-msvc-ninja-debug", + "buildPreset": "windows-msvc-ninja-debug", + "testPreset": "windows-msvc-ninja-debug" + } +} +``` + +현재 `.harness/config.example.json`에는 preset 필드가 없다. `CMakePresets.json`이 존재하거나 예시 설정을 복사했다는 사실만으로 preset이 선택되지는 않는다. Preset 없는 adapter 기본값과 FESA preset 사용법을 구분하여 설명한다. + +### 결과와 보장 범위 + +| 조건 | 현재 동작 | +| --- | --- | +| 구성된 검증이 모두 성공 | runner exit 0, 실행 명령·cwd·exit와 test 출력 요약 | +| config/discovery/toolchain/adapter 오류, backend 실패·timeout, non-MSVC, CTest 0개 등 | runner exit 1. Backend의 원래 nonzero는 진단에 남지만 runner가 같은 숫자를 그대로 반환하는 것은 아님 | +| 자동 감지에서 build metadata 없음 | `not configured`와 exit 2. 검증 통과나 조용한 skip이 아님 | +| 명시한 projectType에 필요한 metadata가 없음 | 잘못된 명시 설정 경로의 실패로 exit 1 | +| 옛 ``, `--push`, `--approve-danger-full-access` 인자 | argparse usage error, exit 2. 검증을 시작하지 않음 | +| legacy `tdd` 항목 | `load_config` 호출 시 폐기 안내를 내고 무시. Config를 자동 수정하지 않음 | +| CMake 경로 | configure → MSVC 확인 → build → CTest discovery/0개 거부 → test | +| MSBuild adapter 경로 | build → 명시된 testCommand. FESA의 solution-only 검증을 승인하는 의미가 아님 | + +명령은 `shell=False`로 실행하며 repository-relative 설정 경로와 cwd 범위, timeout을 검사한다. 전체 deadline은 현재 1,800초이고 각 명령에는 남은 시간과 명령 timeout 중 짧은 값이 적용된다. 실패 후 후속 단계나 자동 재시도를 실행하지 않는다. Config·preset·실행 파일 자체의 side effect를 sandbox처럼 격리하는 기능은 아니다. + +내부 Codex 호출·프롬프트 주입, phase 상태기계, branch/commit/push, 대응 파일명 TDD gate, 등록된 PreToolUse/Stop과 자체 sandbox 승인은 제거되었다. 실제 도구·runtime 권한은 계속 따른다. 기존 phase·hook 기록은 이력으로 남기며 새 runner의 입력이나 필수 정리 대상으로 삼지 않는다. + +## 6. 실행 순서와 문서별 완료 확인 + +### Task 1: 공통 운영 결정과 제품 완료 기준 + +**Modify:** `docs/ADR.md`, `docs/PRD.md`. + +**입력:** AH-01~05, 현재 공통 ADR-012·024~027, GEN-010·012. **결과:** 나머지 문서가 참조할 단일 현행 운영 결정과 완료 기준. + +- [ ] ADR-028과 §4의 대체 안내를 작성하고 기존 결정 본문·번호를 보존한다. +- [ ] PRD의 문서 역할, GEN-010·012, 검증·완료 절을 §3대로 수정한다. +- [ ] 새 수치 변경의 독립 검토, 필요한 물리/수치/reference evidence가 여전히 필수인지 확인한다. Release audit는 명시 요청일 때만 수행하도록 맞춘다. +- [ ] 두 문서의 diff를 읽어 운영 이외 제품 요구가 변경되지 않았고, 현재 FESA의 ADR-013에 경량화 신뢰 경계를 덮어쓰지 않았는지 확인한다. + +### Task 2: Agent·Skill·Feature 문서 운영 + +**Modify:** `docs/SOLVER_AGENT_DESIGN.md`, `docs/SOLVER_SKILL_DESIGN.md`, `docs/FEATURE_DOCUMENTATION.md`. + +**입력:** Task 1, 현재 profile·SKILL.md. **결과:** 조건부 역할 선택, 최소 인계, 핵심 문서 3개의 일관된 계약. + +- [ ] 7개 역할을 호출 조건과 기본 강도로 설명하고 메인의 직접 계획·구현·수정 책임을 명시한다. +- [ ] 고정 stage/envelope/outcome/retry budget을 제거한다. Dispatch는 작업·관련 경로/절·수정 파일·검증 기준, return은 결과·변경 파일·검사 결과·미해결 항목으로 정리한다. +- [ ] 필요한 문서만 읽고 연속 수정은 같은 owner가 수행하도록 정리한다. 지원되는 경우 `fork_turns="none"`을 사용하되 실제 도구·역할 설정이 기준임을 유지한다. +- [ ] PRD checklist·선택적 requirements 및 상세 보고서, 기존 coordination 이력 보존을 세 문서에서 일치시킨다. +- [ ] 기존 numerical/reference/physics 검토의 실질적 내용이 단순 역할 삭제와 함께 사라지지 않았는지 확인한다. + +### Task 3: Harness 사용법과 실행 흐름 + +**Modify:** `docs/HARNESS.md`, `docs/HARNESS_WORKFLOW.md`. + +**입력:** Task 1~2, runner/config/discovery/adapter/process, 현재 preset. **결과:** §5와 일치하는 사용법과 영향별 검증 사례. + +- [ ] HARNESS에는 설치·설정·정확한 CLI·exit·이전 방식 변경 안내를 둔다. 기존 설정을 무조건 덮어쓰는 복사 안내는 피한다. +- [ ] HARNESS_WORKFLOW는 메인의 개발 흐름과 runner 내부 실행 순서로 재작성한다. 설치/JSON 예시는 HARNESS에 연결하여 중복을 줄인다. +- [ ] 문서만 변경하면 정적 검토, 일반 버그는 재현·관련 검사, 새 수치 기능은 필요한 정식화·독립 검토·구현·물리/reference 검사로 분기하는 표를 작성한다. +- [ ] 도움말·usage·backend 결과는 소스로 대조한다. 문서 갱신 확인을 위해 실제 runner나 pytest를 실행하지 않는다. + +### Task 4: 루트 지침·아키텍처·코딩 지침 동기화 + +**Modify:** `AGENTS.md`, `docs/ARCHITECTURE.md`, `docs/CODINGSTYLE.md`. + +**입력:** Task 1~3의 현행 계약. **결과:** 다음 작업부터 적용되는 짧고 모순 없는 루트 지침. + +- [ ] AGENTS의 운영·Feature 관리·검증 절을 갱신하고 상세 전담 문서에 링크한다. 모든 문서·모든 stage를 매 작업마다 읽으라는 의무를 제거한다. +- [ ] ARCHITECTURE의 개발 흐름과 owner 표를 바꾸고 solver runtime 책임과 물리/수치 계약을 보존한다. +- [ ] CODINGSTYLE의 동작 검증·refactor 예외·전체 검증 시점·담당자 checklist만 수정한다. Doxygen/naming/formatting 요구는 유지한다. +- [ ] “agent profile 제거”와 “해당 전문 skill/검증 제거”를 혼동한 문장이 없는지 확인한다. + +### Task 5: 통합 정적 확인과 인계 + +**Modify:** 앞선 10개 문서의 발견된 모순만 수정한다. 새 자동화·테스트 파일을 추가하지 않는다. + +- [ ] AH-01은 AGENTS/AGENT_DESIGN/ARCHITECTURE, AH-02는 HARNESS/WORKFLOW, AH-03은 PRD/CODINGSTYLE, AH-04는 AGENT_DESIGN/SKILL_DESIGN, AH-05는 FEATURE_DOCUMENTATION/PRD에 반영됐는지 확인한다. 공통 근거는 ADR-028로 연결한다. +- [ ] 아래 검색 결과를 현행 규칙, 폐기 안내, 과거 ADR 본문으로 분류한다. 폐기한 기능을 현행 의무로 설명하는 결과가 없어야 한다. +- [ ] 변경 문서의 상대 링크·절 링크·agent/skill 이름·CLI·preset 값을 확인한다. 삭제된 profile/hook 경로는 현재 파일 링크로 두지 않는다. +- [ ] root AGENTS의 byte 크기를 확인한다. 내용을 줄이되 필수 FESA 계약을 제거하여 분량만 맞추지 않는다. +- [ ] 최종 diff가 요청한 10개 문서에 한정되는지 확인하고 기존 사용자 변경은 보존한다. 문서 정합성과 미실행 검사를 구분하여 보고한다. + +정적 검색·diff 예시(PowerShell, 저장소 루트): + +```powershell +$docTargets = @( + 'AGENTS.md', 'docs/ADR.md', 'docs/ARCHITECTURE.md', 'docs/PRD.md', + 'docs/SOLVER_AGENT_DESIGN.md', 'docs/SOLVER_SKILL_DESIGN.md', + 'docs/HARNESS_WORKFLOW.md', 'docs/HARNESS.md', 'docs/CODINGSTYLE.md', + 'docs/FEATURE_DOCUMENTATION.md' +) +rg -n 'coordinator-agent|implementation-planning-agent|correction-agent|release-agent|xhigh|coordination\.md|owned_paths|attempt_history|retry_key|PreToolUse|Stop|hooks\.json|FEM_HARNESS_CODEX_SANDBOX|approve-danger-full-access|--push|9개|정규 stage' @docTargets +rg -n 'execute\.py|GEN-010|GEN-012|ADR-028|medium|high|reference|TOLERANCE' @docTargets +git diff --check -- $docTargets +git diff --stat -- $docTargets +git diff -- $docTargets +(Get-Item -LiteralPath 'AGENTS.md').Length +``` + +검색어를 전부 없애는 것이 합격 조건은 아니다. ADR 이력과 명시적인 폐기 안내는 허용하며, solver의 해석 step/state/retry 의미를 개발 phase와 혼동하여 삭제하지 않는다. UTF-8과 기존 개행을 보존하며 링크와 의미는 사람이 함께 확인한다. 자동 문자열·heading 맞춤 테스트를 만들지 않는다. + +## 7. 범위 밖 후속 정합성 항목 + +다음은 현재 파일을 읽어 확인한 불일치다. 테스트를 실행하여 얻은 실패 결과는 아니며, 이번 문서 수정의 코드/테스트 작업으로 편입하지 않는다. + +| 파일 | 현재 남아 있는 기대 | 후속 작업의 방향 | +| --- | --- | --- | +| [tests/test_execute.py](../../../tests/test_execute.py), [tests/test_execute_ownership.py](../../../tests/test_execute_ownership.py) | 삭제된 `StepExecutor`, phase·Git·owned_paths·retry 처리 | 별도 구현 작업에서 새 runner의 성공·실패·timeout·Git 무변경 동작에 맞는 coverage로 정리 | +| [tests/test_hook_validation_scope.py](../../../tests/test_hook_validation_scope.py) | 삭제된 `scripts.hooks` import와 Stop 동작 | 폐기된 hook 검사와 유지할 실행기 검증을 구분 | +| [tests/test_agent_skill_workflow_contract.py](../../../tests/test_agent_skill_workflow_contract.py) | 전용 Coordinator, 9단계, `xhigh`, phase 예시 preflight | 실제 7개 profile과 조건부 skill 계약에 맞추되 문구 강제를 새로운 합격 기준으로 만들지 않음 | +| [tests/test_harness_preset_contract.py](../../../tests/test_harness_preset_contract.py) | tracked config 예시가 Ninja preset 필드를 모두 포함한다고 기대 | 간소화된 예시와 FESA 명시 preset 지원을 구분하여 검증 | + +문서 10개를 갱신하는 일은 이 불일치의 해결과 별개로 완료할 수 있다. 다만 저장소 전체 Python 검사, 실제 C++ build/test, 수치/reference 검증이 통과했다고 보고할 수는 없다. 이번 계획과 후속 문서 작업에는 이 실행들을 포함하지 않는다. + +## 8. AGENTS.md Quality Report + +### Summary + +- Files found: `AGENTS.md`, `docs2/AGENTS.md`의 2개. 수정·평가 대상은 요청된 루트 파일 1개다. +- Active project chain at `C:/git/FESADev`: `AGENTS.md`. 프로젝트 내 override는 발견되지 않았다. +- `docs2/AGENTS.md`는 별도 subtree에만 적용되는 참고 자료다. 루트 체인에 합산하지 않으며 전역 사용자 지침은 이번 audit 범위 밖이다. +- Average score: **60/100**. Files needing update in scope: **1**. +- Combined selected project-chain size: **24,487 bytes**; 기본 비교 한도 32 KiB 이내다. 전역 지침을 포함한 runtime 실제 주입량을 측정한 값은 아니다. + +### File-by-File Assessment + +#### 1. AGENTS.md (project root; active) + +**Score: 60/100 (Grade: C)**. 점수는 문서 정합성 평가이며 솔버 품질 평가가 아니다. + +| Criterion | Score | Evidence | +| --- | ---: | --- | +| Commands and workflows | 10/20 | CMake/CTest 진입점은 남아 있으나 phase CLI·hook·전용 Coordinator workflow는 현재 구현과 다름 | +| Repository map and instruction scope | 15/20 | FESA runtime/Feature 경계는 유효하나 삭제한 profile·hook 경로를 현행 지침으로 참조 | +| Non-obvious constraints and gotchas | 15/15 | Source identity, 수치/물리 검증, reference 무결성, state·HDF5 보존의 구체적 제약 유지 | +| Conciseness and duplication | 5/15 | stage·handoff·retry·hook의 상세 의무를 여러 전담 문서와 중복 유지 | +| Currency against the codebase | 5/15 | 7개 profile·medium/high·인자 없는 runner·hook 삭제를 아직 반영하지 않음 | +| Actionability and verifiability | 10/15 | 검증 명령과 경계는 구체적이나 현재 수행할 수 없는 절차를 의무화 | + +**Issues:** 삭제된 운영 기능을 요구하고, 간소화된 skill보다 더 강한 상태기계·파일명 TDD·전체 검증 반복을 지시한다. + +**Recommended changes:** §3의 AGENTS 수정 범위만 반영한다. 상세 기술·수치 규칙은 유지하고 전담 문서와의 중복 운영 설명을 줄인다. + +### Update: AGENTS.md + +**Why:** AH-01~05와 실제 profile/runner/skill에 맞게 현행 지침을 바꾼다. 아래는 핵심 문구의 제안 diff이며 전체 적용 범위는 §3·Task 4를 따른다. 이 계획 작성 중에는 적용하지 않는다. + +```diff +- CRITICAL: 새 기능 또는 동작 변경은 테스트를 먼저 작성하고 실패를 확인한 뒤 구현한다. +- CRITICAL: C++ production file을 바꿀 때는 관련 C++ test file이 있어야 한다. ++ 동작 추가·수정은 해당 동작을 확인하는 테스트로 검증한다. 버그는 가능한 경우 실패를 재현한 뒤 최소 수정한다. ++ 기존 coverage가 충분한 rename·refactor나 문서 수정에는 형식적인 새 테스트를 요구하지 않는다. +``` + +```diff +- Codex custom agent의 `model_reasoning_effort`는 `xhigh`이며, 모델과 역할별 설정은 [.codex/agents](.codex/agents)의 현재 profile을 따른다. ++ 일반 specialist의 기본 추론 강도는 `medium`, 정식화·수치·물리 검토는 `high`다. 모델과 역할별 설정은 [.codex/agents](.codex/agents)의 현재 profile을 따른다. +``` + +```diff +- 기능 개발은 아래 `Agent/Skill Workflow`의 9개 정규 stage를 순서대로 통과한다. ++ 메인 assistant가 범위를 파악하고 필요한 전문 작업만 위임하며 구현·검증·결과 확인을 조정한다. ++ 수식·요소·재료·적분·상태 갱신 변경의 독립 numerical review와 필요한 analytical/invariant·reference 검증은 유지한다. ++ 변경 중에는 관련 검사를, 솔버 기능 완료 시에는 구성된 전체 build/test와 필수 reference 비교를 한 번 수행한다. 이후 변경·실패가 없으면 반복하지 않는다. +``` + +```diff +- python scripts/execute.py ++ python scripts/execute.py +``` + +새 CLI 한 줄 교체만으로 완료하지 않는다. 기존 phase 인자·push·sandbox·hook 설명을 §5에 맞게 함께 갱신하고, 관리 문서 표에서 신규 `coordination.md` 요구를 제거하여 PRD checklist로 연결한다. + +## 9. 최종 산출물과 완료 기준 + +- 요청된 문서 10개의 검토 가능한 diff와 ADR-028의 명확한 대체 관계. +- 현재 역할·skill·CLI·설정·검증 시점이 일치하고 폐기 기능을 현행 필수 절차로 요구하지 않음. +- FESA 제품·수치·입출력·코딩 계약과 필요한 독립 검증이 보존됨. +- 상대 링크·소스 대조·diff/공백 검사를 정적으로 확인하고, 과거 evidence와 현재 미실행 항목을 구분해 보고함. +- 사용자 구현 변경·테스트·개인 설정·기존 phase/Feature 이력은 보존됨. 저장소 전체 검증 완료나 commit/push 완료로 확대하여 보고하지 않음. diff --git a/scripts/execute.py b/scripts/execute.py index f4a33f7..3b04fa2 100644 --- a/scripts/execute.py +++ b/scripts/execute.py @@ -1,1360 +1,59 @@ #!/usr/bin/env python3 -""" -Harness Step Executor — phase 내 Step을 순차 실행하고 결과와 파일 소유권을 검증한다. - -Usage: - python scripts/execute.py [--push] -""" +"""Run the configured C/C++ build and tests once: python scripts/execute.py.""" import argparse -import contextlib -import json -import os -import re -import subprocess import sys -import tempfile -import threading import time -import types -from datetime import datetime, timezone, timedelta -from pathlib import Path, PureWindowsPath -from typing import Optional +from pathlib import Path -ROOT = Path(__file__).resolve().parent.parent +from msvc_harness.adapters.base import AdapterError +from msvc_harness.adapters.cmake import CMakeAdapter +from msvc_harness.adapters.msbuild import MSBuildAdapter +from msvc_harness.config import ConfigError, load_config +from msvc_harness.discovery import DiscoveryError, discover_project +from msvc_harness.models import ProjectKind +from msvc_harness.process import ValidationFailure, execute_plan +from msvc_harness.toolchain import ToolchainError, discover_toolchain -class HarnessError(RuntimeError): - """Executor가 안전하게 계속할 수 없는 검증 또는 실행 오류.""" +ROOT = Path(__file__).resolve().parents[1] -class CodexEnvironmentError(HarnessError): - """재시도로 해결할 수 없는 Codex CLI 환경 오류.""" - - -class StepOwnershipError(HarnessError): - """승인된 Step 파일 범위 밖의 변경; 사용자 데이터를 되돌리지 않는다.""" - - -def _configure_utf8_stdio(): - """Windows 콘솔에서도 Harness 진행 문자를 안정적으로 출력한다.""" - for stream in (sys.stdout, sys.stderr): - reconfigure = getattr(stream, "reconfigure", None) - if reconfigure is not None: - reconfigure(encoding="utf-8") - - -@contextlib.contextmanager -def progress_indicator(label: str): - """터미널 진행 표시기. with 문으로 사용하며 .elapsed 로 경과 시간을 읽는다.""" - frames = "◐◓◑◒" - stop = threading.Event() - t0 = time.monotonic() - - def _animate(): - idx = 0 - while not stop.wait(0.12): - sec = int(time.monotonic() - t0) - sys.stderr.write(f"\r{frames[idx % len(frames)]} {label} [{sec}s]") - sys.stderr.flush() - idx += 1 - sys.stderr.write("\r" + " " * (len(label) + 20) + "\r") - sys.stderr.flush() - - th = threading.Thread(target=_animate, daemon=True) - th.start() - info = types.SimpleNamespace(elapsed=0.0) +def run_validations(root: Path) -> int: + deadline = time.monotonic() + 1800 try: - yield info - finally: - stop.set() - th.join() - info.elapsed = time.monotonic() - t0 - - -class StepExecutor: - """Phase 디렉토리 안의 step들을 순차 실행하는 하네스.""" - - MAX_TRANSPORT_ATTEMPTS = 2 - CODEX_TIMEOUT_SECONDS = 1800 - CODEX_SANDBOX_ENV = "FEM_HARNESS_CODEX_SANDBOX" - CODEX_SANDBOX_MODES = frozenset({"workspace-write", "danger-full-access"}) - PHASE_NAME = re.compile(r"^[a-z0-9]+(?:[._-][a-z0-9]+)*$") - STEP_NAME = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$") - STEP_STATUSES = frozenset({"pending", "completed", "error", "blocked"}) - AGENT_STEP_FIELDS = frozenset( - {"status", "summary", "error_message", "blocked_reason"} - ) - IMPLEMENTATION_AGENT_PROFILE = Path( - ".codex/agents/implementation-agent.toml" - ) - FEAT_MSG = "feat({phase}): step {num} - {name}" - CHORE_MSG = "chore({phase}): step {num} output" - TZ = timezone(timedelta(hours=9)) - - def __init__( - self, - phase_dir_name: str, - *, - auto_push: bool = False, - danger_full_access_approved: bool = False, - ): - if not isinstance(phase_dir_name, str) or not self.PHASE_NAME.fullmatch( - phase_dir_name - ): - raise HarnessError( - "phase directory must be one safe repository-relative name" - ) - root_path = ROOT.resolve() - self._root = str(root_path) - self._phases_dir = (root_path / "phases").resolve() - try: - self._phases_dir.relative_to(root_path) - except ValueError as exc: - raise HarnessError( - "phases directory must resolve inside the Harness repository root" - ) from exc - self._phase_dir = (self._phases_dir / phase_dir_name).resolve() - try: - self._phase_dir.relative_to(self._phases_dir.resolve()) - except ValueError as exc: - raise HarnessError( - "phase directory must stay inside the repository phases directory" - ) from exc - self._phase_dir_name = phase_dir_name - self._top_index_file = self._phases_dir / "index.json" - self._auto_push = auto_push - self._danger_full_access_approved = danger_full_access_approved - self._validated_sandbox_mode: str | None = None - self._implementation_profile_cache: tuple[str, str, str] | None = None - - if not self._phase_dir.is_dir(): - raise HarnessError(f"phase directory not found: {self._phase_dir}") - - self._index_file = self._phase_dir / "index.json" - if not self._index_file.exists(): - raise HarnessError(f"phase index not found: {self._index_file}") - if not self._top_index_file.is_file(): - raise HarnessError( - f"top-level phase index not found: {self._top_index_file}" - ) - - self._read_top_index() - idx = self._read_phase_index() - self._project = idx["project"] - self._phase_name = idx["phase"] - self._total = len(idx["steps"]) - - def run(self): - self._print_header() - self._check_blockers() - self._preflight_repository() - self._checkout_branch() - guardrails = self._load_guardrails() - self._ensure_created_at() - self._execute_all_steps(guardrails) - self._finalize() - - # --- timestamps --- - - def _stamp(self) -> str: - return datetime.now(self.TZ).strftime("%Y-%m-%dT%H:%M:%S%z") - - # --- JSON I/O --- - - def _control_scope(self, path: Path) -> Path: - if path == self._top_index_file: - return self._phases_dir - try: - path.relative_to(self._phase_dir) - except ValueError as exc: - raise HarnessError( - f"control path is outside the selected phase: {path}" - ) from exc - return self._phase_dir - - def _validate_control_parent(self, path: Path, scope: Path) -> None: - root = Path(self._root) - try: - resolved_scope = scope.resolve(strict=True) - resolved_scope.relative_to(root) - path.parent.resolve(strict=True).relative_to(resolved_scope) - except (OSError, ValueError) as exc: - raise HarnessError( - f"control path parent escapes its trusted scope: {path}" - ) from exc - - def _read_control_bytes(self, path: Path) -> bytes: - scope = self._control_scope(path) - self._validate_control_parent(path, scope) - try: - metadata = path.lstat() - resolved = path.resolve(strict=True) - resolved.relative_to(scope.resolve(strict=True)) - except (OSError, ValueError) as exc: - raise HarnessError( - f"protected control file is missing or escapes its scope: {path}" - ) from exc - if path.is_symlink() or not path.is_file() or metadata.st_nlink != 1: - raise HarnessError( - f"protected control file must be a non-link regular file: {path}" - ) - try: - return path.read_bytes() - except OSError as exc: - raise HarnessError( - f"protected control file could not be read: {path}: {exc}" - ) from exc - - def _atomic_write_control_bytes(self, path: Path, contents: bytes) -> None: - scope = self._control_scope(path) - self._validate_control_parent(path, scope) - if path.exists() and not path.is_symlink() and not path.is_file(): - raise HarnessError( - f"control output path is not a regular file: {path}" - ) - - temporary_path: Path | None = None - try: - with tempfile.NamedTemporaryFile( - mode="wb", - dir=path.parent, - prefix=f".{path.name}.", - suffix=".tmp", - delete=False, - ) as handle: - temporary_path = Path(handle.name) - handle.write(contents) - handle.flush() - os.fsync(handle.fileno()) - os.replace(temporary_path, path) - except OSError as exc: - raise HarnessError( - f"control output could not be written atomically: {path}: {exc}" - ) from exc - finally: - if temporary_path is not None and temporary_path.exists(): - temporary_path.unlink() - - def _read_json(self, p: Path) -> dict: - try: - data = json.loads(self._read_control_bytes(p).decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError) as exc: - raise HarnessError(f"invalid JSON file {p}: {exc}") from exc - if not isinstance(data, dict): - raise HarnessError(f"JSON root must be an object: {p}") - return data - - def _write_json(self, p: Path, data: dict): - contents = json.dumps(data, indent=2, ensure_ascii=False).encode("utf-8") - self._atomic_write_control_bytes(p, contents) - - def _read_phase_index(self) -> dict: - index = self._read_json(self._index_file) - self._validate_phase_index(index) - return index - - def _read_top_index(self) -> dict: - index = self._read_json(self._top_index_file) - phases = index.get("phases") - if not isinstance(phases, list) or not phases: - raise HarnessError("top-level phase index requires a non-empty phases array") - - selected_count = 0 - seen: set[str] = set() - for position, phase in enumerate(phases): - if not isinstance(phase, dict): - raise HarnessError( - f"top-level phase entry {position} must be an object" - ) - directory = phase.get("dir") - if not isinstance(directory, str) or not self.PHASE_NAME.fullmatch( - directory - ): - raise HarnessError( - f"top-level phase entry {position} has an invalid directory" - ) - if directory in seen: - raise HarnessError( - f"top-level phase '{directory}' must appear exactly once" - ) - seen.add(directory) - if directory == self._phase_dir_name: - selected_count += 1 - if phase.get("status") not in self.STEP_STATUSES: - raise HarnessError( - f"top-level phase entry {position} has an invalid status" - ) - - if selected_count != 1: - raise HarnessError( - f"selected phase '{self._phase_dir_name}' must appear exactly once " - "in the top-level phase index" - ) - return index - - def _validate_phase_index(self, index: dict) -> None: - project = index.get("project") - if not isinstance(project, str) or not project.strip(): - raise HarnessError("phase index project must be a non-empty string") - phase = index.get("phase") - if phase != self._phase_dir_name: - raise HarnessError( - "phase index phase must match its phase directory name" - ) - steps = index.get("steps") - if not isinstance(steps, list) or not steps: - raise HarnessError("phase index steps must be a non-empty array") - - expected_steps = list(range(len(steps))) - actual_steps = [step.get("step") if isinstance(step, dict) else None for step in steps] - if actual_steps != expected_steps: - raise HarnessError("phase step numbers must be contiguous from zero") - - state = "completed-prefix" - for expected, step in enumerate(steps): - if not isinstance(step, dict): - raise HarnessError(f"phase step {expected} must be an object") - name = step.get("name") - if not isinstance(name, str) or not self.STEP_NAME.fullmatch(name): - raise HarnessError( - f"phase step {expected} name must be a kebab-case slug" - ) - status = step.get("status") - if status not in self.STEP_STATUSES: - raise HarnessError(f"phase step {expected} has invalid status") - if "owned_paths" in step: - self._step_owned_paths(step) - self._validate_attempt_history(step) - - if status == "completed": - if state != "completed-prefix": - raise HarnessError("phase step status order is invalid") - if not isinstance(step.get("summary"), str) or not step["summary"].strip(): - raise HarnessError( - f"completed phase step {expected} requires summary" - ) - elif status == "pending": - if state == "completed-prefix": - state = "pending-suffix" - else: - if state != "completed-prefix": - raise HarnessError("phase step status order is invalid") - detail_key = "error_message" if status == "error" else "blocked_reason" - if not isinstance(step.get(detail_key), str) or not step[detail_key].strip(): - raise HarnessError( - f"{status} phase step {expected} requires {detail_key}" - ) - state = "terminal-then-pending" - - if state == "terminal-then-pending" and status == "pending": - state = "pending-suffix" - - step_file = self._phase_dir / f"step{expected}.md" - if not step_file.is_file(): - raise HarnessError(f"phase step file not found: {step_file}") - - @staticmethod - def _path_key(path: str) -> str: - return os.path.normcase(path).replace("\\", "/") - - def _step_owned_paths(self, step: dict) -> tuple[str, ...]: - paths = step.get("owned_paths") - if not isinstance(paths, list): - raise HarnessError(f"Step {step['step']} requires an owned_paths file array before execution") - normalized = [] - seen = set() - for path in paths: - if not isinstance(path, str): - raise HarnessError("owned_paths entries must be repository-relative file paths") - path = path.replace("\\", "/") - parts = path.split("/") - if ( - not path or PureWindowsPath(path).drive or path.startswith("/") - or any(part in {"", ".", ".."} or part.endswith((".", " ")) for part in parts) - or any(ord(char) < 32 or char in ':*?[]<>"|' for char in path) - or any(part.casefold() == ".git" or PureWindowsPath(part).is_reserved() for part in parts) - or parts[0].casefold() == "phases" - ): - raise HarnessError(f"owned_paths requires an exact non-control relative file path: {path!r}") - key = self._path_key(path) - if key in seen: - raise HarnessError(f"owned_paths contains duplicate/aliased paths: {path}") - seen.add(key) - normalized.append(path) - return tuple(normalized) - - def _validate_owned_file(self, path: str) -> None: - root = Path(self._root) - candidate = root / path - try: - resolved = candidate.resolve() - resolved.relative_to(root) - if resolved != candidate or candidate.is_symlink() or candidate.is_dir(): - raise ValueError("directory or linked path") - if candidate.exists() and candidate.lstat().st_nlink != 1: - raise ValueError("hard-linked file") - except (OSError, RuntimeError, ValueError) as exc: - raise HarnessError(f"owned_paths must name non-linked files inside the repository: {path}") from exc - - def _validate_attempt_history(self, step: dict) -> None: - if "attempt_history" not in step: - return - history = step["attempt_history"] - if not isinstance(history, list): - raise HarnessError("attempt_history must be an Executor-owned array") - for number, record in enumerate(history, 1): - if ( - not isinstance(record, dict) - or type(record.get("attempt")) is not int or record["attempt"] != number - or "exit_code" not in record - or (record["exit_code"] is not None and type(record["exit_code"]) is not int) - or not isinstance(record.get("reported_status"), str) - or record["reported_status"] not in self.STEP_STATUSES - or not isinstance(record.get("recorded_at"), str) or not record["recorded_at"] - or not isinstance(record.get("reported_reason"), str) - or not isinstance(record.get("reason"), str) - or not isinstance(record.get("diagnostic"), str) - or not isinstance(record.get("classification"), str) - or record["classification"] not in { - "environment", "reported-blocked", "reported-error", "completed", - "inconsistent-result", "transport-timeout", "process-error", "missing-result", - "ownership-violation", "commit-error", - } - ): - raise HarnessError(f"attempt_history contains an invalid record at attempt {number}") - - def _snapshot_phase_control_files( - self, index: dict - ) -> tuple[bytes, dict[str, bytes]]: - expected_names = {f"step{step['step']}.md" for step in index["steps"]} - current_names = { - path.name - for path in self._phase_dir.glob("step*.md") - if path.is_file() - } - if current_names != expected_names: - raise HarnessError( - "protected phase control file inventory does not match the phase index" - ) - try: - top_index = self._read_control_bytes(self._top_index_file) - step_files = { - f"step{step['step']}.md": ( - self._read_control_bytes( - self._phase_dir / f"step{step['step']}.md" - ) - ) - for step in index["steps"] - } - except HarnessError as exc: - raise HarnessError( - f"protected phase control file could not be read: {exc}" - ) from exc - return top_index, step_files - - def _validate_phase_control_files( - self, snapshot: tuple[bytes, dict[str, bytes]] - ) -> None: - expected_top, expected_steps = snapshot - try: - current_top = self._read_control_bytes(self._top_index_file) - current_names = { - path.name - for path in self._phase_dir.glob("step*.md") - if path.is_file() - } - current_steps = { - name: self._read_control_bytes(self._phase_dir / name) - for name in current_names - } - except HarnessError as exc: - raise HarnessError( - f"protected phase control file changed or disappeared: {exc}" - ) from exc - if current_top != expected_top or current_steps != expected_steps: - raise HarnessError( - "Codex modified a protected phase control file; only the current " - "Step outcome in the phase index may change" - ) - - def _record_untrusted_step_result( - self, - index_before: dict, - current_step: int, - classification: str, - reason: str, - control_snapshot: tuple[bytes, dict[str, bytes]], - ) -> None: - expected_top, expected_steps = control_snapshot - self._top_index_file.parent.mkdir(parents=True, exist_ok=True) - self._atomic_write_control_bytes(self._top_index_file, expected_top) - self._phase_dir.mkdir(parents=True, exist_ok=True) - for name, contents in expected_steps.items(): - self._atomic_write_control_bytes(self._phase_dir / name, contents) - - recovered = json.loads(json.dumps(index_before)) - current = recovered["steps"][current_step] - self._clear_step_outcome(current) - current["status"] = "error" - current["error_message"] = f"[{classification}] {reason}" - current["failed_at"] = self._stamp() - self._write_json(self._index_file, recovered) - self._update_top_index("error") - - def _validate_step_index_mutation( - self, before: dict, after: dict, current_step: int - ) -> None: - before_metadata = {key: value for key, value in before.items() if key != "steps"} - after_metadata = {key: value for key, value in after.items() if key != "steps"} - if before_metadata != after_metadata: - raise HarnessError( - "Codex modified protected phase index metadata" - ) - - before_steps = before["steps"] - after_steps = after["steps"] - if len(before_steps) != len(after_steps): - raise HarnessError("Codex modified the protected Step inventory") - - for position, (old_step, new_step) in enumerate( - zip(before_steps, after_steps) - ): - if position != current_step: - if old_step != new_step: - raise HarnessError( - f"Codex modified non-current Step {position}" - ) - continue - old_fixed = { - key: value - for key, value in old_step.items() - if key not in self.AGENT_STEP_FIELDS - } - new_fixed = { - key: value - for key, value in new_step.items() - if key not in self.AGENT_STEP_FIELDS - } - if old_fixed != new_fixed: - raise HarnessError( - "Codex modified immutable metadata on the current Step" - ) - - # --- git --- - - def _run_git(self, *args) -> subprocess.CompletedProcess: - cmd = ["git"] + list(args) - return subprocess.run( - cmd, cwd=self._root, capture_output=True, text=True, encoding="utf-8" - ) - - def _run_git_checked(self, *args) -> subprocess.CompletedProcess: - result = self._run_git(*args) - if result.returncode != 0: - diagnostic = (result.stderr or result.stdout).strip() - message = f"git {args[0]} failed" - if diagnostic: - message = f"{message}: {diagnostic}" - raise HarnessError(message) - return result - - def _git_execution_identity(self) -> tuple[str, str]: - branch = self._run_git_checked( - "symbolic-ref", "--quiet", "HEAD" - ).stdout.strip() - head = self._run_git_checked( - "rev-parse", "--verify", "HEAD" - ).stdout.strip() - if not branch or not head: - raise HarnessError("Git branch and HEAD identity must be non-empty") - return branch, head - - def _worktree_paths(self) -> tuple[str, ...]: - result = self._run_git_checked( - "status", "--porcelain=v1", "-z", "--untracked-files=all" - ) - paths: list[str] = [] - records = result.stdout.split("\0") - position = 0 - while position < len(records): - record = records[position] - position += 1 - if not record: - continue - if len(record) < 4 or record[2] != " ": - raise HarnessError("git status returned an invalid porcelain record") - status = record[:2] - paths.append(record[3:].replace("\\", "/")) - if "R" in status or "C" in status: - if position >= len(records) or not records[position]: - raise HarnessError( - "git status returned an incomplete rename/copy record" - ) - paths.append(records[position].replace("\\", "/")) - position += 1 - return tuple(dict.fromkeys(paths)) - - def _is_phase_owned_path(self, path: str) -> bool: - phase_prefix = f"phases/{self._phase_dir_name}/" - declared = { - "phases/index.json", - f"{phase_prefix}index.json", - *( - f"{phase_prefix}step{step_num}.md" - for step_num in range(self._total) - ), - } - return path in declared or self._is_step_output_path(path) - - def _is_step_output_path(self, path: str) -> bool: - phase_prefix = f"phases/{self._phase_dir_name}/" - if not path.startswith(phase_prefix): - return False - name = path.removeprefix(phase_prefix) - match = re.fullmatch(r"step(\d+)-output\.json", name) - return match is not None and int(match.group(1)) < self._total - - def _preflight_repository(self) -> None: - for step in self._read_phase_index()["steps"]: - if step["status"] == "pending": - for path in self._step_owned_paths(step): - self._validate_owned_file(path) - self._implementation_agent_profile() - top_level_result = self._run_git_checked("rev-parse", "--show-toplevel") - raw_top_level = top_level_result.stdout.strip() - if not raw_top_level or Path(raw_top_level).resolve() != Path(self._root): - raise HarnessError( - "Git top-level must exactly match the Harness repository root" - ) - mode = self._codex_sandbox_mode() - paths = self._worktree_paths() - if mode == "danger-full-access": - if paths: - raise CodexEnvironmentError( - "danger-full-access requires a clean worktree" - ) - return - unrelated = [path for path in paths if not self._is_phase_owned_path(path)] - if unrelated: - preview = ", ".join(unrelated[:5]) - raise HarnessError( - "Harness requires a clean worktree outside the selected phase; " - f"unrelated changes: {preview}" - ) - - def _is_isolated_worktree(self) -> bool: - git_dir = Path( - self._run_git_checked("rev-parse", "--absolute-git-dir").stdout.strip() - ).resolve() - common_raw = self._run_git_checked("rev-parse", "--git-common-dir").stdout.strip() - common_dir = Path(common_raw) - if not common_dir.is_absolute(): - common_dir = Path(self._root) / common_dir - return git_dir != common_dir.resolve() - - def _checkout_branch(self): - branch = f"feat-{self._phase_name}" - branch_ref = f"refs/heads/{branch}" - - current = self._run_git("symbolic-ref", "--quiet", "HEAD") - if current.returncode == 0 and current.stdout.strip() == branch_ref: - return - - exists = self._run_git( - "show-ref", "--verify", "--quiet", branch_ref - ) - if exists.returncode == 0: - switched = self._run_git("switch", branch) - elif exists.returncode == 1: - switched = self._run_git("switch", "-c", branch) - else: - raise HarnessError( - f"git show-ref failed for branch '{branch}': " - f"{(exists.stderr or exists.stdout).strip()}" - ) - - if switched.returncode != 0: - raise HarnessError( - f"git switch failed for branch '{branch}': " - f"{(switched.stderr or switched.stdout).strip()}" - ) - - verified = self._run_git_checked( - "symbolic-ref", "--quiet", "HEAD" - ) - if verified.stdout.strip() != branch_ref: - raise HarnessError( - f"Git did not enter the expected local branch '{branch}'; " - f"actual={verified.stdout.strip()!r}" - ) - - print(f" Branch: {branch}") - - def _assert_step_scope(self, owned_paths: tuple[str, ...]) -> tuple[str, ...]: - allowed = {self._path_key(path) for path in owned_paths} - changed = self._worktree_paths() - unexpected = [ - path for path in changed - if not self._is_phase_owned_path(path) and self._path_key(path) not in allowed - ] - if unexpected: - raise StepOwnershipError("Step ownership violation: " + ", ".join(unexpected)) - try: - for path in owned_paths: - self._validate_owned_file(path) - except HarnessError as exc: - raise StepOwnershipError(str(exc)) from exc - return changed - - def _commit_paths( - self, paths: list[str], message: str, *, owned_paths: tuple[str, ...] = () - ) -> bool: - validated_paths = self._assert_step_scope(owned_paths) - if not paths: - return False - # Codex may stage files even though the prompt tells it not to. Reset only - # the index so the following path-scoped add controls the commit content; - # working-tree data is preserved. This also expands staged renames back to - # a deletion/addition pair, allowing both porcelain pathnames to be staged. - if validated_paths: - self._run_git_checked( - "--literal-pathspecs", "reset", "--quiet", "HEAD", "--", *sorted(validated_paths) - ) - self._run_git_checked("--literal-pathspecs", "add", "-A", "--", *sorted(paths)) - staged = self._run_git_checked( - "diff", "--cached", "--name-only", "--no-renames", "-z" - ).stdout - selected = {self._path_key(path) for path in paths} - unexpected = [ - path for path in staged.split("\0") - if path and self._path_key(path) not in selected - ] - if unexpected: - raise StepOwnershipError("Unexpected staged paths before commit: " + ", ".join(unexpected)) - self._assert_step_scope(owned_paths) - if not staged: - return False - self._run_git_checked("commit", "-m", message) - return True - - def _commit_step(self, step_num: int, step_name: str, owned_paths: tuple[str, ...]): - changed = self._assert_step_scope(owned_paths) - code_paths = [ - path - for path in changed - if not self._is_phase_owned_path(path) - ] - message = self.FEAT_MSG.format( - phase=self._phase_name, num=step_num, name=step_name - ) - if self._commit_paths(code_paths, message, owned_paths=owned_paths): - print(f" Commit: {message}") - - metadata_paths = [ - path - for path in self._assert_step_scope(owned_paths) - if self._is_phase_owned_path(path) and not self._is_step_output_path(path) - ] - message = self.CHORE_MSG.format( - phase=self._phase_name, num=step_num - ) - self._commit_paths(metadata_paths, message, owned_paths=owned_paths) - - # --- top-level index --- - - def _update_top_index(self, status: str): - if status not in {"pending", "completed", "error", "blocked"}: - raise HarnessError(f"invalid top-level phase status: {status}") - top = self._read_top_index() - phases = top["phases"] - ts = self._stamp() - matched = False - for phase in phases: - if not isinstance(phase, dict): - raise HarnessError("top-level phase entry must be an object") - if phase.get("dir") == self._phase_dir_name: - matched = True - phase["status"] = status - ts_key = {"completed": "completed_at", "error": "failed_at", "blocked": "blocked_at"}.get(status) - for key in ("completed_at", "failed_at", "blocked_at"): - if key != ts_key: - phase.pop(key, None) - if ts_key: - phase[ts_key] = ts - break - if not matched: # Defensive: _read_top_index already enforces this invariant. - raise HarnessError("selected phase is missing from the top-level phase index") - self._write_json(self._top_index_file, top) - - # --- guardrails & context --- - - def _load_guardrails(self) -> str: - sections = [] - agents_md = ROOT / "AGENTS.md" - if agents_md.exists(): - sections.append( - "## 프로젝트 규칙 (AGENTS.md)\n\n" - f"{agents_md.read_text(encoding='utf-8')}" - ) - docs_dir = ROOT / "docs" - if docs_dir.is_dir(): - for doc in sorted(docs_dir.glob("*.md")): - sections.append( - f"## {doc.stem}\n\n{doc.read_text(encoding='utf-8')}" - ) - return "\n\n---\n\n".join(sections) if sections else "" - - @staticmethod - def _build_step_context(index: dict) -> str: - lines = [ - f"- Step {s['step']} ({s['name']}): {s['summary']}" - for s in index["steps"] - if s["status"] == "completed" and s.get("summary") - ] - if not lines: - return "" - return "## 이전 Step 산출물\n\n" + "\n".join(lines) + "\n\n" - - def _build_preamble(self, guardrails: str, step_context: str, - prev_error: Optional[str] = None) -> str: - retry_section = "" - if prev_error: - retry_section = ( - f"\n## ⚠ 이전 시도 실패 — 아래 에러를 반드시 참고하여 수정하라\n\n" - f"{prev_error}\n\n---\n\n" - ) - _, _, role_instructions = self._implementation_agent_profile() - return ( - f"당신은 {self._project} 프로젝트의 개발자입니다. 아래 step을 수행하세요.\n\n" - f"## Implementation Agent role\n\n{role_instructions}\n\n---\n\n" - f"{guardrails}\n\n---\n\n" - f"{step_context}{retry_section}" - f"## 작업 규칙\n\n" - f"1. 이전 step에서 작성된 코드를 확인하고 일관성을 유지하라.\n" - f"2. 이 step에 명시된 작업만 수행하라. 추가 기능이나 파일을 만들지 마라.\n" - f"3. 기존 테스트를 깨뜨리지 마라.\n" - f"4. AC(Acceptance Criteria) 검증을 직접 실행하라.\n" - f"5. /phases/{self._phase_dir_name}/index.json의 해당 step status를 업데이트하라:\n" - f" - AC 통과 → \"completed\" + \"summary\" 필드에 이 step의 산출물을 한 줄로 요약\n" - f" - 구현 또는 검증 실패 → \"error\" + \"error_message\" 기록\n" - f" - 사용자 개입이 필요한 경우 (API 키, 인증, 수동 설정 등) → \"blocked\" + \"blocked_reason\" 기록 후 즉시 중단\n" - f"6. 변경사항을 직접 커밋하지 마라. Git 커밋과 timestamp는 실행기가 처리한다.\n\n" - f"---\n\n" - ) - - # --- Codex 호출 --- - - def _codex_sandbox_mode(self) -> str: - if self._validated_sandbox_mode is not None: - return self._validated_sandbox_mode - mode = os.environ.get(self.CODEX_SANDBOX_ENV, "workspace-write") - if mode not in self.CODEX_SANDBOX_MODES: - allowed = ", ".join(sorted(self.CODEX_SANDBOX_MODES)) - raise CodexEnvironmentError( - f"{self.CODEX_SANDBOX_ENV} must be one of: {allowed}" - ) - if mode == "danger-full-access": - if not self._danger_full_access_approved: - raise CodexEnvironmentError( - "danger-full-access requires explicit authorization through " - "--approve-danger-full-access" - ) - if not self._is_isolated_worktree(): - raise CodexEnvironmentError( - "danger-full-access requires an isolated linked worktree" - ) - if self._worktree_paths(): - raise CodexEnvironmentError( - "danger-full-access requires a clean worktree" - ) - self._validated_sandbox_mode = mode - return mode - - def _implementation_agent_profile(self) -> tuple[str, str, str]: - if self._implementation_profile_cache is not None: - return self._implementation_profile_cache - profile_path = Path(self._root) / self.IMPLEMENTATION_AGENT_PROFILE - try: - profile_text = profile_path.read_text(encoding="utf-8") - except OSError as exc: - raise CodexEnvironmentError( - f"Implementation Agent profile을 읽을 수 없습니다: {profile_path}" - ) from exc - - settings = {} - for line in profile_text.splitlines(): - key, separator, value = line.partition("=") - key = key.strip() - if separator and key in {"model", "model_reasoning_effort"}: - try: - settings[key] = json.loads(value.strip()) - except json.JSONDecodeError as exc: - raise CodexEnvironmentError( - f"Implementation Agent profile의 {key} 값이 올바른 문자열이 아닙니다." - ) from exc - - model = settings.get("model") - reasoning_effort = settings.get("model_reasoning_effort") - if not isinstance(model, str) or not isinstance(reasoning_effort, str): - raise CodexEnvironmentError( - "Implementation Agent profile에 model과 model_reasoning_effort 문자열이 필요합니다." - ) - match = re.search( - r'^developer_instructions\s*=\s*"""(.*?)"""\s*$', - profile_text, - re.MULTILINE | re.DOTALL, - ) - if match is None or not match.group(1).strip(): - raise CodexEnvironmentError( - "Implementation Agent profile에 developer_instructions가 필요합니다." - ) - instructions = match.group(1).strip() - self._implementation_profile_cache = ( - model, - reasoning_effort, - instructions, - ) - return self._implementation_profile_cache - - def _implementation_agent_settings(self) -> tuple[str, str]: - model, reasoning_effort, _ = self._implementation_agent_profile() - return model, reasoning_effort - - @staticmethod - def _process_text(value: str | bytes | None) -> str: - if value is None: - return "" - if isinstance(value, bytes): - return value.decode("utf-8", errors="replace") - return value - - def _invoke_codex(self, step: dict, preamble: str) -> dict: - step_num, step_name = step["step"], step["name"] - step_file = self._phase_dir / f"step{step_num}.md" - - if not step_file.exists(): - print(f" ERROR: {step_file} not found") - sys.exit(1) - - try: - step_text = self._read_control_bytes(step_file).decode("utf-8") - except UnicodeDecodeError as exc: - raise HarnessError(f"Step instruction must be valid UTF-8: {step_file}") from exc - prompt = preamble + step_text - sandbox_mode = self._codex_sandbox_mode() - model, reasoning_effort = self._implementation_agent_settings() - command = [ - "codex", - "exec", - "--disable", - "unified_exec", - "--json", - "--model", - model, - "--config", - f"model_reasoning_effort={json.dumps(reasoning_effort)}", - "--sandbox", - sandbox_mode, - "--dangerously-bypass-hook-trust", - "--cd", - self._root, - "-", - ] - transport_failure = None - try: - result = subprocess.run( - command, - cwd=self._root, - input=prompt, - capture_output=True, - text=True, - encoding="utf-8", - timeout=self.CODEX_TIMEOUT_SECONDS, - ) - except FileNotFoundError as exc: - raise CodexEnvironmentError( - "Codex CLI를 찾을 수 없습니다. codex를 설치하고 PATH를 확인하세요." - ) from exc - except subprocess.TimeoutExpired as exc: - transport_failure = "timeout" - timeout_message = f"Codex timed out after {exc.timeout} seconds." - stdout = self._process_text(exc.stdout) - stderr = self._process_text(exc.stderr) - if stderr: - stderr = f"{timeout_message}\n{stderr}" - else: - stderr = timeout_message - result = subprocess.CompletedProcess( - command, 124, stdout=stdout, stderr=stderr - ) - - if result.returncode != 0: - print(f"\n WARN: Codex가 비정상 종료됨 (code {result.returncode})") - if result.stderr: - print(f" stderr: {result.stderr[:500]}") - - output = { - "step": step_num, "name": step_name, - "exitCode": result.returncode, - "stdout": result.stdout, "stderr": result.stderr, - "transportFailure": transport_failure, - } - out_path = self._phase_dir / f"step{step_num}-output.json" - self._write_json(out_path, output) - - return output - - @staticmethod - def _codex_environment_failure(output: dict) -> Optional[str]: - diagnostic = ( - f"{output.get('stderr', '')}\n{output.get('stdout', '')}" - ).lower() - if "orchestrator_helper_launch_failed" in diagnostic: - return "Codex Windows sandbox helper를 실행할 수 없습니다." - if output.get("exitCode", 0) == 0: - return None - markers = { - "not logged in": "Codex 인증이 필요합니다.", - "authentication": "Codex 인증에 실패했습니다.", - "unexpected argument": "현재 Codex CLI가 필요한 옵션을 지원하지 않습니다.", - "unrecognized option": "현재 Codex CLI가 필요한 옵션을 지원하지 않습니다.", - } - for marker, message in markers.items(): - if marker in diagnostic: - return message - return None - - # --- 헤더 & 검증 --- - - def _print_header(self): - print(f"\n{'='*60}") - print(f" Harness Step Executor") - print(f" Phase: {self._phase_name} | Steps: {self._total}") - if self._auto_push: - print(f" Auto-push: enabled") - print(f"{'='*60}") - - def _check_blockers(self): - index = self._read_phase_index() - current = next( - (step for step in index["steps"] if step["status"] != "completed"), - None, - ) - if current is None or current["status"] == "pending": - return - if current["status"] == "error": - print(f"\n ✗ Step {current['step']} ({current['name']}) failed.") - print(f" Error: {current['error_message']}") - print(" Coordinator must classify the workflow correction before retry.") - sys.exit(1) - print(f"\n ⏸ Step {current['step']} ({current['name']}) blocked.") - print(f" Reason: {current['blocked_reason']}") - print(" Resolve the blocker and reset the Step to pending before retry.") - sys.exit(2) - - @staticmethod - def _clear_step_outcome(step: dict, keep: frozenset[str] = frozenset()) -> None: - for key in ( - "summary", - "completed_at", - "error_message", - "failed_at", - "blocked_reason", - "blocked_at", - ): - if key not in keep: - step.pop(key, None) - - def _ensure_created_at(self): - index = self._read_phase_index() - changed = False - has_pending = any(step["status"] == "pending" for step in index["steps"]) - if "created_at" not in index: - index["created_at"] = self._stamp() - changed = True - if has_pending: - if "completed_at" in index: - index.pop("completed_at") - changed = True - for step in index["steps"]: - if step["status"] != "pending": - continue - before = dict(step) - self._clear_step_outcome(step) - if step != before: - changed = True - if changed: - self._write_json(self._index_file, index) - if has_pending: - top = self._read_top_index() - selected = next( - phase - for phase in top["phases"] - if phase["dir"] == self._phase_dir_name - ) - if selected["status"] != "pending" or any( - key in selected - for key in ("completed_at", "failed_at", "blocked_at") - ): - self._update_top_index("pending") - - # --- 실행 루프 --- - - def _classify_attempt( - self, current: dict, output: dict, environment_failure: Optional[str] - ) -> tuple[str, str, str]: - """Return local classification, action and reason; never infer retry from exit alone.""" - environment_failure = environment_failure or self._codex_environment_failure(output) - if environment_failure: - return "environment", "blocked", environment_failure - status = current["status"] - if status == "blocked": - return "reported-blocked", "blocked", current["blocked_reason"] - if status == "error": - return "reported-error", "error", current["error_message"] - exit_code = output["exitCode"] - if status == "completed": - if exit_code == 0: - return "completed", "completed", current["summary"] - return ( - "inconsistent-result", "error", - f"Step reported completed but Codex exited with code {exit_code}", - ) - diagnostic = (output.get("stderr", "").strip() or output.get("stdout", "").strip())[-4000:] - if output.get("transportFailure") == "timeout": - return "transport-timeout", "retry", diagnostic - if exit_code != 0: - return "process-error", "error", diagnostic or f"Codex exited with code {exit_code}" - return "missing-result", "error", "Step did not update its workflow status" - - def _record_attempt(self, current: dict, output: dict, classification: str, reason: str) -> None: - history = current.setdefault("attempt_history", []) - field = {"completed": "summary", "error": "error_message", "blocked": "blocked_reason"}.get(current["status"]) - history.append({ - "attempt": len(history) + 1, - "recorded_at": self._stamp(), - "exit_code": output["exitCode"], - "reported_status": current["status"], - "reported_reason": current.get(field, "") if field else "", - "classification": classification, - "reason": reason, - "diagnostic": (output.get("stderr", "").strip() or output.get("stdout", "").strip())[-4000:], - }) - - def _stop_step(self, index: dict, step_num: int, status: str, reason: str) -> None: - current = index["steps"][step_num] - current["attempt_history"][-1]["reason"] = reason - self._clear_step_outcome(current) - current["status"] = status - field, timestamp, exit_code = ( - ("blocked_reason", "blocked_at", 2) if status == "blocked" - else ("error_message", "failed_at", 1) - ) - current[field] = reason - current[timestamp] = self._stamp() - self._write_json(self._index_file, index) - self._update_top_index(status) - print(f" Step {step_num}: {status} — {reason}") - sys.exit(exit_code) - - def _execute_single_step(self, step: dict, guardrails: str) -> bool: - """Step을 실행한다. 자동 재시도는 Codex transport 실패에만 적용한다.""" - step_num, step_name = step["step"], step["name"] - owned_paths = self._step_owned_paths(self._read_phase_index()["steps"][step_num]) - for path in owned_paths: - self._validate_owned_file(path) - done = sum( - 1 - for item in self._read_phase_index()["steps"] - if item["status"] == "completed" - ) - prev_error = None - - for attempt in range(1, self.MAX_TRANSPORT_ATTEMPTS + 1): - index = self._read_phase_index() - step_context = self._build_step_context(index) - preamble = self._build_preamble(guardrails, step_context, prev_error) - control_snapshot = self._snapshot_phase_control_files(index) - index_before_invocation = index - git_identity = self._git_execution_identity() - - tag = f"Step {step_num}/{self._total - 1} ({done} done): {step_name}" - if attempt > 1: - tag += ( - f" [transport retry {attempt}/" - f"{self.MAX_TRANSPORT_ATTEMPTS}]" - ) - - environment_failure = None - with progress_indicator(tag) as pi: - try: - output = self._invoke_codex(step, preamble) - except CodexEnvironmentError as exc: - environment_failure = str(exc) - output = {"exitCode": None, "stdout": "", "stderr": str(exc)} - elapsed = int(pi.elapsed) - - try: - if self._git_execution_identity() != git_identity: - raise HarnessError( - "Codex changed the Git branch or HEAD; Git history is " - "Executor-owned" - ) - self._validate_phase_control_files(control_snapshot) - index = self._read_phase_index() - self._validate_step_index_mutation( - index_before_invocation, index, step_num - ) - except HarnessError as exc: - self._record_untrusted_step_result( - index_before_invocation, - step_num, - "control violation", - str(exc), - control_snapshot, - ) - raise - - exit_code = output.get("exitCode") - if type(exit_code) is not int and environment_failure is None: - reason = "Codex output requires an integer exitCode" - self._record_untrusted_step_result( - index_before_invocation, - step_num, - "protocol violation", - reason, - control_snapshot, - ) - raise HarnessError(reason) - - current = index["steps"][step_num] - ts = self._stamp() - try: - self._assert_step_scope(owned_paths) - except StepOwnershipError as exc: - self._record_attempt(current, output, "ownership-violation", str(exc)) - self._stop_step(index, step_num, "error", str(exc)) - classification, action, reason = self._classify_attempt( - current, output, environment_failure - ) - self._record_attempt(current, output, classification, reason) - - if action == "retry": - if attempt < self.MAX_TRANSPORT_ATTEMPTS: - self._clear_step_outcome(current) - self._write_json(self._index_file, index) - prev_error = reason - print( - f" ↻ Step {step_num}: transport retry " - f"{attempt}/{self.MAX_TRANSPORT_ATTEMPTS} — {reason}" - ) - continue - reason = ( - f"[transport failure after {self.MAX_TRANSPORT_ATTEMPTS} " - f"attempts] {reason}" - ) - action = "error" - - if action == "completed": - self._clear_step_outcome( - current, frozenset({"summary", "completed_at"}) - ) - current["completed_at"] = ts - self._write_json(self._index_file, index) - try: - self._commit_step(step_num, step_name, owned_paths) - except HarnessError as exc: - current["attempt_history"][-1]["classification"] = ( - "ownership-violation" if isinstance(exc, StepOwnershipError) else "commit-error" - ) - self._stop_step(index, step_num, "error", str(exc)) - print(f" ✓ Step {step_num}: {step_name} [{elapsed}s]") - return True - - self._stop_step(index, step_num, action, reason) - - return False # unreachable - - def _execute_all_steps(self, guardrails: str): - while True: - index = self._read_phase_index() - pending = next((s for s in index["steps"] if s["status"] == "pending"), None) - if pending is None: - print("\n All steps completed!") - return - - step_num = pending["step"] - for s in index["steps"]: - if s["step"] == step_num and "started_at" not in s: - s["started_at"] = self._stamp() - self._write_json(self._index_file, index) - break - - self._execute_single_step(pending, guardrails) - - def _finalize(self): - index = self._read_phase_index() - if any(step["status"] != "completed" for step in index["steps"]): - raise HarnessError("phase cannot finalize before every Step is completed") - - changed = list(self._worktree_paths()) - unexpected = [ - path - for path in changed - if not self._is_phase_owned_path(path) - ] - if unexpected: - raise HarnessError( - "uncommitted implementation paths remain before finalization: " - + ", ".join(unexpected[:5]) - ) - index["completed_at"] = self._stamp() - self._write_json(self._index_file, index) - self._update_top_index("completed") - changed = list(self._worktree_paths()) - metadata_paths = [ - path for path in changed if not self._is_step_output_path(path) - ] - msg = f"chore({self._phase_name}): mark phase completed" - if self._commit_paths(metadata_paths, msg): - print(f" ✓ {msg}") - - if self._auto_push: - branch = f"feat-{self._phase_name}" - self._run_git_checked("push", "-u", "origin", branch) - print(f" ✓ Pushed to origin/{branch}") - - print(f"\n{'='*60}") - print(f" Phase '{self._phase_name}' completed!") - print(f"{'='*60}") - - -def main(): - _configure_utf8_stdio() - parser = argparse.ArgumentParser(description="Harness Step Executor") - parser.add_argument("phase_dir", help="Phase directory name (e.g. 0-mvp)") - parser.add_argument("--push", action="store_true", help="Push branch after completion") - parser.add_argument( - "--approve-danger-full-access", - action="store_true", - help=( - "Explicitly authorize danger-full-access when the matching sandbox " - "environment setting is used in a clean linked worktree" - ), - ) - args = parser.parse_args() - - try: - StepExecutor( - args.phase_dir, - auto_push=args.push, - danger_full_access_approved=args.approve_danger_full_access, - ).run() - except HarnessError as exc: - print(f"ERROR: {exc}") - sys.exit(1) + config = load_config(root) + selection = discover_project(root, config).selection + if selection is None: + print("not configured: no CMake or MSBuild project found", file=sys.stderr) + return 2 + tools = discover_toolchain(selection.kind, deadline=deadline) + adapter = CMakeAdapter() if selection.kind is ProjectKind.CMAKE else MSBuildAdapter() + plan = adapter.create_plan(root, selection, config, tools) + results = execute_plan(plan, root, deadline=deadline) + except (ConfigError, DiscoveryError, ToolchainError, AdapterError, ValidationFailure, OSError) as exc: + print(str(exc), file=sys.stderr) + return 1 + + for result in results: + print(f"{result.command.stage}: argv={list(result.command.argv)!r}; " + f"cwd={str(result.command.cwd)!r}; exit {result.returncode}") + if result.command.stage == "test": + output = (result.stdout + "\n" + result.stderr).strip() + tail = "\n".join(output.splitlines()[-8:])[-2000:] + if tail != output: + print("[test output tail]") + if tail: + print(tail) + print(f"Validation passed ({len(results)} commands).") + return 0 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.parse_args(argv) + return run_validations(ROOT) if __name__ == "__main__": - main() + raise SystemExit(main()) diff --git a/scripts/hooks/pre_tool_use.py b/scripts/hooks/pre_tool_use.py deleted file mode 100644 index 30e26e6..0000000 --- a/scripts/hooks/pre_tool_use.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/env python3 -"""Codex PreToolUse 정책: 위험 명령과 테스트 없는 구현 파일 수정을 차단한다.""" - -import json -import re -import sys -from pathlib import Path -from typing import Any - -SCRIPTS_DIR = Path(__file__).resolve().parents[1] -if str(SCRIPTS_DIR) not in sys.path: - sys.path.insert(0, str(SCRIPTS_DIR)) - -from msvc_harness.config import ConfigError, load_config -from msvc_harness.tdd_policy import CPP_SUFFIXES, evaluate_paths -from hooks.validation_scope import EDIT_TOOL_NAMES, record_edit_scope - - -DANGEROUS_PATTERNS = ( - re.compile(r"\bgit\s+reset\s+--hard\b", re.IGNORECASE), - re.compile(r"\bgit\s+push\b[^\n]*--force(?:-with-lease)?\b", re.IGNORECASE), - re.compile(r"\brm\s+-rf\b", re.IGNORECASE), - re.compile( - r"\bRemove-Item\b(?=[^\n]*-Recurse\b)(?=[^\n]*-Force\b)", - re.IGNORECASE, - ), - re.compile( - r"\b(?:rmdir|rd)\b(?=[^\n]*/s\b)(?=[^\n]*/q\b)", - re.IGNORECASE, - ), - re.compile(r"\bDROP\s+TABLE\b", re.IGNORECASE), -) -EXECUTOR_OWNED_GIT = re.compile( - r"\bgit(?:\.exe)?\b[^\r\n;&|]*\b(?:commit|push|switch|checkout|branch|tag|" - r"merge|rebase|reset|cherry-pick|revert|stash|clean|update-ref|symbolic-ref|" - r"worktree|fetch|pull)\b", - re.IGNORECASE, -) -PATCH_PATH = re.compile( - r"^\*\*\* (?:(?:Add|Update|Delete) File:|Move to:) (?P.+?)\s*$", - re.MULTILINE, -) - - -class HookInputError(ValueError): - pass - - -def _tool_input(payload: dict[str, Any]) -> dict[str, Any]: - value = payload.get("tool_input") - if not isinstance(value, dict): - raise HookInputError("hook tool_input must be an object") - return value - - -def _candidate_paths(payload: dict[str, Any], root: Path) -> list[Path]: - tool_input = _tool_input(payload) - raw_paths: list[str] = [] - for key in ("path", "file_path"): - value = tool_input.get(key) - if isinstance(value, str) and value.strip(): - raw_paths.append(value.strip()) - - edits = tool_input.get("edits") - if isinstance(edits, list): - for edit in edits: - if not isinstance(edit, dict): - continue - value = edit.get("path") - if isinstance(value, str) and value.strip(): - raw_paths.append(value.strip()) - - for key in ("command", "patch", "input"): - value = tool_input.get(key) - if isinstance(value, str): - raw_paths.extend(match.group("path") for match in PATCH_PATH.finditer(value)) - - paths: list[Path] = [] - for raw_path in raw_paths: - path = Path(raw_path) - paths.append(path.resolve() if path.is_absolute() else (root / path).resolve()) - return list(dict.fromkeys(paths)) - - -def evaluate(payload: dict[str, Any], root: Path) -> str | None: - """Return a blocking reason, or None when the tool call is allowed.""" - tool_name = payload.get("tool_name") - if not isinstance(tool_name, str) or not tool_name: - raise HookInputError("hook tool_name must be a non-empty string") - tool_input = _tool_input(payload) - - if tool_name in {"Bash", "shell_command", "PowerShell"}: - command = tool_input.get("command") - if not isinstance(command, str): - raise HookInputError("shell tool_input.command must be a string") - if EXECUTOR_OWNED_GIT.search(command): - return ( - "Harness-owned Git operation detected. The implementation session " - "must leave branch, commit, push, and history operations to the Executor." - ) - if any( - pattern.search(command) for pattern in DANGEROUS_PATTERNS - ): - return "위험한 명령어가 감지되어 실행을 차단했습니다." - - if tool_name not in EDIT_TOOL_NAMES: - return None - - paths = _candidate_paths(payload, root) - if not paths: - raise HookInputError( - f"{tool_name} input did not contain a path that can be checked" - ) - try: - config = load_config(root) - except ConfigError as exc: - if any(path.suffix.lower() in CPP_SUFFIXES for path in paths): - return f"TDD GUARD: .harness/config.json must be repaired: {exc}" - return None - return evaluate_paths(paths, root, config.tdd) - - -def main() -> int: - try: - payload = json.load(sys.stdin) - if not isinstance(payload, dict): - raise HookInputError("hook input must be a JSON object") - cwd = payload.get("cwd") - if cwd is not None and not isinstance(cwd, str): - raise HookInputError("hook cwd must be a string") - - root = Path(cwd or Path.cwd()).resolve() - reason = evaluate(payload, root) - except ( - json.JSONDecodeError, - HookInputError, - ConfigError, - KeyError, - ValueError, - OSError, - ) as exc: - print(f"TDD GUARD: hook input rejected: {exc}", file=sys.stderr) - return 2 - - if reason: - print(reason, file=sys.stderr) - return 2 - if payload["tool_name"] in EDIT_TOOL_NAMES: - try: - record_edit_scope(payload, root, _candidate_paths(payload, root)) - except (ValueError, OSError) as exc: - print(f"TDD GUARD: edit scope could not be recorded: {exc}", file=sys.stderr) - return 2 - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/hooks/stop_validation.py b/scripts/hooks/stop_validation.py deleted file mode 100644 index 7c3555f..0000000 --- a/scripts/hooks/stop_validation.py +++ /dev/null @@ -1,168 +0,0 @@ -#!/usr/bin/env python3 -"""Codex Stop hook: validate discovered C/C++ projects with MSVC.""" - -import json -import os -import subprocess -import sys -import time -from pathlib import Path - - -SCRIPTS = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(SCRIPTS)) - -from msvc_harness.adapters.base import AdapterError -from msvc_harness.adapters.cmake import CMakeAdapter -from msvc_harness.adapters.msbuild import MSBuildAdapter -from msvc_harness.config import ConfigError, load_config -from msvc_harness.discovery import DiscoveryError, discover_project -from msvc_harness.models import ProjectKind -from msvc_harness.process import ValidationFailure, execute_plan -from msvc_harness.toolchain import ToolchainError, discover_toolchain -from hooks.validation_scope import is_document_only_turn - - -REENTRY_ENV = "CODEX_STOP_VALIDATION_ACTIVE" -TOTAL_TIMEOUT_SECONDS = 1800 - - -def _remaining(deadline, clock, stage): - remaining = deadline - clock() - if remaining <= 0: - raise ValidationFailure(f"{stage} timed out before it could start") - return remaining - - -def _project_root( - cwd: Path, - *, - deadline: float, - run=subprocess.run, - clock=time.monotonic, -) -> Path: - argv = ["git", "rev-parse", "--show-toplevel"] - resolved_cwd = cwd.resolve() - try: - result = run( - argv, - cwd=resolved_cwd, - capture_output=True, - text=True, - shell=False, - timeout=_remaining(deadline, clock, "repository discovery"), - ) - except subprocess.TimeoutExpired as exc: - raise ValidationFailure( - f"repository discovery timed out; argv={argv!r}; " - f"cwd={str(resolved_cwd)!r}" - ) from exc - if result.returncode == 0 and result.stdout.strip(): - return Path(result.stdout.strip()).resolve() - return resolved_cwd - - -def run_validations( - root: Path, - *, - deadline: float | None = None, - clock=time.monotonic, -) -> tuple[bool, str]: - """Build and test a discovered C/C++ project, when one exists.""" - if deadline is None: - deadline = clock() + TOTAL_TIMEOUT_SECONDS - try: - config = load_config(root) - discovery = discover_project(root, config) - if discovery.selection is None: - return True, "" - selection = discovery.selection - tools = discover_toolchain( - selection.kind, - deadline=deadline, - clock=clock, - ) - adapter = ( - CMakeAdapter() - if selection.kind is ProjectKind.CMAKE - else MSBuildAdapter() - ) - plan = adapter.create_plan(root, selection, config, tools) - child_env = os.environ.copy() - child_env[REENTRY_ENV] = "1" - execute_plan( - plan, - root, - env=child_env, - deadline=deadline, - clock=clock, - ) - return True, "" - except ( - ConfigError, - DiscoveryError, - ToolchainError, - AdapterError, - ValidationFailure, - OSError, - ) as exc: - return False, str(exc) - - -def _emit_stop_response(message: str) -> None: - print( - json.dumps( - { - "decision": "block", - "reason": message, - }, - ensure_ascii=False, - ) - ) - - -def main(*, run=subprocess.run, clock=time.monotonic) -> int: - if os.environ.get(REENTRY_ENV) == "1": - return 0 - - try: - raw_payload = sys.stdin.read() - payload = json.loads(raw_payload) if raw_payload.strip() else {} - if not isinstance(payload, dict): - raise TypeError("hook input must be a JSON object") - cwd = payload.get("cwd") - if cwd is not None and not isinstance(cwd, str): - raise TypeError("hook cwd must be a string") - stop_hook_active = payload.get("stop_hook_active", False) - if not isinstance(stop_hook_active, bool): - raise TypeError("stop_hook_active must be a boolean") - except (json.JSONDecodeError, TypeError) as exc: - _emit_stop_response(f"validation hook input rejected: {exc}") - return 0 - - if stop_hook_active: - return 0 - - deadline = clock() + TOTAL_TIMEOUT_SECONDS - try: - root = _project_root( - Path(cwd or Path.cwd()), - deadline=deadline, - run=run, - clock=clock, - ) - if is_document_only_turn(payload, root): - return 0 - ok, message = run_validations(root, deadline=deadline, clock=clock) - except Exception as exc: - _emit_stop_response(f"validation hook failed: {exc}") - return 0 - - if ok: - return 0 - _emit_stop_response(message) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/hooks/validation_scope.py b/scripts/hooks/validation_scope.py deleted file mode 100644 index 5bfd4c9..0000000 --- a/scripts/hooks/validation_scope.py +++ /dev/null @@ -1,109 +0,0 @@ -"""Track whether a Codex turn edited Markdown files only.""" - -import hashlib -import json -from pathlib import Path -from typing import Any, Iterable - - -EDIT_TOOL_NAMES = frozenset({"apply_patch", "Edit", "MultiEdit", "Write"}) -STATE_VERSION = 1 - - -def _identifier(payload: dict[str, Any], name: str) -> str | None: - value = payload.get(name) - if not isinstance(value, str) or not value.strip(): - return None - return value - - -def _digest(value: str) -> str: - return hashlib.sha256(value.encode("utf-8")).hexdigest() - - -def _state_path(root: Path, session_id: str) -> Path: - return root / ".harness" / "hook-state" / f"{_digest(session_id)}.json" - - -def _is_markdown_in_root(path: Path, root: Path) -> bool: - resolved_root = root.resolve() - resolved_path = path.resolve() - try: - resolved_path.relative_to(resolved_root) - except ValueError: - return False - return resolved_path.suffix.lower() == ".md" - - -def record_edit_scope( - payload: dict[str, Any], - root: Path, - paths: Iterable[Path], -) -> bool: - """Record an allowed edit; return False when turn identity is unavailable.""" - session_id = _identifier(payload, "session_id") - turn_id = _identifier(payload, "turn_id") - if session_id is None or turn_id is None: - return False - - edit_paths = list(paths) - if not edit_paths: - raise ValueError("edit scope requires at least one path") - - turn_digest = _digest(turn_id) - state_path = _state_path(root, session_id) - document_only = all( - _is_markdown_in_root(path, root) for path in edit_paths - ) - - if state_path.is_file(): - try: - previous = json.loads(state_path.read_text(encoding="utf-8")) - valid_previous = ( - isinstance(previous, dict) - and previous.get("version") == STATE_VERSION - and isinstance(previous.get("turn"), str) - and isinstance(previous.get("document_only"), bool) - ) - if not valid_previous: - document_only = False - elif previous["turn"] == turn_digest: - document_only = previous["document_only"] and document_only - except (json.JSONDecodeError, OSError): - document_only = False - - state_path.parent.mkdir(parents=True, exist_ok=True) - temporary_path = state_path.with_suffix(".tmp") - temporary_path.write_text( - json.dumps( - { - "version": STATE_VERSION, - "turn": turn_digest, - "document_only": document_only, - } - ), - encoding="utf-8", - ) - temporary_path.replace(state_path) - return True - - -def is_document_only_turn(payload: dict[str, Any], root: Path) -> bool: - """Return True only for a valid state proving Markdown-only edits.""" - session_id = _identifier(payload, "session_id") - turn_id = _identifier(payload, "turn_id") - if session_id is None or turn_id is None: - return False - - state_path = _state_path(root, session_id) - try: - state = json.loads(state_path.read_text(encoding="utf-8")) - except (FileNotFoundError, json.JSONDecodeError, OSError): - return False - - return ( - isinstance(state, dict) - and state.get("version") == STATE_VERSION - and state.get("turn") == _digest(turn_id) - and state.get("document_only") is True - ) diff --git a/scripts/msvc_harness/config.py b/scripts/msvc_harness/config.py index 8723605..aab8571 100644 --- a/scripts/msvc_harness/config.py +++ b/scripts/msvc_harness/config.py @@ -1,16 +1,9 @@ import json +import sys from pathlib import Path -from string import Formatter from typing import Any -from .models import CMakeConfig, HarnessConfig, MSBuildConfig, TDDConfig - -DEFAULT_TEST_PATTERNS = ( - "{stem}_test.cpp", - "{stem}_tests.cpp", - "test_{stem}.cpp", - "{stem}.test.cpp", -) +from .models import CMakeConfig, HarnessConfig, MSBuildConfig class ConfigError(ValueError): @@ -60,38 +53,6 @@ def _string_array(value: Any, label: str) -> tuple[str, ...]: ) -def _validate_test_pattern(pattern: str) -> None: - candidate = Path(pattern) - if ( - candidate.is_absolute() - or bool(candidate.drive) - or "/" in pattern - or "\\" in pattern - or candidate.name != pattern - ): - raise ConfigError( - "every tdd.testPatterns entry must be a safe basename pattern" - ) - try: - fields = [ - (field_name, format_spec, conversion) - for _, field_name, format_spec, conversion in Formatter().parse(pattern) - if field_name is not None - ] - except ValueError as exc: - raise ConfigError(f"invalid tdd.testPatterns entry: {exc}") from exc - if ( - not fields - or any( - field_name != "stem" or format_spec or conversion - for field_name, format_spec, conversion in fields - ) - ): - raise ConfigError( - "every tdd.testPatterns entry may contain only the {stem} field" - ) - - def load_config(root: Path) -> HarnessConfig: root = root.resolve() config_path = root / ".harness" / "config.json" @@ -166,21 +127,12 @@ def load_config(root: Path) -> HarnessConfig: else None ) - tdd_data = _mapping(data.get("tdd", {}), "tdd") - _reject_unknown(tdd_data, {"testRoots", "testPatterns", "exclude"}, "tdd") - raw_test_roots = _string_array(tdd_data["testRoots"], "tdd.testRoots") if "testRoots" in tdd_data else ("tests", "test") - test_roots = tuple(_repo_path(root, item, "tdd.testRoots") for item in raw_test_roots) - test_patterns = _string_array(tdd_data["testPatterns"], "tdd.testPatterns") if "testPatterns" in tdd_data else DEFAULT_TEST_PATTERNS - for pattern in test_patterns: - _validate_test_pattern(pattern) - exclude = _string_array(tdd_data["exclude"], "tdd.exclude") if "exclude" in tdd_data else () - for item in exclude: - _repo_path(root, item, "tdd.exclude") + if "tdd" in data: + print("Deprecated config field 'tdd' is ignored; it may be removed.", file=sys.stderr) return HarnessConfig( version=1, project_type=project_type, cmake=CMakeConfig(source_dir, binary_dir, configure_preset, build_preset, test_preset), msbuild=MSBuildConfig(solution, configuration, platform, test_command), - tdd=TDDConfig(test_roots, test_patterns, exclude), ) diff --git a/scripts/msvc_harness/discovery.py b/scripts/msvc_harness/discovery.py index 0c51fea..69218f6 100644 --- a/scripts/msvc_harness/discovery.py +++ b/scripts/msvc_harness/discovery.py @@ -1,7 +1,6 @@ from pathlib import Path from .models import DiscoveryResult, HarnessConfig, ProjectKind, ProjectSelection -from .tdd_policy import find_cpp_files class DiscoveryError(RuntimeError): @@ -68,10 +67,4 @@ def discover_project(root: Path, config: HarnessConfig) -> DiscoveryResult: ProjectSelection(ProjectKind.MSBUILD, projects[0]) ) - cpp_files = find_cpp_files(root) - if cpp_files: - raise DiscoveryError( - "C/C++ files exist but no CMakeLists.txt, preset, .sln, or .vcxproj " - "was found; configure projectType and project path" - ) - return DiscoveryResult(None, ()) + return DiscoveryResult(None) diff --git a/scripts/msvc_harness/models.py b/scripts/msvc_harness/models.py index 1c03085..fe640aa 100644 --- a/scripts/msvc_harness/models.py +++ b/scripts/msvc_harness/models.py @@ -30,20 +30,12 @@ class MSBuildConfig: test_command: tuple[str, ...] | None = None -@dataclass(frozen=True) -class TDDConfig: - test_roots: tuple[Path, ...] - test_patterns: tuple[str, ...] - exclude: tuple[str, ...] = () - - @dataclass(frozen=True) class HarnessConfig: version: int project_type: str cmake: CMakeConfig msbuild: MSBuildConfig - tdd: TDDConfig @dataclass(frozen=True) @@ -55,7 +47,6 @@ class ProjectSelection: @dataclass(frozen=True) class DiscoveryResult: selection: ProjectSelection | None - cpp_files: tuple[Path, ...] = () @dataclass(frozen=True) diff --git a/scripts/msvc_harness/tdd_policy.py b/scripts/msvc_harness/tdd_policy.py deleted file mode 100644 index b5f5b8c..0000000 --- a/scripts/msvc_harness/tdd_policy.py +++ /dev/null @@ -1,88 +0,0 @@ -from fnmatch import fnmatch -from pathlib import Path - -CPP_SUFFIXES = frozenset({".c", ".cc", ".cpp", ".cxx", ".h", ".hpp", ".hxx"}) -DEFAULT_EXCLUDES = ( - ".harness/build/**", - "build/**", - "out/**", - "cmake-build-*/**", - "third_party/**", - "external/**", - "vendor/**", - "generated/**", -) - - -def is_excluded_path(path: Path, root: Path, extra: tuple[str, ...] = ()) -> bool: - try: - relative = path.resolve().relative_to(root.resolve()).as_posix() - except ValueError: - return False - return any(fnmatch(relative, pattern) for pattern in DEFAULT_EXCLUDES + extra) - - -def find_cpp_files( - root: Path, - extra_excludes: tuple[str, ...] = (), -) -> tuple[Path, ...]: - found = ( - path - for path in root.resolve().rglob("*") - if path.is_file() - and path.suffix.lower() in CPP_SUFFIXES - and not is_excluded_path(path, root, extra_excludes) - ) - return tuple(sorted(found)) - - -def is_test_file(path: Path, root: Path, config) -> bool: - resolved = path.resolve() - if any(root == resolved or root in resolved.parents for root in config.test_roots): - return True - relative = resolved.relative_to(root.resolve()) - if {"test", "tests"} & {part.lower() for part in relative.parts}: - return True - stem = resolved.stem.lower() - return stem.startswith("test_") or stem.endswith(("_test", "_tests", ".test")) - - -def matching_test_exists(path: Path, config) -> bool: - names = tuple(pattern.format(stem=path.stem) for pattern in config.test_patterns) - roots = ( - *config.test_roots, - path.parent / "tests", - path.parent / "test", - ) - for root in roots: - if not root.is_dir(): - continue - for name in names: - if any(candidate.is_file() for candidate in root.rglob(name)): - return True - return False - - -def evaluate_paths(paths, root: Path, config) -> str | None: - root = root.resolve() - for raw in paths: - path = raw.resolve() - try: - path.relative_to(root) - except ValueError: - return f"TDD GUARD: '{path}' is outside the repository" - if path.suffix.lower() not in CPP_SUFFIXES: - continue - if ( - path.name.lower() == "main.cpp" - or is_excluded_path(path, root, config.exclude) - or is_test_file(path, root, config) - ): - continue - if not matching_test_exists(path, config): - expected = config.test_patterns[0].format(stem=path.stem) - return ( - f"TDD GUARD: '{path.name}' requires an existing test such as " - f"'{expected}'. Add the test in a configured test root first." - ) - return None