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84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
"""Host-owned sequential TODO state for native ``todowrite`` calls.

The model submits a complete list, while revision/session metadata and all
state-machine decisions remain owned by the host.
"""

from __future__ import annotations

import hashlib
import json
import os
import tempfile
from contextlib import contextmanager
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any, Callable, Iterable

try:
    import fcntl
except ImportError:  # pragma: no cover - Windows fallback
    fcntl = None


STATUSES = {"pending", "in_progress", "completed", "cancelled"}
PRIORITIES = {"high", "medium", "low"}
DEFAULT_ITEMS = [
    "Preflight: collect choices and validate inputs, references, outputs, and UT defaults",
    "Stage 1: analyze spec, route knowledge, and confirm feature tree",
    "Stage 2: decompose confirmed features into UT testpoints",
    "Stage 3: map confirmed testpoints into testcases",
    "Stage 4: generate selected optional testpoint sections",
    "Stage 5: validate and assemble the testpoint decomposition report",
    "Handoff: validate the testpoint report as verification-plan input",
    "Stage 6: design the verification environment architecture",
    "Stage 7: define stimulus and checking requirements",
    "Stage 8: identify verification difficulties and countermeasures",
    "Stage 9: select and define special verification methods",
    "Stage 10: build the functional coverage model",
    "Stage 11: design verification components and protection mechanisms",
    "Stage 12: validate and assemble the verification plan",
]


class TodoError(ValueError):
    """A safe, user-facing TODO contract or transition failure."""

    def __init__(self, message: str, code: str = "invalid_update") -> None:
        super().__init__(message)
        self.code = code


@dataclass(frozen=True)
class TodoItem:
    content: str
    status: str
    priority: str = "medium"


@dataclass(frozen=True)
class TodoLedger:
    schema_version: int
    run_id: str
    writer_session: str
    revision: int
    todos: tuple[TodoItem, ...]

    def to_dict(self) -> dict[str, Any]:
        return {
            "schema_version": self.schema_version,
            "run_id": self.run_id,
            "writer_session": self.writer_session,
            "revision": self.revision,
            "todos": [asdict(item) for item in self.todos],
        }


def _canonical_json(value: object) -> bytes:
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")


def build_contract(
    run_id: str,
    expected_items: Iterable[str] = DEFAULT_ITEMS,
    *,
    max_content_chars: int = 512,
    protected_completion_positions: Iterable[int] = (5, 13),
) -> dict[str, Any]:
    items = list(expected_items)
    if not run_id or not isinstance(run_id, str):
        raise TodoError("run_id must be a non-empty string", "invalid_contract")
    if not items or len(items) > 128 or any(not isinstance(item, str) or not item.strip() for item in items):
        raise TodoError("contract items must be non-empty bounded strings", "invalid_contract")
    contract = {
        "schema_version": 1,
        "run_id": run_id,
        "expected_items": items,
        "statuses": sorted(STATUSES),
        "priorities": sorted(PRIORITIES),
        "sequential": True,
        "max_items": len(items),
        "max_content_chars": max_content_chars,
        "protected_completion_positions": list(protected_completion_positions),
    }
    contract["contract_sha256"] = hashlib.sha256(_canonical_json(contract)).hexdigest()
    return contract


def _safe_internal_path(workspace_root: Path, value: str, name: str) -> Path:
    if not isinstance(value, str) or not value or Path(value).is_absolute() or ".." in Path(value).parts:
        raise TodoError(f"{name} must be a relative path without '..'", "invalid_config")
    path = Path(value)
    if path.parts[:1] != (".nano_agent",):
        raise TodoError(f"{name} must be inside .nano_agent", "invalid_config")
    resolved_root = workspace_root.resolve()
    resolved = (resolved_root / path).resolve()
    try:
        resolved.relative_to(resolved_root / ".nano_agent")
    except ValueError as error:
        raise TodoError(f"{name} escapes .nano_agent", "invalid_config") from error
    return resolved


class TodoStore:
    """Validated, atomic ledger store used by the Gateway and host conductor."""

    def __init__(
        self,
        workspace_root: Path,
        *,
        ledger_path: str = ".nano_agent/todo.json",
        contract_path: str = ".nano_agent/todo_contract.json",
        run_id: str,
        writer_session: str,
        event_logger: Any | None = None,
        expected_items: Iterable[str] = DEFAULT_ITEMS,
        protected_completion_positions: Iterable[int] = (5, 13),
    ) -> None:
        self.workspace_root = Path(workspace_root).resolve()
        self.ledger_path = _safe_internal_path(self.workspace_root, ledger_path, "ledger_path")
        self.contract_path = _safe_internal_path(self.workspace_root, contract_path, "contract_path")
        self.run_id = run_id
        self.writer_session = writer_session
        self.events = event_logger
        self._expected_items = tuple(expected_items)
        self._protected_completion_positions = tuple(protected_completion_positions)
        if not run_id or not writer_session:
            raise TodoError("run_id and writer_session must be non-empty", "invalid_config")
        if self.contract_path.is_file():
            self._contract = self._read_contract()
        else:
            raise TodoError(f"todo contract not found: {self.contract_path}", "missing_contract")
        if not self.ledger_path.is_file():
            self._write(self._initial_ledger())

    @property
    def contract(self) -> dict[str, Any]:
        return dict(self._contract)

    @property
    def contract_hash(self) -> str:
        return str(self._contract["contract_sha256"])

    def _read_contract(self) -> dict[str, Any]:
        try:
            data = json.loads(self.contract_path.read_text(encoding="utf-8"))
        except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error:
            raise TodoError(f"cannot read todo contract: {error}", "invalid_contract") from error
        if not isinstance(data, dict):
            raise TodoError("todo contract must be an object", "invalid_contract")
        expected = build_contract(
            self.run_id,
            self._expected_items,
            protected_completion_positions=self._protected_completion_positions,
        )
        supplied_hash = data.get("contract_sha256")
        candidate = dict(data)
        candidate.pop("contract_sha256", None)
        if supplied_hash != hashlib.sha256(_canonical_json(candidate)).hexdigest():
            raise TodoError("todo contract hash mismatch", "invalid_contract")
        if data != expected:
            raise TodoError("todo contract does not match the configured run", "invalid_contract")
        self._protected_completion_positions = tuple(data["protected_completion_positions"])
        return data

    def _initial_ledger(self) -> TodoLedger:
        return TodoLedger(
            schema_version=1,
            run_id=self.run_id,
            writer_session=self.writer_session,
            revision=0,
            todos=tuple(
                TodoItem(item, "in_progress" if index == 0 else "pending", "high")
                for index, item in enumerate(self._expected_items)
            ),
        )

    def read(self) -> TodoLedger:
        try:
            data = json.loads(self.ledger_path.read_text(encoding="utf-8"))
        except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error:
            raise TodoError(f"cannot read todo ledger: {error}", "invalid_ledger") from error
        if not isinstance(data, dict):
            raise TodoError("todo ledger must be an object", "invalid_ledger")
        try:
            raw_todos = data["todos"]
            if not isinstance(raw_todos, list):
                raise TypeError("todos must be an array")
            todos = tuple(TodoItem(**item) for item in raw_todos)
            supplied_run_id = data.get("run_id")
            supplied_session = data.get("writer_session")
            # Read the pre-native conductor shape once, then write only the
            # canonical schema on the next successful update.
            if supplied_run_id is None and data.get("session_id") is not None:
                supplied_run_id = self.run_id
            if supplied_session is None and data.get("session_id") is not None:
                supplied_session = data.get("session_id")
            if supplied_run_id is None or supplied_session is None:
                raise TypeError("run_id and writer_session are required")
            ledger = TodoLedger(
                int(data.get("schema_version", 1)),
                str(supplied_run_id),
                str(supplied_session),
                int(data["revision"]),
                todos,
            )
        except (KeyError, TypeError, ValueError) as error:
            raise TodoError(f"invalid todo ledger: {error}", "invalid_ledger") from error
        if ledger.run_id != self.run_id or ledger.schema_version != 1 or ledger.revision < 0:
            raise TodoError("todo ledger belongs to another run or schema", "invalid_ledger")
        self._validate_items(ledger.todos, previous=None, allow_initial=True)
        return ledger

    def update(self, raw_todos: object) -> dict[str, Any]:
        with self._ledger_lock():
            return self._update_unlocked(raw_todos)

    def _update_unlocked(self, raw_todos: object) -> dict[str, Any]:
        try:
            previous = self.read()
            todos = self._parse_items(raw_todos)
            self._validate_items(todos, previous=previous)
            ledger = TodoLedger(1, self.run_id, self.writer_session, previous.revision + 1, tuple(todos))
            self._write(ledger)
            changed = [i for i, (old, new) in enumerate(zip(previous.todos, todos)) if old != new]
            self._log("todo_updated", revision=ledger.revision, changed_positions=changed, item_count=len(todos))
            return {
                "ok": True,
                "run_id": self.run_id,
                "revision": ledger.revision,
                "changed_positions": changed,
                "status_counts": self._status_counts(todos),
            }
        except TodoError as error:
            item_count = len(raw_todos) if isinstance(raw_todos, list) else None
            self._log("todo_update_rejected", error_code=error.code, item_count=item_count)
            raise

    def complete_after_evidence(self, position: int, evidence: dict[str, Any]) -> dict[str, Any]:
        with self._ledger_lock():
            return self._complete_after_evidence_unlocked(position, evidence)

    def _complete_after_evidence_unlocked(self, position: int, evidence: dict[str, Any]) -> dict[str, Any]:
        try:
            if (
                not isinstance(evidence, dict)
                or evidence.get("exit_code") != 0
                or not (evidence.get("validator") or evidence.get("evidence_id"))
            ):
                raise TodoError(
                    "completion evidence must have exit_code=0 and a validator/evidence_id",
                    "missing_evidence",
                )
            previous = self.read()
            if not isinstance(position, int) or isinstance(position, bool) or not 0 <= position < len(previous.todos):
                raise TodoError(f"todo position out of range: {position}", "invalid_position")
            if previous.todos[position].status != "in_progress":
                raise TodoError("only an in_progress item can be completed", "invalid_transition")
            updated = list(previous.todos)
            updated[position] = TodoItem(updated[position].content, "completed", updated[position].priority)
            if position + 1 < len(updated) and any(item.status == "pending" for item in updated[position + 1 :]):
                updated[position + 1] = TodoItem(updated[position + 1].content, "in_progress", updated[position + 1].priority)
            self._validate_items(tuple(updated), previous=previous, allow_host_completion=True)
            ledger = TodoLedger(1, self.run_id, self.writer_session, previous.revision + 1, tuple(updated))
            self._write(ledger)
            self._log("todo_completed_with_evidence", revision=ledger.revision, position=position, evidence_keys=sorted(evidence))
            return {"ok": True, "revision": ledger.revision, "position": position}
        except TodoError as error:
            self._log("todo_completion_rejected", error_code=error.code, position=position)
            raise

    def _parse_items(self, raw: object) -> tuple[TodoItem, ...]:
        if not isinstance(raw, list):
            raise TodoError("todos must be an array", "invalid_arguments")
        items: list[TodoItem] = []
        for index, value in enumerate(raw):
            if not isinstance(value, dict) or set(value) != {"content", "status", "priority"}:
                raise TodoError(f"todo item {index} has unexpected fields", "invalid_arguments")
            content, status, priority = value["content"], value["status"], value["priority"]
            if not isinstance(content, str) or not content.strip():
                raise TodoError(f"todo item {index} content is empty", "invalid_arguments")
            if len(content) > int(self._contract.get("max_content_chars", 512)):
                raise TodoError(f"todo item {index} content is too long", "invalid_arguments")
            if not isinstance(status, str) or status not in STATUSES:
                raise TodoError(f"todo item {index} has invalid status", "invalid_arguments")
            if not isinstance(priority, str) or priority not in PRIORITIES:
                raise TodoError(f"todo item {index} has invalid priority", "invalid_arguments")
            items.append(TodoItem(content, status, priority))
        return tuple(items)

    def _validate_items(
        self,
        todos: tuple[TodoItem, ...],
        *,
        previous: TodoLedger | None,
        allow_initial: bool = False,
        allow_host_completion: bool = False,
    ) -> None:
        if len(todos) != len(self._expected_items):
            raise TodoError(f"expected {len(self._expected_items)} TODO items, got {len(todos)}", "invalid_items")
        for index, (item, expected) in enumerate(zip(todos, self._expected_items)):
            if item.content != expected:
                raise TodoError(f"todo item {index} content/order mismatch", "invalid_items")
            if item.status not in STATUSES:
                raise TodoError(f"todo item {index} has invalid status", "invalid_items")
            if item.priority not in PRIORITIES:
                raise TodoError(f"todo item {index} has invalid priority", "invalid_items")
            if len(item.content) > int(self._contract.get("max_content_chars", 512)):
                raise TodoError(f"todo item {index} content is too long", "invalid_items")
            if (
                previous is not None
                and not allow_host_completion
                and index in self._protected_completion_positions
                and previous.todos[index].status != "completed"
                and item.status == "completed"
            ):
                raise TodoError(f"item {index} requires host evidence before completion", "host_evidence_required")
        incomplete = [item for item in todos if item.status in {"pending", "in_progress"}]
        active = [item for item in todos if item.status == "in_progress"]
        if incomplete and len(active) != 1:
            raise TodoError("work remains but exactly one item must be in_progress", "invalid_transition")
        if not incomplete and active:
            raise TodoError("completed ledger cannot contain in_progress", "invalid_transition")
        if previous:
            if previous.writer_session != self.writer_session and previous.revision > 0:
                # Session changes are host-controlled, but the revision remains global.
                pass
            for index, (old, new) in enumerate(zip(previous.todos, todos)):
                if old.status == "completed" and new.status == "pending":
                    raise TodoError(f"item {index} cannot move completed -> pending", "invalid_transition")
                if old.status == "cancelled" and new.status != "cancelled":
                    raise TodoError(f"item {index} cannot leave cancelled", "invalid_transition")
        for index, item in enumerate(todos):
            if item.status not in {"completed", "cancelled"}:
                if any(downstream.status in {"completed", "in_progress"} for downstream in todos[index + 1 :]):
                    raise TodoError(f"item {index} blocks a downstream item", "invalid_transition")
        if previous is None and not allow_initial:
            raise TodoError("previous ledger is required", "invalid_ledger")

    @staticmethod
    def _status_counts(todos: Iterable[TodoItem]) -> dict[str, int]:
        counts = {status: 0 for status in STATUSES}
        for item in todos:
            counts[item.status] += 1
        return counts

    def _write(self, ledger: TodoLedger) -> None:
        self.ledger_path.parent.mkdir(parents=True, exist_ok=True)
        fd, temporary = tempfile.mkstemp(dir=str(self.ledger_path.parent), prefix=".todo-")
        try:
            with os.fdopen(fd, "w", encoding="utf-8") as stream:
                json.dump(ledger.to_dict(), stream, ensure_ascii=False, indent=2)
                stream.write("\n")
                stream.flush()
                os.fsync(stream.fileno())
            os.replace(temporary, self.ledger_path)
        except BaseException:
            try:
                os.unlink(temporary)
            except OSError:
                pass
            raise

    @contextmanager
    def _ledger_lock(self):
        """Serialize each complete ledger transaction across host processes."""
        lock_path = self.ledger_path.with_name(".todo.lock")
        lock_path.parent.mkdir(parents=True, exist_ok=True)
        with lock_path.open("a+", encoding="utf-8") as stream:
            if fcntl is not None:
                fcntl.flock(stream.fileno(), fcntl.LOCK_EX)
            try:
                yield
            finally:
                if fcntl is not None:
                    fcntl.flock(stream.fileno(), fcntl.LOCK_UN)

    def _log(self, event_type: str, **fields: Any) -> None:
        if self.events is None:
            return
        try:
            self.events.log(event_type, run_id=self.run_id, writer_session=self.writer_session, **fields)
        except Exception:
            pass


def write_contract(path: Path, contract: dict[str, Any]) -> None:
    """Write a generated contract atomically for conductor-owned workspaces."""
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(path.name + ".tmp")
    temporary.write_text(json.dumps(contract, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    os.replace(temporary, path)


def write_initial_ledger(path: Path, run_id: str, writer_session: str, expected_items: Iterable[str] = DEFAULT_ITEMS) -> None:
    items = tuple(
        TodoItem(item, "in_progress" if index == 0 else "pending", "high")
        for index, item in enumerate(expected_items)
    )
    ledger = TodoLedger(1, run_id, writer_session, 0, items)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(ledger.to_dict(), ensure_ascii=False, indent=2) + "\n", encoding="utf-8")