@yasaswy.nagavolu/agents 0.30.3 → 0.32.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.
Files changed (80) hide show
  1. package/README.md +6 -3
  2. package/bin/cli.js +45 -5
  3. package/content/global/hooks/compact_context.py +39 -3
  4. package/content/hooks/reconcile_landing.py +109 -0
  5. package/content/hooks/reconcile_session_start.py +47 -0
  6. package/content/hooks/reconcile_triggers.py +257 -0
  7. package/content/hooks/task_completion_gate.py +104 -0
  8. package/content/hooks/tracker_proof_gate.py +110 -37
  9. package/content/manifest.json +82 -13
  10. package/content/mods/handoff/README.md +4 -4
  11. package/content/mods/handoff/hooks/register.js +6 -3
  12. package/content/mods/handoff/lib/prep.mjs +3 -1
  13. package/content/mods/handoff/lib/reconcile.mjs +31 -0
  14. package/content/mods/handoff/lib/template.mjs +1 -1
  15. package/content/mods/handoff/lib/validate-cli.mjs +9 -1
  16. package/content/mods/handoff/lib/validate.mjs +8 -1
  17. package/content/mods/handoff/prompts/handoff-prep.md +1 -1
  18. package/content/mods/handoff/tests/reconcile.test.mjs +116 -0
  19. package/content/mods/handoff/tests/register.test.mjs +33 -0
  20. package/content/mods/handoff/tests/template.test.mjs +1 -0
  21. package/content/proxy/README.md +1 -2
  22. package/content/proxy/chat_exit.py +725 -0
  23. package/content/proxy/chat_exit_report.py +115 -0
  24. package/content/proxy/chat_inbox_hook.py +10 -24
  25. package/content/proxy/chat_ledger.py +1 -32
  26. package/content/proxy/gitlab_mutation_guard.py +5 -3
  27. package/content/proxy/html_mocker_monitor_guard.py +95 -4
  28. package/content/proxy/litellm/start.ps1 +1 -1
  29. package/content/proxy/log_retention.py +1 -0
  30. package/content/proxy/mem_sampler.py +65 -9
  31. package/content/proxy/memory_reclaim.py +1 -16
  32. package/content/proxy/proc_policy.py +2 -8
  33. package/content/proxy/register_mem_sampler.ps1 +6 -3
  34. package/content/proxy/register_task.ps1 +1 -1
  35. package/content/scripts/reconcile_records.py +539 -0
  36. package/content/scripts/tests/test_reconcile_records.py +408 -0
  37. package/content/skills/README.md +1 -1
  38. package/content/skills/ci-runner/SKILL.md +6 -3
  39. package/content/skills/ci-runner/ci-runner-pool.md +61 -0
  40. package/content/skills/low-ram-advisor/SKILL.md +17 -37
  41. package/content/skills/low-ram-advisor/advisor.py +2 -190
  42. package/content/skills/low-ram-advisor/memwatch.py +19 -115
  43. package/content/skills/low-ram-advisor/ram_notice.py +58 -0
  44. package/content/skills/low-ram-advisor/ram_optimize.py +29 -1
  45. package/content/skills/low-ram-advisor/ram_prompt.py +4 -83
  46. package/content/skills/low-ram-advisor/tests/conftest.py +1 -0
  47. package/content/skills/low-ram-advisor/tests/test_advisor.py +14 -280
  48. package/content/skills/low-ram-advisor/tests/test_deep_report.py +9 -9
  49. package/content/skills/low-ram-advisor/tests/test_memwatch.py +47 -77
  50. package/content/skills/low-ram-advisor/tests/test_ram_notice.py +67 -0
  51. package/content/skills/low-ram-advisor/tests/test_ram_optimize.py +37 -10
  52. package/content/skills/low-ram-advisor/tests/test_ram_prompt.py +10 -85
  53. package/content/skills/low-ram-advisor/tests/test_restart_verdict.py +0 -23
  54. package/content/statusline/statusline-command.ps1 +13 -0
  55. package/content/statusline/statusline-command.py +14 -0
  56. package/lib/bypassOnly.js +4 -2
  57. package/lib/doctor.js +4 -0
  58. package/lib/memSafety.js +1 -2
  59. package/lib/pwshStore.js +171 -0
  60. package/lib/runner/args.js +6 -2
  61. package/lib/runner/banner.js +159 -0
  62. package/lib/runner/budget.js +27 -21
  63. package/lib/runner/cap.js +165 -0
  64. package/lib/runner/dockerChecks.js +84 -0
  65. package/lib/runner/gitlab.js +25 -0
  66. package/lib/runner/hints.js +8 -0
  67. package/lib/runner/index.js +94 -19
  68. package/lib/runner/janitor.js +16 -55
  69. package/lib/runner/janitorPlan.js +14 -87
  70. package/lib/runner/janitorTask.js +36 -9
  71. package/lib/runner/managed.js +20 -24
  72. package/lib/runner/pool.js +14 -89
  73. package/lib/runner/profiles/linuxDocker.js +8 -3
  74. package/lib/runner/result.js +1 -1
  75. package/lib/runner/stableCli.js +130 -0
  76. package/lib/secretsPrompt.js +1 -1
  77. package/lib/secretsSet.js +68 -0
  78. package/package.json +1 -1
  79. package/content/proxy/memory_reclaim_hook.py +0 -86
  80. package/content/skills/low-ram-advisor/tests/test_advisor_deep.py +0 -45
package/README.md CHANGED
@@ -121,10 +121,13 @@ agents-cli install
121
121
  token (the Microsoft Store stub makes it fail), a missing `hooks/pyrun.js` launcher, an unresolvable interpreter, and a
122
122
  WindowsApps python stub ahead of a real interpreter on PATH; `--fix` rewrites the bare tokens to
123
123
  `node <target>/hooks/pyrun.js <script>` and never edits PATH or App Execution Aliases.
124
+ On Windows it also warns (report only, never changes the exit code) when the shell hosting the chat, `pwsh` first on PATH,
125
+ a visible Windows Terminal profile, or a `Claude*`/`LiteLLM*` scheduled task points at the Microsoft Store (MSIX)
126
+ PowerShell, because a Store update force-closes running chats. Fix with `tools/pwsh_msi_cutover.ps1` in the my-agents repo.
124
127
  It also checks `~/.claude/settings.json` for bypass-only, no auto mode: `permissions.defaultMode` `bypassPermissions`,
125
- `permissions.disableAutoMode` `disable`, `skipDangerousModePermissionPrompt` `true`, `useAutoModeDuringPlan` `false`, and no
126
- `permissions.disableBypassPermissionsMode`. `--fix`, `install` and `update` set those keys and leave every other key,
127
- including `permissions.deny`, untouched; a project `defaultMode` weaker than `bypassPermissions` is flagged too.
128
+ `skipDangerousModePermissionPrompt` `true`, `useAutoModeDuringPlan` `false`, and neither
129
+ `permissions.disableBypassPermissionsMode` nor `permissions.disableAutoMode`. `--fix`, `install` and `update` set the
130
+ required keys, remove the forbidden ones, and leave every other key, including `permissions.deny`, untouched; a project `defaultMode` weaker than `bypassPermissions` is flagged too.
128
131
  It also flags a project `permissions.defaultMode` weaker than the global default in `~/.claude/settings.json`
129
132
  (for example `dontAsk` under a global `bypassPermissions`); `--fix` removes it from `settings.local.json`
130
133
  only, a committed `settings.json` is reported and never edited. The `permission_mode_enforce.js` hook
package/bin/cli.js CHANGED
@@ -46,6 +46,7 @@ const pyrun = require('../lib/pyrun');
46
46
  const { checkModVersions } = require('../lib/claudeVersion');
47
47
  const memSafety = require('../lib/memSafety');
48
48
  const portalHealth = require('../lib/portalHealth');
49
+ const pwshStore = require('../lib/pwshStore');
49
50
  const { staleCheckoutGate } = require('../lib/staleCheckout');
50
51
  const releaseLock = require('../lib/releaseLock');
51
52
  const claudeProfile = require('../lib/claudeProfile');
@@ -184,6 +185,8 @@ Flags for runner:
184
185
  runner attach | detach --project-id <id> Enable/disable the saved runners on a project (--no-cloud on
185
186
  attach also turns off cloud runners for it)
186
187
  runner pool --pool-file <spec> [--apply] Merge runners into one capped pool (dry run without --apply; refuses while a job runs)
188
+ runner cap <class> <size> Change a class memory cap now (for example: runner cap release 12g); no restart, running jobs keep the old cap
189
+ runner concurrent <n> | pause | resume Change the job slots, or stop and start taking jobs (running jobs finish)
187
190
  runner janitor [--dry-run] [--watch] Remove finished job containers, per-job volumes and unused images; --watch cleans after every job
188
191
  runner init-project [--profile node|python|docker|macos|blank] [--write] [--attach --project-id <id>]
189
192
  Write a .gitlab-ci.yml that uses the shared templates (dry run unless --write)
@@ -226,9 +229,9 @@ than bypassPermissions (for example "dontAsk" or "auto"), which silently downgra
226
229
  --fix removes the key from settings.local.json only; a committed settings.json is reported, never edited.
227
230
 
228
231
  doctor also checks <target>/settings.json for bypassPermissions only with no auto mode: permissions.defaultMode
229
- "bypassPermissions", permissions.disableAutoMode "disable", skipDangerousModePermissionPrompt true,
230
- useAutoModeDuringPlan false, and no permissions.disableBypassPermissionsMode. --fix (and every update) sets
231
- those keys and leaves all other keys, including permissions.deny, untouched.
232
+ "bypassPermissions", skipDangerousModePermissionPrompt true, useAutoModeDuringPlan false, and neither
233
+ permissions.disableBypassPermissionsMode nor permissions.disableAutoMode. --fix (and every update) sets the
234
+ required keys, removes the forbidden ones, and leaves all other keys, including permissions.deny, untouched.
232
235
 
233
236
  doctor reports, without changing anything: orphans (files/directories sitting inside
234
237
  a path this CLI manages that the ledger does not claim — e.g. a stale file left behind
@@ -677,6 +680,7 @@ async function runInteractiveMenu({ advanced, targetDir, targetConfig, noSecrets
677
680
  runSelfProfileStepsIfNeeded({ profile, targetDir });
678
681
  runMemSamplerStep({ targetDir, noScheduledTasks });
679
682
  }
683
+ await runRunnerBannerStep({ bundleKeys: installedBundles.map((b) => b.key), targetDir });
680
684
 
681
685
  printFinalSummary({ installed: installedResults, skipped, targetBase: targetDir || defaultTargetBase() });
682
686
 
@@ -732,6 +736,7 @@ async function runInstall(argv, { captureSelection = false } = {}) {
732
736
  runMemSamplerStep({ targetDir: args.targetDir, noScheduledTasks: args.noScheduledTasks });
733
737
  printPythonSyncIssues([result]);
734
738
  printModVersionWarnings([args.bundle], result.targetBase);
739
+ await runRunnerBannerStep({ bundleKeys: [args.bundle], targetDir: args.targetDir });
735
740
  return 0;
736
741
  } catch (err) {
737
742
  if (err instanceof InstallError || err instanceof ManifestError || err instanceof LedgerError || err instanceof WiringError) {
@@ -742,6 +747,15 @@ async function runInstall(argv, { captureSelection = false } = {}) {
742
747
  }
743
748
  }
744
749
 
750
+ async function runRunnerBannerStep({ bundleKeys, targetDir }) {
751
+ if (!bundleKeys.includes('runner')) return;
752
+ try {
753
+ await require('../lib/runner/banner').runBundleBanner({ targetBase: targetDir || defaultTargetBase(), live: !isTestRun() });
754
+ } catch (err) {
755
+ console.log(` (could not run the prerequisite checks: ${err.message})`);
756
+ }
757
+ }
758
+
745
759
  function parseUninstallArgs(argv) {
746
760
  const args = { bundle: null, yes: false, targetDir: null, targetConfig: null };
747
761
  for (let i = 0; i < argv.length; i += 1) {
@@ -887,6 +901,11 @@ function parseSecretsArgs(argv) {
887
901
  } else if (arg === '--remove') {
888
902
  args.remove = argv[i + 1];
889
903
  i += 1;
904
+ } else if (arg === '--set') {
905
+ const name = argv[i + 1];
906
+ if (!name || name.startsWith('--')) throw Object.assign(new InstallError('--set needs a secret name, for example: secrets --set GITLAB_RUNNER_PAT'), { exitCode: 2 });
907
+ args.set = name;
908
+ i += 1;
890
909
  } else if (arg === '--purge-unused') {
891
910
  args.purgeUnused = true;
892
911
  } else if (arg === '--yes') {
@@ -925,7 +944,7 @@ async function runSecrets(argv) {
925
944
  args = parseSecretsArgs(argv);
926
945
  } catch (err) {
927
946
  console.error(err.message);
928
- return 1;
947
+ return err.exitCode || 1;
929
948
  }
930
949
 
931
950
  const targetBase = args.targetDir || defaultTargetBase();
@@ -945,6 +964,16 @@ async function runSecrets(argv) {
945
964
  return 0;
946
965
  }
947
966
 
967
+ if (args.set) {
968
+ const { setSecretFromInput } = require('../lib/secretsSet');
969
+ const set = await setSecretFromInput({
970
+ name: args.set, targetBase, manifest, isTTY: !!(process.stdin.isTTY && process.stdout.isTTY),
971
+ });
972
+ (set.ok ? console.log : console.error)(set.message);
973
+ if (set.warning) console.log(` Warning: ${set.warning}`);
974
+ return set.ok ? 0 : 1;
975
+ }
976
+
948
977
  if (args.purgeUnused) {
949
978
  const stillNeeded = secretsStillNeeded(targetBase, manifest);
950
979
  const { values } = readSecrets(targetBase);
@@ -995,7 +1024,7 @@ async function runSecrets(argv) {
995
1024
  const keys = installedBundleKeys(targetBase, pkg.version);
996
1025
  bundles = keys.map((key) => findBundle(manifest, key)).filter(Boolean);
997
1026
  if (bundles.length === 0) {
998
- console.log(`No installed bundles found at ${targetBase} — nothing to do. Pass --bundle <key> to target one directly.`);
1027
+ console.log(`No installed bundles found at ${targetBase} — nothing to do. Pass --bundle <key> to target one directly, for example the CI runner token: npx -y @yasaswy.nagavolu/agents secrets --bundle runner`);
999
1028
  return 0;
1000
1029
  }
1001
1030
  }
@@ -1522,6 +1551,15 @@ function runDoctor(argv) {
1522
1551
  for (const f of p.findings) console.log(` ${mark('fail')} ${f}`);
1523
1552
  };
1524
1553
 
1554
+ const printPwshStore = () => {
1555
+ const p = result.pwshStore;
1556
+ if (!p) return;
1557
+ console.log('\nPowerShell build (the Microsoft Store build is force-closed, with its chats, by Store updates; report only):');
1558
+ for (const line of pwshStore.describePwshStore(p)) console.log(` ${line}`);
1559
+ if (p.healthy) console.log(' no Store pwsh behind the chat shell, PATH, Windows Terminal or Claude tasks');
1560
+ for (const f of p.findings) console.log(` ${mark('skip')} ${f}`);
1561
+ };
1562
+
1525
1563
  const printRoutingMod = () => {
1526
1564
  if (!result.routingMod) return;
1527
1565
  console.log('\nModel routing:');
@@ -1538,6 +1576,7 @@ function runDoctor(argv) {
1538
1576
  printRoutingMod();
1539
1577
  printMemorySafety();
1540
1578
  printPortal();
1579
+ printPwshStore();
1541
1580
  printModeDrift();
1542
1581
  return 0;
1543
1582
  }
@@ -1561,6 +1600,7 @@ function runDoctor(argv) {
1561
1600
  printRoutingMod();
1562
1601
  printMemorySafety();
1563
1602
  printPortal();
1603
+ printPwshStore();
1564
1604
  printProjectHooks();
1565
1605
  printPythonLaunchReport(py);
1566
1606
  printModeDrift();
@@ -20,6 +20,9 @@ STATUS_LINE_CHARS = 90
20
20
  TASK_MAX = 6
21
21
  TASK_SUBJECT_CHARS = 70
22
22
  HANDOFF_MAX_AGE_SECS = 24 * 3600
23
+ RECONCILE_SCRIPTS_DIR = Path.home() / ".claude" / "scripts"
24
+ SUPERSEDED_MARK = "[SUPERSEDED BY EVIDENCE]"
25
+ EV_ANCHOR = "<!--ev"
23
26
  TASKLIST_HINT = "Open tasks: not readable from disk for this session id; call TaskList to see them."
24
27
  OPEN_STATUSES = ("in_progress", "pending")
25
28
  SAFE_ID = re.compile(r"^[A-Za-z0-9_.-]+$")
@@ -80,7 +83,39 @@ def open_tasks(session_id: str) -> list[str] | None:
80
83
  return []
81
84
 
82
85
 
83
- def newest_handoff() -> str | None:
86
+ def age_label(seconds: float) -> str:
87
+ if seconds >= 86400:
88
+ days = int(seconds // 86400)
89
+ return f"{days} day{'s' * (days != 1)} old"
90
+ hours = int(max(seconds, 0) // 3600)
91
+ return "under 1 hour old" if hours == 0 else f"{hours} hour{'s' * (hours != 1)} old"
92
+
93
+
94
+ def handoff_line(path: str, age_secs: float, superseded: bool = False) -> str:
95
+ return f"Latest handoff: {path} ({age_label(age_secs)})" + (f" {SUPERSEDED_MARK}" if superseded else "")
96
+
97
+
98
+ def handoff_superseded(path: str) -> bool:
99
+ """True when the handoff has an anchored pending line whose evidence is already true. Never fetches; fails open."""
100
+ try:
101
+ text = Path(path).read_text(encoding="utf-8")
102
+ engine_path = RECONCILE_SCRIPTS_DIR / "reconcile_records.py"
103
+ if EV_ANCHOR not in text or not engine_path.is_file():
104
+ return False
105
+ import importlib.util
106
+ name = "reconcile_records_for_compact"
107
+ spec = importlib.util.spec_from_file_location(name, engine_path)
108
+ engine = importlib.util.module_from_spec(spec)
109
+ sys.modules[name] = engine
110
+ spec.loader.exec_module(engine)
111
+ engine._fetch_branch = lambda repo, branch, ctx: False
112
+ rows = engine.analyze_text(text, path, engine.Context())
113
+ return any(row.get("status") == "DONE_BY_EVIDENCE" for row in rows)
114
+ except Exception:
115
+ return False
116
+
117
+
118
+ def newest_handoff() -> tuple[str, float] | None:
84
119
  directory = Path.home() / ".claude" / "handoffs"
85
120
  try:
86
121
  files = [(p.stat().st_mtime, p) for p in directory.glob("*.md")]
@@ -89,7 +124,8 @@ def newest_handoff() -> str | None:
89
124
  if not files:
90
125
  return None
91
126
  mtime, path = max(files)
92
- return path.as_posix() if time.time() - mtime <= HANDOFF_MAX_AGE_SECS else None
127
+ age = time.time() - mtime
128
+ return (path.as_posix(), age) if age <= HANDOFF_MAX_AGE_SECS else None
93
129
 
94
130
 
95
131
  def build(payload: dict) -> str:
@@ -107,7 +143,7 @@ def build(payload: dict) -> str:
107
143
  lines.append(f"Branch: {branch}")
108
144
  handoff = newest_handoff()
109
145
  if handoff:
110
- lines.append(f"Latest handoff: {handoff}")
146
+ lines.append(handoff_line(*handoff, handoff_superseded(handoff[0])))
111
147
  tasks = open_tasks(str(payload.get("session_id") or ""))
112
148
  if tasks is None:
113
149
  lines.append(TASKLIST_HINT)
@@ -0,0 +1,109 @@
1
+ #!/usr/bin/env python3
2
+ """PostToolUse (Bash): after a landing command (git push, ship.py, commit_repo.py --promote-to,
3
+ etiquette.py verify, cut_release.py) run the reconcile engine with --apply in a hidden background process.
4
+
5
+ Never blocks and never prints; fails open."""
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import shlex
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ if os.environ.get("CLAUDE_HOOK_CHILD"):
14
+ sys.exit(0)
15
+
16
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "proxy"))
17
+
18
+ PYTHON_NAMES = ("python", "python3", "py", "pythonw")
19
+ LANDING_SCRIPTS = {"ship.py": None, "cut_release.py": None, "commit_repo.py": "--promote-to", "etiquette.py": "verify"}
20
+ PUSH_DRY_RUN = ("--dry-run", "-n")
21
+
22
+
23
+ def _tokens(segment: str) -> list[str]:
24
+ try:
25
+ return shlex.split(segment, posix=True)
26
+ except ValueError:
27
+ return segment.split()
28
+
29
+
30
+ def _git_dir(tokens: list[str], cwd: Path) -> Path:
31
+ from shell_parse import resolve_dir
32
+
33
+ for i, token in enumerate(tokens[:-1]):
34
+ if token == "-C":
35
+ return resolve_dir(cwd, tokens[i + 1])
36
+ return cwd
37
+
38
+
39
+ def _script_landing(tokens: list[str]) -> bool:
40
+ from shell_parse import binary_name
41
+
42
+ name = binary_name(tokens[0])
43
+ args = tokens[1:]
44
+ if name in PYTHON_NAMES:
45
+ script = next((a for a in args if not a.startswith("-")), None)
46
+ if script is None:
47
+ return False
48
+ name = binary_name(script)
49
+ args = args[args.index(script) + 1:]
50
+ if name not in LANDING_SCRIPTS:
51
+ return False
52
+ required = LANDING_SCRIPTS[name]
53
+ return required is None or any(a == required or a.startswith(required + "=") for a in args)
54
+
55
+
56
+ def landing_cwd(command: str, cwd: str | Path) -> Path | None:
57
+ """Directory in which the command lands work, or None when it is not a landing command."""
58
+ from git_shell_parse import find_git_subcommand
59
+ from shell_parse import apply_cd, split_pipe_stages, split_segments, strip_env_assignments
60
+
61
+ here = Path(cwd)
62
+ for segment in split_segments(command):
63
+ tokens = _tokens(segment)
64
+ moved = apply_cd(here, strip_env_assignments(tokens))
65
+ if moved is not None:
66
+ here = moved
67
+ continue
68
+ for stage in split_pipe_stages(tokens):
69
+ stage = strip_env_assignments(stage)
70
+ if not stage:
71
+ continue
72
+ found = find_git_subcommand(stage)
73
+ if found is not None:
74
+ if found[0] == "push" and not any(a in PUSH_DRY_RUN for a in found[1]):
75
+ return _git_dir(stage, here)
76
+ continue
77
+ if _script_landing(stage):
78
+ return here
79
+ return None
80
+
81
+
82
+ def run() -> None:
83
+ import reconcile_triggers as rt
84
+
85
+ payload = rt.read_payload()
86
+ command = (payload.get("tool_input") or {}).get("command")
87
+ response = payload.get("tool_response")
88
+ if payload.get("tool_name") != "Bash" or not isinstance(command, str):
89
+ return
90
+ if isinstance(response, dict) and (response.get("is_error") or response.get("interrupted")):
91
+ return
92
+ where = landing_cwd(command, payload.get("cwd") or os.getcwd())
93
+ if where is None:
94
+ return
95
+ root = rt.git_root(where)
96
+ if root is not None and rt.discover(root)[0]:
97
+ rt.spawn_refresh(root, apply=True)
98
+
99
+
100
+ def main() -> int:
101
+ try:
102
+ run()
103
+ except Exception:
104
+ pass
105
+ return 0
106
+
107
+
108
+ if __name__ == "__main__":
109
+ sys.exit(main())
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env python3
2
+ """SessionStart (startup, resume, compact): inject a cached "STALE RECORDS" block; refresh the cache in a hidden background run.
3
+
4
+ Reads only a cache file and never waits on the network. Fails open and prints nothing when clean."""
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import sys
9
+ import time
10
+
11
+ if os.environ.get("CLAUDE_HOOK_CHILD"):
12
+ sys.exit(0)
13
+
14
+ SOURCES = ("startup", "resume", "compact")
15
+
16
+
17
+ def run() -> str:
18
+ import reconcile_triggers as rt
19
+
20
+ payload = rt.read_payload()
21
+ if payload.get("source") not in SOURCES:
22
+ return ""
23
+ root = rt.git_root(payload.get("cwd") or os.getcwd())
24
+ if root is None:
25
+ return ""
26
+ cache = rt.read_cache(root)
27
+ age = time.time() - cache["generated"] if cache else None
28
+ if (age is None or age > rt.CACHE_TTL_SECS) and not rt.refresh_running(root):
29
+ if cache is not None or rt.discover(root)[0]:
30
+ rt.spawn_refresh(root, apply=False)
31
+ if cache is None or age > rt.CACHE_MAX_AGE_SECS:
32
+ return ""
33
+ return rt.render(root, cache)
34
+
35
+
36
+ def main() -> int:
37
+ try:
38
+ text = run()
39
+ if text:
40
+ sys.stdout.write(text + "\n")
41
+ except Exception:
42
+ pass
43
+ return 0
44
+
45
+
46
+ if __name__ == "__main__":
47
+ sys.exit(main())
@@ -0,0 +1,257 @@
1
+ #!/usr/bin/env python3
2
+ """Shared core of the stale-record triggers: record discovery, result cache, hidden background refresh.
3
+
4
+ Worker (spawned detached and hidden by the hooks): python reconcile_triggers.py run --root DIR [--apply]
5
+ --apply reaches issue: records only; file records are report-only so a hook never dirties a working tree.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import re
14
+ import subprocess
15
+ import sys
16
+ import time
17
+ from pathlib import Path
18
+
19
+ HERE = Path(__file__).resolve().parent
20
+ ENGINE = HERE.parent / "scripts" / "reconcile_records.py"
21
+ for _dir in (ENGINE.parent, HERE.parent / "proxy"):
22
+ sys.path.insert(0, str(_dir))
23
+
24
+ from headless_process import headless_popen_detached, headless_run # noqa: E402
25
+
26
+ CONFIG_REL = ".claude/reconcile.json"
27
+ ANCHOR_MARK = "<!--ev "
28
+ ISSUE_REF = re.compile(r"^issue:\d+$")
29
+ BOX_PREFIX = re.compile(r"^\s*[-*]\s*\[[ xX]\]\s*")
30
+ CACHE_TTL_SECS = 600
31
+ CACHE_MAX_AGE_SECS = 86400
32
+ LOCK_STALE_SECS = 600
33
+ LOCK_WAIT_SECS = 120
34
+ GIT_TIMEOUT_SECS = 3
35
+ MAX_ANCHORED_FILES = 50
36
+ MAX_CHARS = 1200
37
+ ROW_TEXT_CHARS = 60
38
+ ROW_DETAIL_CHARS = 60
39
+ SHOWN_STATUSES = ("DONE_BY_EVIDENCE", "CONTRADICTED")
40
+
41
+
42
+ def clip(text: str, limit: int) -> str:
43
+ text = " ".join(str(text).split())
44
+ return text if len(text) <= limit else text[: limit - 3] + "..."
45
+
46
+
47
+ def cache_dir() -> Path:
48
+ override = os.environ.get("RECONCILE_CACHE_DIR")
49
+ return Path(override) if override else Path.home() / ".claude" / ".reconcile_cache"
50
+
51
+
52
+ def cache_path(root: Path) -> Path:
53
+ key = hashlib.sha1(root.as_posix().lower().encode("utf-8")).hexdigest()[:16]
54
+ return cache_dir() / f"{key}.json"
55
+
56
+
57
+ def _git(root: Path, *args: str) -> subprocess.CompletedProcess | None:
58
+ try:
59
+ return headless_run(["git", "--no-optional-locks", "-C", str(root), *args], capture_output=True, text=True,
60
+ encoding="utf-8", errors="replace", timeout=GIT_TIMEOUT_SECS)
61
+ except (OSError, subprocess.SubprocessError):
62
+ return None
63
+
64
+
65
+ def git_root(cwd: str | Path) -> Path | None:
66
+ if not Path(cwd).is_dir():
67
+ return None
68
+ proc = _git(Path(cwd), "rev-parse", "--show-toplevel")
69
+ if proc is None or proc.returncode != 0 or not proc.stdout.strip():
70
+ return None
71
+ return Path(proc.stdout.strip())
72
+
73
+
74
+ def load_config(root: Path) -> dict | None:
75
+ path = root / CONFIG_REL
76
+ if not path.is_file():
77
+ return None
78
+ try:
79
+ data = json.loads(path.read_text(encoding="utf-8"))
80
+ except (OSError, ValueError):
81
+ return {"records": []}
82
+ return data if isinstance(data, dict) else {"records": []}
83
+
84
+
85
+ def _config_records(root: Path, entries: object) -> list[str]:
86
+ out: list[str] = []
87
+ for entry in entries if isinstance(entries, list) else []:
88
+ if not isinstance(entry, str) or not entry.strip():
89
+ continue
90
+ entry = entry.strip()
91
+ if ISSUE_REF.match(entry):
92
+ out.append(entry)
93
+ continue
94
+ path = Path(entry) if Path(entry).is_absolute() else root / entry
95
+ out.append(str(path))
96
+ return out
97
+
98
+
99
+ def _anchored_files(root: Path) -> list[str]:
100
+ proc = _git(root, "grep", "-l", "-F", "-e", ANCHOR_MARK, "--", "*.md")
101
+ if proc is None or proc.returncode != 0:
102
+ return []
103
+ names = [n for n in proc.stdout.splitlines() if n.strip()]
104
+ return [str(root / name) for name in names[:MAX_ANCHORED_FILES]]
105
+
106
+
107
+ def discover(root: Path) -> tuple[list[str], str | None]:
108
+ config = load_config(root)
109
+ if config is not None:
110
+ project = config.get("project")
111
+ return _config_records(root, config.get("records")), project if isinstance(project, str) else None
112
+ return _anchored_files(root), None
113
+
114
+
115
+ def read_cache(root: Path) -> dict | None:
116
+ try:
117
+ data = json.loads(cache_path(root).read_text(encoding="utf-8"))
118
+ except (OSError, ValueError):
119
+ return None
120
+ return data if isinstance(data, dict) and isinstance(data.get("generated"), (int, float)) else None
121
+
122
+
123
+ def write_cache(root: Path, data: dict) -> None:
124
+ path = cache_path(root)
125
+ path.parent.mkdir(parents=True, exist_ok=True)
126
+ tmp = path.with_suffix(f".{os.getpid()}.tmp")
127
+ tmp.write_text(json.dumps(data), encoding="utf-8")
128
+ os.replace(tmp, path)
129
+
130
+
131
+ def _lock_path(root: Path) -> Path:
132
+ return cache_path(root).with_suffix(".lock")
133
+
134
+
135
+ def refresh_running(root: Path) -> bool:
136
+ try:
137
+ return time.time() - _lock_path(root).stat().st_mtime < LOCK_STALE_SECS
138
+ except OSError:
139
+ return False
140
+
141
+
142
+ def _acquire(root: Path, wait_secs: float) -> bool:
143
+ path = _lock_path(root)
144
+ path.parent.mkdir(parents=True, exist_ok=True)
145
+ deadline = time.monotonic() + wait_secs
146
+ while True:
147
+ try:
148
+ os.close(os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY))
149
+ return True
150
+ except FileExistsError:
151
+ if not refresh_running(root):
152
+ path.unlink(missing_ok=True)
153
+ continue
154
+ except OSError:
155
+ return False
156
+ if time.monotonic() >= deadline:
157
+ return False
158
+ time.sleep(0.5)
159
+
160
+
161
+ def spawn_refresh(root: Path, apply: bool) -> bool:
162
+ cmd = [sys.executable, str(Path(__file__).resolve()), "run", "--root", str(root)] + (["--apply"] if apply else [])
163
+ try:
164
+ headless_popen_detached(cmd, cwd=str(root), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True)
165
+ except OSError:
166
+ return False
167
+ return True
168
+
169
+
170
+ def shown_rows(lines: list[dict]) -> list[dict]:
171
+ return [{"status": r["status"], "source": r["source"], "line": r["line"], "text": clip(BOX_PREFIX.sub("", r.get("text", "")), ROW_TEXT_CHARS),
172
+ "detail": clip(r.get("detail", ""), ROW_DETAIL_CHARS), "applied": bool(r.get("applied"))}
173
+ for r in lines if r.get("status") in SHOWN_STATUSES]
174
+
175
+
176
+ def refresh(root: Path, apply: bool) -> bool:
177
+ records, project = discover(root)
178
+ if not records:
179
+ return False
180
+ if not _acquire(root, LOCK_WAIT_SECS):
181
+ return False
182
+ try:
183
+ import reconcile_records
184
+ rows: list[dict] = []
185
+ for record in records:
186
+ result = reconcile_records.reconcile(record, project=project, apply=apply and bool(ISSUE_REF.match(record)), cwd=root)
187
+ rows += shown_rows(result["lines"])
188
+ write_cache(root, {"root": root.as_posix(), "generated": time.time(), "records": records, "rows": rows})
189
+ finally:
190
+ _lock_path(root).unlink(missing_ok=True)
191
+ return True
192
+
193
+
194
+ def _display_source(root: Path, source: str) -> str:
195
+ try:
196
+ return Path(source).relative_to(root).as_posix()
197
+ except ValueError:
198
+ return source
199
+
200
+
201
+ def _row_text(root: Path, row: dict) -> str:
202
+ where = f"{_display_source(root, row['source'])}:{row['line']}"
203
+ if row["status"] == "DONE_BY_EVIDENCE":
204
+ verdict = "box ticked automatically with an evidence note" if row["applied"] else "evidence says it is done; tick it in your next commit"
205
+ else:
206
+ verdict = "marked done but evidence says it is not"
207
+ return f"- {row['status']} {where} \"{row['text']}\" -- {verdict} ({row['detail']})"
208
+
209
+
210
+ def render(root: Path, cache: dict, now: float | None = None) -> str:
211
+ rows = cache.get("rows") or []
212
+ if not rows:
213
+ return ""
214
+ age_min = int(max((now or time.time()) - cache["generated"], 0) // 60)
215
+ header = f"STALE RECORDS: {len(rows)} line(s) disagree with evidence (checked {age_min} min ago)."
216
+ footer = f"Re-check: python {ENGINE.as_posix()} --records <file|issue:IID> --apply"
217
+ lines = [header]
218
+ budget = MAX_CHARS - len(header) - len(footer) - 40
219
+ used = 0
220
+ shown = 0
221
+ for row in rows:
222
+ text = _row_text(root, row)
223
+ if used + len(text) + 1 > budget:
224
+ break
225
+ lines.append(text)
226
+ used += len(text) + 1
227
+ shown += 1
228
+ if shown < len(rows):
229
+ lines.append(f"+{len(rows) - shown} more")
230
+ lines.append(footer)
231
+ return "\n".join(lines)[:MAX_CHARS]
232
+
233
+
234
+ def read_payload() -> dict:
235
+ try:
236
+ data = json.loads(sys.stdin.buffer.read().decode("utf-8", errors="replace") or "{}")
237
+ except (OSError, ValueError):
238
+ return {}
239
+ return data if isinstance(data, dict) else {}
240
+
241
+
242
+ def main(argv: list[str] | None = None) -> int:
243
+ parser = argparse.ArgumentParser(description="Background refresh of the stale-record cache")
244
+ sub = parser.add_subparsers(dest="cmd", required=True)
245
+ run = sub.add_parser("run")
246
+ run.add_argument("--root", required=True)
247
+ run.add_argument("--apply", action="store_true")
248
+ args = parser.parse_args(argv)
249
+ try:
250
+ refresh(Path(args.root), args.apply)
251
+ except Exception:
252
+ pass
253
+ return 0
254
+
255
+
256
+ if __name__ == "__main__":
257
+ sys.exit(main())