@christang/keel 5.222.0 → 5.223.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.222.0",
3
+ "version": "5.223.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",
package/README.md CHANGED
@@ -183,7 +183,7 @@ model toward or away from using one (#414).
183
183
  Do the spec work through OpenSpec's workflow skills (`openspec-propose`, `openspec-apply-change`,
184
184
  `openspec-sync-specs`, `openspec-archive-change`); Keel generates them as skills only, with no OpenSpec
185
185
  slash commands (#406). Keel's own commands and the skills a person can invoke are listed in
186
- [docs/commands.md](docs/commands.md). Keel's gates run at the task boundaries. The whole loop:
186
+ [docs/commands.md](docs/commands.md). To report a problem with Keel from any project, run `/keel:feedback <one sentence>` or `keel feedback "<one sentence>"`: it drafts an issue for the Keel repository with the version, the failing command and its output (`--command`, `--output-file`, with `--expected`, `--repro` and `--impact` for the rest, and `--doctor` to attach the doctor output), redacts tokens, Slack IDs, e-mail addresses and local paths, lists similar open issues, and creates nothing until `--create` is run, which needs your approval (`--confirmed`) or a project that declares `issue:TanglmChris/keel`. Keel's gates run at the task boundaries. The whole loop:
187
187
 
188
188
  ```
189
189
  keel --init → keel context → openspec-apply-change (tasks in order)
package/README.zh-CN.md CHANGED
@@ -156,7 +156,7 @@ agent 复跑,也不引导模型去用或不用它(#414)。
156
156
 
157
157
  spec 相关的活走 OpenSpec 的工作流 skill(`openspec-propose`、`openspec-apply-change`、`openspec-sync-specs`、
158
158
  `openspec-archive-change`);Keel 只生成 skill,不生成 OpenSpec 斜杠命令(#406)。Keel 自己的命令和可以手动调用的技能列在
159
- [docs/commands.zh-CN.md](docs/commands.zh-CN.md)。Keel 的门禁在任务边界处运行。整个回路:
159
+ [docs/commands.zh-CN.md](docs/commands.zh-CN.md)。要在任何项目里反馈 Keel 的问题,运行 `/keel:feedback <一句话>` 或 `keel feedback "<一句话>"`:它给 Keel 仓库起草一份带版本、失败命令及其输出的 issue(`--command`、`--output-file`,其余用 `--expected`、`--repro`、`--impact`,`--doctor` 附上诊断输出),脱敏 token、Slack ID、邮箱和本机路径,列出相近的 issue,在运行 `--create` 之前不创建任何东西,而 `--create` 需要你的批准(`--confirmed`)或项目声明了 `issue:TanglmChris/keel`。Keel 的门禁在任务边界处运行。整个回路:
160
160
 
161
161
  ```
162
162
  keel --init → keel context → openspec-apply-change(按顺序做 task)
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.222.0 -->
1
+ <!-- keel:start version=5.223.0 -->
2
2
  ## Keel Bootstrap
3
3
 
4
4
  - Start every session with `keel context`; OpenSpec artifacts and Git are the durable authority, and memory or transcripts may only inform.
package/bin/keel.js CHANGED
@@ -96,6 +96,7 @@ Usage:
96
96
  keel mail role|send|list|read|hook [repo] ... (cross-host mailbox; see keel mail help)
97
97
  keel triage [repo] [--labels <l1,l2>] [--issue <n>] [--json]
98
98
  keel agents [name] [--repo path] [--json] (external model CLIs, read on demand; Keel launches none)
99
+ keel feedback "<one sentence>" [--command <cmd>] [--output-file <file>] [--expected <t>] [--repro <t>] [--impact <t>] [--doctor] [--create [--confirmed]] (draft a redacted issue for Keel; creates nothing without --create)
99
100
  keel branches [repo] [--role <role>] [--json] (a role's merged task branches, with their sha; fetches and deletes nothing)
100
101
  keel branches prune [repo] [--role <role>] [--json] (delete them, local and remote, under authorize: delete-branch:merged; exit 3 without it)
101
102
  keel shift request|check|ready|start|resume|status ... (a role's shift change; see keel shift --help)
@@ -3325,6 +3326,10 @@ function main() {
3325
3326
  if (process.argv[2] === "tick") {
3326
3327
  return require("../src/core/tick").runTick(process.argv.slice(3));
3327
3328
  }
3329
+ // `keel feedback` likewise: a redacted issue draft for Keel (#505).
3330
+ if (process.argv[2] === "feedback") {
3331
+ return require("../src/core/feedback").runFeedback(process.argv.slice(3));
3332
+ }
3328
3333
  if (process.argv[2] === "worktrees") {
3329
3334
  return require("../src/core/worktrees").runWorktrees(process.argv.slice(3));
3330
3335
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.222.0",
3
+ "version": "5.223.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.222.0",
9
+ "version": "5.223.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.222.0",
5
+ "version": "5.223.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.222.0",
3
+ "version": "5.223.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.222.0",
3
+ "version": "5.223.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",
@@ -0,0 +1,38 @@
1
+ ---
2
+ description: Draft a redacted issue for Keel from this session — version, reproduction, near-duplicates — and create it only after the user agrees
3
+ argument-hint: "<one sentence about the problem>"
4
+ ---
5
+
6
+ File feedback about Keel itself. The mechanism is `keel feedback`; this command only orders the steps and asks before anything is created. It works from any project, not only Keel's.
7
+
8
+ ## 1. Draft
9
+
10
+ Take the problem from the arguments: `$ARGUMENTS`, or else ask for one sentence. If a Keel command just failed, pass it and its output so the issue carries them:
11
+
12
+ ```bash
13
+ keel feedback "<one sentence>" --command "<the command that failed>" --output-file <file holding its output> --expected "<what should have happened>" --repro "<the steps>" --impact "<what it blocks>"
14
+ ```
15
+
16
+ Write the output to a file first and pass the file; do not paste it into the command line. Add `--doctor` only when the problem is about setup, because the doctor output carries local paths (they are redacted, but the user should know it is attached). Nothing is created by this step.
17
+
18
+ ## 2. Show it
19
+
20
+ Show the user the whole draft as printed: title, sections, the count of redacted values, and any similar issues. Check it yourself for project content that should not be public — a customer name, an unreleased design — that the redaction cannot know, and fix it by rerunning with the text changed.
21
+
22
+ ## 3. Ask
23
+
24
+ Ask through the structured-choice surface, with the first option recommended:
25
+
26
+ - **new issue** — create it now.
27
+ - **add to #n myself** — when a similar issue exists; print the `gh issue comment` command from the draft for the user to run. Keel runs no comment and edits no issue.
28
+ - **cancel** — leave the draft file where it is and stop.
29
+
30
+ ## 4. Create, only on "new issue"
31
+
32
+ ```bash
33
+ keel feedback "<the same arguments>" --create --confirmed
34
+ ```
35
+
36
+ Drop `--confirmed` only when this project's `keel/config.yaml` declares `issue:TanglmChris/keel`; the declaration is the owner's standing approval, and without it `--create` is refused. Add no label, assignee or milestone, and do not add the issue to any `triage:` list: whether it is worth doing stays the owner's decision.
37
+
38
+ Report the issue URL the command prints. If `gh` is missing or not logged in the command exits 4 with the draft saved: give the user the saved file and the `gh issue create` command it printed, and do not retry.
@@ -35,10 +35,10 @@ os.environ["KEEL_UPDATE_CLAUDE"] = str(Path(tempfile.gettempdir()) / "keel-suite
35
35
  os.environ["KEEL_UPDATE_CODEX"] = str(Path(tempfile.gettempdir()) / "keel-suite-has-no-codex")
36
36
 
37
37
 
38
- PACKAGE_VERSION = "5.222.0"
38
+ PACKAGE_VERSION = "5.223.0"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.222.0"
41
+ PROTOCOL_VERSION = "5.223.0"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -0,0 +1,324 @@
1
+ """Issue #505: `keel feedback` drafts, redacts, searches and (under a declaration or a confirmation) creates."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+ import tempfile
10
+ from contextlib import contextmanager
11
+ from pathlib import Path
12
+
13
+ from validation.common import ROOT, report, run_keel, write_authorize_config, write_text
14
+
15
+ KEEL_REPO = "TanglmChris/keel"
16
+ CREATED_URL = f"https://github.com/{KEEL_REPO}/issues/999"
17
+
18
+
19
+ def version() -> str:
20
+ return json.loads((ROOT / "package.json").read_text(encoding="utf-8"))["version"]
21
+
22
+
23
+ def secret(*parts: str) -> str:
24
+ """Join pieces so this file holds no literal that looks like a credential."""
25
+ return "".join(parts)
26
+
27
+
28
+ @contextmanager
29
+ def feedback_world(prefix: str, *, with_gh: bool = True):
30
+ """A scratch git project that is not Keel, a stub `gh`, and an environment that finds both.
31
+
32
+ Yields `(project, env, log, bin_dir)`. The stub logs its arguments, prints
33
+ `list.json` for `issue list` and a fixed URL for `issue create`, and with a
34
+ `fail` file beside it prints `gh: not logged in` and exits 1.
35
+ """
36
+ with tempfile.TemporaryDirectory(prefix=prefix) as raw:
37
+ base = Path(raw).resolve()
38
+ project = base / "secret-project-name"
39
+ project.mkdir()
40
+ for args in (["init", "-q", "-b", "main"], ["config", "user.email", "t@example.invalid"], ["config", "user.name", "t"]):
41
+ subprocess.run(["git", *args], cwd=project, check=True, capture_output=True)
42
+ home = base / "home"
43
+ home.mkdir()
44
+ bin_dir = base / "stub-bin"
45
+ bin_dir.mkdir()
46
+ for tool in ("node", "git", "cat"):
47
+ found = shutil.which(tool)
48
+ (bin_dir / tool).symlink_to(found)
49
+ log = base / "gh.log"
50
+ if with_gh:
51
+ script = bin_dir / "gh"
52
+ script.write_text(
53
+ "#!/bin/sh\n"
54
+ f'echo "$*" >> "{log}"\n'
55
+ 'case "$1 $2" in\n'
56
+ f' "issue list"|"issue create") if [ -f "{bin_dir}/fail" ]; then echo "gh: not logged in" >&2; exit 1; fi ;;\n'
57
+ "esac\n"
58
+ 'case "$1 $2" in\n'
59
+ f' "issue list") cat "{bin_dir}/list.json" ;;\n'
60
+ f' "issue create") echo "{CREATED_URL}" ;;\n'
61
+ "esac\n",
62
+ encoding="utf-8",
63
+ )
64
+ script.chmod(0o755)
65
+ write_text(bin_dir / "list.json", "[]")
66
+ env = {k: v for k, v in os.environ.items() if not k.startswith(("CLAUDE", "KEEL_"))}
67
+ env["PATH"] = str(bin_dir)
68
+ env["HOME"] = str(home)
69
+ yield project, env, log, bin_dir
70
+
71
+
72
+ def gh_log(log: Path) -> str:
73
+ return log.read_text(encoding="utf-8") if log.exists() else ""
74
+
75
+
76
+ def saved_file(stdout: str) -> Path | None:
77
+ match = re.search(r"^Saved: (\S+)$", stdout, re.MULTILINE)
78
+ return Path(match.group(1)) if match else None
79
+
80
+
81
+ def validate_feedback_draft_scenario() -> int:
82
+ """Issue #505: a draft carries the version, the command and its output, and creates nothing."""
83
+ label = "feedback-draft:"
84
+ with feedback_world("keel-feedback-draft-") as (project, env, log, _bin):
85
+ write_text(project / "out.txt", "keel gate: FAILED no task 1.1 in the change\n")
86
+ result = run_keel(
87
+ project, "feedback", "gate refuses a valid task",
88
+ "--command", "keel gate task-start", "--output-file", "out.txt",
89
+ "--expected", "the gate passes", "--repro", "run it in the project", "--impact", "blocks the work",
90
+ env=env,
91
+ )
92
+ if result.returncode != 0:
93
+ report(f"{label} exit {result.returncode}: {result.stdout}{result.stderr}")
94
+ return 1
95
+ out = result.stdout
96
+ needles = (
97
+ version(), "keel gate task-start", "no task 1.1 in the change", "gate refuses a valid task",
98
+ "现象", "期望", "复现", "证据", "影响", "环境", "the gate passes", "blocks the work",
99
+ )
100
+ missing = [n for n in needles if n not in out]
101
+ if missing:
102
+ report(f"{label} the draft lacks {missing!r}: {out}")
103
+ return 1
104
+ saved = saved_file(out)
105
+ if saved is None:
106
+ report(f"{label} the draft does not name the file it saved: {out}")
107
+ return 1
108
+ if not saved.exists():
109
+ report(f"{label} the file {saved} the draft names does not exist.")
110
+ return 1
111
+ if "no task 1.1 in the change" not in saved.read_text(encoding="utf-8"):
112
+ report(f"{label} the saved file does not hold the output: {saved}")
113
+ return 1
114
+ if "issue create" in gh_log(log):
115
+ report(f"{label} a draft without --create asked gh to create an issue: {gh_log(log)}")
116
+ return 1
117
+ for private in ("secret-project-name", "origin"):
118
+ if private in out:
119
+ report(f"{label} the draft holds {private!r}, project content nobody asked to publish: {out}")
120
+ return 1
121
+ report("feedback-draft scenario passed.")
122
+ return 0
123
+
124
+
125
+ def validate_feedback_redacts_scenario() -> int:
126
+ """Issue #505: tokens, Slack IDs, e-mail, credentials and local paths never reach the draft."""
127
+ label = "feedback-redacts:"
128
+ with feedback_world("keel-feedback-redact-") as (project, env, log, _bin):
129
+ home = Path(env["HOME"])
130
+ secrets = {
131
+ "a GitHub token": secret("gh", "p_", "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8"),
132
+ "a Slack bot token": secret("xo", "xb-", "1234567890-abcdefghijklmnop"),
133
+ "a Slack user ID": secret("U", "01ABC", "DE23F"),
134
+ "a bearer credential": secret("Bearer ", "abcdef0123456789zz"),
135
+ "a key=value secret": secret("hunt", "er2"),
136
+ "an e-mail address": secret("someone", "@", "example.org"),
137
+ "a URL password": secret("pa", "ssw0rd9"),
138
+ }
139
+ lines = [
140
+ f"token was {secrets['a GitHub token']} and {secrets['a Slack bot token']}",
141
+ f"posted as {secrets['a Slack user ID']} to the channel",
142
+ f"Authorization: {secrets['a bearer credential']}",
143
+ f"API_KEY={secrets['a key=value secret']}",
144
+ f"contact {secrets['an e-mail address']}",
145
+ f"clone https://deploy:{secrets['a URL password']}@git.example.org/x.git",
146
+ f"read {home}/notes/private.txt and {project}/src/a.js",
147
+ "The Gate refused TASK 12 at line 4 with UNREADABLE input",
148
+ ]
149
+ write_text(project / "out.txt", "\n".join(lines) + "\n")
150
+ result = run_keel(project, "feedback", "output leaks", "--output-file", "out.txt", env=env)
151
+ if result.returncode != 0:
152
+ report(f"{label} exit {result.returncode}: {result.stdout}{result.stderr}")
153
+ return 1
154
+ saved = saved_file(result.stdout)
155
+ if saved is None or not saved.exists():
156
+ report(f"{label} no saved file: {result.stdout}")
157
+ return 1
158
+ shown = result.stdout + saved.read_text(encoding="utf-8")
159
+ for what, value in secrets.items():
160
+ if value in shown:
161
+ report(f"{label} {what} reached the draft or the saved file: {value!r}")
162
+ return 1
163
+ if not re.search(r"[Rr]edacted \d+", result.stdout):
164
+ report(f"{label} the draft does not report how many values it redacted: {result.stdout}")
165
+ return 1
166
+ for expected in ("~/notes/private.txt", "<project>/src/a.js"):
167
+ if expected not in shown:
168
+ report(f"{label} the draft lacks the shortened path {expected!r}: {shown}")
169
+ return 1
170
+ if "The Gate refused TASK 12 at line 4 with UNREADABLE input" not in shown:
171
+ report(f"{label} ordinary prose was changed by the redaction: {shown}")
172
+ return 1
173
+ report("feedback-redacts scenario passed.")
174
+ return 0
175
+
176
+
177
+ def validate_feedback_duplicates_scenario() -> int:
178
+ """Issue #505: near-duplicates are listed first, and Keel runs no comment."""
179
+ label = "feedback-duplicates:"
180
+ with feedback_world("keel-feedback-dup-") as (project, env, log, bin_dir):
181
+ write_text(bin_dir / "list.json", json.dumps([
182
+ {"number": 12, "title": "the push guard refuses a tag", "state": "OPEN", "url": f"https://github.com/{KEEL_REPO}/issues/12"},
183
+ ]))
184
+ result = run_keel(project, "feedback", "push guard refuses tag pushes", env=env)
185
+ if result.returncode != 0:
186
+ report(f"{label} exit {result.returncode}: {result.stdout}{result.stderr}")
187
+ return 1
188
+ for needle in ("#12", "the push guard refuses a tag", f"https://github.com/{KEEL_REPO}/issues/12", "gh issue comment 12"):
189
+ if needle not in result.stdout:
190
+ report(f"{label} the draft lacks {needle!r}: {result.stdout}")
191
+ return 1
192
+ recorded = gh_log(log)
193
+ if f"issue list --repo {KEEL_REPO}" not in recorded:
194
+ report(f"{label} the duplicate search was not run against {KEEL_REPO}: {recorded!r}")
195
+ return 1
196
+ if "issue comment" in recorded:
197
+ report(f"{label} Keel ran a comment: {recorded!r}")
198
+ return 1
199
+ report("feedback-duplicates scenario passed.")
200
+ return 0
201
+
202
+
203
+ def creations(log: Path) -> list[str]:
204
+ return [line for line in gh_log(log).splitlines() if line.startswith("issue create")]
205
+
206
+
207
+ def validate_feedback_create_scenario() -> int:
208
+ """Issue #505: --create needs the declaration or a confirmation, and adds no label."""
209
+ label = "feedback-create:"
210
+ with feedback_world("keel-feedback-create-") as (project, env, log, _bin):
211
+ refused = run_keel(project, "feedback", "gate refuses a valid task", "--create", env=env)
212
+ if refused.returncode != 3:
213
+ report(f"{label} --create with no declaration and no --confirmed exited {refused.returncode}, not 3: {refused.stdout}{refused.stderr}")
214
+ return 1
215
+ if "Title:" not in refused.stdout:
216
+ report(f"{label} the refusal did not print the draft: {refused.stdout}")
217
+ return 1
218
+ if creations(log):
219
+ report(f"{label} a refused --create still ran gh: {gh_log(log)!r}")
220
+ return 1
221
+ confirmed = run_keel(project, "feedback", "gate refuses a valid task", "--create", "--confirmed", env=env)
222
+ if confirmed.returncode != 0:
223
+ report(f"{label} --create --confirmed exited {confirmed.returncode}: {confirmed.stdout}{confirmed.stderr}")
224
+ return 1
225
+ if CREATED_URL not in confirmed.stdout:
226
+ report(f"{label} the new issue's URL was not printed: {confirmed.stdout}")
227
+ return 1
228
+ made = creations(log)
229
+ if len(made) != 1:
230
+ report(f"{label} --confirmed ran {len(made)} creations: {gh_log(log)!r}")
231
+ return 1
232
+ for needle in (f"--repo {KEEL_REPO}", "--title", "--body-file"):
233
+ if needle not in made[0]:
234
+ report(f"{label} the creation lacks {needle!r}: {made[0]!r}")
235
+ return 1
236
+ for forbidden in ("--label", "--assignee", "--milestone"):
237
+ if forbidden in made[0]:
238
+ report(f"{label} the creation carries {forbidden}: {made[0]!r}")
239
+ return 1
240
+ write_authorize_config(project, "authorize:\n - issue:acme/widgets\n")
241
+ elsewhere = run_keel(project, "feedback", "gate refuses a valid task", "--create", env=env)
242
+ if elsewhere.returncode != 3:
243
+ report(f"{label} a declaration for another repository exited {elsewhere.returncode}, not 3: {elsewhere.stdout}")
244
+ return 1
245
+ write_authorize_config(project, f"authorize:\n - issue:{KEEL_REPO}\n")
246
+ declared = run_keel(project, "feedback", "gate refuses a valid task", "--create", env=env)
247
+ if declared.returncode != 0:
248
+ report(f"{label} the declared project was refused ({declared.returncode}): {declared.stdout}{declared.stderr}")
249
+ return 1
250
+ if len(creations(log)) != 2:
251
+ report(f"{label} the declared project did not create exactly one more issue: {gh_log(log)!r}")
252
+ return 1
253
+ report("feedback-create scenario passed.")
254
+ return 0
255
+
256
+
257
+ def validate_feedback_gh_missing_scenario() -> int:
258
+ """Issue #505: no usable gh loses nothing."""
259
+ label = "feedback-gh-missing:"
260
+ attempts = (("no gh on PATH", False, None), ("a gh that is not logged in", True, "fail"))
261
+ for what, with_gh, marker in attempts:
262
+ with feedback_world("keel-feedback-nogh-", with_gh=with_gh) as (project, env, log, bin_dir):
263
+ if marker:
264
+ write_text(bin_dir / marker, "")
265
+ draft = run_keel(project, "feedback", "gate refuses a valid task", env=env)
266
+ if draft.returncode != 0:
267
+ report(f"{label} with {what} the draft exited {draft.returncode}: {draft.stdout}{draft.stderr}")
268
+ return 1
269
+ if "not searched" not in draft.stdout:
270
+ report(f"{label} with {what} the draft does not say the search was not run: {draft.stdout}")
271
+ return 1
272
+ created = run_keel(project, "feedback", "gate refuses a valid task", "--create", "--confirmed", env=env)
273
+ if created.returncode != 4:
274
+ report(f"{label} with {what} --create --confirmed exited {created.returncode}, not 4: {created.stdout}{created.stderr}")
275
+ return 1
276
+ saved = saved_file(created.stdout)
277
+ if saved is None or not saved.exists():
278
+ report(f"{label} with {what} the draft was lost: {created.stdout}")
279
+ return 1
280
+ if f"gh issue create --repo {KEEL_REPO}" not in created.stdout:
281
+ report(f"{label} with {what} no command to run was printed: {created.stdout}")
282
+ return 1
283
+ report("feedback-gh-missing scenario passed.")
284
+ return 0
285
+
286
+
287
+ def validate_feedback_command_surface_scenario() -> int:
288
+ """Issue #505: the slash command orders the steps, and the docs list it."""
289
+ label = "feedback-command-surface:"
290
+ command = ROOT / "plugins/keel/commands/feedback.md"
291
+ if not command.exists():
292
+ report(f"{label} {command.relative_to(ROOT)} does not exist.")
293
+ return 1
294
+ text = command.read_text(encoding="utf-8")
295
+ if not text.startswith("---\n"):
296
+ report(f"{label} the command file has no front matter.")
297
+ return 1
298
+ front = text.split("---", 2)[1]
299
+ for key in ("description:", "argument-hint:"):
300
+ if key not in front:
301
+ report(f"{label} the command file's front matter lacks {key}")
302
+ return 1
303
+ for needle in ("keel feedback", "--create", "--confirmed", "$ARGUMENTS", "no label", "comment"):
304
+ if needle not in text:
305
+ report(f"{label} the command file lacks {needle!r}.")
306
+ return 1
307
+ for answer in ("new issue", "add to", "cancel"):
308
+ if answer not in text.lower():
309
+ report(f"{label} the command file does not offer the answer {answer!r}.")
310
+ return 1
311
+ for doc, count in (("docs/commands.md", "six"), ("docs/commands.zh-CN.md", "六个")):
312
+ body = (ROOT / doc).read_text(encoding="utf-8")
313
+ if "/keel:feedback" not in body:
314
+ report(f"{label} {doc} does not list /keel:feedback.")
315
+ return 1
316
+ if count not in body:
317
+ report(f"{label} {doc} does not say {count!r} commands.")
318
+ return 1
319
+ for readme in ("README.md", "README.zh-CN.md"):
320
+ if "keel feedback" not in (ROOT / readme).read_text(encoding="utf-8"):
321
+ report(f"{label} {readme} does not name `keel feedback`.")
322
+ return 1
323
+ report("feedback-command-surface scenario passed.")
324
+ return 0
@@ -872,7 +872,7 @@ def validate_slash_menu_ships_scenario() -> int:
872
872
  # The four everyday flows a person runs, each naming the keel command it orders.
873
873
  commands_root = ROOT / PLUGIN_ROOT / "commands"
874
874
  commands = sorted(path.stem for path in commands_root.glob("*.md"))
875
- expected = {"context": "keel context", "start": "keel gate task-start", "done": "keel gate task-complete", "chat": "keel chat unread"}
875
+ expected = {"context": "keel context", "start": "keel gate task-start", "done": "keel gate task-complete", "chat": "keel chat unread", "feedback": "keel feedback"}
876
876
  if commands != sorted([*expected, "shift"]):
877
877
  report(f"{label} the plugin's commands are {commands!r}, not {sorted([*expected, 'shift'])!r}.")
878
878
  return 1
@@ -8,6 +8,7 @@ from validation import shift
8
8
  from validation import docs
9
9
  from validation import selfcheck
10
10
  from validation import export
11
+ from validation import feedback
11
12
 
12
13
 
13
14
 
@@ -535,6 +536,12 @@ SCENARIOS: tuple = (
535
536
  ("push-tag-grant", guard.validate_push_tag_grant_scenario),
536
537
  ("push-tag-branches", guard.validate_push_tag_branches_scenario),
537
538
  ("push-tag-keeps-verdicts", guard.validate_push_tag_keeps_verdicts_scenario),
539
+ ("feedback-draft", feedback.validate_feedback_draft_scenario),
540
+ ("feedback-redacts", feedback.validate_feedback_redacts_scenario),
541
+ ("feedback-duplicates", feedback.validate_feedback_duplicates_scenario),
542
+ ("feedback-create", feedback.validate_feedback_create_scenario),
543
+ ("feedback-gh-missing", feedback.validate_feedback_gh_missing_scenario),
544
+ ("feedback-command-surface", feedback.validate_feedback_command_surface_scenario),
538
545
  ("push-protected-guard", guard.validate_push_protected_guard_scenario),
539
546
  ("authorize-role-scoped", guard.validate_authorize_role_scoped_scenario),
540
547
  ("touch-guard-record-layer", guard.validate_touch_guard_record_layer_scenario),
@@ -0,0 +1,286 @@
1
+ "use strict";
2
+
3
+ // `keel feedback "<one sentence>"` (#505): drafts a fixed-structure issue for
4
+ // the Keel repository from inside any project, redacted before anything is
5
+ // shown, and lists near-duplicates. It creates nothing here; that is a later
6
+ // step under a declaration or a confirmation.
7
+
8
+ const fs = require("fs");
9
+ const os = require("os");
10
+ const path = require("path");
11
+ const { spawnSync } = require("child_process");
12
+
13
+ const PACKAGE_JSON = require("../../package.json");
14
+
15
+ // The target is Keel itself, read from the package's own repository URL: the
16
+ // command is feedback to Keel, and a flag would make it a general issue filer.
17
+ const KEEL_REPO = (() => {
18
+ const url = typeof PACKAGE_JSON.repository === "string" ? PACKAGE_JSON.repository : PACKAGE_JSON.repository.url;
19
+ const match = String(url).match(/github\.com[:/]([^/]+\/[^/.]+)(?:\.git)?$/);
20
+ return match ? match[1] : "TanglmChris/keel";
21
+ })();
22
+
23
+ const USAGE = [
24
+ "keel feedback \"<one sentence>\" [--command <cmd>] [--output-file <file>] [--expected <text>] [--repro <text>] [--impact <text>] [--host <name>] [--doctor] [--create [--confirmed]]",
25
+ " Draft an issue for the Keel repository: the version, the command and its output, redacted. Creates nothing without --create;",
26
+ " --create needs `issue:TanglmChris/keel` in this project's authorize: or --confirmed (the user approved this draft).",
27
+ ].join("\n");
28
+
29
+ // Redaction runs on everything shown. The order matters: block and token
30
+ // shapes first, then the looser key=value form, then paths.
31
+ const RULES = [
32
+ ["private-key", /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g, "[private key]"],
33
+ ["token", /\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|sk-[A-Za-z0-9_-]{20,}|xox[abprs]-[A-Za-z0-9-]{10,}|xapp-[A-Za-z0-9-]{10,}|AKIA[0-9A-Z]{16})\b/g, "[token]"],
34
+ ["token", /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}/g, "[token]"],
35
+ ["token", /\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/g, "Bearer [token]"],
36
+ ["url-credential", /([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^\s/:@]+:[^\s/@]+@/g, "$1[credential]@"],
37
+ ["secret", /\b([A-Za-z0-9_.-]*(?:token|secret|password|passwd|api[_-]?key|private[_-]?key|access[_-]?key)[A-Za-z0-9_.-]*)([ \t]*[=:][ \t]*)(["']?)(?!\[)[^\s"']{4,}/gi, "$1$2$3[redacted]"],
38
+ ["slack-id", /\b[UWCDGTB](?=[A-Z0-9]*\d)[A-Z0-9]{8,11}\b/g, "[slack-id]"],
39
+ ["email", /[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/g, "[email]"],
40
+ ];
41
+
42
+ function escapeRegExp(value) {
43
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
44
+ }
45
+
46
+ // Returns the text with every match replaced, and a count per kind. A value is
47
+ // never reported, only how many were.
48
+ function redact(text, context = {}) {
49
+ const counts = {};
50
+ let out = String(text);
51
+ for (const [kind, pattern, replacement] of RULES) {
52
+ out = out.replace(pattern, (...match) => {
53
+ counts[kind] = (counts[kind] || 0) + 1;
54
+ return replacement.replace(/\$(\d)/g, (_, n) => match[Number(n)] || "");
55
+ });
56
+ }
57
+ const roots = [];
58
+ for (const [value, short] of [[context.project, "<project>"], [context.home || os.homedir(), "~"]]) {
59
+ if (!value) continue;
60
+ for (const variant of new Set([value, safeRealpath(value)])) {
61
+ if (variant && variant !== "/") roots.push([variant, short]);
62
+ }
63
+ }
64
+ roots.sort((a, b) => b[0].length - a[0].length);
65
+ for (const [value, short] of roots) {
66
+ out = out.replace(new RegExp(`${escapeRegExp(value)}(?=$|[/\\s"'\`)\\]:,;])`, "gm"), () => {
67
+ counts.path = (counts.path || 0) + 1;
68
+ return short;
69
+ });
70
+ }
71
+ return { text: out, counts };
72
+ }
73
+
74
+ function safeRealpath(value) {
75
+ try {
76
+ return fs.realpathSync(value);
77
+ } catch {
78
+ return value;
79
+ }
80
+ }
81
+
82
+ function merge(total, counts) {
83
+ for (const [kind, n] of Object.entries(counts)) total[kind] = (total[kind] || 0) + n;
84
+ }
85
+
86
+ function git(cwd, args) {
87
+ const result = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf8", timeout: 5000 });
88
+ return result.status === 0 ? String(result.stdout || "").trim() : null;
89
+ }
90
+
91
+ function parse(argv) {
92
+ const options = { words: [], unknown: null, missing: null };
93
+ const valued = { "--command": "command", "--output-file": "outputFile", "--expected": "expected", "--repro": "repro", "--impact": "impact", "--host": "host" };
94
+ for (let i = 0; i < argv.length; i += 1) {
95
+ const arg = argv[i];
96
+ if (arg === "--help" || arg === "-h") options.help = true;
97
+ else if (arg === "--doctor") options.doctor = true;
98
+ else if (arg === "--create") options.create = true;
99
+ else if (arg === "--confirmed") options.confirmed = true;
100
+ else if (valued[arg]) {
101
+ if (i + 1 >= argv.length) options.missing = arg;
102
+ else options[valued[arg]] = argv[++i];
103
+ } else if (arg.startsWith("--")) options.unknown = options.unknown || arg;
104
+ else options.words.push(arg);
105
+ }
106
+ return options;
107
+ }
108
+
109
+ // What is collected, and nothing else (#505 D4).
110
+ function environment(cwd, options) {
111
+ const host = options.host || (process.env.CLAUDECODE ? "claude" : "unknown");
112
+ const entry = path.join(__dirname, "..", "..", "bin", "keel.js");
113
+ const context = spawnSync(process.execPath, [entry, "context"], { cwd, encoding: "utf8", timeout: 20000 });
114
+ const lines = String(context.stdout || "").split(/\r?\n/)
115
+ .filter((line) => /^(Keel context|Next action):/.test(line));
116
+ const facts = [
117
+ `Keel: ${PACKAGE_JSON.version}`,
118
+ `Node: ${process.version}`,
119
+ `Platform: ${process.platform} ${process.arch}`,
120
+ `Host: ${host}`,
121
+ ...lines,
122
+ ];
123
+ if (options.doctor) {
124
+ const doctor = spawnSync(process.execPath, [entry, "--doctor"], { cwd, encoding: "utf8", timeout: 30000 });
125
+ facts.push("", "`keel --doctor`:", "```", String(doctor.stdout || "").trimEnd(), "```");
126
+ }
127
+ return facts;
128
+ }
129
+
130
+ function readOutput(cwd, file) {
131
+ if (!file) return null;
132
+ try {
133
+ const text = fs.readFileSync(path.resolve(cwd, file), "utf8");
134
+ const lines = text.split(/\r?\n/);
135
+ const kept = lines.length > 80 ? [...lines.slice(0, 80), `… (${lines.length - 80} more lines not included)`] : lines;
136
+ return kept.join("\n").slice(0, 8000);
137
+ } catch (error) {
138
+ return `(could not read ${file}: ${error.code || error.message})`;
139
+ }
140
+ }
141
+
142
+ function build(cwd, options) {
143
+ const project = git(cwd, ["rev-parse", "--show-toplevel"]) || cwd;
144
+ const counts = {};
145
+ const clean = (text) => {
146
+ const result = redact(text, { project });
147
+ merge(counts, result.counts);
148
+ return result.text;
149
+ };
150
+ const summary = clean(options.words.join(" ").trim());
151
+ const placeholder = (value, text) => (value ? clean(value) : text);
152
+ const output = readOutput(cwd, options.outputFile);
153
+ const evidence = [];
154
+ if (options.command) evidence.push("命令:", "```", clean(options.command), "```");
155
+ if (output !== null) evidence.push("输出:", "```", clean(output), "```");
156
+ const body = [
157
+ "## 现象", "", summary, "",
158
+ "## 期望", "", placeholder(options.expected, "(未填写)"), "",
159
+ "## 复现", "", placeholder(options.repro, "(未填写)"), "",
160
+ "## 证据", "", evidence.length ? evidence.join("\n") : "(未提供命令或输出)", "",
161
+ "## 影响", "", placeholder(options.impact, "(未填写)"), "",
162
+ "## 环境", "", ...environment(cwd, options).map((line) => (line.startsWith("`") || line.startsWith("```") || line === "" ? clean(line) : `- ${clean(line)}`)), "",
163
+ "---",
164
+ "由 `keel feedback` 起草;未带任何准入标签,是否值得做由负责人决定。", "",
165
+ ].join("\n");
166
+ return { title: summary.split(/\r?\n/)[0].slice(0, 120), body, counts };
167
+ }
168
+
169
+ // The three longest distinct ASCII words of at least four characters, else the
170
+ // first twelve characters (#505 D5).
171
+ function keywords(summary) {
172
+ const words = [...new Set((summary.match(/[A-Za-z0-9][A-Za-z0-9_.:-]{3,}/g) || []).map((w) => w.toLowerCase()))]
173
+ .sort((a, b) => b.length - a.length).slice(0, 3);
174
+ return words.length ? words.join(" ") : summary.slice(0, 12);
175
+ }
176
+
177
+ function ghAvailable() {
178
+ const result = spawnSync("gh", ["--version"], { encoding: "utf8", timeout: 10000 });
179
+ return !result.error && result.status === 0;
180
+ }
181
+
182
+ function duplicates(title) {
183
+ if (!ghAvailable()) return { searched: false, reason: "gh is not available", found: [] };
184
+ const result = spawnSync("gh", [
185
+ "issue", "list", "--repo", KEEL_REPO, "--state", "all", "--search", keywords(title),
186
+ "--limit", "5", "--json", "number,title,state,url",
187
+ ], { encoding: "utf8", timeout: 30000 });
188
+ if (result.status !== 0) {
189
+ return { searched: false, reason: String(result.stderr || "gh failed").trim().split(/\r?\n/)[0], found: [] };
190
+ }
191
+ try {
192
+ return { searched: true, found: JSON.parse(result.stdout || "[]").slice(0, 5) };
193
+ } catch {
194
+ return { searched: false, reason: "gh printed something that is not JSON", found: [] };
195
+ }
196
+ }
197
+
198
+ function shellQuote(value) {
199
+ return `'${String(value).replace(/'/g, `'\\''`)}'`;
200
+ }
201
+
202
+ function saveDraft(draft) {
203
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "keel-feedback-"));
204
+ const file = path.join(dir, "issue.md");
205
+ fs.writeFileSync(file, `# ${draft.title}\n\n${draft.body}`);
206
+ return file;
207
+ }
208
+
209
+ function describe(draft, file, dup) {
210
+ const lines = ["Keel feedback draft — nothing was created.", "", `Title: ${draft.title}`, "", draft.body];
211
+ const kinds = Object.entries(draft.counts).map(([kind, n]) => `${kind} ${n}`);
212
+ lines.push(`Redacted ${Object.values(draft.counts).reduce((a, b) => a + b, 0)} value(s)${kinds.length ? ` (${kinds.join(", ")})` : ""}; the values are not printed.`);
213
+ lines.push(`Saved: ${file}`, "");
214
+ if (!dup.searched) {
215
+ lines.push(`Similar issues: not searched (${dup.reason}).`);
216
+ } else if (!dup.found.length) {
217
+ lines.push("Similar issues: none found.");
218
+ } else {
219
+ lines.push("Similar issues (up to 5):");
220
+ for (const issue of dup.found) lines.push(` #${issue.number} ${issue.title} (${issue.state}) ${issue.url}`);
221
+ lines.push("To add to one yourself (Keel runs no comment):");
222
+ lines.push(` gh issue comment ${dup.found[0].number} --repo ${KEEL_REPO} --body-file ${file}`);
223
+ }
224
+ lines.push("To create it:", ` gh issue create --repo ${KEEL_REPO} --title ${shellQuote(draft.title)} --body-file ${file}`);
225
+ return lines.join("\n");
226
+ }
227
+
228
+ // `issue:TanglmChris/keel` in the project's own `authorize:` waives the
229
+ // per-issue confirmation (#505 D6). A declaration Keel cannot read grants
230
+ // nothing, as everywhere else.
231
+ function authorized(project) {
232
+ try {
233
+ const { declared } = require("./config").readStandingAuthorization(project);
234
+ return declared.some((entry) => entry === `issue:${KEEL_REPO}` || entry.startsWith(`issue:${KEEL_REPO}@`));
235
+ } catch {
236
+ return false;
237
+ }
238
+ }
239
+
240
+ // No label, assignee or milestone is ever passed, and nothing else of any
241
+ // issue is touched (#505 D6).
242
+ function create(draft, file) {
243
+ const result = spawnSync("gh", ["issue", "create", "--repo", KEEL_REPO, "--title", draft.title, "--body-file", file], {
244
+ encoding: "utf8", timeout: 60000,
245
+ });
246
+ if (result.error || result.status !== 0) {
247
+ const why = result.error ? result.error.code || result.error.message : String(result.stderr || "gh failed").trim().split(/\r?\n/)[0];
248
+ return { ok: false, why };
249
+ }
250
+ const url = String(result.stdout || "").trim().split(/\r?\n/).pop();
251
+ return { ok: true, url };
252
+ }
253
+
254
+ function runFeedback(argv) {
255
+ const options = parse(argv);
256
+ if (options.help) {
257
+ process.stdout.write(`${USAGE}\n`);
258
+ return 0;
259
+ }
260
+ if (options.unknown || options.missing || !options.words.length) {
261
+ const why = options.unknown ? `unknown option ${options.unknown}` : options.missing ? `${options.missing} needs a value` : "a one-sentence summary is required";
262
+ process.stderr.write(`keel feedback: ${why}\n${USAGE}\n`);
263
+ return 2;
264
+ }
265
+ const cwd = process.cwd();
266
+ const draft = build(cwd, options);
267
+ const file = saveDraft(draft);
268
+ process.stdout.write(`${describe(draft, file, duplicates(draft.title))}\n`);
269
+ if (!options.create) return 0;
270
+ if (!options.confirmed && !authorized(git(cwd, ["rev-parse", "--show-toplevel"]) || cwd)) {
271
+ process.stderr.write(
272
+ `keel feedback: not created. This project does not declare \`issue:${KEEL_REPO}\` in authorize:, so the user must approve this draft first; `
273
+ + "rerun with --create --confirmed once they have.\n"
274
+ );
275
+ return 3;
276
+ }
277
+ const made = create(draft, file);
278
+ if (!made.ok) {
279
+ process.stderr.write(`keel feedback: not created (${made.why}). The draft is saved at ${file}; run the \`gh issue create\` command above when gh works.\n`);
280
+ return 4;
281
+ }
282
+ process.stdout.write(`Created: ${made.url}\n`);
283
+ return 0;
284
+ }
285
+
286
+ module.exports = { KEEL_REPO, USAGE, redact, keywords, runFeedback };