@elvis1513/auto-coding-skill 5.1.0 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@elvis1513/auto-coding-skill",
3
- "version": "5.1.0",
3
+ "version": "5.2.0",
4
4
  "description": "Lightweight engineering guidance and a managed installer that preserves project-owned documentation.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -10,6 +10,7 @@
10
10
  "cli/src",
11
11
  "cli/assets/skill",
12
12
  "cli/assets/managed-install.json",
13
+ "src/git-workflow/*.py",
13
14
  "README.md",
14
15
  "LICENSE"
15
16
  ],
@@ -21,7 +22,8 @@
21
22
  "test:src": "node -e \"const fs=require('fs'); for (const file of ['src/auto-coding-skill/SKILL.md','src/auto-coding-skill/data/templates/ENVIRONMENT.md','src/auto-coding-skill/data/templates/PROJECT.md','src/auto-coding-skill/data/templates/architecture/.gitkeep','src/auto-coding-skill/data/templates/product/.gitkeep','src/auto-coding-skill/data/templates/bridges/AGENTS.md']) if (!fs.existsSync(file)) throw new Error('missing '+file); console.log('source-doc-assets-ok')\"",
22
23
  "check:assets": "node cli/src/sync-assets.js --check",
23
24
  "sync-assets": "node cli/src/sync-assets.js",
24
- "release:check": "npm run check:assets && npm run test:src && npm run test && npm run check:package"
25
+ "test:guard": "python3 -B src/git-workflow/test_guard.py -q",
26
+ "release:check": "npm run check:assets && npm run test:src && npm run test && npm run test:guard && npm run check:package"
25
27
  },
26
28
  "license": "MIT",
27
29
  "publishConfig": {
@@ -0,0 +1,451 @@
1
+ #!/usr/bin/env python3
2
+ """Local Git policy: isolated codex worktrees, verified integration into dev.
3
+
4
+ Explicit opt-in per clone; never installed by CI. This is an accident guard,
5
+ not a security boundary against an owner disabling or rewriting local hooks.
6
+ """
7
+ import hashlib
8
+ import json
9
+ import os
10
+ from pathlib import Path
11
+ import re
12
+ import shlex
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ import tempfile
17
+
18
+ VERSION = 2
19
+ STATE_FILE = "state.json"
20
+ TASK_REF_PREFIX = "refs/heads/codex/"
21
+ DEV_REF = "refs/heads/dev"
22
+ REMOTE_DEV_REF = "refs/remotes/origin/dev"
23
+ HOOKS_PATH_KEY = "core.hooksPath"
24
+ HOOKS = {
25
+ "pre-commit", "pre-applypatch", "pre-rebase", "post-commit",
26
+ "post-applypatch", "post-merge", "post-rewrite", "pre-push", "reference-transaction",
27
+ }
28
+ OID = re.compile(r"^[0-9a-f]{40}(?:[0-9a-f]{24})?$")
29
+
30
+
31
+ class Rejected(Exception):
32
+ pass
33
+
34
+
35
+ def git(*args, check=True, cwd=None):
36
+ result = subprocess.run(["git", *args], cwd=cwd, text=True, capture_output=True)
37
+ if check and result.returncode:
38
+ raise Rejected("Git inspection failed: " + " ".join(args[:2]))
39
+ return result
40
+
41
+
42
+ def value(*args, **kwargs):
43
+ return git(*args, **kwargs).stdout.strip()
44
+
45
+
46
+ def common_dir():
47
+ return Path(value("rev-parse", "--git-common-dir")).resolve()
48
+
49
+
50
+ def state_dir():
51
+ return common_dir() / "codex-workflow-guard"
52
+
53
+
54
+ def atomic_json(path, data):
55
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
56
+ fd, name = tempfile.mkstemp(prefix=".pending-", dir=path.parent)
57
+ try:
58
+ with os.fdopen(fd, "w") as stream:
59
+ json.dump(data, stream, indent=2)
60
+ stream.write("\n")
61
+ os.replace(name, path)
62
+ finally:
63
+ if os.path.exists(name):
64
+ os.unlink(name)
65
+
66
+
67
+ def config():
68
+ return json.loads((state_dir() / STATE_FILE).read_text())
69
+
70
+
71
+ def ancestor(old, new):
72
+ return bool(old and new) and git("merge-base", "--is-ancestor", old, new,
73
+ check=False).returncode == 0
74
+
75
+
76
+ def task_context():
77
+ directory = Path(value("rev-parse", "--absolute-git-dir")).resolve()
78
+ if directory == common_dir():
79
+ return None
80
+ branch = value("symbolic-ref", "--quiet", "HEAD", check=False)
81
+ if not branch:
82
+ for folder in ("rebase-merge", "rebase-apply"):
83
+ head_name = directory / folder / "head-name"
84
+ if head_name.is_file():
85
+ branch = head_name.read_text().strip()
86
+ break
87
+ if not branch.startswith(TASK_REF_PREFIX) or branch == TASK_REF_PREFIX:
88
+ return None
89
+ return {"branch": branch, "git_dir": str(directory),
90
+ "worktree": value("rev-parse", "--show-toplevel")}
91
+
92
+
93
+ def require_task():
94
+ task = task_context()
95
+ if not task:
96
+ raise Rejected("Develop in a linked worktree on codex/<task>, not dev or "
97
+ "the primary checkout. Create an independent worktree from "
98
+ "current dev; do not switch/stash another conversation's files.")
99
+ return task
100
+
101
+
102
+ def receipt_path(sha):
103
+ if not OID.fullmatch(sha):
104
+ raise Rejected("Invalid commit identity")
105
+ return state_dir() / "commits" / (sha + ".json")
106
+
107
+
108
+ def record(sha, context, kind="task"):
109
+ atomic_json(receipt_path(sha), {"commit": sha, "kind": kind, **context})
110
+
111
+
112
+ def certified(sha):
113
+ path = receipt_path(sha)
114
+ if not path.is_file():
115
+ return False
116
+ data = json.loads(path.read_text())
117
+ return data.get("commit") == sha and data.get("kind") in {
118
+ "task", "integration", "existing-isolated-task", "rewrite",
119
+ }
120
+
121
+
122
+ def verify_commits(tip, base, include_remote=False):
123
+ exclusions = [config()["baseline"]]
124
+ if base and set(base) != {"0"}:
125
+ exclusions.append(base)
126
+ if include_remote:
127
+ remote = value("rev-parse", "--verify", REMOTE_DEV_REF, check=False)
128
+ if remote:
129
+ exclusions.append(remote)
130
+ commits = value("rev-list", tip, *("^" + x for x in exclusions)).splitlines()
131
+ missing = [sha for sha in commits if not certified(sha)]
132
+ if missing:
133
+ raise Rejected("Unverified commit origin: " + ", ".join(x[:12] for x in missing[:4])
134
+ + ". Commit/reconcile in the task's codex worktree first.")
135
+
136
+
137
+ def merge_tree(left, right):
138
+ result = git("merge-tree", "--write-tree", left, right, check=False)
139
+ if result.returncode or not result.stdout.splitlines():
140
+ raise Rejected("Resolve merge conflicts in the independent codex worktree, "
141
+ "not in the shared dev checkout.")
142
+ return result.stdout.splitlines()[0]
143
+
144
+
145
+ def safe_merge_commit(old, new):
146
+ parents = value("show", "-s", "--format=%P", new).split()
147
+ if len(parents) != 2 or parents[0] != old:
148
+ return False
149
+ try:
150
+ verify_commits(parents[1], old, include_remote=True)
151
+ if not certified(parents[1]):
152
+ return False
153
+ if value("show", "-s", "--format=%T", new) != merge_tree(*parents):
154
+ return False
155
+ except Rejected:
156
+ return False
157
+ record(new, {"parents": parents}, "integration")
158
+ return True
159
+
160
+
161
+ def commit_check():
162
+ if task_context():
163
+ return
164
+ # A pure integration commit is not development on dev. Any manual content
165
+ # change or conflicted merge must instead be resolved in the task worktree.
166
+ if value("symbolic-ref", "--quiet", "HEAD", check=False) == DEV_REF:
167
+ merge_head = Path(value("rev-parse", "--git-path", "MERGE_HEAD"))
168
+ if merge_head.is_file():
169
+ parents = merge_head.read_text().split()
170
+ if len(parents) == 1 and certified(parents[0]):
171
+ old = value("rev-parse", "HEAD")
172
+ verify_commits(parents[0], old, include_remote=True)
173
+ if value("write-tree") == merge_tree(old, parents[0]):
174
+ return
175
+ require_task()
176
+
177
+
178
+ def prunes_only_loose_dev(old):
179
+ """In the files backend a real packed deletion must lock packed-refs.
180
+
181
+ At 'prepared', pack-refs has already committed the identical packed value
182
+ and holds only the loose ref lock. Unknown layouts or zero OIDs fail closed.
183
+ """
184
+ if not OID.fullmatch(old) or set(old) == {"0"}:
185
+ return False
186
+ root = common_dir()
187
+ loose = root / DEV_REF
188
+ if (root / "packed-refs.lock").exists() or not Path(str(loose) + ".lock").is_file():
189
+ return False
190
+ try:
191
+ if loose.is_symlink() or loose.read_bytes().strip() != old.encode():
192
+ return False
193
+ entry = (old + " " + DEV_REF).encode()
194
+ with (root / "packed-refs").open("rb") as refs:
195
+ return any(line.rstrip(b"\n") == entry for line in refs)
196
+ except OSError:
197
+ return False
198
+
199
+
200
+ def check_dev_reference(old, new, ref):
201
+ if set(new) == {"0"} and prunes_only_loose_dev(old):
202
+ return
203
+ current = value("rev-parse", "--verify", ref, check=False)
204
+ before = current if set(old) == {"0"} else old
205
+ if set(new) == {"0"} or (before and not ancestor(before, new)):
206
+ raise Rejected("dev deletion/history rewriting is blocked; integrate without force.")
207
+ remote = value("rev-parse", "--verify", REMOTE_DEV_REF, check=False)
208
+ if remote and ancestor(new, remote):
209
+ return # A clean fetch/fast-forward from the integration remote.
210
+ if certified(new):
211
+ verify_commits(new, before, include_remote=True)
212
+ return
213
+ if before and safe_merge_commit(before, new):
214
+ return
215
+ raise Rejected("Direct development on dev is blocked. Complete the codex worktree "
216
+ "change, reconcile latest dev, then fast-forward or make a pure merge.")
217
+
218
+
219
+ def reference_check(data):
220
+ task = task_context()
221
+ for line in data.splitlines():
222
+ old, new, ref = line.split()
223
+ if not ref.startswith("refs/heads/") or (old == new and set(new) != {"0"}):
224
+ continue
225
+ if ref == DEV_REF:
226
+ check_dev_reference(old, new, ref)
227
+ elif set(old) != {"0"} and set(new) != {"0"} and (not task or task["branch"] != ref):
228
+ raise Rejected("Branch updates require that branch's independent codex worktree.")
229
+
230
+
231
+ def push_check(data, remote_name):
232
+ for line in data.splitlines():
233
+ _, tip, target, remote = line.split()
234
+ if target != DEV_REF and not target.startswith(TASK_REF_PREFIX):
235
+ continue
236
+ if set(tip) == {"0"}:
237
+ if target == DEV_REF:
238
+ raise Rejected("Deleting remote dev is blocked.")
239
+ continue
240
+ if set(remote) != {"0"} and not ancestor(remote, tip):
241
+ raise Rejected("Fetch and reconcile the latest remote branch in the task "
242
+ "worktree before pushing; non-fast-forward updates are blocked.")
243
+ # For task pushes to the integration remote, its fetched dev history
244
+ # was already accepted there. No such exemption for dev or other remotes.
245
+ verify_commits(tip, remote, include_remote=remote_name == "origin"
246
+ and target.startswith(TASK_REF_PREFIX))
247
+
248
+
249
+ def previous_hook(name, args, data):
250
+ saved = config()["previous_hooks"]
251
+ hook = Path(saved) / name
252
+ if not hook.is_absolute():
253
+ hook = Path(value("rev-parse", "--show-toplevel")) / hook
254
+ if hook.is_file() and os.access(hook, os.X_OK):
255
+ return subprocess.run([str(hook), *args], input=data, text=True).returncode
256
+ return 0
257
+
258
+
259
+ def record_rewritten_commits(data):
260
+ task = require_task()
261
+ for line in data.splitlines():
262
+ old, new = line.split()[:2]
263
+ if not certified(old) and not ancestor(old, config()["baseline"]):
264
+ raise Rejected("Rewritten commit lacks isolated-worktree provenance.")
265
+ record(new, task, "rewrite")
266
+
267
+
268
+ def dispatch(name, args):
269
+ data = sys.stdin.read() if name in {"pre-push", "post-rewrite", "reference-transaction"} else ""
270
+ if name in {"pre-commit", "pre-applypatch"}:
271
+ commit_check()
272
+ elif name == "pre-rebase":
273
+ task = require_task()
274
+ if len(args) > 1 and args[1] not in {task["branch"], task["branch"].removeprefix("refs/heads/")}:
275
+ raise Rejected("Rebase only the branch owned by this worktree.")
276
+ elif name == "reference-transaction" and args == ["prepared"]:
277
+ reference_check(data)
278
+ elif name == "pre-push":
279
+ push_check(data, args[0] if args else None)
280
+ elif name in {"post-commit", "post-applypatch", "post-merge"} and task_context():
281
+ record(value("rev-parse", "HEAD"), require_task())
282
+ elif name == "post-rewrite":
283
+ record_rewritten_commits(data)
284
+ return previous_hook(name, args, data)
285
+
286
+
287
+ def worktree_fields(entry):
288
+ pairs = (line.split(" ", 1) for line in entry.splitlines() if " " in line)
289
+ return dict(pairs)
290
+
291
+
292
+ def check_worktree_overrides():
293
+ # A per-worktree override would silently defeat shared activation.
294
+ for entry in value("worktree", "list", "--porcelain").split("\n\n"):
295
+ path = worktree_fields(entry).get("worktree", "")
296
+ if not path or not Path(path).is_dir():
297
+ continue
298
+ directory = Path(value("rev-parse", "--absolute-git-dir", cwd=path))
299
+ cfg = directory / "config.worktree"
300
+ if cfg.is_file() and value("config", "--file", str(cfg), "--get", HOOKS_PATH_KEY, check=False):
301
+ raise Rejected("Existing worktree-specific hooksPath requires manual review.")
302
+
303
+
304
+ def replace_bytes(target, data, mode):
305
+ if target.is_file() and target.read_bytes() == data and target.stat().st_mode & 0o777 == mode:
306
+ return
307
+ fd, tmp = tempfile.mkstemp(dir=target.parent, prefix=".pending-")
308
+ try:
309
+ with os.fdopen(fd, "wb") as stream:
310
+ stream.write(data)
311
+ os.fchmod(stream.fileno(), mode)
312
+ os.replace(tmp, target)
313
+ finally:
314
+ if os.path.exists(tmp):
315
+ os.unlink(tmp)
316
+
317
+
318
+ def hook_script(interpreter, name):
319
+ # Preserve the selected interpreter; a package-manager upgrade can remove
320
+ # its versioned path. A missing fallback still fails the Git operation.
321
+ return ("#!/bin/sh\npy=" + shlex.quote(interpreter) + '\n[ -x "$py" ] || py=python3\n'
322
+ 'exec "$py" "${0%/*}/../guard.py" hook ' + name + ' "$@"\n').encode()
323
+
324
+
325
+ def install_hooks(root, state):
326
+ payload = Path(__file__).read_bytes()
327
+ digest = hashlib.sha256(payload).hexdigest()
328
+ runtime = root / ("runtime-" + digest[:16])
329
+ hooks = runtime / "hooks"
330
+ hooks.mkdir(parents=True, exist_ok=True, mode=0o700)
331
+ replace_bytes(runtime / "guard.py", payload, 0o600)
332
+ old_dir = Path(state["previous_hooks"])
333
+ if not old_dir.is_absolute():
334
+ old_dir = Path(value("rev-parse", "--show-toplevel")) / old_dir
335
+ names = HOOKS | ({path.name for path in old_dir.iterdir() if path.is_file()
336
+ and os.access(path, os.X_OK) and not path.name.endswith(".sample")}
337
+ if old_dir.is_dir() else set())
338
+ for name in names:
339
+ if not re.fullmatch(r"[a-z][a-z-]*", name):
340
+ raise Rejected("Unexpected existing hook name; manual chaining required")
341
+ replace_bytes(hooks / name, hook_script(sys.executable, name), 0o700)
342
+ state.update(hooks_path=str(hooks), source_sha256=digest, version=VERSION,
343
+ interpreter=sys.executable, hook_names=sorted(names))
344
+ atomic_json(root / STATE_FILE, state)
345
+ return hooks
346
+
347
+
348
+ def record_existing_tasks(common, baseline):
349
+ # Preserve already-running isolated tasks without rewriting their commits.
350
+ for entry in value("worktree", "list", "--porcelain").split("\n\n"):
351
+ fields = worktree_fields(entry)
352
+ branch, path = fields.get("branch", ""), fields.get("worktree", "")
353
+ if not branch.startswith(TASK_REF_PREFIX) or not Path(path).is_dir():
354
+ continue
355
+ directory = Path(value("rev-parse", "--absolute-git-dir", cwd=path)).resolve()
356
+ if directory == common:
357
+ continue
358
+ for sha in value("rev-list", fields["HEAD"], "^" + baseline).splitlines():
359
+ record(sha, {"branch": branch, "worktree": path, "git_dir": str(directory)},
360
+ "existing-isolated-task")
361
+
362
+
363
+ def install():
364
+ version = re.match(r"git version (\d+)\.(\d+)", value("--version"))
365
+ if not version or tuple(map(int, version.groups())) < (2, 38):
366
+ raise Rejected("Git 2.38+ is required for reference checks and safe merge verification")
367
+ if sys.version_info < (3, 9):
368
+ raise Rejected("Python 3.9+ is required")
369
+ root = state_dir()
370
+ common = common_dir()
371
+ check_worktree_overrides()
372
+ effective = value("config", "--get", HOOKS_PATH_KEY, check=False)
373
+ local = git("config", "--local", "--get", HOOKS_PATH_KEY, check=False)
374
+ prior = config() if (root / STATE_FILE).is_file() else None
375
+ if prior and effective != prior["hooks_path"]:
376
+ raise Rejected("hooksPath changed since installation; preserve it and review before updating.")
377
+ if prior:
378
+ state = prior
379
+ else:
380
+ state = {"version": VERSION, "baseline": value("rev-parse", REMOTE_DEV_REF),
381
+ "previous_local": local.stdout.strip() if local.returncode == 0 else None,
382
+ "previous_hooks": effective or str(common / "hooks")}
383
+ hooks = install_hooks(root, state)
384
+ if not prior:
385
+ record_existing_tasks(common, state["baseline"])
386
+ git("config", "--local", HOOKS_PATH_KEY, str(hooks))
387
+ print(json.dumps({"installed": True, "version": VERSION, "hooks_path": str(hooks),
388
+ "chained_hooks": state["previous_hooks"]}))
389
+
390
+
391
+ def status():
392
+ state = config()
393
+ actual = value("config", "--get", HOOKS_PATH_KEY, check=False)
394
+ runtime = Path(state["hooks_path"]).parent / "guard.py"
395
+ version_ok = state["version"] == VERSION
396
+ source_ok = hashlib.sha256(Path(__file__).read_bytes()).hexdigest() == state["source_sha256"]
397
+ runtime_ok = runtime.is_file() and hashlib.sha256(runtime.read_bytes()).hexdigest() == state["source_sha256"]
398
+ pinned = state.get("interpreter", "")
399
+ interpreter = "pinned" if pinned and os.access(pinned, os.X_OK) else (
400
+ "path-fallback" if version_ok and shutil.which("python3") else "unknown-or-missing")
401
+ hooks_ok = version_ok and all(
402
+ re.fullmatch(r"[a-z][a-z-]*", h) and (Path(actual) / h).is_file()
403
+ and os.access(Path(actual) / h, os.X_OK)
404
+ and (Path(actual) / h).read_bytes() == hook_script(pinned, h)
405
+ for h in HOOKS | set(state.get("hook_names", [])))
406
+ ok = (actual == state["hooks_path"] and version_ok and source_ok and runtime_ok
407
+ and hooks_ok and interpreter != "unknown-or-missing")
408
+ print(json.dumps({"ok": ok, "version": state["version"], "hooks_path": actual,
409
+ "expected_version": VERSION, "source_matches": source_ok,
410
+ "runtime_matches": runtime_ok, "hooks_match": hooks_ok,
411
+ "interpreter": interpreter,
412
+ "chained_hooks": state["previous_hooks"]}))
413
+ return 0 if ok else 1
414
+
415
+
416
+ def uninstall():
417
+ state = config()
418
+ if value("config", "--get", HOOKS_PATH_KEY, check=False) != state["hooks_path"]:
419
+ raise Rejected("hooksPath changed; refusing to overwrite another configuration")
420
+ if state["previous_local"] is None:
421
+ git("config", "--local", "--unset", HOOKS_PATH_KEY)
422
+ else:
423
+ git("config", "--local", HOOKS_PATH_KEY, state["previous_local"])
424
+ # Keep receipts/runtime available for recovery; no files or branches removed.
425
+ (state_dir() / STATE_FILE).rename(state_dir() / "uninstalled-state.json")
426
+ print("Previous hooks configuration restored; recovery data retained.")
427
+
428
+
429
+ def main():
430
+ try:
431
+ command = sys.argv[1] if len(sys.argv) > 1 else "status"
432
+ if command == "hook":
433
+ return dispatch(sys.argv[2], sys.argv[3:])
434
+ if command == "install":
435
+ install()
436
+ elif command == "status":
437
+ return status()
438
+ elif command == "uninstall":
439
+ uninstall()
440
+ elif command == "check":
441
+ commit_check()
442
+ else:
443
+ raise Rejected("Use install, status, check or uninstall")
444
+ return 0
445
+ except (Rejected, OSError, ValueError, KeyError) as error:
446
+ print("[codex-workflow-guard] " + str(error), file=sys.stderr)
447
+ return 1
448
+
449
+
450
+ if __name__ == "__main__":
451
+ sys.exit(main())