@christang/keel 5.139.0 → 5.141.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.
@@ -0,0 +1,141 @@
1
+ {
2
+ "name": "keel",
3
+ "version": "5.141.0",
4
+ "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
+ "author": {
6
+ "name": "TanglmChris",
7
+ "url": "https://github.com/TanglmChris"
8
+ },
9
+ "repository": "https://github.com/TanglmChris/keel",
10
+ "license": "MIT",
11
+ "keywords": [
12
+ "openspec",
13
+ "workflow",
14
+ "keel",
15
+ "discipline"
16
+ ],
17
+ "skills": [
18
+ "./plugins/keel/skills/"
19
+ ],
20
+ "agents": [
21
+ "./plugins/keel/agents/keel-single-task-goal-claude.md"
22
+ ],
23
+ "hooks": {
24
+ "SessionStart": [
25
+ {
26
+ "hooks": [
27
+ {
28
+ "type": "command",
29
+ "command": "node",
30
+ "args": [
31
+ "${CLAUDE_PLUGIN_ROOT}/plugins/keel/scripts/session-start.js"
32
+ ],
33
+ "timeout": 15
34
+ }
35
+ ]
36
+ },
37
+ {
38
+ "hooks": [
39
+ {
40
+ "type": "command",
41
+ "command": "node",
42
+ "args": [
43
+ "${CLAUDE_PLUGIN_ROOT}/plugins/keel/scripts/mail-hook.js",
44
+ "session-start"
45
+ ],
46
+ "timeout": 10
47
+ }
48
+ ]
49
+ }
50
+ ],
51
+ "PreToolUse": [
52
+ {
53
+ "matcher": "Edit|Write|NotebookEdit",
54
+ "hooks": [
55
+ {
56
+ "type": "command",
57
+ "command": "node",
58
+ "args": [
59
+ "${CLAUDE_PLUGIN_ROOT}/plugins/keel/scripts/pretooluse-guard.js"
60
+ ],
61
+ "timeout": 10
62
+ }
63
+ ]
64
+ },
65
+ {
66
+ "matcher": "Bash",
67
+ "hooks": [
68
+ {
69
+ "type": "command",
70
+ "command": "node",
71
+ "args": [
72
+ "${CLAUDE_PLUGIN_ROOT}/plugins/keel/scripts/pretooluse-guard.js"
73
+ ],
74
+ "timeout": 10
75
+ }
76
+ ]
77
+ }
78
+ ],
79
+ "UserPromptSubmit": [
80
+ {
81
+ "hooks": [
82
+ {
83
+ "type": "command",
84
+ "command": "node",
85
+ "args": [
86
+ "${CLAUDE_PLUGIN_ROOT}/plugins/keel/scripts/mail-hook.js",
87
+ "user-prompt-submit"
88
+ ],
89
+ "timeout": 10
90
+ }
91
+ ]
92
+ }
93
+ ],
94
+ "PostToolUse": [
95
+ {
96
+ "hooks": [
97
+ {
98
+ "type": "command",
99
+ "command": "node",
100
+ "args": [
101
+ "${CLAUDE_PLUGIN_ROOT}/plugins/keel/scripts/mail-hook.js",
102
+ "post-tool-use"
103
+ ],
104
+ "timeout": 10
105
+ }
106
+ ]
107
+ }
108
+ ],
109
+ "FileChanged": [
110
+ {
111
+ "hooks": [
112
+ {
113
+ "type": "command",
114
+ "command": "node",
115
+ "args": [
116
+ "${CLAUDE_PLUGIN_ROOT}/plugins/keel/scripts/mail-hook.js",
117
+ "file-changed"
118
+ ],
119
+ "timeout": 10,
120
+ "asyncRewake": true
121
+ }
122
+ ]
123
+ }
124
+ ],
125
+ "SessionEnd": [
126
+ {
127
+ "hooks": [
128
+ {
129
+ "type": "command",
130
+ "command": "node",
131
+ "args": [
132
+ "${CLAUDE_PLUGIN_ROOT}/plugins/keel/scripts/mail-hook.js",
133
+ "session-end"
134
+ ],
135
+ "timeout": 10
136
+ }
137
+ ]
138
+ }
139
+ ]
140
+ }
141
+ }
package/README.md CHANGED
@@ -47,16 +47,40 @@ Node.js `>=20.19.0` (the bundled OpenSpec CLI needs it).
47
47
 
48
48
  ## Install
49
49
 
50
- **Claude Code** — the plugin is the whole install. It is this repository at the release's tag,
51
- the same tree npm publishes as `@christang/keel`, so it carries the `keel` CLI along with the
50
+ **Claude Code** — the plugin is the whole install. It is the npm package `@christang/keel` at the
51
+ release version, the same package the `keel` CLI comes from, so it carries the CLI along with the
52
52
  skills and hooks, and Claude installs the pinned OpenSpec from its lockfile when it installs the
53
- plugin. The agent's `keel` commands run the copy the plugin brought:
53
+ plugin (#337). The agent's `keel` commands run the copy the plugin brought:
54
54
 
55
55
  ```bash
56
56
  claude plugin marketplace add TanglmChris/keel
57
57
  claude plugin install keel@keel-marketplace
58
58
  ```
59
59
 
60
+ The plugin is fetched with your npm client; only the marketplace catalog,
61
+ `.claude-plugin/marketplace.json`, is read from GitHub. If cloning GitHub fails on a machine — an SSH
62
+ host key, a proxy — read the catalog over HTTPS instead, with a `url` marketplace source:
63
+
64
+ ```bash
65
+ claude plugin marketplace add https://raw.githubusercontent.com/TanglmChris/keel/main/.claude-plugin/marketplace.json
66
+ ```
67
+
68
+ or, declared in `~/.claude/settings.json`:
69
+
70
+ ```json
71
+ "extraKnownMarketplaces": {
72
+ "keel-marketplace": {
73
+ "source": {
74
+ "source": "url",
75
+ "url": "https://raw.githubusercontent.com/TanglmChris/keel/main/.claude-plugin/marketplace.json"
76
+ }
77
+ }
78
+ }
79
+ ```
80
+
81
+ Claude Code does not yet load a marketplace from an npm package (its reference lists that source as
82
+ not implemented), so the catalog cannot come from npm too.
83
+
60
84
  Updates arrive by themselves once a project is set up: `keel --init --target claude` (and
61
85
  `keel --install`) declares auto-update for `keel-marketplace` in the project's
62
86
  `.claude/settings.json`, which Claude reads before its own default of off. A new release is fetched
@@ -666,11 +690,21 @@ keel gate task-start --change <c> --task <t> --record --keep-evidence M1,M3
666
690
  ```
667
691
 
668
692
  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
693
+ the narrowing came from your declaration. **Keel does not verify the claim** — the anchor keeps the
670
694
  previous fingerprint, not the capsule behind it, so it cannot compare a check's former text to its
671
695
  current one. State your reason in the task's `Reauthorizations` line, where a reviewer can disagree
672
696
  with it. Nothing about completion changes: every check still needs its Evidence.
673
697
 
698
+ When Git can say what moved, the drift message says it instead (#342). The anchor records the Keel
699
+ version beside the digest — `- Contract: keel-task-capsule/v1 sha256:<hex> (keel <version>)` — and
700
+ on drift Keel compiles the task's sources from the commit that recorded the anchor with the running
701
+ compiler. If that commit reproduces the anchor, the message names the capsule fields that changed
702
+ since it. If it does not, but the anchor came from another Keel version and the commit compiles to
703
+ today's fingerprint, the cause is a compiler change: re-record with `task-start --record`, and the
704
+ evidence stands without a `--keep-evidence` claim. Otherwise nothing is claimed. A checked task
705
+ whose only change since its recording commit is the inherited standing authorization in
706
+ `keel/config.yaml` does not fail `change-close`; it is named in a warning.
707
+
674
708
  ## Pausing a change
675
709
 
676
710
  A change you have deliberately stopped — waiting on something outside the repository, or simply
package/README.zh-CN.md CHANGED
@@ -38,8 +38,8 @@ Node.js `>=20.19.0`(内置的 OpenSpec CLI 需要)。
38
38
 
39
39
  ## 安装
40
40
 
41
- **Claude Code** —— 装插件就够了。插件就是本仓库在发布 tag 上的那棵树,和 npm 发布的 `@christang/keel`
42
- 是同一份,技能和 hook 之外还带着 `keel` CLI;安装插件时 Claude 会按锁文件装好锁定版本的 OpenSpec。
41
+ **Claude Code** —— 装插件就够了。插件就是发布版本的 npm 包 `@christang/keel`,和 `keel` CLI 来自同一个包,
42
+ 技能和 hook 之外还带着 `keel` CLI;安装插件时 Claude 会按锁文件装好锁定版本的 OpenSpec(#337)。
43
43
  agent 运行的 `keel` 就是插件带来的这一份:
44
44
 
45
45
  ```bash
@@ -47,6 +47,28 @@ claude plugin marketplace add TanglmChris/keel
47
47
  claude plugin install keel@keel-marketplace
48
48
  ```
49
49
 
50
+ 插件用你的 npm 客户端获取;只有 marketplace 清单 `.claude-plugin/marketplace.json` 从 GitHub 读取。
51
+ 如果某台机器 clone GitHub 失败(SSH host key、代理等),可以改为用 `url` 来源、通过 HTTPS 读取清单:
52
+
53
+ ```bash
54
+ claude plugin marketplace add https://raw.githubusercontent.com/TanglmChris/keel/main/.claude-plugin/marketplace.json
55
+ ```
56
+
57
+ 或者在 `~/.claude/settings.json` 里声明:
58
+
59
+ ```json
60
+ "extraKnownMarketplaces": {
61
+ "keel-marketplace": {
62
+ "source": {
63
+ "source": "url",
64
+ "url": "https://raw.githubusercontent.com/TanglmChris/keel/main/.claude-plugin/marketplace.json"
65
+ }
66
+ }
67
+ }
68
+ ```
69
+
70
+ Claude Code 目前还不支持从 npm 包加载 marketplace(其参考文档把这种来源列为尚未实现),所以清单本身还不能也从 npm 来。
71
+
50
72
  项目初始化后,更新会自己到来:`keel --init --target claude`(以及 `keel --install`)会在项目的
51
73
  `.claude/settings.json` 里为 `keel-marketplace` 声明自动更新,Claude 先读这个声明,而不是它默认的"关闭"。
52
74
  新版本会在会话发出第一条消息后在后台下载。从 5.89.0 起,正在运行的会话在下一次 hook 调用时就用上新版;
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.139.0 -->
1
+ <!-- keel:start version=5.141.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.141.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.141.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.141.0",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -19,6 +19,7 @@
19
19
  "README.md",
20
20
  "npm-shrinkwrap.json",
21
21
  "plugins/",
22
+ ".claude-plugin/plugin.json",
22
23
  "!**/__pycache__",
23
24
  "!**/*.pyc"
24
25
  ],
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.139.0",
3
+ "version": "5.141.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.141.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",
@@ -62,9 +62,9 @@ function bumpPackageFiles(newVersion) {
62
62
  process.stdout.write(" updated npm-shrinkwrap.json\n");
63
63
  }
64
64
 
65
- // On Claude the plugin is the tagged repository tree. Its root manifest carries
66
- // the release version, and Keel's marketplace entry names that version and the
67
- // tag it installs from git. All three move, or a refresh installs the old tree.
65
+ // On Claude the plugin is the npm package (#337). Its root manifest carries the
66
+ // release version, and Keel's marketplace entry names that version and the
67
+ // package version it installs. All three move, or a refresh installs the old one.
68
68
  function bumpClaudeMarketplace(newVersion) {
69
69
  const manifestRel = ".claude-plugin/plugin.json";
70
70
  const manifestPath = path.join(ROOT, manifestRel);
@@ -81,12 +81,12 @@ function bumpClaudeMarketplace(newVersion) {
81
81
  !entry
82
82
  || !entry.source
83
83
  || typeof entry.source !== "object"
84
- || entry.source.source !== "url"
84
+ || entry.source.source !== "npm"
85
85
  ) {
86
- fail(`expected a git-sourced keel entry in ${relPath}`);
86
+ fail(`expected an npm-sourced keel entry in ${relPath}`);
87
87
  }
88
88
  entry.version = newVersion;
89
- entry.source.ref = `v${newVersion}`;
89
+ entry.source.version = newVersion;
90
90
  writeJson(filePath, market);
91
91
  process.stdout.write(` updated ${relPath}\n`);
92
92
  }
@@ -11,6 +11,7 @@ import re
11
11
  import shutil
12
12
  import subprocess
13
13
  import sys
14
+ import tarfile
14
15
  import tempfile
15
16
  import threading
16
17
  import time
@@ -47,8 +48,8 @@ REQUIRED_SCRIPTS = [
47
48
  "scripts/validate_plugin.py",
48
49
  ]
49
50
 
50
- PACKAGE_VERSION = "5.139.0"
51
- PROTOCOL_VERSION = "5.139.0"
51
+ PACKAGE_VERSION = "5.141.0"
52
+ PROTOCOL_VERSION = "5.141.0"
52
53
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
53
54
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
54
55
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -8182,7 +8183,7 @@ def validate_record_derives_skeleton_scenario() -> int:
8182
8183
  after = tasks.read_text(encoding="utf-8")
8183
8184
  before_lines, after_lines = red_green.splitlines(), after.splitlines()
8184
8185
  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]
8186
+ want = [" - Evidence:", f" - Contract: keel-task-capsule/v1 sha256:{fingerprint} (keel {PACKAGE_VERSION})", *expected_slots]
8186
8187
  if added != want:
8187
8188
  report(f"{label} --record added {added!r}, expected {want!r}.")
8188
8189
  return 1
@@ -8240,7 +8241,7 @@ def validate_record_derives_skeleton_scenario() -> int:
8240
8241
  return 1
8241
8242
  fingerprint = payload["contract"]["fingerprint"]["value"]
8242
8243
  got = evidence_lines(tasks.read_text(encoding="utf-8"))
8243
- want = [f" - Contract: keel-task-capsule/v1 sha256:{fingerprint}", *expected_slots]
8244
+ want = [f" - Contract: keel-task-capsule/v1 sha256:{fingerprint} (keel {PACKAGE_VERSION})", *expected_slots]
8244
8245
  if got != want:
8245
8246
  report(f"{label} --record over Contract, Blocker and Reauthorizations left the block out of "
8246
8247
  f"template order: {got!r}, expected {want!r}.")
@@ -8834,10 +8835,10 @@ def validate_version_alignment_scenario() -> int:
8834
8835
  )
8835
8836
  return 1
8836
8837
 
8837
- # M5 — on Claude the plugin is the tagged repository: the root manifest
8838
- # carries the version, and the marketplace entry names it and the tag it
8839
- # installs, so all three are version markers, and the script that moves
8840
- # every marker has to move them.
8838
+ # M5 — on Claude the plugin is the npm package: the root manifest carries
8839
+ # the version, and the marketplace entry names it and the package version
8840
+ # it installs, so all three are version markers, and the script that moves
8841
+ # every marker has to move them (#337).
8841
8842
  def claude_entry_versions(root: Path) -> dict:
8842
8843
  market = json.loads(
8843
8844
  (root / ".claude-plugin/marketplace.json").read_text(encoding="utf-8")
@@ -8846,10 +8847,9 @@ def validate_version_alignment_scenario() -> int:
8846
8847
  (e for e in market.get("plugins", []) if e.get("name") == "keel"), {}
8847
8848
  )
8848
8849
  source = entry.get("source") if isinstance(entry.get("source"), dict) else {}
8849
- ref = source.get("ref")
8850
8850
  return {
8851
8851
  "version": entry.get("version"),
8852
- "source.ref": ref[1:] if isinstance(ref, str) and ref.startswith("v") else ref,
8852
+ "source.version": source.get("version"),
8853
8853
  }
8854
8854
 
8855
8855
  def root_manifest_version(root: Path) -> str | None:
@@ -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", [])
@@ -21747,7 +21879,7 @@ def validate_native_plugin_manifests_scenario() -> int:
21747
21879
  ),
21748
21880
  None,
21749
21881
  )
21750
- # M1 — on Claude the plugin is the tagged repository tree, and the manifest
21882
+ # M1 — on Claude the plugin is the npm package's tree, and the manifest
21751
21883
  # at its root is the one Claude manifest, so a directory entry nobody here
21752
21884
  # controls only has to say where the repository is.
21753
21885
  root_manifest_path = ROOT / ".claude-plugin/plugin.json"
@@ -21849,15 +21981,15 @@ def validate_native_plugin_manifests_scenario() -> int:
21849
21981
  )
21850
21982
  return 1
21851
21983
 
21852
- # M2 — Keel's own entry installs the same tagged tree the official
21853
- # directory would, from git. It pins the tag rather than a commit because
21854
- # the file is part of the commit it would have to name, and it restates no
21855
- # component, so the root manifest stays the only place they are declared.
21984
+ # M2 — Keel's own entry installs the npm package the CLI comes from, at
21985
+ # exactly this release (#337). It restates no component, so the root
21986
+ # manifest stays the only place they are declared, and the package has to
21987
+ # ship that manifest or the installed plugin has no components at all.
21856
21988
  source = (claude_entry or {}).get("source")
21857
21989
  want_source = {
21858
- "source": "url",
21859
- "url": KEEL_REPOSITORY_GIT_URL,
21860
- "ref": f"v{package_version}",
21990
+ "source": "npm",
21991
+ "package": "@christang/keel",
21992
+ "version": package_version,
21861
21993
  }
21862
21994
  restated = [
21863
21995
  key for key in ("skills", "agents", "hooks") if key in (claude_entry or {})
@@ -21869,7 +22001,7 @@ def validate_native_plugin_manifests_scenario() -> int:
21869
22001
  ):
21870
22002
  report(
21871
22003
  "native-plugin-manifests claude marketplace entry is not the "
21872
- f"tagged repository at v{package_version}: source {source!r}, "
22004
+ f"npm package at {package_version}: source {source!r}, "
21873
22005
  f"version {(claude_entry or {}).get('version')!r}, restated "
21874
22006
  f"components {restated!r}"
21875
22007
  )
@@ -21903,6 +22035,7 @@ def validate_native_plugin_manifests_scenario() -> int:
21903
22035
  for name, ok in (
21904
22036
  ("bin/keel", modes.get("bin/keel", 0) & 0o111),
21905
22037
  ("npm-shrinkwrap.json", "npm-shrinkwrap.json" in modes),
22038
+ (".claude-plugin/plugin.json", ".claude-plugin/plugin.json" in modes),
21906
22039
  )
21907
22040
  if not ok
21908
22041
  ]
@@ -22429,9 +22562,6 @@ def validate_native_plugin_session_start_scenario() -> int:
22429
22562
  # one independently: the plugin's by planting a manifest beside a copy of the
22430
22563
  # shipping hook, the CLI's by what the fake CLI prints, and the repository's by
22431
22564
  # the managed block in its AGENTS.md.
22432
- # Where the Claude plugin is fetched from, by Keel's marketplace and by the
22433
- # official directory entry each release states.
22434
- KEEL_REPOSITORY_GIT_URL = "https://github.com/TanglmChris/keel.git"
22435
22565
  VERSION_DRIFT_STATEMENT = "runtime versions disagree"
22436
22566
  # How an update applies: the hooks are fixed when the plugin loads, and the
22437
22567
  # host's `/reload-plugins` reloads it in the running session (#164). A restart
@@ -24120,39 +24250,37 @@ def validate_release_notes_name_the_directory_branch_scenario() -> int:
24120
24250
 
24121
24251
 
24122
24252
  def stage_claude_market_under_test(tmp: Path) -> tuple[Path, str, str] | str:
24123
- """A Claude marketplace that installs this tree rather than GitHub's.
24124
-
24125
- The committed entry installs the Keel repository at this release's tag,
24126
- which does not exist until the release lands, and at a tag that does exist
24127
- it installs GitHub's copy and tests nothing here. So an install smoke
24128
- stages the working tree — tracked and untracked-but-not-ignored files, as
24129
- they are on disk — as a scratch git repository tagged the same way, and
24130
- puts it behind a copy of the committed entry whose URL points at it and
24131
- whose other fields are unchanged. The host then fetches it through git and
24132
- installs its dependencies exactly as it would from GitHub. A sentinel only
24133
- the staged tree carries lets the caller prove which copy was installed.
24134
- Returns the marketplace directory, its name, and the sentinel, or a failure
24135
- message.
24253
+ """A Claude marketplace that installs this tree's npm package, not npm's.
24254
+
24255
+ The committed entry installs `@christang/keel` from npm at this release's
24256
+ version, which is not published until the release lands, and a published
24257
+ version installs npm's copy and tests nothing here. An npm source also
24258
+ refuses a local folder or `file:` package (#337). So an install smoke packs
24259
+ this tree with `npm pack`, unpacks the tarball — exactly the files the
24260
+ package publishes — and serves it as a scratch git repository behind a copy
24261
+ of the committed entry whose source points at it and whose other fields are
24262
+ unchanged. The host then copies it and installs its dependencies as it
24263
+ would from npm; only the transport differs. A sentinel only the staged
24264
+ package carries lets the caller prove which copy was installed. Returns the
24265
+ marketplace directory, its name, and the sentinel, or a failure message.
24136
24266
  """
24137
24267
  git = shutil.which("git")
24138
- if git is None:
24139
- return "needs git to stage the tree under test."
24140
- listed = subprocess.run(
24141
- [git, "ls-files", "-z", "--cached", "--others", "--exclude-standard"],
24142
- cwd=ROOT,
24143
- capture_output=True,
24144
- check=False,
24268
+ npm = shutil.which("npm")
24269
+ if git is None or npm is None:
24270
+ return "needs git and npm to stage the package under test."
24271
+ packs = tmp / "packed"
24272
+ packs.mkdir(parents=True, exist_ok=True)
24273
+ packed = subprocess.run(
24274
+ [npm, "pack", "--json", "--pack-destination", str(packs)],
24275
+ cwd=ROOT, capture_output=True, text=True, check=False,
24145
24276
  )
24146
- if listed.returncode != 0:
24147
- return "git ls-files failed: " + listed.stderr.decode("utf-8", "replace")
24148
- staged = tmp / "keel-under-test"
24149
- for relative in filter(None, listed.stdout.decode("utf-8").split("\0")):
24150
- source = ROOT / relative
24151
- if not source.is_file():
24152
- continue
24153
- target = staged / relative
24154
- target.parent.mkdir(parents=True, exist_ok=True)
24155
- shutil.copy2(source, target)
24277
+ try:
24278
+ tarball = packs / json.loads(packed.stdout)[0]["filename"]
24279
+ except (ValueError, KeyError, IndexError):
24280
+ return "npm pack failed: " + (packed.stderr or packed.stdout).strip()[:400]
24281
+ with tarfile.open(tarball) as archive:
24282
+ archive.extractall(packs, filter="data")
24283
+ staged = packs / "package"
24156
24284
  sentinel = ".keel-package-under-test"
24157
24285
  write_text(staged / sentinel, "\n")
24158
24286
  committed = json.loads(
@@ -24161,22 +24289,20 @@ def stage_claude_market_under_test(tmp: Path) -> tuple[Path, str, str] | str:
24161
24289
  entry = next(
24162
24290
  (e for e in committed.get("plugins", []) if e.get("name") == "keel"), None
24163
24291
  )
24164
- source_field = (entry or {}).get("source")
24165
- if not isinstance(source_field, dict) or not source_field.get("ref"):
24166
- return f"the committed Claude entry pins no git ref: {source_field!r}"
24292
+ if not isinstance((entry or {}).get("source"), dict):
24293
+ return f"the committed Claude entry has no source object: {entry!r}"
24167
24294
  identity = ["-c", "user.name=keel", "-c", "user.email=keel@invalid"]
24168
24295
  for args in (
24169
24296
  ["init", "-q"],
24170
24297
  ["add", "-A"],
24171
- [*identity, "commit", "-q", "-m", "tree under test"],
24172
- ["tag", source_field["ref"]],
24298
+ [*identity, "commit", "-q", "-m", "package under test"],
24173
24299
  ):
24174
24300
  done = subprocess.run(
24175
24301
  [git, *args], cwd=staged, capture_output=True, text=True, check=False
24176
24302
  )
24177
24303
  if done.returncode != 0:
24178
- return f"git {args[-1]} failed staging the tree: {done.stderr.strip()}"
24179
- source_field["url"] = staged.resolve().as_uri()
24304
+ return f"git {args[-1]} failed staging the package: {done.stderr.strip()}"
24305
+ entry["source"] = {"source": "url", "url": staged.resolve().as_uri()}
24180
24306
  market = tmp / "claude-market"
24181
24307
  write_text(
24182
24308
  market / ".claude-plugin/marketplace.json",
@@ -24720,7 +24846,7 @@ def validate_native_plugin_marketplaces_scenario() -> int:
24720
24846
  "which does not carry the sentinel the staged tree does."
24721
24847
  )
24722
24848
  return 1
24723
- # M4 — the git install is a working plugin: the host loaded the
24849
+ # M4 — the packaged install is a working plugin: the host loaded the
24724
24850
  # skills and both hooks from the root manifest, and installed the
24725
24851
  # OpenSpec the lockfile pins, since nothing in the tree carries it.
24726
24852
  details = run_claude("plugin", "details", f"keel@{claude_market_name}")
@@ -24738,12 +24864,12 @@ def validate_native_plugin_marketplaces_scenario() -> int:
24738
24864
  if details.returncode != 0:
24739
24865
  report(
24740
24866
  "native-plugin-marketplaces claude plugin details failed for "
24741
- f"the git-installed plugin: {(details.stderr or details_text).strip()!r}"
24867
+ f"the packaged plugin: {(details.stderr or details_text).strip()!r}"
24742
24868
  )
24743
24869
  return 1
24744
24870
  if missing:
24745
24871
  report(
24746
- "native-plugin-marketplaces the git-installed plugin lacks "
24872
+ "native-plugin-marketplaces the packaged plugin lacks "
24747
24873
  f"{missing!r} in claude plugin details: {details_text!r}"
24748
24874
  )
24749
24875
  return 1
@@ -24758,7 +24884,7 @@ def validate_native_plugin_marketplaces_scenario() -> int:
24758
24884
  openspec_bin = install_path / "node_modules/.bin/openspec"
24759
24885
  if not openspec_bin.exists():
24760
24886
  report(
24761
- "native-plugin-marketplaces the git-installed plugin has no "
24887
+ "native-plugin-marketplaces the packaged plugin has no "
24762
24888
  f"installed OpenSpec at {openspec_bin}; the host did not "
24763
24889
  "install the tree's dependencies."
24764
24890
  )
@@ -24772,13 +24898,13 @@ def validate_native_plugin_marketplaces_scenario() -> int:
24772
24898
  pinned = shrinkwrap_openspec_version()
24773
24899
  if probe.returncode != 0:
24774
24900
  report(
24775
- "native-plugin-marketplaces the git-installed OpenSpec failed "
24901
+ "native-plugin-marketplaces the packaged OpenSpec failed "
24776
24902
  f"to run: {(probe.stderr or probe.stdout).strip()!r}"
24777
24903
  )
24778
24904
  return 1
24779
24905
  if pinned not in probe.stdout:
24780
24906
  report(
24781
- "native-plugin-marketplaces the git-installed plugin does not "
24907
+ "native-plugin-marketplaces the packaged plugin does not "
24782
24908
  f"carry the pinned OpenSpec {pinned}: {probe.stdout.strip()!r}"
24783
24909
  )
24784
24910
  return 1
@@ -40917,6 +41043,7 @@ SCENARIOS: tuple = (
40917
41043
  "contract-anchor-is-compared",
40918
41044
  validate_contract_anchor_is_compared_scenario,
40919
41045
  ),
41046
+ ("contract-drift-diagnosis", validate_contract_drift_diagnosis_scenario),
40920
41047
  (
40921
41048
  "guard-scope-is-the-repository",
40922
41049
  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()