@christang/keel 5.139.0 → 5.140.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.
package/README.md CHANGED
@@ -666,11 +666,21 @@ keel gate task-start --change <c> --task <t> --record --keep-evidence M1,M3
666
666
  ```
667
667
 
668
668
  The report then names only the checks still stale, names the ones you declared unaffected, and says
669
- the narrowing came from your declaration. **Keel does not verify the claim** — it keeps only the
669
+ the narrowing came from your declaration. **Keel does not verify the claim** — the anchor keeps the
670
670
  previous fingerprint, not the capsule behind it, so it cannot compare a check's former text to its
671
671
  current one. State your reason in the task's `Reauthorizations` line, where a reviewer can disagree
672
672
  with it. Nothing about completion changes: every check still needs its Evidence.
673
673
 
674
+ When Git can say what moved, the drift message says it instead (#342). The anchor records the Keel
675
+ version beside the digest — `- Contract: keel-task-capsule/v1 sha256:<hex> (keel <version>)` — and
676
+ on drift Keel compiles the task's sources from the commit that recorded the anchor with the running
677
+ compiler. If that commit reproduces the anchor, the message names the capsule fields that changed
678
+ since it. If it does not, but the anchor came from another Keel version and the commit compiles to
679
+ today's fingerprint, the cause is a compiler change: re-record with `task-start --record`, and the
680
+ evidence stands without a `--keep-evidence` claim. Otherwise nothing is claimed. A checked task
681
+ whose only change since its recording commit is the inherited standing authorization in
682
+ `keel/config.yaml` does not fail `change-close`; it is named in a warning.
683
+
674
684
  ## Pausing a change
675
685
 
676
686
  A change you have deliberately stopped — waiting on something outside the repository, or simply
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.139.0 -->
1
+ <!-- keel:start version=5.140.0 -->
2
2
  ## Keel Bootstrap
3
3
 
4
4
  - Start every session with `keel context`; OpenSpec artifacts and Git are the only durable authority — never native memory, goals, or transcripts.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.139.0",
3
+ "version": "5.140.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.139.0",
9
+ "version": "5.140.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@fission-ai/openspec": "^1.4.1"
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@christang/keel",
3
3
  "displayName": "Keel",
4
4
  "description": "Keel OpenSpec execution discipline CLI for Claude Code, Codex, and OpenCode.",
5
- "version": "5.139.0",
5
+ "version": "5.140.0",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.139.0",
3
+ "version": "5.140.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.139.0",
3
+ "version": "5.140.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
47
47
  "scripts/validate_plugin.py",
48
48
  ]
49
49
 
50
- PACKAGE_VERSION = "5.139.0"
51
- PROTOCOL_VERSION = "5.139.0"
50
+ PACKAGE_VERSION = "5.140.0"
51
+ PROTOCOL_VERSION = "5.140.0"
52
52
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
53
53
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
54
54
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -8182,7 +8182,7 @@ def validate_record_derives_skeleton_scenario() -> int:
8182
8182
  after = tasks.read_text(encoding="utf-8")
8183
8183
  before_lines, after_lines = red_green.splitlines(), after.splitlines()
8184
8184
  added = [line for line in after_lines if line not in before_lines]
8185
- want = [" - Evidence:", f" - Contract: keel-task-capsule/v1 sha256:{fingerprint}", *expected_slots]
8185
+ want = [" - Evidence:", f" - Contract: keel-task-capsule/v1 sha256:{fingerprint} (keel {PACKAGE_VERSION})", *expected_slots]
8186
8186
  if added != want:
8187
8187
  report(f"{label} --record added {added!r}, expected {want!r}.")
8188
8188
  return 1
@@ -8240,7 +8240,7 @@ def validate_record_derives_skeleton_scenario() -> int:
8240
8240
  return 1
8241
8241
  fingerprint = payload["contract"]["fingerprint"]["value"]
8242
8242
  got = evidence_lines(tasks.read_text(encoding="utf-8"))
8243
- want = [f" - Contract: keel-task-capsule/v1 sha256:{fingerprint}", *expected_slots]
8243
+ want = [f" - Contract: keel-task-capsule/v1 sha256:{fingerprint} (keel {PACKAGE_VERSION})", *expected_slots]
8244
8244
  if got != want:
8245
8245
  report(f"{label} --record over Contract, Blocker and Reauthorizations left the block out of "
8246
8246
  f"template order: {got!r}, expected {want!r}.")
@@ -16743,6 +16743,138 @@ def _anchor_fixture(
16743
16743
  )
16744
16744
 
16745
16745
 
16746
+ def validate_contract_drift_diagnosis_scenario() -> int:
16747
+ """Issue #342: drift names its cause when Git ties the anchor to a commit.
16748
+
16749
+ Measured on rtl_ppa_prj: one upgrade-time drift was a compiler change
16750
+ (5.81.0), the other a `keel/config.yaml` edit. Every case here commits real
16751
+ gate output in a real repository and asks the real CLI what moved.
16752
+ """
16753
+ label = "contract-drift-diagnosis:"
16754
+ version = json.loads((ROOT / "package.json").read_text(encoding="utf-8"))["version"]
16755
+ with tempfile.TemporaryDirectory(prefix="keel-drift-342-") as raw:
16756
+ repo = mailbox_repository(Path(raw) / "repo")
16757
+
16758
+ def git(*args: str) -> str:
16759
+ return subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True, text=True).stdout.strip()
16760
+
16761
+ def commit(message: str) -> str:
16762
+ git("add", "-A")
16763
+ git("commit", "-q", "-m", message)
16764
+ return git("rev-parse", "HEAD")
16765
+
16766
+ def change(name: str, doc: str) -> Path:
16767
+ path = repo / "openspec/changes" / name / "tasks.md"
16768
+ write_text(path, doc)
16769
+ write_text(
16770
+ repo / "openspec/changes" / name / "specs/demo/spec.md",
16771
+ "## ADDED Requirements\n\n"
16772
+ "### Requirement: Demo\nKeel MUST demo.\n\n"
16773
+ "#### Scenario: demo\n- **WHEN** a\n- **THEN** b\n",
16774
+ )
16775
+ return path
16776
+
16777
+ def gate(name: str, stage: str, *extra: str) -> dict:
16778
+ return json.loads(run_keel(repo, "gate", stage, "--change", name, *extra, "--json").stdout)
16779
+
16780
+ def record(name: str) -> dict:
16781
+ return gate(name, "task-start", "--task", "1.1", "--record", "--no-guard")
16782
+
16783
+ def drift_message(payload: dict) -> str:
16784
+ found = [p.get("message", "") for p in payload.get("problems", []) if p.get("code") == "contract-drift"]
16785
+ return found[0] if found else ""
16786
+
16787
+ def rewrite_anchor(path: Path, digest: str, keel: str) -> None:
16788
+ text = path.read_text(encoding="utf-8")
16789
+ text = re.sub(r"- Contract: .*", f"- Contract: keel-task-capsule/v1 sha256:{digest} (keel {keel})", text, count=1)
16790
+ write_text(path, text)
16791
+
16792
+ write_authorize_config(repo, "authorize:\n - commit\n - push:main\n")
16793
+
16794
+ # A compiler change: the committed sources compile to today's
16795
+ # fingerprint, and the anchor holds another digest from another version.
16796
+ comp = change("comp", _anchor_fixture(contract=f"keel-task-capsule/v1 sha256:{'a' * 64} (keel 5.0.0)"))
16797
+ sha = commit("comp recorded under an older compiler")
16798
+ message = drift_message(gate("comp", "task-complete", "--task", "1.1"))
16799
+ if "compiler" not in message:
16800
+ report(f"{label} the drift message does not name a compiler change: {message!r}")
16801
+ return 1
16802
+ for needle in (sha[:12], "5.0.0", version, "no `--keep-evidence` is needed"):
16803
+ if needle not in message:
16804
+ report(f"{label} the compiler-change message does not name {needle!r}: {message!r}")
16805
+ return 1
16806
+ rerecord = record("comp")
16807
+ warned = " ".join(rerecord.get("warnings", []))
16808
+ if "evidence stands" not in warned or sha[:12] not in warned:
16809
+ report(f"{label} the compiler-only re-record does not say the evidence stands at {sha[:12]}: {warned!r}")
16810
+ return 1
16811
+ if "stale" in warned:
16812
+ report(f"{label} the compiler-only re-record still calls evidence stale: {warned!r}")
16813
+ return 1
16814
+ # The anchor carries the version that recorded it.
16815
+ if f"(keel {version})" not in comp.read_text(encoding="utf-8"):
16816
+ report(f"{label} the recorded anchor does not carry (keel {version}): "
16817
+ f"{re.search(r'- Contract: .*', comp.read_text(encoding='utf-8')).group(0)!r}")
16818
+ return 1
16819
+
16820
+ # An anchor nothing explains claims nothing.
16821
+ same = change("same", _anchor_fixture(contract="pending"))
16822
+ record("same")
16823
+ rewrite_anchor(same, "b" * 64, version)
16824
+ commit("same: an anchor its sources do not compile to")
16825
+ message = drift_message(gate("same", "task-complete", "--task", "1.1"))
16826
+ if not message:
16827
+ report(f"{label} an unexplained anchor reported no contract drift.")
16828
+ return 1
16829
+ if "compiler" in message or "changed since" in message:
16830
+ report(f"{label} an unexplained anchor was given a cause: {message!r}")
16831
+ return 1
16832
+
16833
+ # An edit is named by the field it changed.
16834
+ edit = change("edit", _anchor_fixture(contract="pending"))
16835
+ record("edit")
16836
+ sha = commit("edit recorded")
16837
+ write_text(edit, edit.read_text(encoding="utf-8").replace("src/feature.js", "src/DRIFTED.js"))
16838
+ message = drift_message(gate("edit", "task-complete", "--task", "1.1"))
16839
+ if "`touch`" not in message or sha[:12] not in message:
16840
+ report(f"{label} the edit drift does not name `touch` and {sha[:12]}: {message!r}")
16841
+ return 1
16842
+ context = run_keel(repo, "context", "--change", "edit", "--task", "1.1")
16843
+ if "`touch`" not in context.stdout:
16844
+ report(f"{label} keel context does not name the changed field: {context.stdout!r}")
16845
+ return 1
16846
+ write_text(edit, edit.read_text(encoding="utf-8").replace("src/DRIFTED.js", "src/feature.js"))
16847
+
16848
+ # A standing-authorization change does not drift a completed task.
16849
+ done = change("auth", _anchor_fixture(contract="pending", checked=True))
16850
+ write_text(done.parent / "proposal.md", "## Why\n\nA fixture.\n")
16851
+ write_text(done.parent / "design.md", "## Context\n\nA fixture.\n")
16852
+ record("auth")
16853
+ going = change("auth2", _anchor_fixture(contract="pending"))
16854
+ record("auth2")
16855
+ commit("auth recorded under push:main")
16856
+ if gate("auth", "change-close", "--action", "archive").get("status") != "pass":
16857
+ report(f"{label} the authorization fixture does not close before the change: "
16858
+ f"{gate('auth', 'change-close', '--action', 'archive')!r}")
16859
+ return 1
16860
+ write_authorize_config(repo, "authorize:\n - commit\n - push-protected:main\n")
16861
+ commit("push:main becomes push-protected:main")
16862
+ closed = gate("auth", "change-close", "--action", "archive")
16863
+ if closed.get("status") != "pass":
16864
+ report(f"{label} a standing-authorization change drifted a completed task at the close: "
16865
+ f"{[p.get('message') for p in closed.get('problems', [])]!r}")
16866
+ return 1
16867
+ warned = " ".join(closed.get("warnings", []))
16868
+ if "1.1" not in warned or "standing authorization" not in warned:
16869
+ report(f"{label} the close does not warn naming 1.1 and the standing authorization: {warned!r}")
16870
+ return 1
16871
+ if not drift_message(gate("auth2", "task-complete", "--task", "1.1")):
16872
+ report(f"{label} an unchecked task inheriting the changed authorization was not drift.")
16873
+ return 1
16874
+ report("contract-drift-diagnosis scenario passed.")
16875
+ return 0
16876
+
16877
+
16746
16878
  def validate_contract_anchor_is_compared_scenario() -> int:
16747
16879
  """Issue #37: completion checked that an anchor existed, never that it matched.
16748
16880
 
@@ -20742,7 +20874,7 @@ def validate_core_gates_scenario() -> int:
20742
20874
  or len(changed_lines) != 1
20743
20875
  or changed_lines[0][0] != " - Contract: pending"
20744
20876
  or changed_lines[0][1]
20745
- != f" - Contract: keel-task-capsule/v1 sha256:{fingerprint}"
20877
+ != f" - Contract: keel-task-capsule/v1 sha256:{fingerprint} (keel {PACKAGE_VERSION})"
20746
20878
  ):
20747
20879
  report(
20748
20880
  "core-gates scenario --record must replace exactly the "
@@ -20816,7 +20948,7 @@ def validate_core_gates_scenario() -> int:
20816
20948
  or len(before_rerecord) != len(after_rerecord)
20817
20949
  or len(rerecord_changed) != 1
20818
20950
  or rerecord_changed[0][1]
20819
- != f" - Contract: keel-task-capsule/v1 sha256:{new_fingerprint}"
20951
+ != f" - Contract: keel-task-capsule/v1 sha256:{new_fingerprint} (keel {PACKAGE_VERSION})"
20820
20952
  or not any(
20821
20953
  fingerprint in warning
20822
20954
  for warning in rerecord_result.get("warnings", [])
@@ -40917,6 +41049,7 @@ SCENARIOS: tuple = (
40917
41049
  "contract-anchor-is-compared",
40918
41050
  validate_contract_anchor_is_compared_scenario,
40919
41051
  ),
41052
+ ("contract-drift-diagnosis", validate_contract_drift_diagnosis_scenario),
40920
41053
  (
40921
41054
  "guard-scope-is-the-repository",
40922
41055
  validate_guard_scope_is_the_repository_scenario,
@@ -23,6 +23,7 @@ const {
23
23
  ownerLanguageRule,
24
24
  } = require("./config");
25
25
  const { isKeelSourceRepo } = require("./capabilities");
26
+ const { diagnoseDrift, driftCause } = require("./drift");
26
27
 
27
28
  const NEXT_ACTIONS = new Set([
28
29
  "discuss",
@@ -122,9 +123,9 @@ function taskHasCompletionEvidence(record, contract) {
122
123
  // wrong record here: an anchor that moved was written up as a Review edit,
123
124
  // which is measurably not covered at all. The capsule already knows the answer
124
125
  // — every authority entry carries the source its text was resolved from — so
125
- // the search set is free. What is not free is the field that moved: only the
126
- // previous fingerprint is retained, not the capsule behind it, so this names
127
- // where to look and never what changed.
126
+ // the search set is free. The field that moved is named only when the commit
127
+ // that recorded the anchor reproduces it (src/core/drift.js, #342); this search
128
+ // set is what remains when no commit does.
128
129
  function driftSearchSet(contract) {
129
130
  const sources = [
130
131
  ...new Set(
@@ -160,10 +161,14 @@ function taskSelection(repo, change, record, source, requestedAction = null) {
160
161
  }
161
162
  const anchor = recordedFingerprint(record);
162
163
  if (anchor && anchor !== contract.fingerprint.value) {
164
+ const anchorLine = (field(record, "Evidence").match(/^\s*-\s*Contract:\s*(.*)$/im) || [])[1];
165
+ const diagnosis = diagnoseDrift(repo, change, record.id, anchorLine, contract);
163
166
  return blocked(
164
167
  `Task contract fingerprint drift for ${change}#${record.id}: recorded `
165
168
  + `sha256:${anchor}, current sha256:${contract.fingerprint.value}. `
166
- + `${driftSearchSet(contract)}`,
169
+ + (diagnosis && diagnosis.kind === "compiler"
170
+ ? driftCause(diagnosis)
171
+ : `${diagnosis ? `${driftCause(diagnosis)} ` : ""}${driftSearchSet(contract)}`),
167
172
  [relativePath(repo, tasksPath)]
168
173
  );
169
174
  }
@@ -0,0 +1,175 @@
1
+ "use strict";
2
+
3
+ // What moved a task's fingerprint, when Git can say (issue #342).
4
+ //
5
+ // Only the previous digest is kept in the anchor, so the capsule behind it is
6
+ // gone — but the commit that recorded the anchor is not. Its task sources,
7
+ // compiled by the running compiler, either reproduce the recorded digest (the
8
+ // commit is the contract that was recorded, so a diff against today names the
9
+ // field that moved), or fail to while the anchor names another Keel version
10
+ // and the commit compiles to today's fingerprint (the compiler moved, not the
11
+ // contract). Anything else is a contract edited between recording and commit,
12
+ // the case a reconstruction from Git cannot see, and nothing is claimed.
13
+
14
+ const fs = require("fs");
15
+ const os = require("os");
16
+ const path = require("path");
17
+ const { execFileSync } = require("child_process");
18
+
19
+ const STANDING_AUTHORIZATION = /^Standing authorization \(keel\/config\.yaml\):/;
20
+
21
+ function git(repo, args) {
22
+ try {
23
+ return execFileSync("git", ["-C", repo, ...args], {
24
+ encoding: "utf8",
25
+ stdio: ["ignore", "pipe", "ignore"],
26
+ maxBuffer: 64 * 1024 * 1024,
27
+ });
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+
33
+ function runningVersion() {
34
+ try {
35
+ return require(path.join(__dirname, "..", "..", "package.json")).version;
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ function anchoredVersion(anchor) {
42
+ const match = String(anchor || "").match(/\(keel\s+([0-9][0-9A-Za-z.+-]*)\)/);
43
+ return match ? match[1] : null;
44
+ }
45
+
46
+ // The newest commit whose tasks.md holds the digest: the one that recorded it.
47
+ function recordingCommit(repo, relative, digest) {
48
+ const log = git(repo, ["log", "--format=%H", "-S", digest, "--", relative]);
49
+ if (!log) return null;
50
+ for (const sha of log.split("\n").filter(Boolean)) {
51
+ const content = git(repo, ["show", `${sha}:./${relative}`]);
52
+ if (content !== null && content.includes(digest)) return sha;
53
+ }
54
+ return null;
55
+ }
56
+
57
+ // Only what the compiler reads: the change, the published specs, the config.
58
+ function materialize(repo, sha, change, into) {
59
+ const listed = git(repo, [
60
+ "ls-tree", "-r", "--name-only", sha, "--",
61
+ `openspec/changes/${change}`, "openspec/specs", "keel/config.yaml",
62
+ ]);
63
+ if (listed === null) return false;
64
+ for (const file of listed.split("\n").filter(Boolean)) {
65
+ const content = git(repo, ["show", `${sha}:./${file}`]);
66
+ if (content === null) return false;
67
+ const target = path.join(into, ...file.split("/"));
68
+ fs.mkdirSync(path.dirname(target), { recursive: true });
69
+ fs.writeFileSync(target, content, "utf8");
70
+ }
71
+ return true;
72
+ }
73
+
74
+ function differences(before, after, at, out) {
75
+ if (JSON.stringify(before) === JSON.stringify(after)) return;
76
+ const isObject = (value) => value && typeof value === "object" && !Array.isArray(value);
77
+ if (
78
+ Array.isArray(before) && Array.isArray(after) && before.length === after.length
79
+ && before.some((item) => item && typeof item === "object")
80
+ ) {
81
+ before.forEach((item, index) => differences(item, after[index], `${at}[${index}]`, out));
82
+ return;
83
+ }
84
+ if (isObject(before) && isObject(after)) {
85
+ for (const key of [...new Set([...Object.keys(before), ...Object.keys(after)])].sort()) {
86
+ differences(before[key], after[key], at ? `${at}.${key}` : key, out);
87
+ }
88
+ return;
89
+ }
90
+ out.push(at);
91
+ }
92
+
93
+ function withoutStandingAuthorization(capsule) {
94
+ const copy = JSON.parse(JSON.stringify(capsule));
95
+ copy.boundaries.autonomy = copy.boundaries.autonomy.filter(
96
+ (entry) => !STANDING_AUTHORIZATION.test(entry)
97
+ );
98
+ return copy;
99
+ }
100
+
101
+ // { kind: "compiler" | "authorization" | "source", commit, recordedVersion,
102
+ // runningVersion, fields } or null when nothing can be said.
103
+ function diagnoseDrift(repo, change, taskId, anchor, current) {
104
+ // Required here rather than at the top: task-contract is the compiler this
105
+ // module drives, and gates and context require both.
106
+ const { compileTaskContract, parseTasks } = require("./task-contract");
107
+ const digest = (String(anchor || "").match(/sha-?256[\s:`]*([a-f0-9]{64})/i) || [])[1];
108
+ if (!digest || !current || !current.capsule) return null;
109
+ const relative = `openspec/changes/${change}/tasks.md`;
110
+ const sha = recordingCommit(repo, relative, digest.toLowerCase());
111
+ if (!sha) return null;
112
+ let scratch = null;
113
+ try {
114
+ scratch = fs.mkdtempSync(path.join(os.tmpdir(), "keel-drift-"));
115
+ if (!materialize(repo, sha, change, scratch)) return null;
116
+ const tasksPath = path.join(scratch, ...relative.split("/"));
117
+ if (!fs.existsSync(tasksPath)) return null;
118
+ const task = parseTasks(fs.readFileSync(tasksPath, "utf8")).find((item) => item.id === taskId);
119
+ if (!task) return null;
120
+ const then = compileTaskContract(scratch, change, task, { gitRepo: repo });
121
+ if (then.diagnostics.length > 0 || !then.capsule) return null;
122
+ const recordedVersion = anchoredVersion(anchor);
123
+ const running = runningVersion();
124
+ const base = { commit: sha, recordedVersion, runningVersion: running };
125
+ if (then.fingerprint.value === digest.toLowerCase()) {
126
+ const fields = [];
127
+ differences(then.capsule, current.capsule, "", fields);
128
+ if (fields.length === 0) return null;
129
+ const authorizationOnly = JSON.stringify(withoutStandingAuthorization(then.capsule))
130
+ === JSON.stringify(withoutStandingAuthorization(current.capsule));
131
+ const named = fields.map((field) => {
132
+ const index = field.match(/^authority\[(\d+)\]/);
133
+ const source = index && current.capsule.authority[Number(index[1])]
134
+ ? current.capsule.authority[Number(index[1])].source
135
+ : null;
136
+ return source ? `${field} (${source})` : field;
137
+ });
138
+ return { ...base, kind: authorizationOnly ? "authorization" : "source", fields: named };
139
+ }
140
+ if (
141
+ recordedVersion && running && recordedVersion !== running
142
+ && then.fingerprint.value === current.fingerprint.value
143
+ ) {
144
+ return { ...base, kind: "compiler", fields: [] };
145
+ }
146
+ return null;
147
+ } catch {
148
+ return null;
149
+ } finally {
150
+ if (scratch) fs.rmSync(scratch, { recursive: true, force: true });
151
+ }
152
+ }
153
+
154
+ // The sentence a drift message carries for a diagnosis, or "".
155
+ function driftCause(diagnosis) {
156
+ if (!diagnosis) return "";
157
+ const short = diagnosis.commit.slice(0, 12);
158
+ if (diagnosis.kind === "compiler") {
159
+ return `Cause: a compiler change. The task's sources as committed in ${short}, `
160
+ + "the commit that recorded this anchor, compile to today's fingerprint under "
161
+ + `Keel ${diagnosis.runningVersion}, and the anchor was recorded by Keel `
162
+ + `${diagnosis.recordedVersion}, so the fingerprint moved with the compiler and `
163
+ + "not with the contract. Re-record with `keel gate task-start --record`; the "
164
+ + "evidence stands and no `--keep-evidence` is needed.";
165
+ }
166
+ const fields = diagnosis.fields.map((field) => `\`${field}\``).join(", ");
167
+ if (diagnosis.kind === "authorization") {
168
+ return `Cause: since ${short}, the commit that recorded this anchor, only the `
169
+ + `inherited standing authorization from keel/config.yaml changed (${fields}).`;
170
+ }
171
+ return `Cause: since ${short}, the commit that recorded this anchor, these capsule `
172
+ + `fields changed: ${fields}.`;
173
+ }
174
+
175
+ module.exports = { anchoredVersion, diagnoseDrift, driftCause, runningVersion };
package/src/core/gates.js CHANGED
@@ -19,6 +19,7 @@ const {
19
19
  unfilledToken,
20
20
  } = require("./task-contract");
21
21
  const { contentSignature, gitPaths, readManifest, startGuard } = require("./guard");
22
+ const { diagnoseDrift, driftCause, runningVersion } = require("./drift");
22
23
 
23
24
  const GATE_STAGES = new Set(["task-start", "task-complete", "change-close"]);
24
25
 
@@ -138,13 +139,19 @@ function hasRecordedAnchor(selection, task) {
138
139
  // down about it. A digest that matches can only have come from the schema that
139
140
  // produced it, so the `keel-task-capsule/v1` prefix is diagnostic detail here
140
141
  // rather than a second thing to require.
141
- function contractDriftProblem(recorded, contract) {
142
+ function contractDriftProblem(recorded, contract, diagnosis = null) {
142
143
  if (!recorded || recorded === contract.fingerprint.value) return null;
144
+ const head = `The Evidence \`Contract\` anchor records sha256:${recorded}, but this `
145
+ + `task now compiles to ${contract.fingerprint.algorithm}:`
146
+ + `${contract.fingerprint.value} under ${contract.schema}. `;
147
+ // A compiler change is the one cause under which the evidence is not stale,
148
+ // and saying it is would send the author to vouch for what Keel just checked.
149
+ if (diagnosis && diagnosis.kind === "compiler") {
150
+ return problem("contract-drift", head + driftCause(diagnosis));
151
+ }
143
152
  return problem(
144
153
  "contract-drift",
145
- `The Evidence \`Contract\` anchor records sha256:${recorded}, but this `
146
- + `task now compiles to ${contract.fingerprint.algorithm}:`
147
- + `${contract.fingerprint.value} under ${contract.schema}. The contract `
154
+ head + `${diagnosis ? `${driftCause(diagnosis)} ` : ""}The contract `
148
155
  + "changed after the anchor was recorded, so the authority this task was "
149
156
  + "implemented under is not the authority it is being judged against. "
150
157
  + "Reauthorize with `keel gate task-start --record`, which rewrites the "
@@ -666,11 +673,18 @@ function taskStartChecked(repo, options) {
666
673
  }
667
674
  }
668
675
  if (result.status === "pass" && anchorPlan) {
676
+ // The version beside the digest is what lets a later drift be told apart
677
+ // from a compiler change (#342); every reader still takes the digest alone.
678
+ const version = runningVersion();
669
679
  const anchorLine =
670
680
  `${anchorPlan.indent}- Contract: keel-task-capsule/v1 `
671
- + `sha256:${compiled.fingerprint.value}${anchorPlan.cr}`;
672
- const unchanged = anchorPlan.lines[anchorPlan.cursor] === anchorLine;
673
- if (!unchanged) {
681
+ + `sha256:${compiled.fingerprint.value}${version ? ` (keel ${version})` : ""}${anchorPlan.cr}`;
682
+ const replacedDigest = anchoredFingerprint(anchorPlan.previous);
683
+ const unchanged = replacedDigest === compiled.fingerprint.value;
684
+ const diagnosis = replacedDigest && !unchanged
685
+ ? diagnoseDrift(repo, selection.change, task.id, anchorPlan.previous, compiled)
686
+ : null;
687
+ if (anchorPlan.lines[anchorPlan.cursor] !== anchorLine) {
674
688
  anchorPlan.lines[anchorPlan.cursor] = anchorLine;
675
689
  fs.writeFileSync(
676
690
  selection.tasksPath,
@@ -689,8 +703,17 @@ function taskStartChecked(repo, options) {
689
703
  // any Evidence already produced under the previous one is stale. The gate
690
704
  // cannot judge which Evidence survives; it names the change and leaves the
691
705
  // call to the current agent's Review.
692
- const replaced = anchoredFingerprint(anchorPlan.previous);
693
- if (replaced && replaced !== compiled.fingerprint.value) {
706
+ const replaced = replacedDigest;
707
+ if (replaced && replaced !== compiled.fingerprint.value && diagnosis && diagnosis.kind === "compiler") {
708
+ result.warnings.push(
709
+ `Re-recorded over a compiler change: was sha256:${replaced}, now `
710
+ + `sha256:${compiled.fingerprint.value}. The task's sources as committed in `
711
+ + `${diagnosis.commit.slice(0, 12)}, the commit that recorded the previous anchor, `
712
+ + `compile to the new fingerprint, and that anchor was recorded by Keel `
713
+ + `${diagnosis.recordedVersion} (now ${diagnosis.runningVersion}), so the `
714
+ + "evidence stands, verified against that commit; no `--keep-evidence` is needed."
715
+ );
716
+ } else if (replaced && replaced !== compiled.fingerprint.value) {
694
717
  // The gate still cannot judge which evidence survives, and this does not
695
718
  // make it able to. What it can stop doing is saying "all of it" to an
696
719
  // author who can see that one check's assertion did not change — because
@@ -1719,9 +1742,13 @@ function taskComplete(repo, options) {
1719
1742
  } else if (usableContract) {
1720
1743
  // Only when an anchor exists: a missing one is already its own problem, and
1721
1744
  // reporting drift on top of it would name a comparison that never ran.
1745
+ const recorded = recordedAnchor(selection, task);
1722
1746
  const drift = contractDriftProblem(
1723
- recordedAnchor(selection, task),
1724
- usableContract
1747
+ recorded,
1748
+ usableContract,
1749
+ recorded && recorded !== usableContract.fingerprint.value
1750
+ ? diagnoseDrift(repo, selection.change, task.id, contractAnchorPlan(selection, task).previous, usableContract)
1751
+ : null
1725
1752
  );
1726
1753
  if (drift) checks.problems.push(drift);
1727
1754
  }
@@ -2188,6 +2215,7 @@ function changeClose(repo, options) {
2188
2215
  const selection = loadSelection(repo, options, false);
2189
2216
  const problems = [];
2190
2217
  const reviewProblems = [];
2218
+ const warnings = [];
2191
2219
  const contracts = [];
2192
2220
  const changeVerify = changeVerifyChecks(selection.content, selection.tasks);
2193
2221
  if (selection.tasks.length === 0) {
@@ -2226,9 +2254,22 @@ function changeClose(repo, options) {
2226
2254
  + "--record` and `keel gate task-complete` before closing."
2227
2255
  )
2228
2256
  );
2229
- } else if (contract.diagnostics.length === 0) {
2230
- const drift = contractDriftProblem(anchor, contract);
2231
- if (drift) {
2257
+ } else if (contract.diagnostics.length === 0 && anchor !== contract.fingerprint.value) {
2258
+ const diagnosis = diagnoseDrift(
2259
+ repo, selection.change, task.id, contractAnchorPlan(selection, task).previous, contract
2260
+ );
2261
+ // A checked task completed under the authorization it recorded; a later
2262
+ // edit to keel/config.yaml changes what comes next, not what was done.
2263
+ if (diagnosis && diagnosis.kind === "authorization") {
2264
+ warnings.push(
2265
+ `Task ${task.id} is checked complete and its anchor no longer matches, `
2266
+ + `${driftCause(diagnosis).replace(/^Cause: s/, "s")} A completed task is `
2267
+ + "not drifted by a standing authorization change, so the close does not "
2268
+ + "count it; work that continues under the new authorization is still "
2269
+ + "compared against it."
2270
+ );
2271
+ } else {
2272
+ const drift = contractDriftProblem(anchor, contract, diagnosis);
2232
2273
  problems.push(problem(drift.code, `Task ${task.id}: ${drift.message}`));
2233
2274
  }
2234
2275
  }
@@ -2287,7 +2328,7 @@ function changeClose(repo, options) {
2287
2328
  selection.change,
2288
2329
  selection.tasks.map((task) => task.id),
2289
2330
  [...problems, ...reviewProblems],
2290
- expectations.report ? [expectations.report] : [],
2331
+ [...warnings, ...(expectations.report ? [expectations.report] : [])],
2291
2332
  null,
2292
2333
  contracts
2293
2334
  );
@@ -1303,7 +1303,7 @@ function couplingProblems(task, mode, designContract, compact) {
1303
1303
  return problems;
1304
1304
  }
1305
1305
 
1306
- function compileTaskContract(repo, change, task) {
1306
+ function compileTaskContract(repo, change, task, options = {}) {
1307
1307
  const mode = normalizeText(field(task, "Mode")).toLowerCase()
1308
1308
  || "implementation";
1309
1309
  const resolved = resolveAuthority(repo, change, task);
@@ -1387,7 +1387,9 @@ function compileTaskContract(repo, change, task) {
1387
1387
  }
1388
1388
  if (taskVerification.strategy.toLowerCase() === "equivalence") {
1389
1389
  resolved.diagnostics.push(
1390
- ...equivalenceProblems(repo, taskVerification)
1390
+ // Git questions go to the real repository when the sources were read
1391
+ // from a commit into a scratch directory (#342).
1392
+ ...equivalenceProblems(options.gitRepo || repo, taskVerification)
1391
1393
  );
1392
1394
  }
1393
1395
  const couplingMode = normalizeText(field(task, "Coupling")).toLowerCase()