agent-bios 0.19.4 → 0.20.0

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 (158) hide show
  1. package/DEPENDENCIES.md +19 -5
  2. package/README.md +14 -19
  3. package/claude/agents/frontier.md +1 -1
  4. package/claude/guides/claude-prompting.md +475 -234
  5. package/claude/guides/cli-multi-model-workflow.md +4 -3
  6. package/claude/guides/gpt-prompting.md +235 -136
  7. package/claude/guides/session-distill-workflow.md +93 -43
  8. package/claude/guides/tooling-gotchas.md +3 -1
  9. package/codex/guides/claude-prompting.md +475 -234
  10. package/codex/guides/cli-multi-model-workflow.md +4 -3
  11. package/codex/guides/gpt-prompting.md +235 -136
  12. package/codex/guides/session-distill-workflow.md +93 -43
  13. package/codex/guides/tooling-gotchas.md +3 -1
  14. package/compose/assemble.py +4 -1
  15. package/compose/canary.sh +8 -6
  16. package/compose/host_platform.py +158 -15
  17. package/compose/instructions-state.py +183 -41
  18. package/compose/instructions_install.py +222 -27
  19. package/compose/instructions_session.py +250 -75
  20. package/compose/instructions_setup_cli.py +2 -36
  21. package/compose/instructions_store.py +160 -3
  22. package/compose/instructions_transaction.py +29 -5
  23. package/docs/advanced-launch.md +4 -0
  24. package/docs/releases/0.20.0.md +102 -0
  25. package/install.sh +42 -14
  26. package/launch/agent-launch.py +152 -18
  27. package/launch/agent-launch.toml +17 -7
  28. package/launch/agent-launch.zsh +104 -13
  29. package/launch/claude_subcommands.py +179 -0
  30. package/launch/shell_integration.py +7 -1
  31. package/learn/collect-learning.py +60 -9
  32. package/learn/migrate-learnings.py +70 -4
  33. package/learn/redact.py +2 -1
  34. package/package.json +36 -3
  35. package/provenance.json +1 -1
  36. package/session-cost.py +80 -9
  37. package/session-distill/coverage.json +6 -0
  38. package/session-distill/distill.py +2575 -0
  39. package/session-distill/grammar/__init__.py +0 -0
  40. package/session-distill/grammar/owner_lines.py +874 -0
  41. package/session-distill/originators.json +9 -0
  42. package/session-distill/packets/cross_review.md +31 -0
  43. package/session-distill/packets/form.md +86 -0
  44. package/session-distill/packets/judge.md +81 -0
  45. package/session-distill/packets/placement_contract.md +90 -0
  46. package/session-distill/packets/propose.md +124 -0
  47. package/session-distill/packets/read.md +57 -0
  48. package/session-distill/packets/reconsider.md +53 -0
  49. package/session-distill/packets/s7b.md +65 -0
  50. package/session-distill/packets/s9b.md +39 -0
  51. package/session-distill/packets/stitch.md +35 -0
  52. package/session-distill/packets/sweep.md +33 -0
  53. package/session-distill/runlib/__init__.py +0 -0
  54. package/session-distill/runlib/bound.py +1102 -0
  55. package/session-distill/runlib/breaker.py +467 -0
  56. package/session-distill/runlib/census.py +2347 -0
  57. package/session-distill/runlib/claims.py +420 -0
  58. package/session-distill/runlib/controls.py +902 -0
  59. package/session-distill/runlib/coverage.py +881 -0
  60. package/session-distill/runlib/declare.py +888 -0
  61. package/session-distill/runlib/delivery_evidence.py +1145 -0
  62. package/session-distill/runlib/derive.py +812 -0
  63. package/session-distill/runlib/destinations.py +3072 -0
  64. package/session-distill/runlib/dispatch.py +7939 -0
  65. package/session-distill/runlib/drift.py +1077 -0
  66. package/session-distill/runlib/entry.py +401 -0
  67. package/session-distill/runlib/evidence.py +890 -0
  68. package/session-distill/runlib/exposure.py +1162 -0
  69. package/session-distill/runlib/gate.py +2727 -0
  70. package/session-distill/runlib/gitread.py +79 -0
  71. package/session-distill/runlib/inventory.py +19624 -0
  72. package/session-distill/runlib/journal.py +1919 -0
  73. package/session-distill/runlib/ledger.py +3210 -0
  74. package/session-distill/runlib/ledger_compat.py +101 -0
  75. package/session-distill/runlib/ledger_migration.py +190 -0
  76. package/session-distill/runlib/lifecycle_intake.py +693 -0
  77. package/session-distill/runlib/lineage.py +454 -0
  78. package/session-distill/runlib/measures.py +249 -0
  79. package/session-distill/runlib/monitor.py +1180 -0
  80. package/session-distill/runlib/operations.py +522 -0
  81. package/session-distill/runlib/packet.py +838 -0
  82. package/session-distill/runlib/placement.py +1769 -0
  83. package/session-distill/runlib/projection.py +4090 -0
  84. package/session-distill/runlib/ranking.py +740 -0
  85. package/session-distill/runlib/receipts.py +200 -0
  86. package/session-distill/runlib/records.py +1965 -0
  87. package/session-distill/runlib/search.py +249 -0
  88. package/session-distill/runlib/sequencing.py +829 -0
  89. package/session-distill/runlib/sources.py +641 -0
  90. package/session-distill/runlib/stage_adjudicate.py +845 -0
  91. package/session-distill/runlib/stage_apply.py +1378 -0
  92. package/session-distill/runlib/stage_approvals.py +758 -0
  93. package/session-distill/runlib/stage_close.py +1220 -0
  94. package/session-distill/runlib/stage_confirm.py +929 -0
  95. package/session-distill/runlib/stage_delivery.py +3080 -0
  96. package/session-distill/runlib/stage_form.py +2576 -0
  97. package/session-distill/runlib/stage_judge.py +4248 -0
  98. package/session-distill/runlib/stage_propose.py +3307 -0
  99. package/session-distill/runlib/stage_read.py +5179 -0
  100. package/session-distill/runlib/stage_render.py +2739 -0
  101. package/session-distill/runlib/stage_retrieve.py +924 -0
  102. package/session-distill/runlib/stage_review_korean.py +1002 -0
  103. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  104. package/session-distill/runlib/stagelock.py +412 -0
  105. package/session-distill/runlib/stop.py +1061 -0
  106. package/session-distill/runlib/targets.py +809 -0
  107. package/session-distill/runlib/usage.py +280 -0
  108. package/session-distill/runlib/validate.py +319 -0
  109. package/session-distill/runlib/views.py +4327 -0
  110. package/session-distill/schemas/adjudication.schema.json +35 -0
  111. package/session-distill/schemas/approval.schema.json +35 -0
  112. package/session-distill/schemas/census.schema.json +128 -0
  113. package/session-distill/schemas/checks.schema.json +207 -0
  114. package/session-distill/schemas/claim.schema.json +16 -0
  115. package/session-distill/schemas/confirmation.schema.json +24 -0
  116. package/session-distill/schemas/coverage.schema.json +66 -0
  117. package/session-distill/schemas/cross_review.schema.json +24 -0
  118. package/session-distill/schemas/event.schema.json +20 -0
  119. package/session-distill/schemas/evidence.schema.json +20 -0
  120. package/session-distill/schemas/expected_observation.schema.json +18 -0
  121. package/session-distill/schemas/form.schema.json +103 -0
  122. package/session-distill/schemas/intake.schema.json +71 -0
  123. package/session-distill/schemas/inventory.schema.json +872 -0
  124. package/session-distill/schemas/judge.schema.json +77 -0
  125. package/session-distill/schemas/ledger.schema.json +313 -0
  126. package/session-distill/schemas/observation.schema.json +16 -0
  127. package/session-distill/schemas/propose.schema.json +555 -0
  128. package/session-distill/schemas/read.schema.json +76 -0
  129. package/session-distill/schemas/reconsider.schema.json +122 -0
  130. package/session-distill/schemas/run.schema.json +150 -0
  131. package/session-distill/schemas/s7b.schema.json +200 -0
  132. package/session-distill/schemas/s9b.schema.json +28 -0
  133. package/session-distill/schemas/stitch.schema.json +25 -0
  134. package/session-distill/schemas/sweep.schema.json +25 -0
  135. package/session-distill/seats.json +149 -0
  136. package/session-distill/tables/allowed_pairs.json +257 -0
  137. package/session-distill/tables/controls.json +30 -0
  138. package/session-distill/tables/delivery_evidence.json +36 -0
  139. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  140. package/session-distill/tables/destinations.json +684 -0
  141. package/session-distill/tables/drift_layers.json +68 -0
  142. package/session-distill/tables/exposure_rules.json +192 -0
  143. package/session-distill/tables/placement_rules.json +148 -0
  144. package/session-distill/tables/propose_fixtures.json +154 -0
  145. package/session-distill/tables/ranking.json +194 -0
  146. package/session-distill/tables/redundancy.json +10 -0
  147. package/session-distill/tables/structural_rules.json +44 -0
  148. package/session-distill/tables/transition_fixtures.json +398 -0
  149. package/session-distill/tables/transitions.json +69 -0
  150. package/session-distill/tables/unit_outcome.json +67 -0
  151. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  152. package/wrappers/claude-run.sh +481 -33
  153. package/wrappers/claude_hermetic_evidence.py +1423 -0
  154. package/wrappers/codex-helm.sh +38 -7
  155. package/wrappers/codex-run.sh +183 -20
  156. package/wrappers/codex_frame_filter.py +1199 -0
  157. package/wrappers/codex_protocol.py +737 -0
  158. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,101 @@
1
+ #!/usr/bin/env python3
2
+ """The read path the old ledger consumers keep (plan S-4): a derived projection, never stored.
3
+
4
+ Schema 2 moves `placed`, `placed_anchor` and `implementation` out of the entry (design §12.2). A
5
+ consumer written for schema 1 reads them as entry fields; `placed_entries` hands it those fields,
6
+ derived from either schema version. Schema 1 passes through untouched, so a consumer switched to
7
+ this module reads the unmigrated ledger exactly as it did, and the migrated one the same way.
8
+ Nothing here is written back: a second copy of a field would be a second authority.
9
+
10
+ The projection's six fields come from the entry alone — `destination.anchor` and
11
+ `destination.package_id`, and the `status`, `learning_id` and `classification` design §12.2 keeps.
12
+ It reads no `decisions[]` element, because an `applied` record carries none of the six; that the
13
+ schema 1 values land in `destination` and on the latest place decision is the migration's
14
+ guarantee, held by `migrate-ledger.py`'s own self-test
15
+ (design/session-distill/2026-10-21T1009--a04f78a--plan-addendum-wp13-correction-2.md §1).
16
+
17
+ The consumers are listed as data in `tables/ledger_readers.json`: `learn/build-promotions.py` reads
18
+ this projection; `compose/instructions-state.py` and `learn/ingest-learnings-export.py` read only
19
+ fields §12.2 keeps and need no projection.
20
+
21
+ ledger_compat.py --self-test
22
+ """
23
+ import copy
24
+ import pathlib
25
+ import sys
26
+
27
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
28
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
29
+
30
+
31
+ class CompatError(Exception):
32
+ """A ledger this projection cannot read; the message starts with LEDGER_SCHEMA_UNSUPPORTED."""
33
+
34
+
35
+ def placed_entries(ledger):
36
+ """`{id, status, learning_id, placed_anchor, placed_package_id, classification}` for every entry
37
+ whose status is `placed`, in ledger order. An absent field is None."""
38
+ version = ledger.get("schema")
39
+ if version not in (1, 2):
40
+ raise CompatError(f"LEDGER_SCHEMA_UNSUPPORTED schema {version!r}: the projection reads schema 1 and 2")
41
+ out = []
42
+ for entry in ledger.get("entries", []):
43
+ if not isinstance(entry, dict) or entry.get("status") != "placed":
44
+ continue
45
+ home = (entry.get("destination") or {}) if version == 2 else {}
46
+ out.append({
47
+ "id": entry.get("id"), "status": "placed", "learning_id": entry.get("learning_id"),
48
+ "placed_anchor": home.get("anchor") if version == 2 else entry.get("placed_anchor"),
49
+ "placed_package_id": home.get("package_id") if version == 2 else entry.get("placed_package_id"),
50
+ "classification": entry.get("classification"),
51
+ })
52
+ return out
53
+
54
+
55
+ def self_test():
56
+ failures = []
57
+ legacy = {"schema": 1, "entries": [
58
+ {"id": "S9-01", "status": "placed", "learning_id": "lid-1", "placed_anchor": "a.md", "placed_package_id": "@x/y", "classification": {"type": "A"}},
59
+ {"id": "S9-02", "status": "incubating", "learning_id": "lid-2", "placed_anchor": "b.md"},
60
+ {"id": "S4-01", "status": "placed"},
61
+ "not an entry"]}
62
+ current = {"schema": 2, "entries": [
63
+ {"id": "S9-01", "status": "placed", "learning_id": "lid-1", "classification": {"type": "A"},
64
+ "destination": {"implementation": "a.md §x", "anchor": "a.md", "package_id": "@x/y"}},
65
+ {"id": "S9-02", "status": "incubating", "learning_id": "lid-2", "destination": None},
66
+ {"id": "S4-01", "status": "placed", "destination": None}]}
67
+ want = [
68
+ {"id": "S9-01", "status": "placed", "learning_id": "lid-1", "placed_anchor": "a.md", "placed_package_id": "@x/y", "classification": {"type": "A"}},
69
+ {"id": "S4-01", "status": "placed", "learning_id": None, "placed_anchor": None, "placed_package_id": None, "classification": None}]
70
+ for label, ledger in (("schema 1", legacy), ("schema 2", current)):
71
+ if placed_entries(ledger) != want:
72
+ failures.append(f"{label}: the projection is {placed_entries(ledger)}, expected {want}")
73
+ before = copy.deepcopy(current)
74
+ placed_entries(current)
75
+ if current != before:
76
+ failures.append("the projection changed the ledger it read")
77
+ if [e["id"] for e in placed_entries(legacy)] != ["S9-01", "S4-01"]:
78
+ failures.append("an incubating entry or a non-entry was projected")
79
+ for label, ledger in (("no schema", {"entries": []}), ("a future schema", {"schema": 3, "entries": []})):
80
+ try:
81
+ placed_entries(ledger)
82
+ failures.append(f"{label}: the projection read a ledger it does not know")
83
+ except CompatError as exc:
84
+ if "LEDGER_SCHEMA_UNSUPPORTED" not in str(exc):
85
+ failures.append(f"{label}: refused without the code: {exc}")
86
+ moved = copy.deepcopy(current)
87
+ moved["entries"][0]["destination"] = None
88
+ if placed_entries(moved)[0]["placed_anchor"] is not None:
89
+ failures.append("a destination removed from a schema 2 entry still projected an anchor")
90
+ for failure in failures:
91
+ print(f"ledger_compat --self-test [FAIL] {failure}")
92
+ if failures:
93
+ return 1
94
+ print("ledger_compat --self-test: OK (schema 1 passthrough and schema 2 projection agree, an unknown schema is refused by name)")
95
+ return 0
96
+
97
+
98
+ if __name__ == "__main__":
99
+ if "--self-test" not in sys.argv[1:]:
100
+ sys.exit("usage: ledger_compat.py --self-test")
101
+ sys.exit(self_test())
@@ -0,0 +1,190 @@
1
+ #!/usr/bin/env python3
2
+ """The schema 1 to schema 2 migration of the ledger (design §12.2), as a function of the ledger's document alone.
3
+
4
+ Moved here from `session-distill/migrate-ledger.py` unchanged (WP-09 commit 4, lead decision D4): S4's lifecycle intake
5
+ migrates a schema 1 pinned ledger in memory with the same function the cutover uses (plan WP-22), and a runlib module
6
+ does not import a script. `migrate-ledger.py` imports every name below and keeps its checks, its reader inventory and its
7
+ self-test; the module docstring there describes the mapping. Nothing here reads or writes a file.
8
+ """
9
+ import copy
10
+ import datetime
11
+ import pathlib
12
+ import re
13
+ import sys
14
+
15
+ if __package__ in (None, ""): # imported by a script that put session-distill/ on the path, or run by path
16
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
17
+ from runlib import ledger as ledger_lib # noqa: E402
18
+
19
+ # design §12.2, "Prefix table for legacy decision text": prefix, disposition, and whether the text
20
+ # records an owner decision (`user-…`, and the recommendations the owner confirmed). Matching takes
21
+ # the longest prefix that ends at a word boundary, so `user-approved` is not `user-approved-default`.
22
+ PREFIXES = (
23
+ ("user-confirmed incubating", "incubate", True), ("user-approved-default", "unknown", True),
24
+ ("recommendation-confirmed", "unknown", True), ("absorbed-as-instance", "none", False),
25
+ ("below-bar-default", "incubate", False), ("PROPOSED resolved", "unknown", False),
26
+ ("curator-placed", "place", False), ("user-promoted", "place", True), ("user-approved", "place", True),
27
+ ("user-adopted", "place", True), ("user-revived", "revival", True), ("incubating", "incubate", False),
28
+ ("selected", "place", False), ("absorbed", "reduce", False),
29
+ )
30
+ DECISION_FIELDS = ("decision", "decision1", "decision2", "decision3")
31
+ EVENT_FIELDS = ("review_note", "classified", "selected", "placement_proposed") # see the module docstring
32
+ REMOVED_FIELDS = ("verdict", "strength", "criteria")
33
+ # Every legacy field, and where it goes. A field in none of these is `FIELD_UNMAPPED`.
34
+ # `keep` passes through: schema 2 requires the field on every entry (`keep_record`, nullable), and
35
+ # a schema 1 keep record already has that exact shape, so the standing records the keep layer
36
+ # delivers survive the migration unchanged. It was named by no row until the WP-22 cutover, which
37
+ # stopped the migration of any entry carrying one — invisible because the ledger has none today.
38
+ KEPT_FIELDS = ("id", "lesson", "principle", "rationale", "status", "surfaced", "domain", "source", "note",
39
+ "learning_id", "baseline_ref", "window", "classification", "recurrence", "absorbed_by", "retired", "retire_reason",
40
+ "keep")
41
+ MOVED_FIELDS = ("supporting_sessions", "placed", "placed_anchor", "placed_package_id", "implementation")
42
+ LEGACY_ONLY = (*REMOVED_FIELDS, *MOVED_FIELDS, *DECISION_FIELDS, *EVENT_FIELDS)
43
+ DATE = re.compile(r"\d{4}-\d{2}-\d{2}")
44
+ CHAIN = re.compile(r"census (?:(\d+)d )?ending (" + DATE.pattern + ")")
45
+ LEGACY_APPLIED = {"commit": None, "paths": [], "operations": [], "delivery": "unverified"}
46
+
47
+
48
+ class MigrationError(Exception):
49
+ """A refusal; the message starts with the named code."""
50
+
51
+
52
+ def match_prefix(text):
53
+ best = None
54
+ for prefix, disposition, owner in PREFIXES:
55
+ if text.startswith(prefix) and (len(text) == len(prefix) or text[len(prefix)] in " :;,(") \
56
+ and (best is None or len(prefix) > len(best[0])):
57
+ best = (prefix, disposition, owner)
58
+ return best
59
+
60
+
61
+ def first_date(text):
62
+ """The first ISO date anywhere in `text`, else None: design §12.2's "`at` from the date in the text"."""
63
+ found = DATE.search(text)
64
+ return found.group(0) if found else None
65
+
66
+
67
+ def element(run, field, disposition, approval, at, text, **extra):
68
+ return {"run": run, "disposition": disposition, "approval_id": approval, "adjudication_id": None, "confirmation": None,
69
+ "applied": None, "tests": None, "expected_observation": None, "at": at, "field": field, "legacy_text": text, **extra}
70
+
71
+
72
+ def migrated_keep(entry):
73
+ """The schema 2 keep record of one schema 1 entry: its units, and the rationale the entry
74
+ carried beside them (F-34). `None` when the entry keeps nothing, which is what schema 2's
75
+ required-but-nullable `keep` holds for every entry of this ledger today."""
76
+ keep = entry.get("keep")
77
+ if not isinstance(keep, dict):
78
+ return None
79
+ record = copy.deepcopy(keep)
80
+ if entry.get("reason") is not None:
81
+ record["reason"] = entry["reason"]
82
+ return record
83
+
84
+
85
+ def migrate_entry(entry, migrated_at):
86
+ """(the schema 2 entry, the values the schema removes) for one schema 1 entry; `migrated_at` is the
87
+ date its `legacy_migration` element carries."""
88
+ eid = entry["id"]
89
+ # `reason` is a schema 1 keep row's rationale and its home in schema 2 is the KEEP RECORD
90
+ # (F-34): an entry forbids additional properties, so it travels into `keep.reason` below. An
91
+ # entry carrying the rationale and no keep record has nothing to carry it, and is refused by
92
+ # name rather than having the sentence dropped on the floor.
93
+ holds_keep = isinstance(entry.get("keep"), dict)
94
+ unknown = sorted(set(entry) - set(KEPT_FIELDS) - set(LEGACY_ONLY) - ({"reason"} if holds_keep else set()))
95
+ if unknown:
96
+ raise MigrationError(f"FIELD_UNMAPPED {eid}: {unknown} are named by no row of design §12.2")
97
+ run = f"legacy-{entry.get('window') or 'unknown'}"
98
+ status = entry["status"]
99
+ new = {k: copy.deepcopy(entry[k]) for k in KEPT_FIELDS if k in entry and k not in ("window", "absorbed_by", "retired", "retire_reason", "status")}
100
+ new["status"] = "incubating" if status == "incubating-G" else status
101
+ new["window"] = entry.get("window") or "unknown"
102
+ classification = new.get("classification")
103
+ if status == "incubating-G":
104
+ new["classification"] = {**(classification or {}), "type": "G"}
105
+ elements, relations = [], {}
106
+ for field in (*DECISION_FIELDS, *EVENT_FIELDS):
107
+ text = entry.get(field)
108
+ if text is None:
109
+ continue
110
+ if field in DECISION_FIELDS:
111
+ row = match_prefix(text)
112
+ if row is None:
113
+ raise MigrationError(f"DECISION_UNMAPPED {eid} {field}: {text!r} starts with none of the 14 prefixes of design §12.2")
114
+ prefix, disposition, owner = row
115
+ elements.append(element(run, field, disposition, "legacy" if owner else "unavailable", first_date(text), text))
116
+ if prefix == "absorbed-as-instance" and status == "placed" and "absorbed_by" in entry:
117
+ relations["instance_of"] = entry["absorbed_by"]
118
+ else:
119
+ elements.append(element(run, field, "unknown", "unavailable", first_date(text), text))
120
+ if "absorbed_by" in entry:
121
+ if status == "absorbed":
122
+ new["absorbed_by"] = entry["absorbed_by"]
123
+ elif "instance_of" not in relations:
124
+ raise MigrationError(f"ABSORBED_BY_UNMAPPED {eid}: absorbed_by on a {status} entry without an absorbed-as-instance decision")
125
+ if "retired" in entry or "retire_reason" in entry:
126
+ if status == "retired":
127
+ new.update({k: entry[k] for k in ("retired", "retire_reason") if k in entry})
128
+ else:
129
+ revived = any(e["disposition"] == "revival" and (e["at"] or "") >= (entry.get("retired") or "") for e in elements)
130
+ elements.append(element(run, "retired", "drop", "unavailable", entry.get("retired"), entry.get("retire_reason", ""),
131
+ kind="legacy_retirement",
132
+ **({} if revived else {"status_note": "current status set without a recorded revival"})))
133
+ moved = {k: entry[k] for k in ("placed", "placed_anchor", "placed_package_id", "implementation") if entry.get(k) is not None}
134
+ new["destination"] = ({"implementation": entry.get("implementation"), "anchor": entry.get("placed_anchor"),
135
+ "package_id": entry.get("placed_package_id")} if moved else None)
136
+ if moved:
137
+ placing = [(e["at"] or "", n) for n, e in enumerate(elements) if e["disposition"] == "place"]
138
+ if placing: # the latest place decision by its date, field order breaking a tie, carries the application
139
+ latest = elements[max(placing)[1]]
140
+ latest["applied"] = copy.deepcopy(LEGACY_APPLIED)
141
+ if entry.get("placed") is not None and latest["at"] != entry["placed"]:
142
+ latest["legacy_placed"] = entry["placed"] # the application's own date, which the decision's date is not
143
+ else:
144
+ first = next(k for k in ("placed", "placed_anchor", "placed_package_id", "implementation") if k in moved)
145
+ elements.append(element(run, first, "unknown", "unavailable", entry.get("placed"), str(entry.get("placed") or ""),
146
+ kind="legacy_application", applied=copy.deepcopy(LEGACY_APPLIED)))
147
+ elements.append(element(run, "status", "unknown", "unavailable", migrated_at, status, kind="legacy_migration", legacy_status=new["status"]))
148
+ new.update(kind="unclassified", diagnosis="unknown", disposition="none",
149
+ evidence=[{"locator": "unavailable", "session": s} for s in entry.get("supporting_sessions", [])],
150
+ independent_lineages="unavailable", consequence={"kinds": list(entry.get("criteria") or [])},
151
+ coverage={"basis": "unavailable"}, keep=migrated_keep(entry),
152
+ relations=relations, decisions=elements)
153
+ return new, {k: entry[k] for k in REMOVED_FIELDS if k in entry}
154
+
155
+
156
+ def windows_of(chain):
157
+ """`windows[]` from the legacy chain string, oldest first; the unknown fields are null."""
158
+ found = CHAIN.findall(chain or "")
159
+ if not found:
160
+ raise MigrationError(f"WINDOW_UNPARSED: {chain!r} holds no 'census … ending <date>'")
161
+ out = []
162
+ for days, end in reversed(found):
163
+ start = (datetime.date.fromisoformat(end) - datetime.timedelta(days=int(days))).isoformat() if days else None
164
+ out.append({"start": start, "end": end, "run_id": f"legacy-{end}", "kind": "legacy", "commit": None,
165
+ "accounted": None, "fully_read": None})
166
+ return out
167
+
168
+
169
+ def migrate(ledger):
170
+ """(the schema 2 ledger, the removed values). A schema 2 ledger is its own migration."""
171
+ if ledger.get("schema") == 2:
172
+ return copy.deepcopy(ledger), {}
173
+ if ledger.get("schema") != 1:
174
+ raise MigrationError(f"LEDGER_SCHEMA_UNSUPPORTED schema {ledger.get('schema')!r}")
175
+ unknown = sorted(set(ledger) - {"schema", "framework", "window", "entries"})
176
+ if unknown:
177
+ raise MigrationError(f"FIELD_UNMAPPED ledger: top-level {unknown}")
178
+ entries, removed = [], {}
179
+ windows = windows_of(ledger.get("window"))
180
+ for entry in ledger["entries"]:
181
+ new, gone = migrate_entry(entry, windows[-1]["end"])
182
+ entries.append(new)
183
+ if gone:
184
+ removed[entry["id"]] = gone
185
+ removed["_ledger"] = {"window": ledger.get("window")}
186
+ migrated = {"schema": 2, "framework": ledger["framework"], "windows": windows, "entries": entries}
187
+ problems = ledger_lib.validate_ledger(migrated)
188
+ if problems:
189
+ raise MigrationError("MIGRATION_INVALID: " + "; ".join(problems[:5]))
190
+ return migrated, removed