@yasaswy.nagavolu/agents 0.26.2 → 0.26.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -1
- package/bin/cli.js +31 -3
- package/content/global/hooks/lib/modeDrift.js +9 -2
- package/content/global/hooks/lib/permissionRules.js +117 -0
- package/content/global/hooks/lib/projectHooks.js +1 -0
- package/content/global/hooks/permission_mode_enforce.js +1 -1
- package/content/global/hooks/permission_mode_guard.py +4 -2
- package/content/global/hooks/project_hook.sh +68 -12
- package/content/global/hooks/project_hook_repair.js +22 -9
- package/content/manifest.json +7 -1
- package/content/mods/handoff/.claude-plugin/plugin.json +1 -1
- package/content/mods/handoff/README.md +6 -6
- package/content/mods/handoff/hooks/register.js +7 -7
- package/content/mods/handoff/lib/activework.mjs +2 -2
- package/content/mods/handoff/prompts/handoff-prep.md +2 -2
- package/content/mods/handoff/tests/activework.test.mjs +5 -5
- package/content/mods/handoff/tests/register.test.mjs +35 -23
- package/content/mods/handoff/tests/template.test.mjs +3 -3
- package/content/proxy/agent_model_guard.py +53 -45
- package/content/proxy/execution_worker_review_gate.py +5 -8
- package/content/proxy/headless_process.py +6 -5
- package/content/proxy/route_lock.py +20 -1
- package/content/proxy/shared_worktree_revert_guard.py +34 -1
- package/content/scripts/item.py +126 -0
- package/content/scripts/tests/test_item_cli.py +66 -0
- package/lib/permissionRules.js +15 -0
- package/package.json +1 -1
|
@@ -502,24 +502,27 @@ test('handoff starts when nothing is running', async () => {
|
|
|
502
502
|
assert.equal(h.toasts.length, 0)
|
|
503
503
|
})
|
|
504
504
|
|
|
505
|
-
|
|
505
|
+
const NOTE = /^Handoff continues with .* still running; they are not stopped$/
|
|
506
|
+
const noteToasts = (h) => h.toasts.filter((t) => NOTE.test(t))
|
|
507
|
+
|
|
508
|
+
test('handoff proceeds to the prep turn while a subagent is running, with one note', async () => {
|
|
506
509
|
const h = await harness()
|
|
507
510
|
await h.start()
|
|
508
511
|
h.agents = [{ id: 'a', status: 'running' }, { id: 'b', status: 'completed' }]
|
|
509
512
|
await startHandoffFlow(h)
|
|
510
|
-
assert.equal(prepSubmitted(h).length,
|
|
511
|
-
assert.
|
|
512
|
-
assert.match(h.toasts[0], /1 subagent\(s\) still running: stop or wait for them first/)
|
|
513
|
+
assert.equal(prepSubmitted(h).length, 1)
|
|
514
|
+
assert.deepEqual(h.toasts, ['Handoff continues with 1 subagent(s) still running; they are not stopped'])
|
|
513
515
|
})
|
|
514
516
|
|
|
515
|
-
test('handoff
|
|
517
|
+
test('handoff proceeds to the prep turn while background tasks from the last turn are running', async () => {
|
|
516
518
|
const h = await harness()
|
|
517
519
|
await h.start()
|
|
518
|
-
await h.
|
|
520
|
+
const turnId = await h.startTurn('work')
|
|
519
521
|
await h.fire('classic.Stop', { background_tasks: [{ id: 'b1', type: 'shell' }, { id: 'b2', type: 'monitor' }] })
|
|
522
|
+
await h.fire('turn.complete', { answer: 'ok', reason: 'answer', turnId })
|
|
520
523
|
await startHandoffFlow(h)
|
|
521
|
-
assert.equal(prepSubmitted(h).length,
|
|
522
|
-
assert.
|
|
524
|
+
assert.equal(prepSubmitted(h).length, 1)
|
|
525
|
+
assert.deepEqual(h.toasts, ['Handoff continues with 2 background task(s) still running; they are not stopped'])
|
|
523
526
|
})
|
|
524
527
|
|
|
525
528
|
test('handoff clears and submits the handoff when no work is running', async () => {
|
|
@@ -531,23 +534,31 @@ test('handoff clears and submits the handoff when no work is running', async ()
|
|
|
531
534
|
assert.ok(h.submitted.some((s) => s.asUser && /Session handoff/.test(s.text)))
|
|
532
535
|
})
|
|
533
536
|
|
|
534
|
-
test('handoff
|
|
537
|
+
test('handoff with 19 running subagents and 19 background tasks completes end to end', async () => {
|
|
535
538
|
const h = await harness()
|
|
536
539
|
await h.start()
|
|
540
|
+
h.agents = Array.from({ length: 19 }, (_, i) => ({ id: 'a' + i, status: 'running' }))
|
|
541
|
+
const tasks = Array.from({ length: 19 }, (_, i) => ({ id: 'b' + i, type: 'shell' }))
|
|
542
|
+
const turnId = await h.startTurn('work')
|
|
543
|
+
await h.fire('classic.Stop', { background_tasks: tasks })
|
|
544
|
+
await h.fire('turn.complete', { answer: 'ok', reason: 'answer', turnId })
|
|
537
545
|
await startHandoffFlow(h)
|
|
538
|
-
h.
|
|
539
|
-
await finishPrep(h)
|
|
540
|
-
assert.equal(h.cleared,
|
|
541
|
-
assert.
|
|
546
|
+
assert.equal(prepSubmitted(h).length, 1)
|
|
547
|
+
await finishPrep(h, tasks)
|
|
548
|
+
assert.equal(h.cleared, 1)
|
|
549
|
+
assert.ok(h.submitted.some((s) => s.asUser && /Session handoff/.test(s.text)))
|
|
550
|
+
assert.ok(!h.toasts.some((t) => /aborted/i.test(t)))
|
|
542
551
|
})
|
|
543
552
|
|
|
544
|
-
test('
|
|
553
|
+
test('the running-work note shows once at start and not again at /clear', async () => {
|
|
545
554
|
const h = await harness()
|
|
546
555
|
await h.start()
|
|
556
|
+
h.agents = [{ id: 'a', status: 'running' }]
|
|
547
557
|
await startHandoffFlow(h)
|
|
558
|
+
assert.equal(noteToasts(h).length, 1)
|
|
548
559
|
await finishPrep(h, [{ id: 'b1', type: 'shell' }])
|
|
549
|
-
assert.equal(h.cleared,
|
|
550
|
-
assert.
|
|
560
|
+
assert.equal(h.cleared, 1)
|
|
561
|
+
assert.equal(noteToasts(h).length, 1)
|
|
551
562
|
})
|
|
552
563
|
|
|
553
564
|
test('handoff does not clear when the branch has unpushed commits and no upstream', async () => {
|
|
@@ -669,17 +680,18 @@ test('a user prompt waiting for its turn queues the handoff, and the tick releas
|
|
|
669
680
|
assert.equal(prepSubmitted(h).length, 1)
|
|
670
681
|
})
|
|
671
682
|
|
|
672
|
-
test('a queued handoff
|
|
683
|
+
test('a queued handoff released while a subagent runs proceeds, with the note shown once at release', async () => {
|
|
673
684
|
const h = await harness()
|
|
674
685
|
await h.start()
|
|
675
686
|
const busyId = await busyTurn(h)
|
|
676
687
|
await startHandoffFlow(h)
|
|
688
|
+
assert.equal(noteToasts(h).length, 0)
|
|
677
689
|
h.agents = [{ id: 'a', status: 'running' }]
|
|
678
690
|
await h.fire('turn.complete', { answer: 'done', reason: 'answer', turnId: busyId })
|
|
679
691
|
await new Promise((resolve) => setImmediate(resolve))
|
|
680
|
-
assert.equal(prepSubmitted(h).length,
|
|
681
|
-
assert.
|
|
682
|
-
assert.
|
|
692
|
+
assert.equal(prepSubmitted(h).length, 1)
|
|
693
|
+
assert.equal(noteToasts(h).length, 1)
|
|
694
|
+
assert.ok(!h.toasts.some((t) => /aborted/i.test(t)))
|
|
683
695
|
})
|
|
684
696
|
|
|
685
697
|
test('cancel drops a queued handoff and nothing is submitted later', async () => {
|
|
@@ -827,13 +839,13 @@ test('auto: a busy turn that starts while the run is starting drops the run quie
|
|
|
827
839
|
assert.equal((await h.render()).children[1].label, 'Handoff')
|
|
828
840
|
})
|
|
829
841
|
|
|
830
|
-
test('auto:
|
|
842
|
+
test('auto: a running subagent does not stop the auto run', async () => {
|
|
831
843
|
const h = await autoHarness()
|
|
832
844
|
h.agents = [{ id: 'a', status: 'running' }]
|
|
833
845
|
await h.tick()
|
|
834
846
|
await settle()
|
|
835
|
-
assert.equal(prepSubmitted(h).length,
|
|
836
|
-
assert.
|
|
847
|
+
assert.equal(prepSubmitted(h).length, 1)
|
|
848
|
+
assert.equal(noteToasts(h).length, 1)
|
|
837
849
|
})
|
|
838
850
|
|
|
839
851
|
test('auto: after an aborted auto run it waits for 5 more points; manual start always works', async () => {
|
|
@@ -27,9 +27,9 @@ test('template renders with no placeholder left and states the contract', () =>
|
|
|
27
27
|
})
|
|
28
28
|
|
|
29
29
|
test('template starts with the running-work step and carries rebase-conflict guidance', () => {
|
|
30
|
-
assert.match(template, /\n0\. Running work\. List running subagents and background tasks\./)
|
|
31
|
-
assert.ok(template.includes('TaskStop'))
|
|
32
|
-
assert.ok(template.includes('
|
|
30
|
+
assert.match(template, /\n0\. Running work\. List any running subagents and background tasks \(name and goal\) in the open risks.*never blocks the handoff\./)
|
|
31
|
+
assert.ok(!template.includes('TaskStop'))
|
|
32
|
+
assert.ok(!template.includes('naming it'))
|
|
33
33
|
assert.ok(template.indexOf('0. Running work') < template.indexOf('1. Tasks'))
|
|
34
34
|
assert.match(template, /4\. Code\..*conflict.*both sides' intent.*re-run the tests.*open risks/)
|
|
35
35
|
})
|
|
@@ -60,11 +60,9 @@ Original checks, retained semantics (first correction wins where relevant):
|
|
|
60
60
|
it stays correct for any farm-style project): `dispatch_tier:
|
|
61
61
|
mandatory-review` bypasses the route lock the same way `dispatch_tier:
|
|
62
62
|
safe` does, but marks a pending-review flag that execution_worker_review_gate.py
|
|
63
|
-
checks before allowing `git commit`.
|
|
64
|
-
|
|
65
|
-
by a dispatch
|
|
66
|
-
dispatching an agent whose frontmatter declares `clears_review: true`
|
|
67
|
-
clears the flag directly (route_lock.clear_pending_review).
|
|
63
|
+
checks before allowing `git commit`. The flag lives at the target
|
|
64
|
+
worktree's own toplevel and is cleared only by a verified
|
|
65
|
+
scripts/review_pass.py stamp, never by a dispatch.
|
|
68
66
|
|
|
69
67
|
Fails OPEN (prints nothing, exit 0) on any unexpected exception, missing
|
|
70
68
|
registry file, or malformed stdin — mirrors agent_dispatch_guard.py.
|
|
@@ -258,42 +256,53 @@ def _parse_worktree_targets(prompt: str) -> list[str]:
|
|
|
258
256
|
|
|
259
257
|
|
|
260
258
|
def _mark_pending_review_per_target(cwd: str, prompt: str) -> None:
|
|
261
|
-
"""
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
259
|
+
"""Flags each `worktree:`-named target's OWN worktree (or the caller's cwd when none is named); never a root shared with other worktrees."""
|
|
260
|
+
for target in _parse_worktree_targets(prompt) or [cwd]:
|
|
261
|
+
route_lock.mark_pending_review(target)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
DISPATCH_LOG_MAX_BYTES = 5 * 1024 * 1024
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _dispatch_log_path() -> str:
|
|
268
|
+
override = os.environ.get("CLAUDE_AGENT_DISPATCH_LOG")
|
|
269
|
+
if override:
|
|
270
|
+
return override
|
|
271
|
+
return os.path.join(os.path.expanduser("~"), ".claude", "logs", "agent_dispatch.jsonl")
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _record_dispatch_error(log_path: str, exc: Exception) -> None:
|
|
275
|
+
try:
|
|
276
|
+
with open(log_path + ".errors", "a", encoding="utf-8") as fh:
|
|
277
|
+
fh.write(f"{time.time():.3f} {type(exc).__name__}: {exc}\n")
|
|
278
|
+
except Exception:
|
|
279
|
+
pass
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _log_dispatch(session_id: str, name: str, subagent_type: str) -> None:
|
|
283
|
+
"""Append one JSON line mapping dispatch name -> effective subagent_type; a write failure is logged, never raised."""
|
|
284
|
+
log_path = _dispatch_log_path()
|
|
285
|
+
try:
|
|
286
|
+
os.makedirs(os.path.dirname(log_path), exist_ok=True)
|
|
287
|
+
try:
|
|
288
|
+
if os.path.getsize(log_path) >= DISPATCH_LOG_MAX_BYTES:
|
|
289
|
+
os.replace(log_path, log_path + ".1")
|
|
290
|
+
except OSError:
|
|
291
|
+
pass
|
|
292
|
+
line = json.dumps({
|
|
293
|
+
"ts": time.time(),
|
|
294
|
+
"session_id": session_id,
|
|
295
|
+
"name": name,
|
|
296
|
+
"agent_id_prefix": None,
|
|
297
|
+
"subagent_type": subagent_type,
|
|
298
|
+
}) + "\n"
|
|
299
|
+
fd = os.open(log_path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o644)
|
|
300
|
+
try:
|
|
301
|
+
os.write(fd, line.encode("utf-8"))
|
|
302
|
+
finally:
|
|
303
|
+
os.close(fd)
|
|
304
|
+
except Exception as exc:
|
|
305
|
+
_record_dispatch_error(log_path, exc)
|
|
297
306
|
|
|
298
307
|
|
|
299
308
|
def _deny(reason: str) -> None:
|
|
@@ -385,6 +394,8 @@ def _safe_main() -> None:
|
|
|
385
394
|
f"identifies this dispatch — address it by this name in teammate messages"
|
|
386
395
|
)
|
|
387
396
|
|
|
397
|
+
_log_dispatch(str(data.get("session_id") or ""), corrected["name"], eff_type)
|
|
398
|
+
|
|
388
399
|
# (a) registered agent + explicit model of a different family →
|
|
389
400
|
# STRIP the param; frontmatter is the routing authority.
|
|
390
401
|
if registered_model and corrected.get("model"):
|
|
@@ -451,10 +462,7 @@ def _safe_main() -> None:
|
|
|
451
462
|
if route_lock.is_farm_style_project(cwd):
|
|
452
463
|
_mark_pending_review_per_target(cwd, prompt)
|
|
453
464
|
elif dispatch_tier == "safe":
|
|
454
|
-
#
|
|
455
|
-
# only via a verified stamp, never here — see _clear_pending_review_per_target.
|
|
456
|
-
if route_lock.agent_clears_review(subagent_type, cwd) and route_lock.is_farm_style_project(cwd):
|
|
457
|
-
_clear_pending_review_per_target(cwd, prompt)
|
|
465
|
+
pass # a worktree's flag is cleared only by a verified scripts/review_pass.py stamp, never by dispatching a reviewer
|
|
458
466
|
elif subagent_type and _find_agent_file(subagent_type, cwd) and route_lock.is_farm_style_project(cwd):
|
|
459
467
|
lock = route_lock.read_lock(cwd)
|
|
460
468
|
if lock:
|
|
@@ -12,12 +12,9 @@ safe` agent it is not gated at dispatch time -- it can be dispatched with no
|
|
|
12
12
|
@tag and no route lock. The compensating control lives here, at commit time:
|
|
13
13
|
if a mandatory-review agent has run in this farm-style project and the
|
|
14
14
|
target's pending-review flag is still set (_is_review_pending_per_target),
|
|
15
|
-
any `git commit` is denied until it clears.
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
without it keeps the older behavior: dispatching an agent whose frontmatter
|
|
19
|
-
declares `clears_review: true` (this project's reviewer-subagent) clears the
|
|
20
|
-
shared route_lock flag directly (route_lock.clear_pending_review).
|
|
15
|
+
any `git commit` is denied until it clears. The flag is the target worktree's
|
|
16
|
+
OWN toplevel flag and is cleared only by a verified review_pass.py stamp,
|
|
17
|
+
never by dispatching a reviewer.
|
|
21
18
|
|
|
22
19
|
Wired as a PreToolUse hook on the "Bash" matcher in ~/.claude/settings.json,
|
|
23
20
|
scoped with an "if": "Bash(git commit *)" permission-rule clause so it only
|
|
@@ -173,9 +170,9 @@ def _toplevel(cwd: str) -> str | None:
|
|
|
173
170
|
|
|
174
171
|
|
|
175
172
|
def _is_review_pending_per_target(cwd: str) -> bool:
|
|
176
|
-
"""
|
|
173
|
+
"""Reads cwd's own worktree flag, falling back to route_lock's resolution outside a git work tree."""
|
|
177
174
|
toplevel = _toplevel(cwd)
|
|
178
|
-
if toplevel
|
|
175
|
+
if toplevel:
|
|
179
176
|
try:
|
|
180
177
|
with open(os.path.join(toplevel, ".claude", ".pending_review.json"), "r", encoding="utf-8") as fh:
|
|
181
178
|
return json.load(fh).get("pending_review") is True
|
|
@@ -6,24 +6,25 @@ import sys
|
|
|
6
6
|
from typing import Any
|
|
7
7
|
|
|
8
8
|
|
|
9
|
-
def headless_popen_kwargs(extra_creationflags: int = 0) -> dict[str, Any]:
|
|
10
|
-
"""Windows-only creationflags/startupinfo/stdin trio for dict-building callers; no-op elsewhere."""
|
|
9
|
+
def headless_popen_kwargs(extra_creationflags: int = 0, no_window: bool = True) -> dict[str, Any]:
|
|
10
|
+
"""Windows-only creationflags/startupinfo/stdin trio for dict-building callers; no-op elsewhere; no_window=False omits CREATE_NO_WINDOW."""
|
|
11
11
|
if sys.platform != "win32":
|
|
12
12
|
return {}
|
|
13
13
|
startupinfo = subprocess.STARTUPINFO()
|
|
14
14
|
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
|
15
15
|
startupinfo.wShowWindow = subprocess.SW_HIDE
|
|
16
16
|
return {
|
|
17
|
-
"creationflags": subprocess.CREATE_NO_WINDOW | extra_creationflags,
|
|
17
|
+
"creationflags": (subprocess.CREATE_NO_WINDOW if no_window else 0) | extra_creationflags,
|
|
18
18
|
"startupinfo": startupinfo,
|
|
19
19
|
"stdin": subprocess.DEVNULL,
|
|
20
20
|
}
|
|
21
21
|
|
|
22
22
|
|
|
23
23
|
def _apply_headless(kw: dict[str, Any], *, allow_input: bool) -> dict[str, Any]:
|
|
24
|
-
"""Mutates and returns kw with the Windows headless trio; new_process_group=True also ORs in CREATE_NEW_PROCESS_GROUP on win32 for a killable child group (no-op on POSIX, which signals the pid directly)."""
|
|
24
|
+
"""Mutates and returns kw with the Windows headless trio; new_process_group=True also ORs in CREATE_NEW_PROCESS_GROUP on win32 for a killable child group (no-op on POSIX, which signals the pid directly); no_window=False omits CREATE_NO_WINDOW (window stays SW_HIDE) so a console child, e.g. Metro, can still receive CTRL_BREAK."""
|
|
25
25
|
extra_creationflags = kw.pop("creationflags", 0)
|
|
26
26
|
new_process_group = kw.pop("new_process_group", False)
|
|
27
|
+
no_window = kw.pop("no_window", True)
|
|
27
28
|
if sys.platform != "win32":
|
|
28
29
|
return kw
|
|
29
30
|
if new_process_group:
|
|
@@ -32,7 +33,7 @@ def _apply_headless(kw: dict[str, Any], *, allow_input: bool) -> dict[str, Any]:
|
|
|
32
33
|
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
|
33
34
|
startupinfo.wShowWindow = subprocess.SW_HIDE
|
|
34
35
|
kw.setdefault("startupinfo", startupinfo)
|
|
35
|
-
kw["creationflags"] = subprocess.CREATE_NO_WINDOW | extra_creationflags
|
|
36
|
+
kw["creationflags"] = (subprocess.CREATE_NO_WINDOW if no_window else 0) | extra_creationflags
|
|
36
37
|
if "stdin" not in kw and not (allow_input and "input" in kw):
|
|
37
38
|
kw["stdin"] = subprocess.DEVNULL
|
|
38
39
|
return kw
|
|
@@ -579,8 +579,27 @@ def _git_common_dir_root(cwd: str) -> str | None:
|
|
|
579
579
|
return root
|
|
580
580
|
|
|
581
581
|
|
|
582
|
+
def _worktree_toplevel(cwd: str) -> str | None:
|
|
583
|
+
"""`cwd`'s own worktree toplevel (a linked worktree or a submodule is its own), or None if not in a git work tree."""
|
|
584
|
+
try:
|
|
585
|
+
result = headless_run(
|
|
586
|
+
["git", "-C", cwd, "rev-parse", "--show-toplevel", "--path-format=absolute"],
|
|
587
|
+
capture_output=True,
|
|
588
|
+
text=True,
|
|
589
|
+
timeout=10,
|
|
590
|
+
env=_clean_git_env(),
|
|
591
|
+
)
|
|
592
|
+
except (OSError, subprocess.SubprocessError):
|
|
593
|
+
return None
|
|
594
|
+
out = result.stdout.strip()
|
|
595
|
+
if result.returncode != 0 or not out:
|
|
596
|
+
return None
|
|
597
|
+
return os.path.realpath(out)
|
|
598
|
+
|
|
599
|
+
|
|
582
600
|
def pending_review_path(cwd: str) -> str:
|
|
583
|
-
|
|
601
|
+
"""One flag per worktree toplevel, never a root shared across worktrees; mirrors scripts/route_lock.py:resolve_flag_root."""
|
|
602
|
+
base = _worktree_toplevel(cwd) or find_project_root(cwd) or cwd
|
|
584
603
|
return os.path.join(base, PENDING_REVIEW_RELPATH)
|
|
585
604
|
|
|
586
605
|
|
|
@@ -180,7 +180,7 @@ OVERRIDE_MARKER_MAX_WINDOW_SECONDS = 3600 # hard 1h cap, regardless of "until"
|
|
|
180
180
|
|
|
181
181
|
# Fast path: skip all parsing if the raw text doesn't even mention git.
|
|
182
182
|
_MENTIONS_GIT_RE = re.compile(r"\bgit\b")
|
|
183
|
-
_RISKY_SUBCOMMAND_RE = re.compile(r"\b(checkout|restore|stash|reset|clean|switch)\b")
|
|
183
|
+
_RISKY_SUBCOMMAND_RE = re.compile(r"\b(checkout|restore|stash|reset|clean|switch|apply)\b")
|
|
184
184
|
# PowerShell `-EncodedCommand`'s base64/UTF-16LE payload can hide a `git`
|
|
185
185
|
# invocation from the raw-text `_MENTIONS_GIT_RE` fast path entirely (the
|
|
186
186
|
# encoded bytes have no reason to contain the literal ASCII substring
|
|
@@ -496,6 +496,36 @@ def _restore_pathspec(rest_args: list[str], dynamic_source: bool = False):
|
|
|
496
496
|
return (paths, False) if paths else None
|
|
497
497
|
|
|
498
498
|
|
|
499
|
+
_APPLY_READONLY_FLAGS = {"--check", "--stat", "--numstat", "--summary"}
|
|
500
|
+
_PATCH_PATH_RE = re.compile(r"^(?:\+\+\+|---) (?:[ab]/)?(\S+)", re.MULTILINE)
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def _apply_reverse_pathspec(rest_args: list[str], repo_dir: Path):
|
|
504
|
+
"""`git apply -R`/`--reverse` undoes a patch in the working tree,
|
|
505
|
+
discarding uncommitted work under the same paths. None when not a
|
|
506
|
+
reverse apply (or inspect-only); else (patch paths, False), or
|
|
507
|
+
([], True) when the paths are unknowable (stdin patch, unreadable file)."""
|
|
508
|
+
if _APPLY_READONLY_FLAGS & set(rest_args):
|
|
509
|
+
return None
|
|
510
|
+
reverse = any(
|
|
511
|
+
a == "--reverse" or (a.startswith("-") and not a.startswith("--") and "R" in a)
|
|
512
|
+
for a in rest_args
|
|
513
|
+
)
|
|
514
|
+
if not reverse:
|
|
515
|
+
return None
|
|
516
|
+
patch_files = [a for a in rest_args if not a.startswith("-")]
|
|
517
|
+
if not patch_files:
|
|
518
|
+
return ([], True)
|
|
519
|
+
paths: list[str] = []
|
|
520
|
+
for name in patch_files:
|
|
521
|
+
try:
|
|
522
|
+
text = (repo_dir / name).read_text(encoding="utf-8", errors="replace")
|
|
523
|
+
except OSError:
|
|
524
|
+
return ([], True)
|
|
525
|
+
paths += [m for m in _PATCH_PATH_RE.findall(text) if m != "/dev/null"]
|
|
526
|
+
return (sorted(set(paths)), False) if paths else ([], True)
|
|
527
|
+
|
|
528
|
+
|
|
499
529
|
def _stash_pathspec(rest_args: list[str]):
|
|
500
530
|
"""Only `stash push`/`stash save` accept a `-- <paths>` pathspec,
|
|
501
531
|
narrowing the check to just those paths. Every other stash form checks
|
|
@@ -608,6 +638,9 @@ def _check_git_invocation_tokens(
|
|
|
608
638
|
elif subcommand == "restore":
|
|
609
639
|
result = _restore_pathspec(rest_args, dynamic_source=dynamic_pathspec_source)
|
|
610
640
|
rule = "restore-dynamic-pathspec-unverifiable" if (result and result[1]) else "restore-path-revert"
|
|
641
|
+
elif subcommand == "apply":
|
|
642
|
+
result = _apply_reverse_pathspec(rest_args, repo_dir)
|
|
643
|
+
rule = "apply-reverse-patch-revert"
|
|
611
644
|
elif subcommand == "stash":
|
|
612
645
|
result = _stash_pathspec(rest_args)
|
|
613
646
|
rule = "stash-may-discard-uncommitted-work"
|
package/content/scripts/item.py
CHANGED
|
@@ -23,13 +23,16 @@ Stdlib only. Atomic writes via tempfile + fsync + os.replace.
|
|
|
23
23
|
from __future__ import annotations
|
|
24
24
|
|
|
25
25
|
import argparse
|
|
26
|
+
import contextlib
|
|
26
27
|
import difflib
|
|
28
|
+
import hashlib
|
|
27
29
|
import json
|
|
28
30
|
import os
|
|
29
31
|
import re
|
|
30
32
|
import subprocess
|
|
31
33
|
import sys
|
|
32
34
|
import tempfile
|
|
35
|
+
import time
|
|
33
36
|
import urllib.parse
|
|
34
37
|
import urllib.request
|
|
35
38
|
from datetime import datetime, timezone
|
|
@@ -75,6 +78,53 @@ class _Refusal(Exception):
|
|
|
75
78
|
pass
|
|
76
79
|
|
|
77
80
|
|
|
81
|
+
# ---------------------------------------------------------------------------
|
|
82
|
+
# Ledger lock — serializes the load-modify-write cycle of mutating commands
|
|
83
|
+
# ---------------------------------------------------------------------------
|
|
84
|
+
|
|
85
|
+
LOCK_TIMEOUT_S = 60
|
|
86
|
+
MUTATING_CMDS = {
|
|
87
|
+
"init", "pickup", "log", "finish", "handoff", "council-gate",
|
|
88
|
+
"concept-analysis", "ext-append", "ext-set",
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@contextlib.contextmanager
|
|
93
|
+
def _ledger_lock(ledger: Path):
|
|
94
|
+
key = hashlib.sha1(str(ledger.resolve()).encode()).hexdigest()[:16]
|
|
95
|
+
lock_path = Path(tempfile.gettempdir()) / f"item_py_{key}.lock"
|
|
96
|
+
fh = open(lock_path, "a+b")
|
|
97
|
+
deadline = time.monotonic() + LOCK_TIMEOUT_S
|
|
98
|
+
try:
|
|
99
|
+
while True:
|
|
100
|
+
try:
|
|
101
|
+
if os.name == "nt":
|
|
102
|
+
import msvcrt
|
|
103
|
+
fh.seek(0)
|
|
104
|
+
msvcrt.locking(fh.fileno(), msvcrt.LK_NBLCK, 1)
|
|
105
|
+
else:
|
|
106
|
+
import fcntl
|
|
107
|
+
fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
108
|
+
break
|
|
109
|
+
except OSError:
|
|
110
|
+
if time.monotonic() > deadline:
|
|
111
|
+
raise _Refusal(f"could not lock ledger '{ledger}' within {LOCK_TIMEOUT_S}s")
|
|
112
|
+
time.sleep(0.05)
|
|
113
|
+
yield
|
|
114
|
+
finally:
|
|
115
|
+
try:
|
|
116
|
+
if os.name == "nt":
|
|
117
|
+
import msvcrt
|
|
118
|
+
fh.seek(0)
|
|
119
|
+
msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, 1)
|
|
120
|
+
else:
|
|
121
|
+
import fcntl
|
|
122
|
+
fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
|
|
123
|
+
except OSError:
|
|
124
|
+
pass
|
|
125
|
+
fh.close()
|
|
126
|
+
|
|
127
|
+
|
|
78
128
|
# ---------------------------------------------------------------------------
|
|
79
129
|
# Project root + ledger discovery
|
|
80
130
|
# ---------------------------------------------------------------------------
|
|
@@ -791,6 +841,59 @@ def cmd_concept_analysis(args: argparse.Namespace, ctx: dict) -> int:
|
|
|
791
841
|
return 0
|
|
792
842
|
|
|
793
843
|
|
|
844
|
+
# ---------------------------------------------------------------------------
|
|
845
|
+
# Subcommand: ext-append — append one JSON object to an allowlisted ext list
|
|
846
|
+
# ---------------------------------------------------------------------------
|
|
847
|
+
|
|
848
|
+
EXT_APPEND_PATHS = {"meshy.tasks"}
|
|
849
|
+
EXT_SET_VALUES = {"body_plan": {"biped", "quadruped", "other"}}
|
|
850
|
+
|
|
851
|
+
|
|
852
|
+
def cmd_ext_append(args: argparse.Namespace, ctx: dict) -> int:
|
|
853
|
+
if args.path not in EXT_APPEND_PATHS:
|
|
854
|
+
raise _Refusal(
|
|
855
|
+
f"ext path '{args.path}' is not appendable; allowed: {sorted(EXT_APPEND_PATHS)}"
|
|
856
|
+
)
|
|
857
|
+
try:
|
|
858
|
+
data = json.loads(args.json_str)
|
|
859
|
+
except json.JSONDecodeError as e:
|
|
860
|
+
raise _Refusal(f"--json is not valid JSON: {e}")
|
|
861
|
+
if not isinstance(data, dict):
|
|
862
|
+
raise _Refusal("ext-append payload must be a JSON object")
|
|
863
|
+
|
|
864
|
+
doc = ctx["doc"]
|
|
865
|
+
item = _find_item(doc, args.id)
|
|
866
|
+
node = item.setdefault("ext", {})
|
|
867
|
+
*parents, leaf = args.path.split(".")
|
|
868
|
+
for key in parents:
|
|
869
|
+
node = node.setdefault(key, {})
|
|
870
|
+
bucket = node.setdefault(leaf, [])
|
|
871
|
+
if not isinstance(bucket, list):
|
|
872
|
+
raise _Refusal(f"ext.{args.path} exists and is not a list")
|
|
873
|
+
bucket.append(data)
|
|
874
|
+
_touch(item)
|
|
875
|
+
_atomic_write(ctx["ledger_path"], doc)
|
|
876
|
+
print(json.dumps({
|
|
877
|
+
"ok": True, "id": args.id, "wrote": f"ext.{args.path}", "count": len(bucket),
|
|
878
|
+
}, indent=2))
|
|
879
|
+
return 0
|
|
880
|
+
|
|
881
|
+
|
|
882
|
+
def cmd_ext_set(args: argparse.Namespace, ctx: dict) -> int:
|
|
883
|
+
allowed = EXT_SET_VALUES.get(args.key)
|
|
884
|
+
if allowed is None:
|
|
885
|
+
raise _Refusal(f"ext key '{args.key}' is not settable; allowed: {sorted(EXT_SET_VALUES)}")
|
|
886
|
+
if args.value not in allowed:
|
|
887
|
+
raise _Refusal(f"ext.{args.key} must be one of {sorted(allowed)}")
|
|
888
|
+
doc = ctx["doc"]
|
|
889
|
+
item = _find_item(doc, args.id)
|
|
890
|
+
item.setdefault("ext", {})[args.key] = args.value
|
|
891
|
+
_touch(item)
|
|
892
|
+
_atomic_write(ctx["ledger_path"], doc)
|
|
893
|
+
print(json.dumps({"ok": True, "id": args.id, "wrote": f"ext.{args.key}", "value": args.value}, indent=2))
|
|
894
|
+
return 0
|
|
895
|
+
|
|
896
|
+
|
|
794
897
|
# ---------------------------------------------------------------------------
|
|
795
898
|
# Resolve — codified fuzzy ID lookup for free-text leaf dispatch
|
|
796
899
|
# ---------------------------------------------------------------------------
|
|
@@ -1017,6 +1120,25 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
1017
1120
|
help="JSON string literal")
|
|
1018
1121
|
pca.set_defaults(func=cmd_concept_analysis)
|
|
1019
1122
|
|
|
1123
|
+
pea = sub.add_parser(
|
|
1124
|
+
"ext-append",
|
|
1125
|
+
help="append a JSON object to an allowlisted ext list (e.g. meshy.tasks)",
|
|
1126
|
+
)
|
|
1127
|
+
pea.add_argument("id")
|
|
1128
|
+
pea.add_argument("path", help="dotted ext path, e.g. meshy.tasks")
|
|
1129
|
+
pea.add_argument("--json", dest="json_str", required=True,
|
|
1130
|
+
help="JSON object literal to append")
|
|
1131
|
+
pea.set_defaults(func=cmd_ext_append)
|
|
1132
|
+
|
|
1133
|
+
pes = sub.add_parser(
|
|
1134
|
+
"ext-set",
|
|
1135
|
+
help="set an allowlisted scalar ext key (e.g. body_plan=biped)",
|
|
1136
|
+
)
|
|
1137
|
+
pes.add_argument("id")
|
|
1138
|
+
pes.add_argument("key", help="ext key, e.g. body_plan")
|
|
1139
|
+
pes.add_argument("--value", required=True)
|
|
1140
|
+
pes.set_defaults(func=cmd_ext_set)
|
|
1141
|
+
|
|
1020
1142
|
pr = sub.add_parser(
|
|
1021
1143
|
"resolve",
|
|
1022
1144
|
help="resolve a free-text query to a single actionable item id (codified picker)",
|
|
@@ -1035,6 +1157,10 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
1035
1157
|
parser = build_parser()
|
|
1036
1158
|
args = parser.parse_args(argv)
|
|
1037
1159
|
try:
|
|
1160
|
+
if args.cmd in MUTATING_CMDS:
|
|
1161
|
+
with _ledger_lock(_ledger_path(_find_project_root())):
|
|
1162
|
+
ctx = _build_context(read_only=False)
|
|
1163
|
+
return args.func(args, ctx)
|
|
1038
1164
|
ctx = _build_context(read_only=(args.cmd == "status"))
|
|
1039
1165
|
return args.func(args, ctx)
|
|
1040
1166
|
except _Refusal as e:
|
|
@@ -608,3 +608,69 @@ class TestCouncilGateRetry:
|
|
|
608
608
|
out = json.loads(r.stdout)
|
|
609
609
|
assert out["retry_count"] == 1
|
|
610
610
|
assert out["verdict"] == "REJECT-RETRY"
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
# ---------------------------------------------------------------------------
|
|
614
|
+
# ext-append — codified append to an allowlisted ext list (ext.meshy.tasks)
|
|
615
|
+
# ---------------------------------------------------------------------------
|
|
616
|
+
|
|
617
|
+
class TestExtAppend:
|
|
618
|
+
def test_appends_record_to_allowlisted_list(self, test_repo):
|
|
619
|
+
_seed_item(test_repo["ledger"], "ENM-T1")
|
|
620
|
+
rec = {"task_id": "abc", "operation": "image-to-3d"}
|
|
621
|
+
_run_cli(["ext-append", "ENM-T1", "meshy.tasks", "--json", json.dumps(rec)],
|
|
622
|
+
test_repo["root"], expect_code=0, ledger=test_repo["ledger"])
|
|
623
|
+
rec2 = {"task_id": "def", "operation": "remesh"}
|
|
624
|
+
_run_cli(["ext-append", "ENM-T1", "meshy.tasks", "--json", json.dumps(rec2)],
|
|
625
|
+
test_repo["root"], expect_code=0, ledger=test_repo["ledger"])
|
|
626
|
+
item = _read(test_repo["ledger"])["items"][0]
|
|
627
|
+
assert item["ext"]["meshy"]["tasks"] == [rec, rec2]
|
|
628
|
+
|
|
629
|
+
def test_refuses_non_allowlisted_path(self, test_repo):
|
|
630
|
+
_seed_item(test_repo["ledger"], "ENM-T2")
|
|
631
|
+
r = _run_cli(["ext-append", "ENM-T2", "council_gate.cleared", "--json", "{}"],
|
|
632
|
+
test_repo["root"], expect_code=1, ledger=test_repo["ledger"])
|
|
633
|
+
assert "REFUSED" in r.stderr
|
|
634
|
+
|
|
635
|
+
def test_refuses_non_object_payload(self, test_repo):
|
|
636
|
+
_seed_item(test_repo["ledger"], "ENM-T3")
|
|
637
|
+
_run_cli(["ext-append", "ENM-T3", "meshy.tasks", "--json", "[1]"],
|
|
638
|
+
test_repo["root"], expect_code=1, ledger=test_repo["ledger"])
|
|
639
|
+
|
|
640
|
+
def test_unknown_item_refused(self, test_repo):
|
|
641
|
+
_run_cli(["ext-append", "NOPE-1", "meshy.tasks", "--json", "{}"],
|
|
642
|
+
test_repo["root"], expect_code=1, ledger=test_repo["ledger"])
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
class TestExtSet:
|
|
646
|
+
def test_sets_body_plan(self, test_repo):
|
|
647
|
+
_seed_item(test_repo["ledger"], "ENM-S1")
|
|
648
|
+
_run_cli(["ext-set", "ENM-S1", "body_plan", "--value", "biped"],
|
|
649
|
+
test_repo["root"], expect_code=0, ledger=test_repo["ledger"])
|
|
650
|
+
assert _read(test_repo["ledger"])["items"][0]["ext"]["body_plan"] == "biped"
|
|
651
|
+
|
|
652
|
+
def test_refuses_bad_value_and_bad_key(self, test_repo):
|
|
653
|
+
_seed_item(test_repo["ledger"], "ENM-S2")
|
|
654
|
+
_run_cli(["ext-set", "ENM-S2", "body_plan", "--value", "dragon"],
|
|
655
|
+
test_repo["root"], expect_code=1, ledger=test_repo["ledger"])
|
|
656
|
+
_run_cli(["ext-set", "ENM-S2", "council_gate", "--value", "x"],
|
|
657
|
+
test_repo["root"], expect_code=1, ledger=test_repo["ledger"])
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
class TestLedgerLock:
|
|
661
|
+
def test_concurrent_ext_append_loses_nothing(self, test_repo):
|
|
662
|
+
import subprocess as sp
|
|
663
|
+
_seed_item(test_repo["ledger"], "ENM-L1")
|
|
664
|
+
env = {**os.environ, "PYTHONIOENCODING": "utf-8", "ITEM_PY_JSON_PATH": str(test_repo["ledger"])}
|
|
665
|
+
n = 8
|
|
666
|
+
procs = [
|
|
667
|
+
sp.Popen([sys.executable, str(ITEM_PY), "ext-append", "ENM-L1", "meshy.tasks",
|
|
668
|
+
"--json", json.dumps({"task_id": f"t{i}"})],
|
|
669
|
+
env=env, cwd=str(test_repo["root"]), stdout=sp.PIPE, stderr=sp.PIPE)
|
|
670
|
+
for i in range(n)
|
|
671
|
+
]
|
|
672
|
+
for p in procs:
|
|
673
|
+
p.communicate(timeout=60)
|
|
674
|
+
assert p.returncode == 0
|
|
675
|
+
tasks = _read(test_repo["ledger"])["items"][0]["ext"]["meshy"]["tasks"]
|
|
676
|
+
assert sorted(t["task_id"] for t in tasks) == sorted(f"t{i}" for i in range(n))
|