Forráskód Böngészése

fix: limit_sync_valid/WAIT_SYNC startup race, real top-level startup tests, mutation test, and agent guard local config.

Codex Resource Selftest 4 hónapja
szülő
commit
2e8a15fb16

+ 0 - 7
.devin/config.json

@@ -1,9 +1,5 @@
 {
   "project_id": "prod2u-door-temp",
-  "protected_roots": [
-    "C:\\Users\\Administrator\\Agentworkspace\\CPLD"
-  ],
-  "active_worktree": "C:\\Users\\Administrator\\CodexTemp\\prod2u-devin-final-f159b9192a4d4e0bbdcf1585c63bb2f8",
   "authority_documents": [
     "projects/prod2u-door-temp/project.json",
     "projects/prod2u-door-temp/requirements.zh-CN.md",
@@ -18,9 +14,6 @@
     "git branch -f",
     "git update-ref"
   ],
-  "denied_paths": [
-    "C:\\Users\\Administrator\\Agentworkspace\\CPLD"
-  ],
   "hardware_access": {
     "com": false,
     "jtag": false,

+ 3 - 0
.gitignore

@@ -1,6 +1,9 @@
 # Local/private files
 *.lic
 Anlogic.lic
+.devin/config.local.json
+.agents/config.local.json
+.cursor/config.local.json
 
 # Original local archives and vendor payloads are inventoried, not tracked.
 reference/original/local_archives/**

+ 0 - 4
agent-team/contract.json

@@ -1,10 +1,6 @@
 {
   "schema": "agent-team-contract-v1",
   "project_id": "prod2u-door-temp",
-  "protected_roots": [
-    "C:\\Users\\Administrator\\Agentworkspace\\CPLD"
-  ],
-  "active_worktree": "C:\\Users\\Administrator\\CodexTemp\\prod2u-devin-final-f159b9192a4d4e0bbdcf1585c63bb2f8",
   "authority_documents": [
     "projects/prod2u-door-temp/project.json",
     "projects/prod2u-door-temp/requirements.zh-CN.md",

+ 1 - 0
config/prod2u_p4_verification_targets_v1.json

@@ -31,6 +31,7 @@
       "frame_tx_uart_tx_tb",
       "temperature_reader_config_tb",
       "prod2u_p4_normal_v3_top_tb",
+      "prod2u_p4_normal_v3_top_startup_tb",
       "output_target_ram_tb",
       "host_watchdog_tb",
       "shared_500us_tick_tb",

+ 15 - 7
src/modules/startup_close_seek.v

@@ -13,6 +13,7 @@ module startup_close_seek #(
     input  wire       clk,
     input  wire       rst_n,
     input  wire       tick_500us,
+    input  wire       limit_sync_valid,
     input  wire [1:0] limit_sync,
     output reg        startup_done,
     output reg        motor_start,
@@ -23,11 +24,12 @@ module startup_close_seek #(
     localparam integer BURST_WIDTH = (MAX_BURSTS <= 1) ? 1 : $clog2(MAX_BURSTS + 1);
     localparam integer TICK_WIDTH = (INTER_BURST_TICKS <= 1) ? 1 : $clog2(INTER_BURST_TICKS + 1);
 
-    localparam [2:0] ST_CHECK      = 3'd0;
-    localparam [2:0] ST_START      = 3'd1;
-    localparam [2:0] ST_WAIT_DONE  = 3'd2;
-    localparam [2:0] ST_WAIT_IDLE  = 3'd3;
-    localparam [2:0] ST_DONE       = 3'd4;
+    localparam [2:0] ST_WAIT_SYNC = 3'd0;
+    localparam [2:0] ST_CHECK      = 3'd1;
+    localparam [2:0] ST_START      = 3'd2;
+    localparam [2:0] ST_WAIT_DONE  = 3'd3;
+    localparam [2:0] ST_WAIT_IDLE  = 3'd4;
+    localparam [2:0] ST_DONE       = 3'd5;
 
     reg [2:0] state;
     reg [1:0] reached_mask;
@@ -35,13 +37,13 @@ module startup_close_seek #(
     reg [BURST_WIDTH-1:0] burst_count_y;
     reg [TICK_WIDTH-1:0] idle_tick;
 
-    wire [1:0] reached_mask_next = reached_mask | limit_sync;
+    wire [1:0] reached_mask_next = reached_mask | (limit_sync_valid ? limit_sync : 2'b00);
     wire [1:0] exhausted_mask = {(burst_count_y >= MAX_BURSTS), (burst_count_x >= MAX_BURSTS)};
     wire [1:0] move_mask = ~reached_mask_next & ~exhausted_mask;
 
     always @(posedge clk or negedge rst_n) begin
         if (!rst_n) begin
-            state <= ST_CHECK;
+            state <= ST_WAIT_SYNC;
             startup_done <= 1'b0;
             motor_start <= 1'b0;
             motor_active_mask <= 2'b00;
@@ -53,6 +55,12 @@ module startup_close_seek #(
         end else begin
             reached_mask <= reached_mask_next;
             case (state)
+                ST_WAIT_SYNC: begin
+                    motor_start <= 1'b0;
+                    if (limit_sync_valid) begin
+                        state <= ST_CHECK;
+                    end
+                end
                 ST_CHECK: begin
                     motor_start <= 1'b0;
                     if (move_mask == 2'b00) begin

+ 15 - 3
src/top/prod2u_p4_normal_v3_top.v

@@ -54,6 +54,8 @@ module prod2u_p4_normal_v3_top (
     (* async_reg = "true" *) reg x_limit_sync0, x_limit_sync1;
     (* async_reg = "true" *) reg y_limit_sync0, y_limit_sync1;
     wire [1:0] limit_sync;
+    reg        limit_sync_valid;
+    reg [1:0]  limit_sync_valid_cnt;
     wire temperature_start;
     wire temperature_done;
     wire tx_start;
@@ -108,11 +110,20 @@ module prod2u_p4_normal_v3_top (
             x_limit_sync1 <= 1'b0;
             y_limit_sync0 <= 1'b0;
             y_limit_sync1 <= 1'b0;
+            limit_sync_valid <= 1'b0;
+            limit_sync_valid_cnt <= 2'd0;
         end else begin
             x_limit_sync0 <= x_limit_raw;
             x_limit_sync1 <= x_limit_sync0;
             y_limit_sync0 <= y_limit_raw;
             y_limit_sync1 <= y_limit_sync0;
+            if (!limit_sync_valid) begin
+                if (limit_sync_valid_cnt < 2'd3) begin
+                    limit_sync_valid_cnt <= limit_sync_valid_cnt + 1'b1;
+                end else begin
+                    limit_sync_valid <= 1'b1;
+                end
+            end
         end
     end
 
@@ -181,9 +192,10 @@ module prod2u_p4_normal_v3_top (
         .DIR_MASK(`P4_STARTUP_DIR_MASK)
     ) u_startup_close_seek (
         .clk(sys_clk), .rst_n(sys_rst_n), .tick_500us(tick_500us),
-        .limit_sync(limit_sync), .startup_done(startup_done),
-        .motor_start(startup_motor_start), .motor_active_mask(startup_motor_active_mask),
-        .motor_dir_mask(startup_motor_dir_mask), .motor_done(motor_done)
+        .limit_sync_valid(limit_sync_valid), .limit_sync(limit_sync),
+        .startup_done(startup_done), .motor_start(startup_motor_start),
+        .motor_active_mask(startup_motor_active_mask), .motor_dir_mask(startup_motor_dir_mask),
+        .motor_done(motor_done)
     );
 
     output_target_ram #(

+ 13 - 0
tests/formal/startup_close_seek_formal.v

@@ -20,6 +20,18 @@ module startup_close_seek_formal (
     reg [2:0] reset_cycles;
     reg [3:0] burst_counter;
     reg motor_busy;
+    reg formal_sync_valid;
+
+    // The synchronizer is modelled as invalid for the first three cycles after reset.
+    always @(posedge clk or negedge rst_n) begin
+        if (!rst_n) begin
+            formal_sync_valid <= 1'b0;
+        end else if (reset_cycles < 3) begin
+            formal_sync_valid <= 1'b0;
+        end else begin
+            formal_sync_valid <= 1'b1;
+        end
+    end
 
     startup_close_seek #(
         .FIXED_STEPS(FORMAL_FIXED_STEPS),
@@ -32,6 +44,7 @@ module startup_close_seek_formal (
         .clk(clk),
         .rst_n(rst_n),
         .tick_500us(tick_500us),
+        .limit_sync_valid(formal_sync_valid),
         .limit_sync(limit_sync),
         .startup_done(startup_done),
         .motor_start(motor_start),

+ 137 - 0
tests/sim/prod2u_p4_normal_v3_top_startup_tb.v

@@ -0,0 +1,137 @@
+`timescale 1ns/1ps
+
+module prod2u_p4_normal_v3_top_startup_tb;
+    reg sys_clk = 1'b0;
+    reg host_uart_rx = 1'b1;
+    wire host_uart_tx;
+    wire [7:0] ptc_pwm_out;
+    wire [3:0] fan_pwm_out;
+    wire motor_en_n;
+    wire x_step;
+    wire x_dir;
+    wire y_step;
+    wire y_dir;
+    reg x_limit_raw = 1'b0;
+    reg y_limit_raw = 1'b0;
+    tri temp_scl;
+    tri temp_sda;
+
+    localparam integer FAST_TICK_DIV = 10;
+    reg [31:0] fast_tick_div;
+    reg fast_tick;
+
+    integer startup_x_steps;
+    integer startup_y_steps;
+    integer host_x_steps;
+    integer host_y_steps;
+    reg prev_x_step;
+    reg prev_y_step;
+    reg startup_phase;
+
+    always #1 sys_clk = ~sys_clk;
+
+    prod2u_p4_normal_v3_top dut (
+        .sys_clk(sys_clk), .host_uart_rx(host_uart_rx), .host_uart_tx(host_uart_tx),
+        .ptc_pwm_out(ptc_pwm_out), .fan_pwm_out(fan_pwm_out),
+        .motor_en_n(motor_en_n), .x_step(x_step), .x_dir(x_dir), .y_step(y_step), .y_dir(y_dir),
+        .x_limit_raw(x_limit_raw), .y_limit_raw(y_limit_raw),
+        .temp_scl(temp_scl), .temp_sda(temp_sda)
+    );
+
+    // Accelerate the 500us tick so the motor engine completes in simulation time.
+    initial begin
+        fast_tick = 1'b0;
+        fast_tick_div = 0;
+        force dut.tick_500us = fast_tick;
+    end
+
+    always @(posedge sys_clk) begin
+        if (fast_tick_div + 1 >= FAST_TICK_DIV) begin
+            fast_tick_div <= 0;
+            fast_tick <= 1'b1;
+        end else begin
+            fast_tick_div <= fast_tick_div + 1'b1;
+            fast_tick <= 1'b0;
+        end
+    end
+
+    always @(posedge sys_clk) begin
+        prev_x_step <= x_step;
+        prev_y_step <= y_step;
+        if (startup_phase) begin
+            if (!prev_x_step && x_step) startup_x_steps <= startup_x_steps + 1;
+            if (!prev_y_step && y_step) startup_y_steps <= startup_y_steps + 1;
+        end else begin
+            if (!prev_x_step && x_step) host_x_steps <= host_x_steps + 1;
+            if (!prev_y_step && y_step) host_y_steps <= host_y_steps + 1;
+        end
+    end
+
+    task wait_for_startup_done;
+        begin
+            while (!dut.startup_done) @(posedge sys_clk);
+        end
+    endtask
+
+    task drive_host_motor;
+        begin
+            @(negedge sys_clk);
+            force dut.host_motor_start = 1'b1;
+            force dut.host_motor_active_mask = 2'b11;
+            force dut.host_motor_dir_mask = 2'b11;
+            @(posedge sys_clk);
+            @(negedge sys_clk);
+            release dut.host_motor_start;
+            release dut.host_motor_active_mask;
+            release dut.host_motor_dir_mask;
+        end
+    endtask
+
+    initial begin
+        startup_x_steps = 0;
+        startup_y_steps = 0;
+        host_x_steps = 0;
+        host_y_steps = 0;
+        startup_phase = 1'b1;
+        prev_x_step = 1'b0;
+        prev_y_step = 1'b0;
+
+        // Scenario: both raw limits are already high at power-on.
+        x_limit_raw = 1'b1;
+        y_limit_raw = 1'b1;
+
+        // Wait for power-on reset and synchronizer valid.
+        repeat (1100) @(posedge sys_clk);
+        wait_for_startup_done();
+
+        if (startup_x_steps !== 0)
+            $fatal(1, "x_step rising edges during startup with both limits high: %0d", startup_x_steps);
+        if (startup_y_steps !== 0)
+            $fatal(1, "y_step rising edges during startup with both limits high: %0d", startup_y_steps);
+
+        // Hand over to host-motor phase and count steps independently.
+        startup_phase = 1'b0;
+        drive_host_motor();
+
+        // Wait for the host motor to finish 450 steps on each axis.
+        while (!dut.u_motor_engine.done) @(posedge sys_clk);
+
+        if (host_x_steps !== 450)
+            $fatal(1, "expected host x_step=450, got %0d", host_x_steps);
+        if (host_y_steps !== 450)
+            $fatal(1, "expected host y_step=450, got %0d", host_y_steps);
+
+        // Startup pulses must not satisfy the 450-step host motor assertion.
+        if (startup_x_steps == 450)
+            $fatal(1, "startup x_step count must not equal host 450-step assertion");
+        if (startup_y_steps == 450)
+            $fatal(1, "startup y_step count must not equal host 450-step assertion");
+
+        $display("prod2u_p4_normal_v3_top_startup_tb PASS");
+        $finish;
+    end
+
+    initial begin
+        #100000000 $fatal(1, "top startup test timeout");
+    end
+endmodule

+ 38 - 1
tests/sim/startup_close_seek_tb.v

@@ -5,6 +5,7 @@ module startup_close_seek_tb;
     reg rst_n = 1'b0;
     reg tick_500us = 1'b0;
     reg [1:0] limit = 2'b00;
+    reg limit_sync_valid = 1'b0;
     wire startup_done;
     wire motor_start;
     wire [1:0] motor_active_mask;
@@ -29,6 +30,7 @@ module startup_close_seek_tb;
         .clk(clk),
         .rst_n(rst_n),
         .tick_500us(tick_500us),
+        .limit_sync_valid(limit_sync_valid),
         .limit_sync(limit),
         .startup_done(startup_done),
         .motor_start(motor_start),
@@ -46,6 +48,14 @@ module startup_close_seek_tb;
         end
     endtask
 
+    task wait_sync_valid;
+        begin
+            // startup_close_seek transitions out of WAIT_SYNC only when limit_sync_valid is 1.
+            repeat (3) @(posedge clk);
+            limit_sync_valid = 1'b1;
+        end
+    endtask
+
     // Fake motor engine: assert done for one cycle shortly after start.
     reg motor_busy;
     always @(posedge clk or negedge rst_n) begin
@@ -82,12 +92,39 @@ module startup_close_seek_tb;
         if (motor_start && !previous_motor_start) burst_count <= burst_count + 1;
     end
 
+    always @(posedge clk) begin
+        if (!limit_sync_valid && motor_start) begin
+            $fatal(1, "motor_start asserted before limit_sync_valid");
+        end
+    end
+
     initial begin
+        // Scenario 1: both limits already high. Startup must finish without any motor burst.
+        limit = 2'b11;
+        limit_sync_valid = 1'b0;
+        burst_count = 0;
         repeat (3) @(posedge clk);
         rst_n = 1'b1;
+        wait_sync_valid();
+
+        while (!startup_done) begin
+            pulse_tick();
+        end
+        if (burst_count !== 0) $fatal(1, "expected 0 bursts when both limits are high, got %0d", burst_count);
+        if (motor_active_mask !== 2'b00) $fatal(1, "motor_active_mask not zero after done");
+        if (motor_dir_mask !== 2'b00) $fatal(1, "motor_dir_mask not zero after done");
+        if (motor_start !== 1'b0) $fatal(1, "motor_start not zero after done");
+
+        // Scenario 2: no limit. Should run MAX_BURSTS (10) bursts and then assert done.
+        rst_n = 1'b0;
+        limit = 2'b00;
+        limit_sync_valid = 1'b0;
+        burst_count = 0;
         @(negedge clk);
+        repeat (3) @(posedge clk);
+        rst_n = 1'b1;
+        wait_sync_valid();
 
-        // No limit: should run MAX_BURSTS (10) bursts and then assert done.
         while (!startup_done) begin
             pulse_tick();
         end

+ 162 - 0
tests/unit/test_agent_guard.py

@@ -0,0 +1,162 @@
+"""Tests for the cross-tool agent guard."""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from typing import Any
+
+ROOT = Path(__file__).resolve().parents[2]
+GUARD_PATH = ROOT / "tools" / "agent_guard.py"
+
+
+def _git(*args: str, cwd: Path) -> subprocess.CompletedProcess[str]:
+    return subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True)
+
+
+def _init_temp_repo() -> Path:
+    """Create a temporary git repository with a single commit."""
+    tmp = Path(tempfile.mkdtemp(prefix="agent_guard_repo_"))
+    _git("init", cwd=tmp)
+    _git("config", "user.email", "guard-test@example.com", cwd=tmp)
+    _git("config", "user.name", "Guard Test", cwd=tmp)
+    (tmp / ".gitignore").write_text("*.local\n", encoding="utf-8")
+    (tmp / "README.md").write_text("# temp\n", encoding="utf-8")
+    _git("add", ".", cwd=tmp)
+    _git("commit", "-m", "init", cwd=tmp)
+    _git("checkout", "-b", "devin/test-guard", cwd=tmp)
+    return tmp
+
+
+def _head(repo: Path) -> str:
+    return _git("rev-parse", "HEAD", cwd=repo).stdout.strip()
+
+
+def _write_local_config(
+    repo: Path,
+    *,
+    active_worktree: str | None = None,
+    expected_branch: str = "devin/test-guard",
+    expected_head: str | None = None,
+    owned_paths: list[str] | None = None,
+    protected_roots: list[str] | None = None,
+) -> None:
+    devin = repo / ".devin"
+    devin.mkdir(exist_ok=True)
+    tracked = {
+        "project_id": "prod2u-door-temp",
+        "denied_commands": ["git reset"],
+        "hardware_access": {"com": False, "jtag": False},
+    }
+    (devin / "config.json").write_text(json.dumps(tracked, indent=2), encoding="utf-8")
+    local: dict[str, Any] = {}
+    if active_worktree is not None:
+        local["active_worktree"] = active_worktree
+    local["expected_branch"] = expected_branch
+    if expected_head is not None:
+        local["expected_head"] = expected_head
+    if owned_paths is not None:
+        local["owned_paths"] = owned_paths
+    if protected_roots is not None:
+        local["protected_roots"] = protected_roots
+    (devin / "config.local.json").write_text(json.dumps(local, indent=2), encoding="utf-8")
+
+
+def _guard(
+    cwd: Path,
+    *,
+    target: str | None = None,
+    command: str | None = None,
+    env: dict[str, str] | None = None,
+) -> tuple[int, str]:
+    env = env or os.environ.copy()
+    argv = [str(sys.executable), str(GUARD_PATH), "--event", "pre_tool_use", "--cwd", str(cwd)]
+    if target:
+        argv.extend(["--target-path", target])
+    if command:
+        argv.extend(["--command", command])
+    result = subprocess.run(
+        argv,
+        cwd=cwd,
+        capture_output=True,
+        text=True,
+        env=env,
+    )
+    return result.returncode, result.stdout
+
+
+class AgentGuardTests(unittest.TestCase):
+    def test_error_cwd_not_a_git_repository(self):
+        tmp = Path(tempfile.mkdtemp(prefix="agent_guard_not_git_"))
+        rc, stdout = _guard(tmp)
+        self.assertEqual(rc, 1)
+        self.assertIn("not_a_git_repository", stdout)
+
+    def test_protected_repository(self):
+        repo = _init_temp_repo()
+        _write_local_config(
+            repo,
+            active_worktree=str(repo),
+            expected_head=_head(repo),
+            protected_roots=[str(repo)],
+        )
+        rc, stdout = _guard(repo)
+        self.assertEqual(rc, 1)
+        self.assertIn("protected_repository", stdout)
+
+    def test_outside_owned_paths(self):
+        repo = _init_temp_repo()
+        _write_local_config(
+            repo,
+            active_worktree=str(repo),
+            expected_branch="devin/test-guard",
+            expected_head=_head(repo),
+            owned_paths=["src/**"],
+        )
+        target = str(repo / "tests" / "example.v")
+        os.makedirs(Path(target).parent, exist_ok=True)
+        Path(target).write_text("module example; endmodule\n", encoding="utf-8")
+        rc, stdout = _guard(repo, target=target)
+        self.assertEqual(rc, 1)
+        self.assertIn("outside_owned_paths", stdout)
+
+    def test_allowed_inside_owned_paths(self):
+        repo = _init_temp_repo()
+        _write_local_config(
+            repo,
+            active_worktree=str(repo),
+            expected_branch="devin/test-guard",
+            expected_head=_head(repo),
+            owned_paths=["src/**", "tests/**"],
+        )
+        target = str(repo / "src" / "example.v")
+        os.makedirs(Path(target).parent, exist_ok=True)
+        Path(target).write_text("module example; endmodule\n", encoding="utf-8")
+        rc, stdout = _guard(repo, target=target)
+        self.assertEqual(rc, 0)
+        self.assertIn('"allowed": true', stdout)
+
+    def test_forbidden_command(self):
+        repo = _init_temp_repo()
+        _write_local_config(
+            repo,
+            active_worktree=str(repo),
+            expected_branch="devin/test-guard",
+            expected_head=_head(repo),
+            owned_paths=["src/**"],
+        )
+        target = str(repo / "src" / "example.v")
+        os.makedirs(Path(target).parent, exist_ok=True)
+        Path(target).write_text("module example; endmodule\n", encoding="utf-8")
+        rc, stdout = _guard(repo, target=target, command="git reset --hard")
+        self.assertEqual(rc, 1)
+        self.assertIn("denied_git_command", stdout)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 15 - 0
tests/unit/test_startup_close_seek.py

@@ -64,7 +64,22 @@ class StartupCloseSeekContractTests(unittest.TestCase):
     def test_top_level_synchronizes_limit_inputs(self):
         top = TOP_PATH.read_text(encoding="utf-8")
         self.assertRegex(top, r"x_limit_sync0\s*<=\s*x_limit_raw")
+        self.assertRegex(top, r"x_limit_sync1\s*<=\s*x_limit_sync0")
         self.assertRegex(top, r"y_limit_sync0\s*<=\s*y_limit_raw")
+        self.assertRegex(top, r"y_limit_sync1\s*<=\s*y_limit_sync0")
+        self.assertIn("limit_sync_valid", top)
+        self.assertRegex(top, r"limit_sync_valid_cnt\s*<\s*2'd3")
+
+    def test_top_level_gates_startup_until_sync_valid(self):
+        top = TOP_PATH.read_text(encoding="utf-8")
+        self.assertIn(".limit_sync_valid(limit_sync_valid)", top)
+
+    def test_startup_module_has_wait_sync_state(self):
+        source = (ROOT / "src" / "modules" / "startup_close_seek.v").read_text(encoding="utf-8")
+        self.assertIn("ST_WAIT_SYNC", source)
+        self.assertIn("limit_sync_valid", source)
+        self.assertIn("if (limit_sync_valid)", source)
+        self.assertIn("reached_mask_next = reached_mask | (limit_sync_valid ? limit_sync : 2'b00)", source)
 
     def test_startup_module_has_expected_parameters(self):
         source = (ROOT / "src" / "modules" / "startup_close_seek.v").read_text(encoding="utf-8")

+ 125 - 0
tests/unit/test_startup_mutation.py

@@ -0,0 +1,125 @@
+"""Mutation test: removing WAIT_SYNC must cause startup_close_seek to fail."""
+
+from __future__ import annotations
+
+import re
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+SOURCE = ROOT / "src" / "modules" / "startup_close_seek.v"
+
+# Import harness tooling for toolchain discovery.
+sys.path.insert(0, str(ROOT / "tools"))
+import prod2u_p4_harness  # type: ignore
+
+
+def mutated_source() -> str:
+    text = SOURCE.read_text(encoding="utf-8")
+    # Make the module ignore limit_sync_valid by removing the WAIT_SYNC state and
+    # the valid gating on reached_mask_next.
+    text = re.sub(
+        r"state\s*<=\s*ST_WAIT_SYNC;",
+        "state <= ST_CHECK;",
+        text,
+        count=1,
+    )
+    text = re.sub(
+        r"reached_mask\s*\|\s*\(limit_sync_valid\s*\?\s*limit_sync\s*:\s*2'b00\)",
+        "reached_mask | limit_sync",
+        text,
+        count=1,
+    )
+    # Remove the WAIT_SYNC case block entirely.
+    text = re.sub(
+        r"ST_WAIT_SYNC:\s*begin\s*motor_start\s*<=\s*1'b0;\s*if\s*\(limit_sync_valid\)\s*begin\s*state\s*<=\s*ST_CHECK;\s*end\s*end\s*",
+        "",
+        text,
+        count=1,
+    )
+    return text
+
+
+class StartupMutationTests(unittest.TestCase):
+    def test_removing_wait_sync_fails(self):
+        """A mutant that ignores limit_sync_valid must assert motor_start early."""
+        iverilog = prod2u_p4_harness.resolve_tool("iverilog")
+        vvp = prod2u_p4_harness.resolve_tool("vvp")
+        if not iverilog or not vvp:
+            self.skipTest("iverilog/vvp not available")
+
+        with tempfile.TemporaryDirectory() as d:
+            tmp = Path(d)
+            mutated = tmp / "startup_close_seek_mut.v"
+            mutated.write_text(mutated_source(), encoding="utf-8")
+            tb = tmp / "tb.v"
+            tb.write_text(
+                """
+`timescale 1ns/1ps
+module tb;
+    reg clk = 1'b0;
+    reg rst_n = 1'b0;
+    reg tick_500us = 1'b0;
+    reg [1:0] limit = 2'b00;
+    reg limit_sync_valid = 1'b0;
+    wire startup_done;
+    wire motor_start;
+    wire [1:0] motor_active_mask;
+    wire [1:0] motor_dir_mask;
+    reg motor_done = 1'b0;
+
+    always #1 clk = ~clk;
+
+    startup_close_seek #(
+        .FIXED_STEPS(450),
+        .DIR_SETUP_TICKS(2),
+        .STEP_HALF_CYCLES(12500),
+        .MAX_BURSTS(10),
+        .INTER_BURST_TICKS(4),
+        .DIR_MASK(2'b11)
+    ) dut (
+        .clk(clk), .rst_n(rst_n), .tick_500us(tick_500us),
+        .limit_sync_valid(limit_sync_valid), .limit_sync(limit),
+        .startup_done(startup_done), .motor_start(motor_start),
+        .motor_active_mask(motor_active_mask), .motor_dir_mask(motor_dir_mask),
+        .motor_done(motor_done)
+    );
+
+    integer i;
+    initial begin
+        repeat (3) @(posedge clk);
+        rst_n = 1'b1;
+        // limit_sync_valid stays 0; limit is not reached. A correct module waits
+        // here; the mutant should start the motor immediately.
+        for (i = 0; i < 20; i = i + 1) begin
+            @(posedge clk);
+            if (motor_start) begin
+                $display("MUTATION_DETECTED");
+                $finish;
+            end
+        end
+        $fatal(1, "mutation was not detected");
+    end
+endmodule
+""",
+                encoding="utf-8",
+            )
+            vvp_out = tmp / "a.out"
+            env = prod2u_p4_harness.tool_env()
+            compile_result = subprocess.run(
+                [iverilog, "-g2005-sv", "-s", "tb", "-o", str(vvp_out), str(mutated), str(tb)],
+                cwd=tmp,
+                capture_output=True,
+                text=True,
+                env=env,
+            )
+            self.assertEqual(compile_result.returncode, 0, compile_result.stderr)
+            run_result = subprocess.run([vvp, str(vvp_out)], cwd=tmp, capture_output=True, text=True, env=env)
+            self.assertIn("MUTATION_DETECTED", run_result.stdout)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 149 - 50
tools/agent_guard.py

@@ -3,21 +3,23 @@
 This script is designed to be invoked by Devin/Cursor/Codex hooks or directly.
 It validates that the agent is operating in the expected repository, branch,
 worktree, owned paths, and that protected operations are not performed.
+
+The tracked configuration lives in `.devin/config.json` and must not contain
+temporary absolute machine paths. Local/session-specific values such as the
+active worktree, expected branch/HEAD, protected roots and owned paths are kept
+in `.devin/config.local.json`, which is gitignored.
 """
 from __future__ import annotations
 
 import argparse
+import fnmatch
 import json
 import subprocess
 import sys
 from pathlib import Path
 from typing import Any
 
-PROTECTED_ROOTS = [
-    Path("C:/Users/Administrator/Agentworkspace/CPLD"),
-]
-
-DENIED_COMMANDS = [
+DEFAULT_DENIED_COMMANDS = [
     "git reset",
     "git clean",
     "git stash",
@@ -26,7 +28,7 @@ DENIED_COMMANDS = [
     "git update-ref",
 ]
 
-HARDWARE_COMMANDS = [
+DEFAULT_HARDWARE_COMMANDS = [
     "com",
     "jtag",
     "program",
@@ -36,44 +38,68 @@ HARDWARE_COMMANDS = [
 ]
 
 
+def _run(cmd: list[str], cwd: Path | None, check: bool = False) -> subprocess.CompletedProcess[str]:
+    return subprocess.run(
+        cmd,
+        cwd=cwd,
+        capture_output=True,
+        text=True,
+        check=check,
+    )
+
+
 def _repo_root(cwd: Path) -> Path | None:
-    try:
-        result = subprocess.run(
-            ["git", "rev-parse", "--show-toplevel"],
-            cwd=cwd,
-            capture_output=True,
-            text=True,
-            check=True,
-        )
-        return Path(result.stdout.strip()).resolve()
-    except (OSError, subprocess.CalledProcessError):
+    result = _run(["git", "rev-parse", "--show-toplevel"], cwd=cwd)
+    if result.returncode != 0 or not result.stdout.strip():
         return None
+    return Path(result.stdout.strip()).resolve()
 
 
 def _current_branch(repo: Path) -> str | None:
-    try:
-        result = subprocess.run(
-            ["git", "branch", "--show-current"],
-            cwd=repo,
-            capture_output=True,
-            text=True,
-            check=True,
-        )
-        return result.stdout.strip()
-    except (OSError, subprocess.CalledProcessError):
+    result = _run(["git", "branch", "--show-current"], cwd=repo)
+    if result.returncode != 0:
         return None
+    return result.stdout.strip()
 
 
-def _load_config(repo: Path) -> dict[str, Any]:
-    config_path = repo / ".devin" / "config.json"
-    if config_path.is_file():
+def _current_head(repo: Path) -> str | None:
+    result = _run(["git", "rev-parse", "HEAD"], cwd=repo)
+    if result.returncode != 0:
+        return None
+    return result.stdout.strip()
+
+
+def _is_worktree_clean(repo: Path) -> bool:
+    result = _run(["git", "status", "--porcelain=v2"], cwd=repo)
+    return result.returncode == 0 and not result.stdout.strip()
+
+
+def _load_json(path: Path) -> dict[str, Any]:
+    if path.is_file():
         try:
-            return json.loads(config_path.read_text(encoding="utf-8-sig"))
+            return json.loads(path.read_text(encoding="utf-8-sig"))
         except (OSError, json.JSONDecodeError):
             pass
     return {}
 
 
+def _load_config(repo: Path) -> dict[str, Any]:
+    """Merge tracked `.devin/config.json` with gitignored `.devin/config.local.json`.
+
+    Local values override tracked values so session-specific state never touches
+    tracked configuration.
+    """
+    tracked = _load_json(repo / ".devin" / "config.json")
+    local = _load_json(repo / ".devin" / "config.local.json")
+    merged = dict(tracked)
+    for key, value in local.items():
+        if isinstance(value, dict) and isinstance(merged.get(key), dict):
+            merged[key] = {**merged[key], **value}
+        else:
+            merged[key] = value
+    return merged
+
+
 def _is_under(path: Path, root: Path) -> bool:
     try:
         path.resolve().relative_to(root.resolve())
@@ -82,53 +108,126 @@ def _is_under(path: Path, root: Path) -> bool:
         return False
 
 
-def _check_command(command: str) -> list[str]:
+def _matches_owned(path: Path, repo: Path, pattern: str) -> bool:
+    """Check whether `path` is under the repo-relative glob `pattern`."""
+    rel = path.resolve()
+    try:
+        repo_rel = rel.relative_to(repo.resolve())
+    except ValueError:
+        return False
+    posix = repo_rel.as_posix()
+    return fnmatch.fnmatch(posix, pattern) or fnmatch.fnmatch(posix, pattern.rstrip("/") + "/**")
+
+
+def _check_command(command: str, denied: list[str], hardware: list[str]) -> list[str]:
     failures: list[str] = []
     lowered = command.lower()
-    for denied in DENIED_COMMANDS:
-        if denied in lowered:
-            failures.append(f"denied_git_command:{denied}")
-    for hw in HARDWARE_COMMANDS:
+    for denied_cmd in denied:
+        if denied_cmd in lowered:
+            failures.append(f"denied_git_command:{denied_cmd}")
+    for hw in hardware:
         if hw in lowered and "prompt" not in lowered:
             failures.append(f"potential_hardware_access:{hw}")
     return failures
 
 
-def _check_path(target: Path, repo: Path, config: dict[str, Any]) -> list[str]:
+def _check_path(
+    target: Path,
+    repo: Path,
+    owned_paths: list[str],
+    protected_roots: list[str],
+) -> list[str]:
     failures: list[str] = []
-    denied_paths = config.get("denied_paths", []) + [str(r) for r in PROTECTED_ROOTS]
-    for denied_str in denied_paths:
-        denied = Path(denied_str).resolve()
-        if _is_under(target, denied) or target.resolve() == denied:
-            failures.append(f"protected_path:{denied}")
+    target_resolved = target.resolve()
+
+    for protected_str in protected_roots:
+        protected = Path(protected_str).resolve()
+        if _is_under(target_resolved, protected) or target_resolved == protected:
+            failures.append(f"protected_path:{protected}")
+
+    if not _is_under(target_resolved, repo):
+        failures.append("outside_repo")
+
+    if owned_paths:
+        under_owned = any(_matches_owned(target_resolved, repo, p) for p in owned_paths)
+        if not under_owned:
+            failures.append(f"outside_owned_paths:{target_resolved.relative_to(repo)}")
+
     return failures
 
 
 def _check_event(event: str, args: argparse.Namespace) -> dict[str, Any]:
     cwd = Path(args.cwd or ".").resolve()
-    repo = _repo_root(cwd)
     result: dict[str, Any] = {
         "event": event,
         "cwd": str(cwd),
-        "repo_root": str(repo) if repo else None,
-        "branch": _current_branch(repo) if repo else None,
+        "repo_root": None,
+        "branch": None,
+        "head": None,
+        "worktree_clean": None,
         "allowed": True,
         "failures": [],
     }
+
+    repo = _repo_root(cwd)
     if repo is None:
         result["allowed"] = False
         result["failures"].append("not_a_git_repository")
         return result
 
+    result["repo_root"] = str(repo)
+    result["branch"] = _current_branch(repo)
+    result["head"] = _current_head(repo)
+    result["worktree_clean"] = _is_worktree_clean(repo)
+
     config = _load_config(repo)
     result["config_loaded"] = bool(config)
 
-    if event in ("pre_tool_use", "post_tool_use") and args.command:
-        result["failures"].extend(_check_command(args.command))
+    protected_roots = [str(p) for p in config.get("protected_roots", [])]
+    for protected_str in protected_roots:
+        protected = Path(protected_str).resolve()
+        if _is_under(cwd, protected) or _is_under(repo, protected) or cwd == protected or repo == protected:
+            result["allowed"] = False
+            result["failures"].append(f"protected_repository:{protected}")
+            return result
+
+    active_worktree_str = config.get("active_worktree")
+    if active_worktree_str:
+        active_worktree = Path(active_worktree_str).resolve()
+        if repo != active_worktree:
+            result["failures"].append(
+                f"worktree_mismatch:expected={active_worktree},actual={repo}"
+            )
+
+    expected_branch = config.get("expected_branch")
+    if expected_branch and result["branch"] != expected_branch:
+        result["failures"].append(
+            f"branch_mismatch:expected={expected_branch},actual={result['branch']}"
+        )
+
+    expected_head = config.get("expected_head")
+    if expected_head and result["head"] != expected_head:
+        result["failures"].append(
+            f"head_mismatch:expected={expected_head},actual={result['head']}"
+        )
+
+    owned_paths = list(config.get("owned_paths", []))
+    if not owned_paths and args.agent_role:
+        # Derive owned paths from the agent-team contract when a role is supplied.
+        contract = _load_json(repo / "agent-team" / "contract.json")
+        team = contract.get("teams", {}).get(args.agent_role, {})
+        owned_paths = list(team.get("owns", []))
 
     if args.target_path:
         target = Path(args.target_path).resolve()
-        result["failures"].extend(_check_path(target, repo, config))
+        result["failures"].extend(
+            _check_path(target, repo, owned_paths, protected_roots)
+        )
+
+    if event in ("pre_tool_use", "post_tool_use") and args.command:
+        denied = config.get("denied_commands", DEFAULT_DENIED_COMMANDS)
+        hardware = DEFAULT_HARDWARE_COMMANDS + list(config.get("hardware_access", {}).keys())
+        result["failures"].extend(_check_command(args.command, denied, hardware))
 
     if result["failures"]:
         result["allowed"] = False
@@ -139,16 +238,16 @@ def main(argv: list[str] | None = None) -> int:
     parser = argparse.ArgumentParser(description="Agent guard for cross-tool operations")
     parser.add_argument("--event", required=True)
     parser.add_argument("--cwd", default=None)
-    parser.add_argument("--repo-root", default=None)
     parser.add_argument("--tool", default=None)
     parser.add_argument("--target-path", default=None)
     parser.add_argument("--command", default=None)
-    parser.add_argument("--exit-code", type=int, default=0)
+    parser.add_argument("--agent-role", default=None)
+    parser.add_argument("--exit-code", type=int, default=1)
     args = parser.parse_args(argv)
 
     result = _check_event(args.event, args)
     print(json.dumps(result, indent=2, sort_keys=True))
-    return 0 if result["allowed"] else 1
+    return 0 if result["allowed"] else args.exit_code
 
 
 if __name__ == "__main__":