@yasaswy.nagavolu/agents 0.31.0 → 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 (56) hide show
  1. package/README.md +6 -3
  2. package/bin/cli.js +43 -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 +80 -0
  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/chat_exit.py +725 -0
  22. package/content/proxy/chat_exit_report.py +115 -0
  23. package/content/proxy/gitlab_mutation_guard.py +5 -3
  24. package/content/proxy/html_mocker_monitor_guard.py +95 -4
  25. package/content/proxy/litellm/start.ps1 +1 -1
  26. package/content/proxy/log_retention.py +1 -0
  27. package/content/proxy/mem_sampler.py +54 -8
  28. package/content/proxy/register_mem_sampler.ps1 +6 -3
  29. package/content/proxy/register_task.ps1 +1 -1
  30. package/content/scripts/reconcile_records.py +539 -0
  31. package/content/scripts/tests/test_reconcile_records.py +408 -0
  32. package/content/skills/ci-runner/SKILL.md +4 -3
  33. package/content/skills/ci-runner/ci-runner-pool.md +61 -0
  34. package/content/skills/low-ram-advisor/SKILL.md +3 -3
  35. package/content/skills/low-ram-advisor/memwatch.py +4 -4
  36. package/content/skills/low-ram-advisor/ram_notice.py +22 -6
  37. package/content/skills/low-ram-advisor/tests/test_memwatch.py +12 -3
  38. package/content/skills/low-ram-advisor/tests/test_ram_notice.py +18 -5
  39. package/content/statusline/statusline-command.ps1 +5 -1
  40. package/content/statusline/statusline-command.py +6 -2
  41. package/lib/bypassOnly.js +4 -2
  42. package/lib/doctor.js +4 -0
  43. package/lib/pwshStore.js +171 -0
  44. package/lib/runner/banner.js +159 -0
  45. package/lib/runner/cap.js +1 -0
  46. package/lib/runner/dockerChecks.js +84 -0
  47. package/lib/runner/gitlab.js +25 -0
  48. package/lib/runner/hints.js +8 -0
  49. package/lib/runner/index.js +62 -5
  50. package/lib/runner/janitorTask.js +36 -9
  51. package/lib/runner/profiles/linuxDocker.js +8 -3
  52. package/lib/runner/result.js +1 -1
  53. package/lib/runner/stableCli.js +130 -0
  54. package/lib/secretsPrompt.js +1 -1
  55. package/lib/secretsSet.js +68 -0
  56. package/package.json +1 -1
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');
@@ -228,9 +229,9 @@ than bypassPermissions (for example "dontAsk" or "auto"), which silently downgra
228
229
  --fix removes the key from settings.local.json only; a committed settings.json is reported, never edited.
229
230
 
230
231
  doctor also checks <target>/settings.json for bypassPermissions only with no auto mode: permissions.defaultMode
231
- "bypassPermissions", permissions.disableAutoMode "disable", skipDangerousModePermissionPrompt true,
232
- useAutoModeDuringPlan false, and no permissions.disableBypassPermissionsMode. --fix (and every update) sets
233
- 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.
234
235
 
235
236
  doctor reports, without changing anything: orphans (files/directories sitting inside
236
237
  a path this CLI manages that the ledger does not claim — e.g. a stale file left behind
@@ -679,6 +680,7 @@ async function runInteractiveMenu({ advanced, targetDir, targetConfig, noSecrets
679
680
  runSelfProfileStepsIfNeeded({ profile, targetDir });
680
681
  runMemSamplerStep({ targetDir, noScheduledTasks });
681
682
  }
683
+ await runRunnerBannerStep({ bundleKeys: installedBundles.map((b) => b.key), targetDir });
682
684
 
683
685
  printFinalSummary({ installed: installedResults, skipped, targetBase: targetDir || defaultTargetBase() });
684
686
 
@@ -734,6 +736,7 @@ async function runInstall(argv, { captureSelection = false } = {}) {
734
736
  runMemSamplerStep({ targetDir: args.targetDir, noScheduledTasks: args.noScheduledTasks });
735
737
  printPythonSyncIssues([result]);
736
738
  printModVersionWarnings([args.bundle], result.targetBase);
739
+ await runRunnerBannerStep({ bundleKeys: [args.bundle], targetDir: args.targetDir });
737
740
  return 0;
738
741
  } catch (err) {
739
742
  if (err instanceof InstallError || err instanceof ManifestError || err instanceof LedgerError || err instanceof WiringError) {
@@ -744,6 +747,15 @@ async function runInstall(argv, { captureSelection = false } = {}) {
744
747
  }
745
748
  }
746
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
+
747
759
  function parseUninstallArgs(argv) {
748
760
  const args = { bundle: null, yes: false, targetDir: null, targetConfig: null };
749
761
  for (let i = 0; i < argv.length; i += 1) {
@@ -889,6 +901,11 @@ function parseSecretsArgs(argv) {
889
901
  } else if (arg === '--remove') {
890
902
  args.remove = argv[i + 1];
891
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;
892
909
  } else if (arg === '--purge-unused') {
893
910
  args.purgeUnused = true;
894
911
  } else if (arg === '--yes') {
@@ -927,7 +944,7 @@ async function runSecrets(argv) {
927
944
  args = parseSecretsArgs(argv);
928
945
  } catch (err) {
929
946
  console.error(err.message);
930
- return 1;
947
+ return err.exitCode || 1;
931
948
  }
932
949
 
933
950
  const targetBase = args.targetDir || defaultTargetBase();
@@ -947,6 +964,16 @@ async function runSecrets(argv) {
947
964
  return 0;
948
965
  }
949
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
+
950
977
  if (args.purgeUnused) {
951
978
  const stillNeeded = secretsStillNeeded(targetBase, manifest);
952
979
  const { values } = readSecrets(targetBase);
@@ -997,7 +1024,7 @@ async function runSecrets(argv) {
997
1024
  const keys = installedBundleKeys(targetBase, pkg.version);
998
1025
  bundles = keys.map((key) => findBundle(manifest, key)).filter(Boolean);
999
1026
  if (bundles.length === 0) {
1000
- 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`);
1001
1028
  return 0;
1002
1029
  }
1003
1030
  }
@@ -1524,6 +1551,15 @@ function runDoctor(argv) {
1524
1551
  for (const f of p.findings) console.log(` ${mark('fail')} ${f}`);
1525
1552
  };
1526
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
+
1527
1563
  const printRoutingMod = () => {
1528
1564
  if (!result.routingMod) return;
1529
1565
  console.log('\nModel routing:');
@@ -1540,6 +1576,7 @@ function runDoctor(argv) {
1540
1576
  printRoutingMod();
1541
1577
  printMemorySafety();
1542
1578
  printPortal();
1579
+ printPwshStore();
1543
1580
  printModeDrift();
1544
1581
  return 0;
1545
1582
  }
@@ -1563,6 +1600,7 @@ function runDoctor(argv) {
1563
1600
  printRoutingMod();
1564
1601
  printMemorySafety();
1565
1602
  printPortal();
1603
+ printPwshStore();
1566
1604
  printProjectHooks();
1567
1605
  printPythonLaunchReport(py);
1568
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())