workflow-coordinator 0.1.0b1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. workflow_coordinator/__init__.py +1 -0
  2. workflow_coordinator/adapter.py +150 -0
  3. workflow_coordinator/claude_adapter.py +289 -0
  4. workflow_coordinator/codex_adapter.py +395 -0
  5. workflow_coordinator/codex_adapter_smoke.py +231 -0
  6. workflow_coordinator/commissioning.py +432 -0
  7. workflow_coordinator/evidence.py +481 -0
  8. workflow_coordinator/execution_boundary.py +187 -0
  9. workflow_coordinator/frontdoor/__init__.py +1 -0
  10. workflow_coordinator/frontdoor/archive.py +1496 -0
  11. workflow_coordinator/frontdoor/audit.py +589 -0
  12. workflow_coordinator/frontdoor/cli.py +42 -0
  13. workflow_coordinator/frontdoor/config.py +287 -0
  14. workflow_coordinator/frontdoor/init.py +228 -0
  15. workflow_coordinator/frontdoor/journal.py +284 -0
  16. workflow_coordinator/frontdoor/lifecycle.py +1093 -0
  17. workflow_coordinator/frontdoor/plan.py +311 -0
  18. workflow_coordinator/frontdoor/postrun.py +254 -0
  19. workflow_coordinator/frontdoor/preservation.py +132 -0
  20. workflow_coordinator/frontdoor/report.py +222 -0
  21. workflow_coordinator/frontdoor/request.py +170 -0
  22. workflow_coordinator/frontdoor/verify.py +137 -0
  23. workflow_coordinator/git_facts.py +1258 -0
  24. workflow_coordinator/implementation_identity.py +68 -0
  25. workflow_coordinator/model.py +958 -0
  26. workflow_coordinator/operator.py +1915 -0
  27. workflow_coordinator/persistence.py +599 -0
  28. workflow_coordinator/prompt.py +272 -0
  29. workflow_coordinator/proof_harness.py +295 -0
  30. workflow_coordinator/reducer.py +2006 -0
  31. workflow_coordinator/resources/agent_operating_contract_v6.txt +97 -0
  32. workflow_coordinator/resources/roles/reviewer.txt +41 -0
  33. workflow_coordinator/resources/roles/simple-self-check.txt +6 -0
  34. workflow_coordinator/resources/roles/worker.txt +24 -0
  35. workflow_coordinator/serialization.py +2392 -0
  36. workflow_coordinator/slice4.py +411 -0
  37. workflow_coordinator/structured_result_schema.py +266 -0
  38. workflow_coordinator/vertical.py +597 -0
  39. workflow_coordinator-0.1.0b1.dist-info/METADATA +120 -0
  40. workflow_coordinator-0.1.0b1.dist-info/RECORD +44 -0
  41. workflow_coordinator-0.1.0b1.dist-info/WHEEL +5 -0
  42. workflow_coordinator-0.1.0b1.dist-info/entry_points.txt +2 -0
  43. workflow_coordinator-0.1.0b1.dist-info/licenses/LICENSE +21 -0
  44. workflow_coordinator-0.1.0b1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1496 @@
1
+ """Installed ``wfc archive`` -- the canonical Evidence archiver, ported.
2
+
3
+ This ports the Evidence repository's own ``scripts/archive_run.py`` (the
4
+ archiver: bounded allow-list, source isolation, digest-verified copy,
5
+ mechanical fact extraction) and ``scripts/wfc-archive-run`` (the wrapper:
6
+ Run-identity derivation and cross-source agreement, OPS-directory discovery,
7
+ semantic-classification destination, dry-run preview, and the scoped
8
+ commit) into one installed, parameterized module, per
9
+ ``wfc_beta1_product_boundary_review_second_pass.adoc``'s BP5 reuse-and-
10
+ sequencing steps. The allow-lists, confinement guards, fact-merge priority
11
+ and cross-source agreement checks are semantically unchanged from the
12
+ ported scripts; ``archived_at`` aside, a freshly written manifest is
13
+ byte-compatible with the one the old scripts would have produced for the
14
+ same inputs.
15
+
16
+ Two things are deliberately new, not present in the ported scripts:
17
+
18
+ * *Staging and atomic placement.* The copy lands in a staging directory
19
+ first and is renamed into the final destination only after the manifest
20
+ itself is verified; a partial copy is never observable at the
21
+ destination.
22
+ * *Idempotent retry.* A destination already fully placed but not yet
23
+ committed resumes at the commit step only after reverifying the placed
24
+ attempt id and recorded sources, every copied file's own digest/size
25
+ against the manifest, and the manifest itself (identity, per-file
26
+ provenance, facts and semantic payload, ``archived_at`` aside) against a
27
+ manifest freshly derived from the current authoritative Run/OPS sources --
28
+ so an interruption followed by tampering (including a file and its own
29
+ recorded digest altered together, or a falsified fact/source/semantic
30
+ field) is refused rather than published; a destination already committed
31
+ with matching content is a no-op; only a destination that exists with
32
+ genuinely different content is refused.
33
+ * *Destination-boundary containment.* The resolved destination and staging
34
+ paths are refused, before any write, if any component of either escapes
35
+ the Evidence repository through a symlink, or if a symlink inside the
36
+ repository makes the two resolve to the same or a nested path.
37
+
38
+ The commit itself is the one Coordinator-owned write surface
39
+ (``git_facts.bounded_path_commit``), not a raw ``git add``/``git commit``
40
+ pair -- the same primitive the Commission commit uses. Because that
41
+ primitive commits a bare subject with no body, the rich identity/file-count
42
+ narrative the old wrapper wrote into the commit *body* is reported on
43
+ stdout instead; the commit subject alone (``evidence: archive <attempt>``)
44
+ is unchanged.
45
+
46
+ Destination-boundary parameterization is limited to accepting the evidence
47
+ repository as a caller-supplied root (rather than deriving it from
48
+ ``__file__`` as the original script did); this port does not implement a
49
+ repository-local destination, which remains explicitly withheld pending
50
+ DG-2 follow-up.
51
+ """
52
+
53
+ from __future__ import annotations
54
+
55
+ import argparse
56
+ import fnmatch
57
+ import getpass
58
+ import hashlib
59
+ import json
60
+ import os
61
+ import re
62
+ import shutil
63
+ import subprocess
64
+ import sys
65
+ from dataclasses import dataclass
66
+ from datetime import datetime, timezone
67
+ from pathlib import Path, PurePosixPath
68
+ from typing import Any, Mapping, Sequence
69
+
70
+ from ..git_facts import (
71
+ GitPreflightError,
72
+ NewPathCommitIntent,
73
+ TrustedCommitError,
74
+ bounded_path_commit,
75
+ repository_head,
76
+ repository_identity,
77
+ )
78
+ from .audit import AuditError, ProjectionError, project_audit, render_audit_json
79
+ from .config import EVIDENCE_RAW_CHOICES
80
+
81
+ # --------------------------------------------------------------------------
82
+ # Ported allow-lists (verbatim from the Evidence repository's archive_run.py)
83
+ # --------------------------------------------------------------------------
84
+
85
+ RUN_ROOT_ALLOW = [
86
+ "operator-plan.json",
87
+ "operator-summary.json",
88
+ "launch-plan.json",
89
+ "checkout-association.json",
90
+ "candidate-artifact.adoc",
91
+ "candidate-artifact.sha256",
92
+ "launcher-source.py",
93
+ "task-payload.txt",
94
+ ]
95
+
96
+ CHECKOUT_ALLOW = [
97
+ "checkpoint.json",
98
+ "result-message.json",
99
+ "run.json",
100
+ "dispatch.json",
101
+ "structured-result.schema.json",
102
+ "execution-evidence.json",
103
+ ]
104
+
105
+ OPS_ROOT_ALLOW = [
106
+ "execution-bindings.yaml",
107
+ "launch.sh",
108
+ "launch-command.sh",
109
+ "launch-command.txt",
110
+ "run.log",
111
+ "run-analysis-*.txt",
112
+ "preparation.log",
113
+ "preparation-continue.log",
114
+ "pinned-revisions.txt",
115
+ "preparation-pins.txt",
116
+ "H*-worker-dirty.diff",
117
+ "H*-worker-dirty.patch",
118
+ "H*-worker-status.txt",
119
+ "H*-check-*.log",
120
+ "H*-check-*.exitcode",
121
+ "baseline-*.log",
122
+ "baseline-*.exitcode",
123
+ ]
124
+
125
+ OPS_SUBDIR_ALLOW = [
126
+ "predecessor-disposition",
127
+ "failed-h*-artifacts",
128
+ ]
129
+
130
+ BULK_DIR_DENY = {
131
+ "runtime-env", "runtime-export",
132
+ "development-env", "development-export",
133
+ "core-evidence-env", "core-export",
134
+ ".venv", "venv", "__pycache__", "node_modules", ".git",
135
+ }
136
+
137
+ RUN_IDENTITY_FIELDS = (
138
+ "run_id", "work_item_id", "policy_id", "policy_revision",
139
+ "profile_id", "profile_revision", "hop_limit", "hop_used",
140
+ "baseline_head", "current_head", "final_head", "stop_reason",
141
+ "status", "run_status",
142
+ )
143
+
144
+ PIN_FILES_IN_PRIORITY = ("pinned-revisions.txt", "preparation-pins.txt")
145
+
146
+
147
+ class ArchiveError(RuntimeError):
148
+ """A refusal in the ported archiver/wrapper; never a partial mutation."""
149
+
150
+
151
+ # --------------------------------------------------------------------------
152
+ # BP6b: retention-aware archive (additive). ``raw_retention=None`` leaves
153
+ # every byte of the above BP5 behaviour unchanged; see ``archive_run``.
154
+ # --------------------------------------------------------------------------
155
+
156
+ AUDIT_FILENAME = "audit.json"
157
+
158
+ # Written into the attempt's own destination directory only for ``commit``
159
+ # retention, as one more committed leaf. The managed root ``.gitignore`` a
160
+ # fresh Evidence repository carries (``frontdoor.config.evidence_gitignore_block``)
161
+ # uses content-style globs (``run/**``, not ``run/``) precisely so this
162
+ # per-Attempt negation can re-include this one Attempt's own raw files --
163
+ # Git refuses to re-include anything beneath a directory excluded by a
164
+ # trailing-slash pattern, no matter where a negation is written.
165
+ _ATTEMPT_COMMIT_GITIGNORE = (
166
+ "# >>> wfc commit-mode raw retention for this attempt (do not edit by hand) >>>\n"
167
+ "!manifest.json\n"
168
+ "!run/**\n"
169
+ "!ops/**\n"
170
+ "# <<< wfc commit-mode raw retention for this attempt <<<\n"
171
+ )
172
+
173
+ # ``manifest.json``'s ``archived_at`` is a wall-clock timestamp that cannot be
174
+ # reproduced from scratch; for ``local``/``commit`` retention this is fine
175
+ # because the first-placed ``manifest.json`` is kept forever and later reads
176
+ # reproject from that one placed file. ``discard`` retention never places
177
+ # ``manifest.json`` anywhere, so every resume/no-op check must rebuild one
178
+ # from scratch to reproject ``audit.json`` -- a real timestamp there would
179
+ # make that rebuild (and therefore ``audit.json`` itself) non-reproducible,
180
+ # breaking idempotency. This fixed placeholder keeps the rebuild
181
+ # deterministic; it is never written to disk anywhere durable.
182
+ _DISCARD_MANIFEST_ARCHIVED_AT = "not-persisted (discard raw retention)"
183
+
184
+
185
+ def _project_audit_text(
186
+ attempt_dir: Path, *, raw_retention: str, lifecycle: Mapping[str, Any] | None = None,
187
+ private_strings: Sequence[str] = (), private_tokens: Sequence[str] = (),
188
+ ) -> str:
189
+ return render_audit_json(
190
+ project_audit(
191
+ attempt_dir, raw_retention=raw_retention, lifecycle=lifecycle,
192
+ private_strings=private_strings, private_tokens=private_tokens,
193
+ )
194
+ )
195
+
196
+
197
+ def _attempt_private_strings(
198
+ *, home_dir: Path, state_root: Path, ops_dir: Path | None,
199
+ ) -> tuple[tuple[str, ...], tuple[str, ...]]:
200
+ """Known private material for ``frontdoor.audit``'s privacy guard, split
201
+ by matching rule: ``(private_strings, private_tokens)``.
202
+
203
+ This Attempt's HOME, state root and OPS directory are matched as plain
204
+ substrings -- a value or key that merely repeats one of these absolute
205
+ paths, without itself looking like an absolute path or a Git remote URL
206
+ (the only things BP6a's own heuristic catches on its own), is refused
207
+ too. The OS user name is matched only as a whole path component or whole
208
+ token (see ``frontdoor.audit._whole_component_or_token_match``): a short
209
+ user name (for example ``ci`` or ``ops``) must not refuse an unrelated
210
+ value or key that merely *contains* it as a substring, while a genuine
211
+ leak of the user name as its own path component or token is still
212
+ refused."""
213
+
214
+ strings = [str(home_dir), str(state_root)]
215
+ if ops_dir is not None:
216
+ strings.append(str(ops_dir))
217
+ try:
218
+ user = getpass.getuser()
219
+ except Exception:
220
+ user = None
221
+ tokens = [user] if user else []
222
+ return tuple(s for s in strings if s), tuple(t for t in tokens if t)
223
+
224
+
225
+ def _path_is_ignored(repository: Path, relpath: str) -> bool:
226
+ completed = subprocess.run(
227
+ ("git", "-C", str(repository), "check-ignore", "-q", "--no-index", "--", relpath),
228
+ check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
229
+ )
230
+ return completed.returncode == 0
231
+
232
+
233
+ def _assert_local_retention_gitignore_coverage(identity: Path, dest_rel: str) -> None:
234
+ """Refuse ``local`` retention, before any write, unless this Evidence
235
+ repository's ``.gitignore`` already excludes every raw path this Attempt
236
+ would place -- a missing or insufficient block would otherwise let raw
237
+ files land on disk unprotected from an accidental future commit."""
238
+
239
+ probes = (
240
+ f"{dest_rel}/manifest.json",
241
+ f"{dest_rel}/run/.wfc-coverage-probe",
242
+ f"{dest_rel}/ops/.wfc-coverage-probe",
243
+ )
244
+ uncovered = [probe for probe in probes if not _path_is_ignored(identity, probe)]
245
+ if uncovered:
246
+ raise ArchiveError(
247
+ "refusing local raw retention: this Evidence repository's .gitignore does not "
248
+ "exclude every raw path a local-retention archive would place on disk ("
249
+ + ", ".join(uncovered) + "); re-run `wfc init` against it, or add the managed "
250
+ "block yourself, before archiving with --raw-retention local"
251
+ )
252
+
253
+
254
+ def _assert_audit_path_not_ignored(identity: Path, dest_rel: str) -> None:
255
+ """Refuse, before any write, when this Evidence repository's own
256
+ ``.gitignore`` would exclude ``audit.json`` -- every raw retention mode
257
+ commits it, so an operator-added pattern that happens to also cover it
258
+ (for example a broad ``*.json``) must be refused up front rather than
259
+ discovered only once placement has already happened and the commit
260
+ itself then fails."""
261
+
262
+ probe = f"{dest_rel}/{AUDIT_FILENAME}"
263
+ if _path_is_ignored(identity, probe):
264
+ raise ArchiveError(
265
+ f"refusing: this Evidence repository's .gitignore excludes {probe}, but every "
266
+ "raw retention mode commits it; adjust the .gitignore before archiving"
267
+ )
268
+
269
+
270
+ def assert_source_isolation(dest: Path, *sources: Path | None) -> None:
271
+ """Refuse a destination that is, or is nested under/over, any source."""
272
+
273
+ for src in sources:
274
+ if src is None:
275
+ continue
276
+ if dest == src:
277
+ raise ArchiveError(f"refusing: destination equals source: {dest}")
278
+ if src in dest.parents:
279
+ raise ArchiveError(f"refusing: destination {dest} is nested inside source {src}")
280
+ if dest in src.parents:
281
+ raise ArchiveError(f"refusing: source {src} is nested inside destination {dest}")
282
+
283
+
284
+ def assert_staging_disjoint_from_destination(staging: Path, dest: Path) -> None:
285
+ """Refuse when the resolved staging and destination paths are equal or
286
+ nested, which a tracked symlink inside the Evidence repository (for
287
+ example ``.wfc-archive-staging`` pointing into ``archive/``) can cause
288
+ even though the two paths are lexically distinct. Checked before any
289
+ cleanup: ``_manifest_candidate`` unconditionally removes the staging
290
+ tree first, and that removal must never alias the placed, not-yet-
291
+ committed destination."""
292
+
293
+ staging_real, dest_real = staging.resolve(), dest.resolve()
294
+ if staging_real == dest_real:
295
+ raise ArchiveError(
296
+ f"refusing: staging directory {staging} resolves to the same path as destination {dest}"
297
+ )
298
+ if staging_real in dest_real.parents or dest_real in staging_real.parents:
299
+ raise ArchiveError(
300
+ f"refusing: staging directory {staging} and destination {dest} resolve to nested paths"
301
+ )
302
+
303
+
304
+ def assert_dest_under_archive_root(dest: Path, archive_root: Path) -> None:
305
+ try:
306
+ dest.relative_to(archive_root)
307
+ except ValueError:
308
+ raise ArchiveError(
309
+ f"refusing: destination {dest} is not under this repository's archive root {archive_root}"
310
+ ) from None
311
+
312
+
313
+ def _is_contained(path: Path, root: Path) -> bool:
314
+ try:
315
+ path.relative_to(root)
316
+ except ValueError:
317
+ return False
318
+ return True
319
+
320
+
321
+ def assert_no_symlink_escape(path: Path, repo_root: Path) -> None:
322
+ """Refuse ``path`` (lexically under ``repo_root``) when any existing
323
+ ancestor component between ``repo_root`` and ``path`` is a symlink whose
324
+ target resolves outside ``repo_root`` -- checked before any write, so a
325
+ tracked symlink (for example ``archive/`` pointing outside the Evidence
326
+ repository) cannot place data outside it even though the eventual commit
327
+ would separately, but only afterward, refuse to commit it."""
328
+
329
+ repo_root_real = repo_root.resolve()
330
+ current = repo_root
331
+ for part in path.relative_to(repo_root).parts:
332
+ current = current / part
333
+ if current.is_symlink() and not _is_contained(current.resolve(), repo_root_real):
334
+ raise ArchiveError(
335
+ f"refusing: {current} is a symlink escaping the evidence repository root {repo_root_real}"
336
+ )
337
+
338
+
339
+ def sha256_of(path: Path) -> str:
340
+ h = hashlib.sha256()
341
+ with path.open("rb") as f:
342
+ for chunk in iter(lambda: f.read(1 << 20), b""):
343
+ h.update(chunk)
344
+ return h.hexdigest()
345
+
346
+
347
+ def matches_any(name: str, patterns: list[str]) -> bool:
348
+ return any(fnmatch.fnmatch(name, p) for p in patterns)
349
+
350
+
351
+ def _copy_one(src: Path, dest_root: Path, rel: Path, copied: list[dict]) -> None:
352
+ dest = dest_root / rel
353
+ if dest.exists():
354
+ raise ArchiveError(f"refusing to overwrite existing destination file: {dest}")
355
+ dest.parent.mkdir(parents=True, exist_ok=True)
356
+ before = sha256_of(src)
357
+ shutil.copy2(src, dest)
358
+ after = sha256_of(dest)
359
+ if before != after:
360
+ raise ArchiveError(f"copy verification failed for {src} -> {dest}")
361
+ copied.append({
362
+ "path": str(rel).replace("\\", "/"),
363
+ "source": str(src),
364
+ "sha256": after,
365
+ "bytes": dest.stat().st_size,
366
+ })
367
+
368
+
369
+ def _plan_run_files(run_dir: Path) -> list[Path]:
370
+ planned: list[Path] = []
371
+ for pattern in RUN_ROOT_ALLOW:
372
+ planned += [p for p in sorted(run_dir.glob(pattern)) if p.is_file()]
373
+ checkouts = run_dir / "checkouts"
374
+ if checkouts.is_dir():
375
+ for checkout_dir in sorted(p for p in checkouts.iterdir() if p.is_dir()):
376
+ for pattern in CHECKOUT_ALLOW:
377
+ planned += [p for p in sorted(checkout_dir.glob(pattern)) if p.is_file()]
378
+ return planned
379
+
380
+
381
+ def _plan_ops_files(ops_dir: Path) -> list[Path]:
382
+ planned: list[Path] = []
383
+ for pattern in OPS_ROOT_ALLOW:
384
+ planned += [p for p in sorted(ops_dir.glob(pattern)) if p.is_file()]
385
+ for pattern in OPS_SUBDIR_ALLOW:
386
+ for subdir in sorted(ops_dir.glob(pattern)):
387
+ if subdir.is_dir() and subdir.name not in BULK_DIR_DENY:
388
+ planned += [p for p in sorted(subdir.rglob("*")) if p.is_file()]
389
+ return planned
390
+
391
+
392
+ def collect_run_files(run_dir: Path, dest_root: Path, copied: list[dict]) -> None:
393
+ for pattern in RUN_ROOT_ALLOW:
394
+ for src in sorted(run_dir.glob(pattern)):
395
+ if src.is_file():
396
+ _copy_one(src, dest_root, Path("run") / src.name, copied)
397
+
398
+ checkouts = run_dir / "checkouts"
399
+ if checkouts.is_dir():
400
+ for checkout_dir in sorted(p for p in checkouts.iterdir() if p.is_dir()):
401
+ for pattern in CHECKOUT_ALLOW:
402
+ for src in sorted(checkout_dir.glob(pattern)):
403
+ if src.is_file():
404
+ rel = Path("run") / "checkouts" / checkout_dir.name / src.name
405
+ _copy_one(src, dest_root, rel, copied)
406
+
407
+
408
+ def collect_ops_files(ops_dir: Path, dest_root: Path, copied: list[dict]) -> None:
409
+ for pattern in OPS_ROOT_ALLOW:
410
+ for src in sorted(ops_dir.glob(pattern)):
411
+ if src.is_file():
412
+ _copy_one(src, dest_root, Path("ops") / src.name, copied)
413
+
414
+ for pattern in OPS_SUBDIR_ALLOW:
415
+ for subdir in sorted(ops_dir.glob(pattern)):
416
+ if subdir.is_dir() and subdir.name not in BULK_DIR_DENY:
417
+ for src in sorted(p for p in subdir.rglob("*") if p.is_file()):
418
+ rel = Path("ops") / subdir.name / src.relative_to(subdir)
419
+ _copy_one(src, dest_root, rel, copied)
420
+
421
+
422
+ def load_json(path: Path) -> dict | None:
423
+ try:
424
+ return json.loads(path.read_text())
425
+ except Exception:
426
+ return None
427
+
428
+
429
+ def parse_kv_file(path: Path) -> dict[str, str]:
430
+ """Parse a flat ``key=value`` pin file; no inference, as the original."""
431
+
432
+ result: dict[str, str] = {}
433
+ for line in path.read_text(errors="replace").splitlines():
434
+ line = line.strip()
435
+ if not line or line.startswith("#") or "=" not in line:
436
+ continue
437
+ key, _, value = line.partition("=")
438
+ key = key.strip()
439
+ if key.isidentifier():
440
+ result[key] = value.strip()
441
+ return result
442
+
443
+
444
+ def _fill_from(source: dict, source_label: str, facts: dict, field_sources: dict) -> None:
445
+ for key in RUN_IDENTITY_FIELDS:
446
+ if facts.get(key) is not None:
447
+ continue
448
+ value = source.get(key)
449
+ if value is not None:
450
+ facts[key] = value
451
+ field_sources[key] = source_label
452
+
453
+
454
+ def extract_facts(run_dir: Path, ops_dir: Path | None) -> dict:
455
+ facts: dict = {key: None for key in RUN_IDENTITY_FIELDS}
456
+ facts.update({
457
+ "hops": [],
458
+ "adapters": [], "models": [], "reasoning_levels": [], "workflow_roles": [],
459
+ "evidence_commands": [],
460
+ "checkouts": [],
461
+ })
462
+ field_sources: dict[str, str] = {}
463
+
464
+ op_summary = load_json(run_dir / "operator-summary.json")
465
+ if op_summary:
466
+ _fill_from(op_summary, "operator-summary.json", facts, field_sources)
467
+ for hop in op_summary.get("hops", []) or []:
468
+ facts["hops"].append({
469
+ "hop_id": hop.get("hop_id"),
470
+ "role": hop.get("role"),
471
+ "outcome": hop.get("outcome"),
472
+ "summary": hop.get("summary"),
473
+ })
474
+ for ev in op_summary.get("execution_evidence", []) or []:
475
+ for k, bucket in (("adapter", "adapters"), ("model", "models"),
476
+ ("reasoning", "reasoning_levels"),
477
+ ("workflow_role", "workflow_roles")):
478
+ v = ev.get(k)
479
+ if v and v not in facts[bucket]:
480
+ facts[bucket].append(v)
481
+
482
+ checkouts_dir = run_dir / "checkouts"
483
+ if checkouts_dir.is_dir():
484
+ for checkout_dir in sorted(p for p in checkouts_dir.iterdir() if p.is_dir()):
485
+ facts["checkouts"].append(checkout_dir.name)
486
+ cp = load_json(checkout_dir / "checkpoint.json")
487
+ if cp:
488
+ for ev in cp.get("evidence", []) or []:
489
+ name = ev.get("command_name") or ev.get("provider")
490
+ if name and name not in facts["evidence_commands"]:
491
+ facts["evidence_commands"].append(name)
492
+ rj = load_json(checkout_dir / "run.json")
493
+ if rj:
494
+ _fill_from(rj, f"checkouts/{checkout_dir.name}/run.json", facts, field_sources)
495
+ if not facts["hops"]:
496
+ for hop in rj.get("hops", []) or []:
497
+ facts["hops"].append({
498
+ "hop_id": hop.get("hop_id"),
499
+ "role": hop.get("role"),
500
+ "outcome": hop.get("outcome"),
501
+ "summary": hop.get("summary"),
502
+ })
503
+
504
+ facts["field_sources"] = field_sources
505
+ facts["ops_source"] = str(ops_dir) if ops_dir else None
506
+
507
+ facts["repository_identities"] = None
508
+ if ops_dir:
509
+ prep = ops_dir / "preparation.log"
510
+ if prep.is_file():
511
+ ids: dict[str, str] = {}
512
+ for line in prep.read_text(errors="replace").splitlines()[:10]:
513
+ for label in ("Core", "WFC", "Runtime", "Codex"):
514
+ prefix = f"{label}:"
515
+ if line.strip().startswith(prefix):
516
+ ids[label] = line.split(":", 1)[1].strip()
517
+ if ids:
518
+ facts["repository_identities"] = ids
519
+
520
+ facts["pinned_revisions"] = None
521
+ if ops_dir:
522
+ merged: dict[str, str] = {}
523
+ used_files: list[str] = []
524
+ for fname in PIN_FILES_IN_PRIORITY:
525
+ p = ops_dir / fname
526
+ if p.is_file():
527
+ used_files.append(fname)
528
+ for k, v in parse_kv_file(p).items():
529
+ merged.setdefault(k, v)
530
+ if merged:
531
+ facts["pinned_revisions"] = {"values": merged, "source_files": used_files}
532
+
533
+ return facts
534
+
535
+
536
+ # --------------------------------------------------------------------------
537
+ # Ported orchestration (from the Evidence repository's wfc-archive-run)
538
+ # --------------------------------------------------------------------------
539
+
540
+ def _reject_control_characters(value: str, *, label: str) -> None:
541
+ if any(ord(ch) < 32 or ord(ch) == 127 for ch in value):
542
+ raise ArchiveError(f"refusing {label}: contains a control character")
543
+
544
+
545
+ def derive_attempt_id(state_root: Path) -> str:
546
+ attempt_id = state_root.name
547
+ if not attempt_id:
548
+ raise ArchiveError(f"cannot derive an attempt id from state root: {state_root}")
549
+ if attempt_id in (".", "..") or attempt_id.startswith("-"):
550
+ raise ArchiveError(f"refusing implausible attempt id derived from state root: {attempt_id}")
551
+ _reject_control_characters(attempt_id, label="attempt id derived from state root")
552
+ return attempt_id
553
+
554
+
555
+ # BP6c identity decision: the product lifecycle (``frontdoor.postrun``) never
556
+ # derives an Attempt identity from the engine state root's own directory name
557
+ # -- BP4a always names that directory ``engine-state``, identical across
558
+ # every checkout on a machine, so every Run of every consumer would collide
559
+ # on one destination. It instead builds an explicit, Run-derived identity
560
+ # (``<repository_name>-<run_id>``, lower-cased) and passes it in here;
561
+ # ``archive_run`` validates it with the same strictness as a state-root-
562
+ # derived id, plus a closed, path-safe character set, since this value can
563
+ # originate from an operator-authored Consumer Config field.
564
+ _ATTEMPT_IDENTITY_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$")
565
+
566
+
567
+ def validate_explicit_attempt_identity(value: str) -> str:
568
+ """Validate a caller-supplied, explicit Attempt identity (BP6c).
569
+
570
+ Used only for ``archive_run``'s additive ``attempt_identity`` parameter;
571
+ the legacy ``derive_attempt_id`` path (engine state root basename) is
572
+ unchanged and keeps its own, looser plausibility checks.
573
+ """
574
+
575
+ if not isinstance(value, str) or not _ATTEMPT_IDENTITY_RE.match(value):
576
+ raise ArchiveError(f"refusing implausible explicit attempt identity: {value!r}")
577
+ _reject_control_characters(value, label="explicit attempt identity")
578
+ return value
579
+
580
+
581
+ def _pick(key: str, *sources: dict) -> str | None:
582
+ for src in sources:
583
+ value = src.get(key)
584
+ if isinstance(value, str) and value.strip():
585
+ return value.strip()
586
+ return None
587
+
588
+
589
+ def _agree(key: str, *labeled_sources: tuple[str, dict]) -> str | None:
590
+ """First non-empty value for ``key`` across ``labeled_sources``, in order.
591
+
592
+ Refuses when two sources that each carry their own non-empty value for
593
+ ``key`` disagree, instead of silently preferring whichever is checked
594
+ first.
595
+ """
596
+
597
+ found = [
598
+ (label, source[key].strip())
599
+ for label, source in labeled_sources
600
+ if isinstance(source.get(key), str) and source.get(key).strip()
601
+ ]
602
+ distinct = sorted({value for _, value in found})
603
+ if len(distinct) > 1:
604
+ detail = ", ".join(f"{label}={value!r}" for label, value in found)
605
+ raise ArchiveError(
606
+ f"{key} disagrees between this Run's own authoritative state ({detail}); "
607
+ "refusing to archive a Run whose own state disagrees with itself"
608
+ )
609
+ return found[0][1] if found else None
610
+
611
+
612
+ @dataclass(frozen=True)
613
+ class RunIdentity:
614
+ run_id: str
615
+ work_item_id: str | None
616
+ run_status: str | None
617
+ checkout_id: str | None
618
+ repository: str | None
619
+
620
+
621
+ def run_identity(state_root: Path) -> RunIdentity:
622
+ summary = load_json(state_root / "operator-summary.json") or {}
623
+ plan = load_json(state_root / "operator-plan.json") or {}
624
+ assoc = load_json(state_root / "checkout-association.json") or {}
625
+ run: dict = {}
626
+ checkouts = state_root / "checkouts"
627
+ if checkouts.is_dir():
628
+ for directory in sorted(p for p in checkouts.iterdir() if p.is_dir()):
629
+ candidate = load_json(directory / "run.json")
630
+ if candidate:
631
+ run = candidate
632
+ break
633
+
634
+ plan_state_root = _pick("state_root", plan)
635
+ if plan_state_root and Path(plan_state_root).resolve() != state_root.resolve():
636
+ raise ArchiveError(
637
+ f"state root {state_root} disagrees with the Run's own operator-plan.json "
638
+ f"state_root ({plan_state_root}); refusing to archive a mismatched state root"
639
+ )
640
+
641
+ run_id = _agree("run_id", ("operator-summary.json", summary), ("operator-plan.json", plan), ("checkouts/*/run.json", run))
642
+ work_item_id = _agree("work_item_id", ("operator-summary.json", summary), ("operator-plan.json", plan), ("checkouts/*/run.json", run))
643
+ run_status = _pick("run_status", summary) or _pick("status", run)
644
+ checkout_id = _agree("checkout_id", ("operator-summary.json", summary), ("checkout-association.json", assoc))
645
+
646
+ repository = _pick("repository", plan)
647
+ canonical_path = _pick("canonical_path", assoc)
648
+ if repository and canonical_path and repository != canonical_path:
649
+ raise ArchiveError(
650
+ f"repository disagrees between operator-plan.json ({repository!r}) and "
651
+ f"checkout-association.json canonical_path ({canonical_path!r}); refusing "
652
+ "to archive a Run whose own state disagrees with itself"
653
+ )
654
+ repository = repository or canonical_path
655
+
656
+ if not run_id:
657
+ raise ArchiveError(
658
+ f"no Run id found under {state_root}: not a WFC Run state root (expected "
659
+ "operator-summary.json, operator-plan.json or checkouts/*/run.json)"
660
+ )
661
+ return RunIdentity(run_id=run_id, work_item_id=work_item_id, run_status=run_status,
662
+ checkout_id=checkout_id, repository=repository)
663
+
664
+
665
+ def resolve_ops_dir(state_root: Path, ops_candidate: Path, attempt_id: str) -> Path | None:
666
+ plan = load_json(state_root / "operator-plan.json") or {}
667
+ bindings = _pick("execution_bindings_source", plan)
668
+ # ``execution_bindings_source`` only names OPS evidence when it points at
669
+ # the conventional ``execution-bindings.yaml`` leaf (see
670
+ # ``OPS_ROOT_ALLOW``) the self-development preparation sequence has
671
+ # always written there. BP6c's installed product lifecycle passes its
672
+ # own, differently-named cached envelope file as the same engine argv
673
+ # (a per-checkout cache, never an OPS directory); that recorded parent
674
+ # must not be mistaken for recorded-but-missing OPS evidence below.
675
+ recorded = (
676
+ Path(bindings).parent
677
+ if bindings and Path(bindings).name == "execution-bindings.yaml" else None
678
+ )
679
+
680
+ if not ops_candidate.is_dir():
681
+ if recorded is not None and recorded.is_dir():
682
+ raise ArchiveError(
683
+ f"default OPS directory {ops_candidate} is absent, but this Run's preparation "
684
+ f"records OPS evidence at {recorded}; refusing to archive without it"
685
+ )
686
+ return None
687
+
688
+ if recorded is not None and recorded.resolve() != ops_candidate.resolve():
689
+ raise ArchiveError(
690
+ f"OPS directory {ops_candidate} is not the one recorded in this Run's preparation "
691
+ f"({recorded}); refusing to archive incoherent OPS evidence"
692
+ )
693
+
694
+ pins = ops_candidate / "preparation-pins.txt"
695
+ if pins.is_file():
696
+ values = parse_kv_file(pins)
697
+ pinned_attempt = values.get("attempt_id")
698
+ if pinned_attempt and pinned_attempt != attempt_id:
699
+ raise ArchiveError(
700
+ f"OPS directory {ops_candidate} was prepared for attempt {pinned_attempt}, "
701
+ f"not {attempt_id}; refusing to archive incoherent OPS evidence"
702
+ )
703
+ pinned_state = values.get("state_root")
704
+ if pinned_state and Path(pinned_state).resolve() != state_root.resolve():
705
+ raise ArchiveError(
706
+ f"OPS directory {ops_candidate} was prepared for state root {pinned_state}, "
707
+ f"not {state_root}; refusing to archive incoherent OPS evidence"
708
+ )
709
+ return ops_candidate
710
+
711
+
712
+ def semantic_annotation(semantic_path: Path | None) -> tuple[dict | None, str | None, str | None]:
713
+ """Return ``(payload, domain, workstream)``; ``payload`` is stored verbatim."""
714
+
715
+ if semantic_path is None:
716
+ return None, None, None
717
+ try:
718
+ payload = json.loads(semantic_path.read_text())
719
+ except Exception as exc:
720
+ raise ArchiveError(f"--semantic-json is not valid JSON: {semantic_path}: {exc}") from exc
721
+ if not isinstance(payload, dict):
722
+ raise ArchiveError(f"--semantic-json must contain a JSON object: {semantic_path}")
723
+
724
+ domain, workstream = payload.get("domain"), payload.get("workstream")
725
+ present = [n for n, v in (("domain", domain), ("workstream", workstream)) if v is not None]
726
+ if not present:
727
+ return payload, None, None
728
+ if len(present) != 2:
729
+ raise ArchiveError(
730
+ f'--semantic-json supplies "{present[0]}" without its counterpart; supply both '
731
+ '"domain" and "workstream" to file the Run under an existing taxonomy entry, '
732
+ "or neither to file it under archive/unclassified/"
733
+ )
734
+
735
+ def segment(name: str, value: object) -> str:
736
+ if not isinstance(value, str) or not value.strip():
737
+ raise ArchiveError(f'--semantic-json "{name}" must be a non-empty string')
738
+ value = value.strip()
739
+ if value in (".", "..") or not all(c.isalnum() or c in "._-" for c in value):
740
+ raise ArchiveError(f'--semantic-json "{name}" is not usable as one path segment: {value!r}')
741
+ return value
742
+
743
+ return payload, segment("domain", domain), segment("workstream", workstream)
744
+
745
+
746
+ def destination_for(evidence_repo: Path, domain: str | None, workstream: str | None, attempt_id: str) -> Path:
747
+ if domain:
748
+ return evidence_repo / "archive" / domain / workstream / attempt_id
749
+ return evidence_repo / "archive" / "unclassified" / attempt_id
750
+
751
+
752
+ def _status_lines(repository: Path) -> list[str]:
753
+ completed = subprocess.run(
754
+ ("git", "-C", str(repository), "status", "--porcelain=v1", "--untracked-files=all"),
755
+ check=False, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
756
+ )
757
+ if completed.returncode != 0:
758
+ raise ArchiveError(completed.stderr.strip() or "git status failed")
759
+ return [line for line in completed.stdout.splitlines() if line]
760
+
761
+
762
+ def _status_path(line: str) -> str:
763
+ rest = line[3:]
764
+ if " -> " in rest:
765
+ rest = rest.split(" -> ", 1)[1]
766
+ return rest
767
+
768
+
769
+ def _assert_narrow_cleanliness(repository: Path, *, allowed_prefixes: tuple[str, ...]) -> None:
770
+ """The narrowed cleanliness rule: nothing staged, nothing dirty outside
771
+ the attempt's own destination and staging directory."""
772
+
773
+ def allowed(path: str) -> bool:
774
+ return any(path == prefix or path.startswith(f"{prefix}/") for prefix in allowed_prefixes)
775
+
776
+ for line in _status_lines(repository):
777
+ index_status, worktree_status = line[0], line[1]
778
+ if index_status not in (" ", "?"):
779
+ raise ArchiveError(f"evidence repository has pre-existing staged state: {_status_path(line)}")
780
+ if worktree_status != " " and not allowed(_status_path(line)):
781
+ raise ArchiveError(
782
+ "evidence repository is not clean outside the archive destination; "
783
+ f"commit or stash local changes first: {_status_path(line)}"
784
+ )
785
+
786
+
787
+ def _path_is_tracked_in_head(repository: Path, path_rel: str) -> bool:
788
+ completed = subprocess.run(
789
+ ("git", "-C", str(repository), "ls-tree", "-r", "--name-only", "HEAD", "--", path_rel),
790
+ check=False, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
791
+ )
792
+ return completed.returncode == 0 and bool(completed.stdout.strip())
793
+
794
+
795
+ def _path_is_tracked_clean(repository: Path, path_rel: str) -> bool:
796
+ """True when nothing under ``path_rel`` is staged or dirty, and it is
797
+ actually committed at HEAD.
798
+
799
+ ``git status`` never lists a path excluded by ``.gitignore``, so status
800
+ silence alone is not proof of a commit: a destination entirely covered
801
+ by this Evidence repository's own managed ``.gitignore`` (for example a
802
+ legacy ``raw_retention=None`` archive placed into a repository whose
803
+ default retention is ``local``) would otherwise be read as already
804
+ committed when it was never committed at all, reporting a false success
805
+ and leaving the destination permanently mismatched on every later
806
+ attempt. Requiring the path to actually appear in the HEAD tree closes
807
+ that gap without changing the outcome for any path that was genuinely
808
+ committed."""
809
+
810
+ for line in _status_lines(repository):
811
+ if _status_path(line) == path_rel or _status_path(line).startswith(f"{path_rel}/"):
812
+ return False
813
+ return _path_is_tracked_in_head(repository, path_rel)
814
+
815
+
816
+ @dataclass(frozen=True)
817
+ class ArchiveReport:
818
+ outcome: str # "dry_run" | "archived" | "resumed_commit" | "no_op"
819
+ attempt_id: str
820
+ run_id: str | None
821
+ work_item_id: str | None
822
+ run_status: str | None
823
+ checkout_id: str | None
824
+ repository: str | None
825
+ state_root: Path
826
+ ops_dir: Path | None
827
+ ops_candidate: Path
828
+ destination_relative: str
829
+ semantic_path: Path | None
830
+ files: int
831
+ commit: str | None
832
+
833
+
834
+ def _manifest_candidate(
835
+ *, attempt_id: str, state_root: Path, ops_dir: Path | None, semantic_payload: dict | None,
836
+ staging: Path, archived_at: str | None = None,
837
+ ) -> tuple[dict, list[dict]]:
838
+ shutil.rmtree(staging, ignore_errors=True)
839
+ staging.mkdir(parents=True)
840
+ copied: list[dict] = []
841
+ collect_run_files(state_root, staging, copied)
842
+ if ops_dir:
843
+ collect_ops_files(ops_dir, staging, copied)
844
+ facts = extract_facts(state_root, ops_dir)
845
+ manifest = {
846
+ "attempt_id": attempt_id,
847
+ "archived_at": archived_at if archived_at is not None else datetime.now(timezone.utc).isoformat(),
848
+ "sources": {"run_dir": str(state_root), "ops_dir": str(ops_dir) if ops_dir else None},
849
+ "copied_files": copied,
850
+ "facts": facts,
851
+ "semantic": semantic_payload,
852
+ }
853
+ return manifest, copied
854
+
855
+
856
+ def _manifests_match_ignoring_archived_at(a: dict, b: dict) -> bool:
857
+ def strip(manifest: dict) -> dict:
858
+ return {k: v for k, v in manifest.items() if k != "archived_at"}
859
+
860
+ def copied_key(entries: list[dict]) -> set[str]:
861
+ # Compare each entry whole, not a fixed projection of known keys --
862
+ # a genuinely derived entry has exactly the keys ``_copy_one``
863
+ # writes, so any *additional* key present only in the placed entry
864
+ # (forged provenance, for example) is otherwise invisible to a
865
+ # per-key comparison. The existing duplicate-path refusal
866
+ # (``_load_existing_manifest``) is the multiplicity guard for a
867
+ # placed manifest listing the same path twice.
868
+ return {json.dumps(e, sort_keys=True) for e in entries}
869
+
870
+ a2, b2 = strip(a), strip(b)
871
+ if copied_key(a2.pop("copied_files", [])) != copied_key(b2.pop("copied_files", [])):
872
+ return False
873
+ return a2 == b2
874
+
875
+
876
+ def _safe_manifest_relpath(rel: object, *, dest: Path) -> Path:
877
+ """Validate a manifest-recorded ``copied_files`` entry path before any
878
+ filesystem access: refuse absolute, traversal or otherwise ambiguous
879
+ paths, and refuse a symlink anywhere along it that escapes ``dest``, so a
880
+ crafted or tampered manifest can never make this read (or later commit)
881
+ outside the archive destination."""
882
+
883
+ if not isinstance(rel, str) or not rel or rel != rel.strip() or "\\" in rel:
884
+ raise ArchiveError(f"existing archived manifest lists an unsafe file path: {rel!r}")
885
+ candidate = PurePosixPath(rel)
886
+ if candidate.is_absolute() or any(part in ("", ".", "..") for part in candidate.parts):
887
+ raise ArchiveError(f"existing archived manifest lists an unsafe file path: {rel!r}")
888
+ if candidate.as_posix() != rel:
889
+ raise ArchiveError(f"existing archived manifest lists an ambiguous file path: {rel!r}")
890
+ dest_real = dest.resolve()
891
+ target = dest
892
+ for part in candidate.parts:
893
+ target = target / part
894
+ if target.is_symlink() and not _is_contained(target.resolve(), dest_real):
895
+ raise ArchiveError(
896
+ f"existing archived manifest file path escapes the archive destination via a symlink: {rel!r}"
897
+ )
898
+ return target
899
+
900
+
901
+ def _load_existing_manifest(dest: Path) -> dict:
902
+ manifest_path = dest / "manifest.json"
903
+ if not manifest_path.is_file():
904
+ raise ArchiveError(f"archive destination exists but has no manifest.json: {dest}")
905
+ try:
906
+ manifest = json.loads(manifest_path.read_text())
907
+ except Exception as exc:
908
+ raise ArchiveError(f"existing archived manifest does not parse: {manifest_path}: {exc}") from exc
909
+ copied = manifest.get("copied_files")
910
+ if not isinstance(copied, list) or not copied:
911
+ raise ArchiveError(f"existing archived manifest lists no copied files: {manifest_path}")
912
+ seen_paths: set[str] = set()
913
+ for entry in copied:
914
+ rel = entry.get("path") if isinstance(entry, dict) else None
915
+ target = _safe_manifest_relpath(rel, dest=dest)
916
+ if rel in seen_paths:
917
+ raise ArchiveError(f"existing archived manifest lists a duplicate file path: {rel!r}")
918
+ seen_paths.add(rel)
919
+ if not target.is_file():
920
+ raise ArchiveError(f"existing archived manifest lists a file that is not present: {rel!r}")
921
+ return manifest
922
+
923
+
924
+ def _verify_resumable_placement(
925
+ manifest: dict, *, dest: Path, attempt_id: str, state_root: Path, ops_dir: Path | None,
926
+ semantic_payload: dict | None, staging: Path,
927
+ ) -> None:
928
+ """Re-verify a placed-but-uncommitted archive before trusting it for
929
+ commit. An interruption between placement and commit leaves data that
930
+ this process (or an attacker) could tamper with before the retry.
931
+ Checking the placed files against their own recorded digest only proves
932
+ internal self-consistency: a file altered together with a matching
933
+ altered digest in its own manifest, or an outright falsified fact,
934
+ source or semantic field, would still pass that check. Refuse unless
935
+ (a) the attempt id and recorded sources match this archive run, (b)
936
+ every placed file still matches its own manifest entry, and (c) the
937
+ placed manifest itself, ignoring only ``archived_at``, matches a
938
+ manifest freshly derived from the current authoritative Run/OPS sources
939
+ -- so a genuinely intact interruption is the only thing that can
940
+ resume."""
941
+
942
+ if manifest.get("attempt_id") != attempt_id:
943
+ raise ArchiveError(
944
+ f"placed archive at {dest} was staged for attempt {manifest.get('attempt_id')!r}, "
945
+ f"not {attempt_id!r}; refusing to commit a mismatched archive"
946
+ )
947
+ sources = manifest.get("sources") or {}
948
+ expected_ops = str(ops_dir) if ops_dir else None
949
+ if sources.get("run_dir") != str(state_root) or sources.get("ops_dir") != expected_ops:
950
+ raise ArchiveError(
951
+ f"placed archive at {dest} was staged from different sources than this archive run; "
952
+ "refusing to commit a mismatched archive"
953
+ )
954
+ for entry in manifest["copied_files"]:
955
+ rel = entry["path"]
956
+ target = dest / rel
957
+ if entry.get("bytes") != target.stat().st_size:
958
+ raise ArchiveError(
959
+ f"placed archive file does not match its recorded size, refusing to commit: {rel}"
960
+ )
961
+ if entry.get("sha256") != sha256_of(target):
962
+ raise ArchiveError(
963
+ f"placed archive file does not match its recorded digest, refusing to commit: {rel}"
964
+ )
965
+
966
+ try:
967
+ candidate_manifest, _ = _manifest_candidate(
968
+ attempt_id=attempt_id, state_root=state_root, ops_dir=ops_dir,
969
+ semantic_payload=semantic_payload, staging=staging,
970
+ )
971
+ finally:
972
+ shutil.rmtree(staging, ignore_errors=True)
973
+ if not _manifests_match_ignoring_archived_at(manifest, candidate_manifest):
974
+ raise ArchiveError(
975
+ f"placed archive at {dest} does not match a manifest freshly derived from the "
976
+ "current authoritative Run/OPS sources; refusing to commit a mismatched or "
977
+ "tampered archive"
978
+ )
979
+
980
+
981
+ def archive_run(
982
+ *, state_root: Path, evidence_repo: Path, semantic_path: Path | None = None, dry_run: bool = False,
983
+ home: Path | None = None, raw_retention: str | None = None, lifecycle: Mapping[str, Any] | None = None,
984
+ attempt_identity: str | None = None,
985
+ ) -> ArchiveReport:
986
+ """Archive ``state_root`` (and its matching OPS directory, if any) into
987
+ ``evidence_repo``, making exactly one scoped commit.
988
+
989
+ ``home`` overrides ``$HOME`` for deriving the default OPS directory
990
+ (``<home>/wfc-ops/<attempt-id>``); it defaults to the real environment,
991
+ exactly as the ported wrapper derived it.
992
+
993
+ ``raw_retention`` is ``None`` (BP5 legacy: every byte of behaviour below
994
+ is unchanged, no ``audit.json``) or one of
995
+ ``frontdoor.config.EVIDENCE_RAW_CHOICES`` (BP6b: ``audit.json`` is
996
+ projected from the verified staged copy and placed/committed per the
997
+ chosen mode; see ``_archive_run_retention_aware``).
998
+
999
+ ``lifecycle`` is caller-supplied lifecycle facts (BP6c: the frontdoor
1000
+ classification and the latest BP4b preservation fact), stored verbatim
1001
+ within ``frontdoor.audit``'s allow-list; it is only used when
1002
+ ``raw_retention`` is not ``None`` and is otherwise ignored, exactly like
1003
+ the legacy path ignores retention altogether.
1004
+
1005
+ ``attempt_identity`` is an additive, explicit Attempt identity (BP6c:
1006
+ the product lifecycle derives it from the Consumer Config repository
1007
+ name and the Run id, never from the engine state root's own directory
1008
+ name). When given, it replaces ``derive_attempt_id(state_root)``
1009
+ entirely, for every ``raw_retention`` value including ``None``. Omitted,
1010
+ every byte of BP5's legacy ``derive_attempt_id`` behaviour is unchanged.
1011
+ """
1012
+
1013
+ if raw_retention is not None and raw_retention not in EVIDENCE_RAW_CHOICES:
1014
+ raise ArchiveError(f"--raw-retention must be one of: {', '.join(EVIDENCE_RAW_CHOICES)}")
1015
+
1016
+ state_root = state_root.expanduser().resolve()
1017
+ if not state_root.is_dir():
1018
+ raise ArchiveError(f"missing state root: {state_root}")
1019
+ _reject_control_characters(str(state_root), label="state root")
1020
+ attempt_id = (
1021
+ validate_explicit_attempt_identity(attempt_identity)
1022
+ if attempt_identity is not None else derive_attempt_id(state_root)
1023
+ )
1024
+
1025
+ evidence_repo = evidence_repo.expanduser().resolve()
1026
+ if not evidence_repo.is_dir():
1027
+ raise ArchiveError(f"missing evidence repository: {evidence_repo}")
1028
+ identity = repository_identity(evidence_repo)
1029
+ if identity != evidence_repo:
1030
+ raise ArchiveError(f"evidence repository path is not the repository root (root is {identity}): {evidence_repo}")
1031
+ if not (identity / "archive").is_dir():
1032
+ raise ArchiveError(f"not a WFC evidence repository (no archive/ directory): {identity}")
1033
+ base_head = repository_head(identity)
1034
+
1035
+ resolved_semantic = semantic_path.expanduser().resolve() if semantic_path else None
1036
+ if resolved_semantic is not None:
1037
+ if not resolved_semantic.is_file():
1038
+ raise ArchiveError(f"--semantic-json is not a readable file: {semantic_path}")
1039
+ _reject_control_characters(str(resolved_semantic), label="--semantic-json path")
1040
+
1041
+ identity_facts = run_identity(state_root)
1042
+
1043
+ home_dir = (home or Path(os.environ.get("HOME", ""))).expanduser()
1044
+ if not str(home_dir):
1045
+ raise ArchiveError("HOME is not set")
1046
+ ops_candidate = home_dir / "wfc-ops" / attempt_id
1047
+ ops_dir = resolve_ops_dir(state_root, ops_candidate, attempt_id)
1048
+ # The old wrapper reports this unresolved candidate verbatim, but
1049
+ # archive_run.py itself always resolves its --ops-dir argument before
1050
+ # using it for anything else (copying, facts, the manifest); match that
1051
+ # split exactly so a symlinked HOME/scratch root cannot produce a
1052
+ # manifest that differs from the old implementation's.
1053
+ ops_dir_resolved = ops_dir.resolve() if ops_dir else None
1054
+
1055
+ semantic_payload, domain, workstream = semantic_annotation(resolved_semantic)
1056
+ dest = destination_for(identity, domain, workstream, attempt_id)
1057
+ dest_rel = dest.relative_to(identity).as_posix()
1058
+ staging = identity / ".wfc-archive-staging" / attempt_id
1059
+ staging_rel = staging.relative_to(identity).as_posix()
1060
+
1061
+ assert_source_isolation(dest, state_root, ops_dir_resolved)
1062
+ assert_source_isolation(staging, state_root, ops_dir_resolved)
1063
+ assert_dest_under_archive_root(dest, identity / "archive")
1064
+ assert_no_symlink_escape(dest, identity)
1065
+ assert_no_symlink_escape(staging, identity)
1066
+ assert_staging_disjoint_from_destination(staging, dest)
1067
+
1068
+ if dry_run:
1069
+ planned = _plan_run_files(state_root) + (_plan_ops_files(ops_dir_resolved) if ops_dir_resolved else [])
1070
+ return ArchiveReport(
1071
+ outcome="dry_run", attempt_id=attempt_id, run_id=identity_facts.run_id,
1072
+ work_item_id=identity_facts.work_item_id, run_status=identity_facts.run_status,
1073
+ checkout_id=identity_facts.checkout_id, repository=identity_facts.repository,
1074
+ state_root=state_root, ops_dir=ops_dir, ops_candidate=ops_candidate,
1075
+ destination_relative=dest_rel, semantic_path=resolved_semantic, files=len(planned), commit=None,
1076
+ )
1077
+
1078
+ _assert_narrow_cleanliness(identity, allowed_prefixes=(dest_rel, staging_rel))
1079
+
1080
+ if raw_retention is not None:
1081
+ _assert_audit_path_not_ignored(identity, dest_rel)
1082
+ if raw_retention == "local":
1083
+ _assert_local_retention_gitignore_coverage(identity, dest_rel)
1084
+ private_strings, private_tokens = _attempt_private_strings(
1085
+ home_dir=home_dir, state_root=state_root, ops_dir=ops_dir_resolved,
1086
+ )
1087
+ return _archive_run_retention_aware(
1088
+ raw_retention=raw_retention, identity=identity, base_head=base_head, attempt_id=attempt_id,
1089
+ state_root=state_root, ops_dir=ops_dir, ops_dir_resolved=ops_dir_resolved,
1090
+ ops_candidate=ops_candidate, semantic_payload=semantic_payload, resolved_semantic=resolved_semantic,
1091
+ dest=dest, dest_rel=dest_rel, staging=staging, identity_facts=identity_facts,
1092
+ private_strings=private_strings, private_tokens=private_tokens, lifecycle=lifecycle,
1093
+ )
1094
+
1095
+ final_run_id, final_work_item_id, final_run_status = (
1096
+ identity_facts.run_id, identity_facts.work_item_id, identity_facts.run_status,
1097
+ )
1098
+
1099
+ if dest.exists():
1100
+ manifest = _load_existing_manifest(dest)
1101
+ if _path_is_tracked_clean(identity, dest_rel):
1102
+ # Already committed: this must be exactly the identical repeat, never
1103
+ # a silent overwrite of a same-named, differently-sourced archive.
1104
+ candidate_manifest, _ = _manifest_candidate(
1105
+ attempt_id=attempt_id, state_root=state_root, ops_dir=ops_dir_resolved,
1106
+ semantic_payload=semantic_payload, staging=staging,
1107
+ )
1108
+ shutil.rmtree(staging, ignore_errors=True)
1109
+ if not _manifests_match_ignoring_archived_at(manifest, candidate_manifest):
1110
+ raise ArchiveError(
1111
+ f"archive destination already exists with different content, refusing to overwrite: {dest_rel}"
1112
+ )
1113
+ facts = manifest.get("facts") or {}
1114
+ final_run_id = facts.get("run_id")
1115
+ final_work_item_id = facts.get("work_item_id")
1116
+ final_run_status = facts.get("run_status") or facts.get("status")
1117
+ commit = _run_git(identity, "log", "-1", "--format=%H", "--", dest_rel).strip()
1118
+ return ArchiveReport(
1119
+ outcome="no_op", attempt_id=attempt_id, run_id=final_run_id, work_item_id=final_work_item_id,
1120
+ run_status=final_run_status, checkout_id=identity_facts.checkout_id,
1121
+ repository=identity_facts.repository, state_root=state_root, ops_dir=ops_dir,
1122
+ ops_candidate=ops_candidate, destination_relative=dest_rel, semantic_path=resolved_semantic,
1123
+ files=len(manifest["copied_files"]), commit=commit or None,
1124
+ )
1125
+ # Placed but never committed (killed between copy and commit): resume,
1126
+ # but only once the placed data is reverified against its own manifest
1127
+ # and against a manifest freshly derived from the current
1128
+ # authoritative Run/OPS sources.
1129
+ _verify_resumable_placement(
1130
+ manifest, dest=dest, attempt_id=attempt_id, state_root=state_root, ops_dir=ops_dir_resolved,
1131
+ semantic_payload=semantic_payload, staging=staging,
1132
+ )
1133
+ copied = manifest["copied_files"]
1134
+ else:
1135
+ try:
1136
+ manifest, copied = _manifest_candidate(
1137
+ attempt_id=attempt_id, state_root=state_root, ops_dir=ops_dir_resolved,
1138
+ semantic_payload=semantic_payload, staging=staging,
1139
+ )
1140
+ (staging / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=False) + "\n")
1141
+ dest.parent.mkdir(parents=True, exist_ok=True)
1142
+ os.rename(staging, dest)
1143
+ except Exception:
1144
+ shutil.rmtree(staging, ignore_errors=True)
1145
+ raise
1146
+ facts = manifest.get("facts") or {}
1147
+ final_run_id = facts.get("run_id")
1148
+ final_work_item_id = facts.get("work_item_id")
1149
+ final_run_status = facts.get("run_status") or facts.get("status")
1150
+
1151
+ paths = tuple(sorted(f"{dest_rel}/{entry['path']}" for entry in copied)) + (f"{dest_rel}/manifest.json",)
1152
+ intent = NewPathCommitIntent(paths=paths, subject=f"evidence: archive {attempt_id}")
1153
+ try:
1154
+ committed = bounded_path_commit(
1155
+ identity, expected_repository=identity, base_head=base_head, allowed_paths=(dest_rel,),
1156
+ intent=intent, work_item_id=attempt_id, hop_id=attempt_id,
1157
+ )
1158
+ except TrustedCommitError as error:
1159
+ raise ArchiveError(f"commit failed: {error}") from error
1160
+
1161
+ return ArchiveReport(
1162
+ outcome="archived", attempt_id=attempt_id, run_id=final_run_id, work_item_id=final_work_item_id,
1163
+ run_status=final_run_status, checkout_id=identity_facts.checkout_id, repository=identity_facts.repository,
1164
+ state_root=state_root, ops_dir=ops_dir, ops_candidate=ops_candidate, destination_relative=dest_rel,
1165
+ semantic_path=resolved_semantic, files=len(copied), commit=committed.commit,
1166
+ )
1167
+
1168
+
1169
+ def _committed_paths_for_retention(raw_retention: str, *, dest_rel: str, copied: list[dict]) -> tuple[str, ...]:
1170
+ audit_rel = f"{dest_rel}/{AUDIT_FILENAME}"
1171
+ if raw_retention == "commit":
1172
+ return tuple(sorted(f"{dest_rel}/{entry['path']}" for entry in copied)) + (
1173
+ f"{dest_rel}/manifest.json", f"{dest_rel}/.gitignore", audit_rel,
1174
+ )
1175
+ return (audit_rel,)
1176
+
1177
+
1178
+ def _commit_retention_archive(
1179
+ *, identity: Path, base_head: str, attempt_id: str, dest_rel: str, committed_paths: tuple[str, ...],
1180
+ ):
1181
+ intent = NewPathCommitIntent(paths=committed_paths, subject=f"evidence: archive {attempt_id}")
1182
+ try:
1183
+ return bounded_path_commit(
1184
+ identity, expected_repository=identity, base_head=base_head, allowed_paths=(dest_rel,),
1185
+ intent=intent, work_item_id=attempt_id, hop_id=attempt_id,
1186
+ )
1187
+ except TrustedCommitError as error:
1188
+ raise ArchiveError(f"commit failed: {error}") from error
1189
+
1190
+
1191
+ def _archive_run_retention_aware(
1192
+ *, raw_retention: str, identity: Path, base_head: str, attempt_id: str, state_root: Path,
1193
+ ops_dir: Path | None, ops_dir_resolved: Path | None, ops_candidate: Path,
1194
+ semantic_payload: dict | None, resolved_semantic: Path | None, dest: Path, dest_rel: str,
1195
+ staging: Path, identity_facts: RunIdentity, private_strings: Sequence[str] = (),
1196
+ private_tokens: Sequence[str] = (), lifecycle: Mapping[str, Any] | None = None,
1197
+ ) -> ArchiveReport:
1198
+ if dest.exists():
1199
+ if raw_retention == "discard":
1200
+ return _resume_or_noop_discard(
1201
+ identity=identity, base_head=base_head, attempt_id=attempt_id, state_root=state_root,
1202
+ ops_dir=ops_dir, ops_dir_resolved=ops_dir_resolved, ops_candidate=ops_candidate,
1203
+ semantic_payload=semantic_payload, resolved_semantic=resolved_semantic, dest=dest,
1204
+ dest_rel=dest_rel, staging=staging, identity_facts=identity_facts,
1205
+ private_strings=private_strings, private_tokens=private_tokens, lifecycle=lifecycle,
1206
+ )
1207
+ return _resume_or_noop_kept_raw(
1208
+ raw_retention=raw_retention, identity=identity, base_head=base_head, attempt_id=attempt_id,
1209
+ state_root=state_root, ops_dir=ops_dir, ops_dir_resolved=ops_dir_resolved,
1210
+ ops_candidate=ops_candidate, semantic_payload=semantic_payload, resolved_semantic=resolved_semantic,
1211
+ dest=dest, dest_rel=dest_rel, staging=staging, identity_facts=identity_facts,
1212
+ private_strings=private_strings, private_tokens=private_tokens, lifecycle=lifecycle,
1213
+ )
1214
+
1215
+ audit_only = staging / ".wfc-discard-placement"
1216
+ try:
1217
+ manifest, copied = _manifest_candidate(
1218
+ attempt_id=attempt_id, state_root=state_root, ops_dir=ops_dir_resolved,
1219
+ semantic_payload=semantic_payload, staging=staging,
1220
+ archived_at=_DISCARD_MANIFEST_ARCHIVED_AT if raw_retention == "discard" else None,
1221
+ )
1222
+ (staging / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=False) + "\n")
1223
+ audit_text = _project_audit_text(
1224
+ staging, raw_retention=raw_retention, lifecycle=lifecycle,
1225
+ private_strings=private_strings, private_tokens=private_tokens,
1226
+ )
1227
+ (staging / AUDIT_FILENAME).write_text(audit_text)
1228
+ if raw_retention == "commit":
1229
+ (staging / ".gitignore").write_text(_ATTEMPT_COMMIT_GITIGNORE)
1230
+ dest.parent.mkdir(parents=True, exist_ok=True)
1231
+ if raw_retention == "discard":
1232
+ audit_only.mkdir(parents=True)
1233
+ (audit_only / AUDIT_FILENAME).write_text(audit_text)
1234
+ os.rename(audit_only, dest)
1235
+ else:
1236
+ os.rename(staging, dest)
1237
+ except Exception:
1238
+ shutil.rmtree(staging, ignore_errors=True)
1239
+ raise
1240
+ finally:
1241
+ if raw_retention == "discard":
1242
+ shutil.rmtree(staging, ignore_errors=True)
1243
+
1244
+ facts = manifest.get("facts") or {}
1245
+ final_run_id = facts.get("run_id")
1246
+ final_work_item_id = facts.get("work_item_id")
1247
+ final_run_status = facts.get("run_status") or facts.get("status")
1248
+
1249
+ committed_paths = _committed_paths_for_retention(raw_retention, dest_rel=dest_rel, copied=copied)
1250
+ committed = _commit_retention_archive(
1251
+ identity=identity, base_head=base_head, attempt_id=attempt_id, dest_rel=dest_rel,
1252
+ committed_paths=committed_paths,
1253
+ )
1254
+
1255
+ return ArchiveReport(
1256
+ outcome="archived", attempt_id=attempt_id, run_id=final_run_id, work_item_id=final_work_item_id,
1257
+ run_status=final_run_status, checkout_id=identity_facts.checkout_id, repository=identity_facts.repository,
1258
+ state_root=state_root, ops_dir=ops_dir, ops_candidate=ops_candidate, destination_relative=dest_rel,
1259
+ semantic_path=resolved_semantic, files=(0 if raw_retention == "discard" else len(copied)),
1260
+ commit=committed.commit,
1261
+ )
1262
+
1263
+
1264
+ def _resume_or_noop_kept_raw(
1265
+ *, raw_retention: str, identity: Path, base_head: str, attempt_id: str, state_root: Path,
1266
+ ops_dir: Path | None, ops_dir_resolved: Path | None, ops_candidate: Path,
1267
+ semantic_payload: dict | None, resolved_semantic: Path | None, dest: Path, dest_rel: str,
1268
+ staging: Path, identity_facts: RunIdentity, private_strings: Sequence[str] = (),
1269
+ private_tokens: Sequence[str] = (), lifecycle: Mapping[str, Any] | None = None,
1270
+ ) -> ArchiveReport:
1271
+ """Resume/no-op for ``local``/``commit`` retention: ``manifest.json`` was
1272
+ placed (atomically, together with ``audit.json`` and, for ``commit``,
1273
+ the per-Attempt ``.gitignore``) and is kept forever, so every check below
1274
+ reprojects ``audit.json`` from that one placed file -- never from a
1275
+ freshly rebuilt manifest, whose own ``archived_at`` would differ."""
1276
+
1277
+ manifest = _load_existing_manifest(dest)
1278
+ audit_path = dest / AUDIT_FILENAME
1279
+ if not audit_path.is_file():
1280
+ raise ArchiveError(f"archive destination exists but has no {AUDIT_FILENAME}: {dest}")
1281
+ existing_audit_text = audit_path.read_text(encoding="utf-8")
1282
+
1283
+ if _path_is_tracked_clean(identity, dest_rel):
1284
+ candidate_manifest, _ = _manifest_candidate(
1285
+ attempt_id=attempt_id, state_root=state_root, ops_dir=ops_dir_resolved,
1286
+ semantic_payload=semantic_payload, staging=staging,
1287
+ )
1288
+ shutil.rmtree(staging, ignore_errors=True)
1289
+ if not _manifests_match_ignoring_archived_at(manifest, candidate_manifest):
1290
+ raise ArchiveError(
1291
+ f"archive destination already exists with different content, refusing to overwrite: {dest_rel}"
1292
+ )
1293
+ recomputed = _project_audit_text(
1294
+ dest, raw_retention=raw_retention, lifecycle=lifecycle,
1295
+ private_strings=private_strings, private_tokens=private_tokens,
1296
+ )
1297
+ if recomputed != existing_audit_text:
1298
+ raise ArchiveError(
1299
+ f"placed {AUDIT_FILENAME} does not match a projection of its own manifest, "
1300
+ f"refusing to treat it as up to date: {dest_rel}/{AUDIT_FILENAME}"
1301
+ )
1302
+ facts = manifest.get("facts") or {}
1303
+ commit = _run_git(identity, "log", "-1", "--format=%H", "--", dest_rel).strip()
1304
+ return ArchiveReport(
1305
+ outcome="no_op", attempt_id=attempt_id, run_id=facts.get("run_id"),
1306
+ work_item_id=facts.get("work_item_id"), run_status=facts.get("run_status") or facts.get("status"),
1307
+ checkout_id=identity_facts.checkout_id, repository=identity_facts.repository, state_root=state_root,
1308
+ ops_dir=ops_dir, ops_candidate=ops_candidate, destination_relative=dest_rel,
1309
+ semantic_path=resolved_semantic, files=len(manifest["copied_files"]), commit=commit or None,
1310
+ )
1311
+
1312
+ # Placed but never committed (killed between placement and commit):
1313
+ # resume, but only once re-verified against the current authoritative
1314
+ # Run/OPS sources and against the placed audit.json's own projection.
1315
+ _verify_resumable_placement(
1316
+ manifest, dest=dest, attempt_id=attempt_id, state_root=state_root, ops_dir=ops_dir_resolved,
1317
+ semantic_payload=semantic_payload, staging=staging,
1318
+ )
1319
+ recomputed = _project_audit_text(
1320
+ dest, raw_retention=raw_retention, lifecycle=lifecycle,
1321
+ private_strings=private_strings, private_tokens=private_tokens,
1322
+ )
1323
+ if recomputed != existing_audit_text:
1324
+ raise ArchiveError(
1325
+ f"placed {AUDIT_FILENAME} at {dest} does not match a projection of its own manifest; "
1326
+ "refusing to commit a mismatched or tampered archive"
1327
+ )
1328
+ copied = manifest["copied_files"]
1329
+ facts = manifest.get("facts") or {}
1330
+
1331
+ committed_paths = _committed_paths_for_retention(raw_retention, dest_rel=dest_rel, copied=copied)
1332
+ committed = _commit_retention_archive(
1333
+ identity=identity, base_head=base_head, attempt_id=attempt_id, dest_rel=dest_rel,
1334
+ committed_paths=committed_paths,
1335
+ )
1336
+
1337
+ return ArchiveReport(
1338
+ outcome="archived", attempt_id=attempt_id, run_id=facts.get("run_id"),
1339
+ work_item_id=facts.get("work_item_id"), run_status=facts.get("run_status") or facts.get("status"),
1340
+ checkout_id=identity_facts.checkout_id, repository=identity_facts.repository, state_root=state_root,
1341
+ ops_dir=ops_dir, ops_candidate=ops_candidate, destination_relative=dest_rel,
1342
+ semantic_path=resolved_semantic, files=len(copied), commit=committed.commit,
1343
+ )
1344
+
1345
+
1346
+ def _resume_or_noop_discard(
1347
+ *, identity: Path, base_head: str, attempt_id: str, state_root: Path, ops_dir: Path | None,
1348
+ ops_dir_resolved: Path | None, ops_candidate: Path, semantic_payload: dict | None,
1349
+ resolved_semantic: Path | None, dest: Path, dest_rel: str, staging: Path, identity_facts: RunIdentity,
1350
+ private_strings: Sequence[str] = (), private_tokens: Sequence[str] = (),
1351
+ lifecycle: Mapping[str, Any] | None = None,
1352
+ ) -> ArchiveReport:
1353
+ """Resume/no-op for ``discard`` retention: no raw file and no
1354
+ ``manifest.json`` is ever placed, so every check rebuilds an ephemeral
1355
+ manifest (with a fixed ``archived_at`` placeholder, never a real
1356
+ timestamp, so the rebuild is reproducible) purely to reproject
1357
+ ``audit.json`` and compare it with the one placed file that exists."""
1358
+
1359
+ entries = sorted(path.name for path in dest.iterdir())
1360
+ if entries != [AUDIT_FILENAME]:
1361
+ raise ArchiveError(
1362
+ f"archive destination exists but is not a valid discard-retention placement "
1363
+ f"(expected only {AUDIT_FILENAME}, found {entries}): {dest}"
1364
+ )
1365
+ existing_audit_text = (dest / AUDIT_FILENAME).read_text(encoding="utf-8")
1366
+
1367
+ try:
1368
+ manifest, _copied = _manifest_candidate(
1369
+ attempt_id=attempt_id, state_root=state_root, ops_dir=ops_dir_resolved,
1370
+ semantic_payload=semantic_payload, staging=staging, archived_at=_DISCARD_MANIFEST_ARCHIVED_AT,
1371
+ )
1372
+ (staging / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=False) + "\n")
1373
+ candidate_audit_text = _project_audit_text(
1374
+ staging, raw_retention="discard", lifecycle=lifecycle,
1375
+ private_strings=private_strings, private_tokens=private_tokens,
1376
+ )
1377
+ finally:
1378
+ shutil.rmtree(staging, ignore_errors=True)
1379
+
1380
+ if existing_audit_text != candidate_audit_text:
1381
+ raise ArchiveError(
1382
+ f"archive destination already exists with different content, refusing to overwrite: "
1383
+ f"{dest_rel}/{AUDIT_FILENAME}"
1384
+ )
1385
+
1386
+ facts = manifest.get("facts") or {}
1387
+ final_run_id = facts.get("run_id")
1388
+ final_work_item_id = facts.get("work_item_id")
1389
+ final_run_status = facts.get("run_status") or facts.get("status")
1390
+
1391
+ if _path_is_tracked_clean(identity, dest_rel):
1392
+ commit = _run_git(identity, "log", "-1", "--format=%H", "--", dest_rel).strip()
1393
+ return ArchiveReport(
1394
+ outcome="no_op", attempt_id=attempt_id, run_id=final_run_id, work_item_id=final_work_item_id,
1395
+ run_status=final_run_status, checkout_id=identity_facts.checkout_id,
1396
+ repository=identity_facts.repository, state_root=state_root, ops_dir=ops_dir,
1397
+ ops_candidate=ops_candidate, destination_relative=dest_rel, semantic_path=resolved_semantic,
1398
+ files=0, commit=commit or None,
1399
+ )
1400
+
1401
+ # Placed (audit.json written) but never committed: resume at the commit step.
1402
+ committed = _commit_retention_archive(
1403
+ identity=identity, base_head=base_head, attempt_id=attempt_id, dest_rel=dest_rel,
1404
+ committed_paths=(f"{dest_rel}/{AUDIT_FILENAME}",),
1405
+ )
1406
+ return ArchiveReport(
1407
+ outcome="archived", attempt_id=attempt_id, run_id=final_run_id, work_item_id=final_work_item_id,
1408
+ run_status=final_run_status, checkout_id=identity_facts.checkout_id, repository=identity_facts.repository,
1409
+ state_root=state_root, ops_dir=ops_dir, ops_candidate=ops_candidate, destination_relative=dest_rel,
1410
+ semantic_path=resolved_semantic, files=0, commit=committed.commit,
1411
+ )
1412
+
1413
+
1414
+ def _run_git(repository: Path, *args: str) -> str:
1415
+ completed = subprocess.run(
1416
+ ("git", "-C", str(repository), *args), check=False, text=True,
1417
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1418
+ )
1419
+ return completed.stdout if completed.returncode == 0 else ""
1420
+
1421
+
1422
+ def render_report(report: ArchiveReport) -> str:
1423
+ header = {
1424
+ "dry_run": "DRY RUN -- NOTHING WRITTEN",
1425
+ "archived": "ARCHIVED WFC RUN",
1426
+ "resumed_commit": "ARCHIVED WFC RUN",
1427
+ "no_op": "ARCHIVE ALREADY UP TO DATE",
1428
+ }[report.outcome]
1429
+ ops_display = str(report.ops_dir) if report.ops_dir else f"none (absent: {report.ops_candidate})"
1430
+ semantic_display = str(report.semantic_path) if report.semantic_path else "none supplied"
1431
+
1432
+ lines = [header, ""]
1433
+ lines.append(f"attempt: {report.attempt_id}")
1434
+ lines.append(f"run: {report.run_id or ''}")
1435
+ if report.work_item_id:
1436
+ lines.append(f"work item: {report.work_item_id}")
1437
+ if report.run_status:
1438
+ lines.append(f"run status: {report.run_status}")
1439
+ if report.repository:
1440
+ lines.append(f"repository: {report.repository}")
1441
+ lines.append(f"source: {report.state_root}")
1442
+ lines.append(f"ops: {ops_display}")
1443
+ lines.append(f"dest: {report.destination_relative}")
1444
+ lines.append(f"semantic: {semantic_display}")
1445
+
1446
+ if report.outcome == "dry_run":
1447
+ lines.append(f"files: {report.files} planned")
1448
+ lines.append("commit: not performed")
1449
+ lines.append("push: not performed")
1450
+ else:
1451
+ lines.append(f"files: {report.files}")
1452
+ lines.append("manifest: valid")
1453
+ lines.append(f"commit: {report.commit}")
1454
+ lines.append("push: not performed")
1455
+ return "\n".join(lines) + "\n"
1456
+
1457
+
1458
+ def _parse_args(argv: list[str]) -> argparse.Namespace:
1459
+ parser = argparse.ArgumentParser(
1460
+ prog="wfc archive",
1461
+ description=(
1462
+ "Archive a completed WFC Run's evidence into the Evidence repository and "
1463
+ "make one local commit. Derives everything but the two positional "
1464
+ "arguments from authoritative Run state; never pushes."
1465
+ ),
1466
+ )
1467
+ parser.add_argument("state_root", metavar="state-root", help="WFC Run state directory, e.g. ~/wfc-state/<attempt-id>")
1468
+ parser.add_argument("evidence_repo", metavar="evidence-repo", help="a checkout of the Evidence repository")
1469
+ parser.add_argument(
1470
+ "--semantic-json", default=None, metavar="PATH",
1471
+ help='curated semantic annotation, stored verbatim; files under archive/<domain>/<workstream>/<attempt> when it carries both',
1472
+ )
1473
+ parser.add_argument("--dry-run", action="store_true", help="plan only: write nothing, commit nothing")
1474
+ parser.add_argument(
1475
+ "--raw-retention", choices=EVIDENCE_RAW_CHOICES, default=None,
1476
+ help="project and commit audit.json per this retention mode (default: legacy BP5 behaviour, no audit.json)",
1477
+ )
1478
+ return parser.parse_args(argv)
1479
+
1480
+
1481
+ def main(argv: list[str] | None = None) -> int:
1482
+ args = _parse_args(sys.argv[1:] if argv is None else argv)
1483
+ try:
1484
+ report = archive_run(
1485
+ state_root=Path(args.state_root), evidence_repo=Path(args.evidence_repo),
1486
+ semantic_path=Path(args.semantic_json) if args.semantic_json else None,
1487
+ dry_run=args.dry_run, raw_retention=args.raw_retention,
1488
+ )
1489
+ except ProjectionError as error:
1490
+ print(f"wfc archive: {error}", file=sys.stderr)
1491
+ return 3
1492
+ except (ArchiveError, GitPreflightError, AuditError) as error:
1493
+ print(f"wfc archive: {error}", file=sys.stderr)
1494
+ return 1
1495
+ print(render_report(report), end="")
1496
+ return 0