@yasaswy.nagavolu/agents 0.27.3 → 0.28.1

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 (35) hide show
  1. package/README.md +6 -1
  2. package/bin/cli.js +110 -13
  3. package/content/global/CLAUDE.md +8 -5
  4. package/content/global/hooks/compact_context.py +156 -0
  5. package/content/manifest.json +286 -1
  6. package/content/proxy/README.md +28 -14
  7. package/content/proxy/bg_process_reaper_hook.py +17 -41
  8. package/content/proxy/bg_process_register_hook.py +10 -5
  9. package/content/proxy/bg_process_registry.py +102 -139
  10. package/content/proxy/chat_inbox_hook.py +64 -0
  11. package/content/proxy/chat_ledger.py +633 -0
  12. package/content/proxy/mem_sampler.py +492 -0
  13. package/content/proxy/memory_reclaim.py +497 -0
  14. package/content/proxy/memory_reclaim_hook.py +86 -0
  15. package/content/proxy/proc_policy.py +376 -0
  16. package/content/proxy/reaper_kill_hook.py +179 -0
  17. package/content/proxy/register_mem_sampler.ps1 +75 -0
  18. package/content/skills/README.md +4 -0
  19. package/content/skills/heavy-gate-runner/SKILL.md +56 -0
  20. package/content/skills/heavy-gate-runner/heavy_gate_runner.py +741 -0
  21. package/content/skills/heavy-gate-runner/tests/conftest.py +5 -0
  22. package/content/skills/heavy-gate-runner/tests/test_heavy_gate_runner.py +524 -0
  23. package/content/skills/low-ram-advisor/SKILL.md +3 -3
  24. package/content/skills/low-ram-advisor/advisor.py +2 -2
  25. package/lib/codex-hook-adapter.js +3 -2
  26. package/lib/codex-trust.js +5 -1
  27. package/lib/codex.js +8 -3
  28. package/lib/doctor.js +7 -2
  29. package/lib/memSafety.js +247 -0
  30. package/lib/modelsApply.js +57 -4
  31. package/lib/prepack.js +28 -2
  32. package/lib/selfProfile.js +6 -1
  33. package/lib/uninstall.js +13 -0
  34. package/lib/wiring.js +38 -4
  35. package/package.json +1 -1
package/README.md CHANGED
@@ -16,6 +16,10 @@ a reviewed Codex contract, are retained as inert compatibility assets and listed
16
16
  in Codex's compatibility report. New skills and agents are discovered during
17
17
  updates; new hook scripts are discovered when their Claude hook registration or
18
18
  adjacent `.deploy.json` declares the event and command.
19
+ Windows releases verify NPX-installed Codex hooks before and after publication in a guarded private home, including native trust, PowerShell/cmd execution, repeat installation, and unchanged live configuration.
20
+
21
+ Generated Codex hook commands use a UTF-8 base64 bootstrap so adapter paths and
22
+ hook commands survive PowerShell, `cmd.exe`, and POSIX shell parsing.
19
23
 
20
24
  `install` opens an interactive checkbox menu of purpose-based bundles when
21
25
  run in a terminal, or installs one bundle non-interactively via
@@ -97,7 +101,7 @@ agents-cli install
97
101
  secrets`). Add `--json` for a machine-readable result that never contains a
98
102
  token. Exit codes: 0 ok, 1 a step failed, 2 usage error.
99
103
  - `agents-cli models usage [--days N] [--json] [--target-dir <path>]` — read-only report of dispatch counts and share per role, from the guard's dispatch log (`logs/agent_dispatch.jsonl`, which records `model` and `role` per dispatch); a missing or empty log prints a note and exits 0.
100
- - `agents-cli models apply [--dry-run] [--target-dir <path>]` — stamp `models.json` into the static consumers: the `model:` of every deployed agent file carrying a `role:` key, and each `settingsStamp` entry (default `env.CLAUDE_CODE_SUBAGENT_MODEL`) in `settings.json`. `models.json` itself ships as a normal bundle file (a local edit survives `update` unless `--theirs`); `install` and `update` run the same step automatically. `--dry-run` prints the diff and writes nothing; the settings `model` key and any key outside `settingsStamp` are never touched. To roll a model back, change that role's id in `~/.claude/models.json` and run it.
104
+ - `agents-cli models apply [--dry-run] [--target-dir <path>]` — stamp `models.json` into the static consumers: the `model:` of every deployed agent file carrying a `role:` key, each `settingsStamp` entry (default `env.CLAUDE_CODE_SUBAGENT_MODEL`) in `settings.json`, and the `Current:` text between the `<!--models-->` markers of `CLAUDE.md`. `models apply --source <repo>` restamps `global/CLAUDE.md` of a repo checkout from its `config/models.json`. `models.json` itself ships as a normal bundle file (a local edit survives `update` unless `--theirs`); `install` and `update` run the same step automatically. `--dry-run` prints the diff and writes nothing; the settings `model` key and any key outside `settingsStamp` are never touched. To roll a model back, change that role's id in `~/.claude/models.json` and run it.
101
105
  - `agents-cli doctor [--fix] [--scan-root <dir>] [--json]` — report orphaned, missing and drifted
102
106
  files under the install target, plus project hooks in the repo's `.claude/settings.json` and
103
107
  `settings.local.json` whose script file is missing or that are bare `python <repo>/.claude/hooks/x.py`
@@ -123,6 +127,7 @@ agents-cli install
123
127
  (Claude Code only matches `Edit(<path>)` for file writes); `--fix`, the `project_hook_repair.js` hook and the
124
128
  `--fix-project-hooks` flag of `install`/`update` rewrite them to `Edit(<path>)` in `settings.local.json` with duplicates
125
129
  dropped, a committed `settings.json` is reported and never edited, bare `Write`/`NotebookEdit` are left alone.
130
+ - `agents-cli sampler <status|register|unregister> [--dry-run] [--target-dir <path>]` — the hidden `ClaudeMemSampler` Windows logon task of the memory-safety stack. `install` and `update` register or start it on their own when the stack is installed (idempotent, hidden, default `~/.claude` install only, skipped under `NODE_ENV=test`; `--no-scheduled-tasks` or `AGENTS_CLI_NO_SCHEDULED_TASKS=1` skips it). `--dry-run` runs `register_mem_sampler.ps1` with `-WhatIf` and changes nothing. `doctor` adds a "Memory-safety stack" block (task, wired hooks, budget file, newest sample in `logs/mem-samples.jsonl`) and exits 1 on a missing task, an unwired hook, an invalid budget file or a stale sample. See [`docs/memory-safety.md`](../../docs/memory-safety.md).
126
131
  - `agents-cli --help` — show usage
127
132
 
128
133
  ### The interactive menu
package/bin/cli.js CHANGED
@@ -18,7 +18,7 @@ const { formatVersionBanner } = require('../lib/version-banner');
18
18
  const { bundleInstallState, installChip, installDetailLine, chipIsChange } = require('../lib/install-state');
19
19
  const { ledgerPath } = require('../lib/ledger');
20
20
  const { WiringError, expectedWiringRecordsForManifest } = require('../lib/wiring');
21
- const { applyModels, formatPlan, ModelsError } = require('../lib/modelsApply');
21
+ const { applyModels, applySourceModels, formatPlan, ModelsError } = require('../lib/modelsApply');
22
22
  const { dispatchUsage, formatUsage } = require('../lib/modelsUsage');
23
23
  const {
24
24
  basicMenuBundles,
@@ -42,6 +42,7 @@ const permissionRules = require('../lib/permissionRules');
42
42
  const pythonHooks = require('../lib/pythonHooks');
43
43
  const pyrun = require('../lib/pyrun');
44
44
  const { checkModVersions } = require('../lib/claudeVersion');
45
+ const memSafety = require('../lib/memSafety');
45
46
 
46
47
  const PACKAGE_ROOT = path.join(__dirname, '..');
47
48
  // One styler for the whole process: colors on only for a real TTY stdout
@@ -74,15 +75,20 @@ Usage:
74
75
  under <dir>); --fix-project-hooks rewrites them to the fail-open launcher.
75
76
  Also reports a project defaultMode weaker than the global one; with
76
77
  --fix-project-hooks it is removed from settings.local.json
77
- agents-cli models apply [--dry-run] [--target-dir <path>] Stamp models.json roles into agent frontmatter (model:) and the
78
- settingsStamp keys of settings.json; --dry-run prints the diff and writes nothing
79
- (also runs on every install and update)
78
+ agents-cli models apply [--dry-run] [--target-dir <path>] Stamp models.json roles into agent frontmatter (model:), the
79
+ settingsStamp keys of settings.json and the <!--models--> fragment of CLAUDE.md;
80
+ --dry-run prints the diff and writes nothing (also runs on every install and update)
81
+ agents-cli models apply --source <repo> [--dry-run] Restamp global/CLAUDE.md of a repo checkout from its config/models.json
80
82
  agents-cli models usage [--days N] [--json] [--target-dir <path>] Dispatch counts and share per role, read from the guard's dispatch log (read-only)
81
83
  agents-cli secrets Prompt for any missing secrets across all installed bundles
82
84
  agents-cli secrets --bundle <key> Prompt for missing secrets for one bundle
83
85
  agents-cli secrets --list Show which secrets are set/missing (names only — never values)
84
86
  agents-cli doctor [--fix] [--scan-root <dir>] Report orphaned/missing/drifted files under the install target
85
87
  and project hooks that would brick a session if their file went missing
88
+ agents-cli sampler <status|register|unregister> [--dry-run] [--target-dir <path>]
89
+ The hidden ClaudeMemSampler task of the memory-safety stack (Windows).
90
+ install/update register it on their own for the default ~/.claude install;
91
+ --dry-run runs the registration script with -WhatIf and changes nothing
86
92
  agents-cli runner <sub> [flags] Install and manage a self-hosted GitLab CI runner (see "Flags for runner")
87
93
  agents-cli --help Show this help
88
94
 
@@ -94,6 +100,7 @@ Runtime deployment:
94
100
  Flags for install:
95
101
  --bundle <key> Bundle to install non-interactively — run "install" with no flags to list keys
96
102
  --yes Required with --bundle: confirms the non-interactive install
103
+ --no-scheduled-tasks Skip registering the hidden ClaudeMemSampler task (also on update)
97
104
  --advanced Interactive menu: show every bundle (incl. advanced) and pick items within one
98
105
  --profile <public|self> Which bundles the menu/listing offers (default: public). "self" adds this
99
106
  repo's maintainer-only bundles (self-infra, self-skills, ...) on top of the
@@ -172,6 +179,11 @@ Flags for runner:
172
179
  Needs a GitLab PAT in GITLAB_RUNNER_PAT (or GITLAB_TOKEN): set it with "agents-cli secrets".
173
180
  Exit codes: 0 ok, 1 a step failed, 2 usage error.
174
181
 
182
+ Memory-safety stack: the agent-orchestration bundle carries the chat ledger, the idle-process reclaimer, the
183
+ reaper_kill recorder, the heavy gate runner and the sampler. On Windows, install/update register the hidden
184
+ ClaudeMemSampler logon task (idempotent, never a visible window, only for the default ~/.claude install, never
185
+ under NODE_ENV=test). doctor reports the task, the wired hooks, the budget file and the newest memory sample.
186
+
175
187
  Flags for doctor:
176
188
  --target-dir <path> Install target base, default ~/.claude (use for testing)
177
189
  --json Print a machine-readable report instead of prose
@@ -210,7 +222,7 @@ deletes or modifies anything; deciding what to do about a finding is a separate
210
222
  }
211
223
 
212
224
  function parseInstallArgs(argv) {
213
- const args = { bundle: null, yes: false, targetDir: null, targetConfig: null, advanced: false, noSecrets: false, profile: 'public' };
225
+ const args = { bundle: null, yes: false, targetDir: null, targetConfig: null, advanced: false, noSecrets: false, noScheduledTasks: false, profile: 'public' };
214
226
  for (let i = 0; i < argv.length; i += 1) {
215
227
  const arg = argv[i];
216
228
  if (arg === '--bundle') {
@@ -231,6 +243,8 @@ function parseInstallArgs(argv) {
231
243
  } else if (arg === '--profile') {
232
244
  args.profile = argv[i + 1];
233
245
  i += 1;
246
+ } else if (arg === '--no-scheduled-tasks') {
247
+ args.noScheduledTasks = true;
234
248
  } else {
235
249
  throw new InstallError(`Unknown install flag: ${arg}`);
236
250
  }
@@ -312,6 +326,25 @@ function runSelfProfileStepsIfNeeded({ profile, targetDir }) {
312
326
  return result;
313
327
  }
314
328
 
329
+ /**
330
+ * Register (or start) the hidden ClaudeMemSampler task when the memory-safety stack is installed.
331
+ * Idempotent; Windows and the default ~/.claude install only. Never throws: a failure is reported, not fatal.
332
+ */
333
+ function runMemSamplerStep({ targetDir, noScheduledTasks = false, quiet = false }) {
334
+ const targetBase = targetDir || defaultTargetBase();
335
+ const ledger = readLedgerSafely(targetBase);
336
+ if (!memSafety.stackInstalled(ledger)) return { action: 'skipped', message: 'memory-safety stack not installed.' };
337
+ const env = noScheduledTasks ? { ...process.env, AGENTS_CLI_NO_SCHEDULED_TASKS: '1' } : process.env;
338
+ let result;
339
+ try {
340
+ result = memSafety.ensureSampler({ targetBase, env });
341
+ } catch (err) {
342
+ result = { action: 'failed', message: `sampler registration error: ${err.message}` };
343
+ }
344
+ if (!quiet && !['skipped', 'blocked'].includes(result.action)) console.log(`\nMemory sampler: ${result.message}`);
345
+ return result;
346
+ }
347
+
315
348
  /**
316
349
  * Builds an install.js progress callback that renders a live, in-place
317
350
  * (\r-redrawn) pip-style bar while files are copied — but only when stdout
@@ -530,7 +563,7 @@ function fetchLatestVersion(pkgName, { timeoutMs = 1500 } = {}) {
530
563
  });
531
564
  }
532
565
 
533
- async function runInteractiveMenu({ advanced, targetDir, targetConfig, noSecrets, profile, captureSelection = false }) {
566
+ async function runInteractiveMenu({ advanced, targetDir, targetConfig, noSecrets, noScheduledTasks, profile, captureSelection = false }) {
534
567
  const { manifest, manifestPath } = loadManifest(PACKAGE_ROOT);
535
568
  const repoRoot = path.dirname(manifestPath);
536
569
  const candidateBundles = advanced ? advancedMenuBundles(manifest, profile) : basicMenuBundles(manifest, profile);
@@ -620,6 +653,7 @@ async function runInteractiveMenu({ advanced, targetDir, targetConfig, noSecrets
620
653
 
621
654
  if (installedBundles.length > 0) {
622
655
  runSelfProfileStepsIfNeeded({ profile, targetDir });
656
+ runMemSamplerStep({ targetDir, noScheduledTasks });
623
657
  }
624
658
 
625
659
  printFinalSummary({ installed: installedResults, skipped, targetBase: targetDir || defaultTargetBase() });
@@ -646,6 +680,7 @@ async function runInstall(argv, { captureSelection = false } = {}) {
646
680
  targetDir: args.targetDir,
647
681
  targetConfig: args.targetConfig,
648
682
  noSecrets: args.noSecrets,
683
+ noScheduledTasks: args.noScheduledTasks,
649
684
  profile: args.profile,
650
685
  captureSelection,
651
686
  });
@@ -672,6 +707,7 @@ async function runInstall(argv, { captureSelection = false } = {}) {
672
707
  manifest,
673
708
  });
674
709
  runSelfProfileStepsIfNeeded({ profile: args.profile, targetDir: args.targetDir });
710
+ runMemSamplerStep({ targetDir: args.targetDir, noScheduledTasks: args.noScheduledTasks });
675
711
  printPythonSyncIssues([result]);
676
712
  printModVersionWarnings([args.bundle], result.targetBase);
677
713
  return 0;
@@ -968,7 +1004,7 @@ async function runSecrets(argv) {
968
1004
  }
969
1005
 
970
1006
  function parseUpdateArgs(argv) {
971
- const args = { bundle: null, yes: false, targetDir: null, targetConfig: null, json: false, theirs: false, keepMine: false };
1007
+ const args = { bundle: null, yes: false, targetDir: null, targetConfig: null, json: false, theirs: false, keepMine: false, noScheduledTasks: false };
972
1008
  for (let i = 0; i < argv.length; i += 1) {
973
1009
  const arg = argv[i];
974
1010
  if (arg === '--bundle') {
@@ -988,6 +1024,8 @@ function parseUpdateArgs(argv) {
988
1024
  args.theirs = true;
989
1025
  } else if (arg === '--keep-mine') {
990
1026
  args.keepMine = true;
1027
+ } else if (arg === '--no-scheduled-tasks') {
1028
+ args.noScheduledTasks = true;
991
1029
  } else {
992
1030
  throw new UpdateError(`Unknown update flag: ${arg}`);
993
1031
  }
@@ -1062,6 +1100,8 @@ async function runUpdate(argv) {
1062
1100
  mcpConfigPath: args.targetConfig,
1063
1101
  });
1064
1102
 
1103
+ result.memSampler = runMemSamplerStep({ targetDir: args.targetDir, noScheduledTasks: args.noScheduledTasks, quiet: true });
1104
+
1065
1105
  if (args.json) {
1066
1106
  console.log(JSON.stringify(result, null, 2));
1067
1107
  return result.exitCode;
@@ -1086,6 +1126,7 @@ async function runUpdate(argv) {
1086
1126
  }
1087
1127
  }
1088
1128
 
1129
+ if (!['skipped', 'blocked'].includes(result.memSampler.action)) console.log(`Memory sampler: ${result.memSampler.message}`);
1089
1130
  printModelsReport(result.models);
1090
1131
  printPythonSyncIssues(result.bundles);
1091
1132
  printModVersionWarnings(result.bundles.map((b) => b.bundle), result.targetBase);
@@ -1111,6 +1152,7 @@ async function runUpdate(argv) {
1111
1152
  function runModels(argv) {
1112
1153
  const [sub, ...rest] = argv;
1113
1154
  let targetDir = null;
1155
+ let sourceRoot = null;
1114
1156
  let dryRun = false;
1115
1157
  let days = null;
1116
1158
  let json = false;
@@ -1127,6 +1169,9 @@ function runModels(argv) {
1127
1169
  } else if (rest[i] === '--target-dir') {
1128
1170
  targetDir = rest[i + 1];
1129
1171
  i += 1;
1172
+ } else if (rest[i] === '--source') {
1173
+ sourceRoot = rest[i + 1];
1174
+ i += 1;
1130
1175
  } else if (rest[i] === '--dry-run') {
1131
1176
  dryRun = true;
1132
1177
  } else {
@@ -1141,25 +1186,26 @@ function runModels(argv) {
1141
1186
  return 0;
1142
1187
  }
1143
1188
  if (sub !== 'apply') {
1144
- console.error('Usage: agents-cli models apply [--dry-run] [--target-dir <path>] | models usage [--days N] [--json]');
1189
+ console.error('Usage: agents-cli models apply [--dry-run] [--target-dir <path> | --source <repo>] | models usage [--days N] [--json]');
1145
1190
  return 1;
1146
1191
  }
1147
1192
  try {
1148
- const ledger = loadLedger(targetBase, pkg.version);
1149
- const result = applyModels({ targetBase, ledger, dryRun });
1193
+ const ledger = sourceRoot ? null : loadLedger(targetBase, pkg.version);
1194
+ const result = sourceRoot ? applySourceModels({ repoRoot: sourceRoot, dryRun }) : applyModels({ targetBase, ledger, dryRun });
1150
1195
  if (!result.applied) {
1151
- console.log(`No models.json at ${targetBase} — install a bundle first.`);
1196
+ console.log(sourceRoot ? `No config/models.json at ${sourceRoot}.` : `No models.json at ${targetBase} — install a bundle first.`);
1152
1197
  return 1;
1153
1198
  }
1154
1199
  if (dryRun) {
1155
1200
  for (const line of formatPlan(result)) console.log(line);
1156
1201
  } else {
1157
- saveLedger(targetBase, ledger);
1202
+ if (ledger) saveLedger(targetBase, ledger);
1158
1203
  for (const a of result.agents) console.log(`${mark('ok')} ${a.file}: model ${a.to}`);
1159
1204
  for (const s of result.settings) console.log(`${mark('ok')} settings.json ${s.key} set to ${s.to}`);
1205
+ for (const i of result.instructions) console.log(`${mark('ok')} ${i.file}: ${i.to}`);
1160
1206
  }
1161
1207
  for (const w of result.warnings) console.log(`${mark('skip')} ${w}`);
1162
- if (result.agents.length === 0 && result.settings.length === 0) console.log('Already in sync with models.json.');
1208
+ if (result.agents.length === 0 && result.settings.length === 0 && result.instructions.length === 0) console.log('Already in sync with models.json.');
1163
1209
  else if (dryRun) console.log('(dry run: nothing written)');
1164
1210
  return 0;
1165
1211
  } catch (err) {
@@ -1394,6 +1440,15 @@ function runDoctor(argv) {
1394
1440
  for (const f of m.findings) console.log(` ${memoryIndexCheck.describe(f)}`);
1395
1441
  };
1396
1442
 
1443
+ const printMemorySafety = () => {
1444
+ const m = result.memorySafety;
1445
+ if (!m) return;
1446
+ console.log('\nMemory-safety stack:');
1447
+ for (const line of memSafety.describeMemorySafety(m)) console.log(` ${line}`);
1448
+ for (const f of m.findings) console.log(` ${mark('fail')} ${f}`);
1449
+ for (const w of m.warnings) console.log(` ${mark('skip')} ${w}`);
1450
+ };
1451
+
1397
1452
  const printRoutingMod = () => {
1398
1453
  if (!result.routingMod) return;
1399
1454
  console.log('\nModel routing:');
@@ -1408,6 +1463,7 @@ function runDoctor(argv) {
1408
1463
  printModValidation();
1409
1464
  printMemoryIndex();
1410
1465
  printRoutingMod();
1466
+ printMemorySafety();
1411
1467
  printModeDrift();
1412
1468
  return 0;
1413
1469
  }
@@ -1429,6 +1485,7 @@ function runDoctor(argv) {
1429
1485
  printModValidation();
1430
1486
  printMemoryIndex();
1431
1487
  printRoutingMod();
1488
+ printMemorySafety();
1432
1489
  printProjectHooks();
1433
1490
  printPythonLaunchReport(py);
1434
1491
  printModeDrift();
@@ -1442,6 +1499,42 @@ function runDoctor(argv) {
1442
1499
  }
1443
1500
  }
1444
1501
 
1502
+ function runSampler(argv) {
1503
+ const [sub, ...rest] = argv;
1504
+ let targetDir = null;
1505
+ let dryRun = false;
1506
+ for (let i = 0; i < rest.length; i += 1) {
1507
+ if (rest[i] === '--target-dir') {
1508
+ targetDir = rest[i + 1];
1509
+ i += 1;
1510
+ } else if (rest[i] === '--dry-run') dryRun = true;
1511
+ else {
1512
+ console.error(`Unknown sampler flag: ${rest[i]}`);
1513
+ return 1;
1514
+ }
1515
+ }
1516
+ const targetBase = targetDir || defaultTargetBase();
1517
+ if (sub === 'status') {
1518
+ const { manifest } = loadManifest(PACKAGE_ROOT);
1519
+ const ledger = readLedgerSafely(targetBase);
1520
+ const report = memSafety.checkMemorySafety({ manifest, ledger, targetBase });
1521
+ if (!report) {
1522
+ console.log('memory-safety stack not installed.');
1523
+ return 0;
1524
+ }
1525
+ for (const line of memSafety.describeMemorySafety(report)) console.log(line);
1526
+ for (const f of report.findings) console.log(`${mark('fail')} ${f}`);
1527
+ return report.healthy ? 0 : 1;
1528
+ }
1529
+ if (sub === 'register' || sub === 'unregister') {
1530
+ const result = sub === 'register' ? memSafety.ensureSampler({ targetBase, dryRun, force: !!targetDir }) : memSafety.unregisterSampler({ targetBase, dryRun });
1531
+ console.log(result.message);
1532
+ return result.action === 'failed' ? 1 : 0;
1533
+ }
1534
+ console.error('Usage: agents-cli sampler <status|register|unregister> [--dry-run] [--target-dir <path>]');
1535
+ return 1;
1536
+ }
1537
+
1445
1538
  async function main(argv, { captureSelection = false } = {}) {
1446
1539
  const [command, ...rest] = argv;
1447
1540
  if (['install','update','uninstall','doctor'].includes(command)) {
@@ -1490,6 +1583,10 @@ async function main(argv, { captureSelection = false } = {}) {
1490
1583
  return runModels(rest);
1491
1584
  }
1492
1585
 
1586
+ if (command === 'sampler') {
1587
+ return runSampler(rest);
1588
+ }
1589
+
1493
1590
  if (command === 'runner') {
1494
1591
  return require('../lib/runner').runRunnerCommand(rest);
1495
1592
  }
@@ -5,7 +5,7 @@ When doing bug fixes, always start with reproducing the bug in an E2E setting as
5
5
  Use git CLI for GitLab access, never glab — we use GitLab, not GitHub.
6
6
  Always track multi-step work with TaskCreate/TaskList/TaskUpdate (persistent across sessions), falling back to TodoWrite only if Task tools are unavailable — never printed markdown checklists. Maintain the TODO list and update the one PRD gitlab issue or the MR for that chat session.
7
7
  When planning or modifying work, start a wayfinder map for anything too big for one session, and always mirror the TODO items in that work's PRD/issue ticket so it stays current.
8
- Never `taskkill /F` or force-stop a shared daemon or another session's process — it can be serving other concurrent chats too (confirmed incident: killing the shared router mid-session broke every other active chat); restart it gracefully via its own scheduled task instead.
8
+ Never `taskkill /F` or force-stop a shared daemon or another session's process — it can be serving other concurrent chats too (confirmed incident: killing the shared router mid-session broke every other active chat); restart it gracefully via its own scheduled task instead; the one exception is ledger-proven idle processes stopped by the reclaimer per docs/memory-safety.md.
9
9
  Never open a visible window or steal focus: every command, script, scheduled task, or browser I launch (PowerShell, cmd, terminals, `Start-Process`, `start`, `wt`, headed Playwright/Chrome) must run headless/hidden in the background (`-WindowStyle Hidden`/`-NoNewWindow`, `pythonw`, hidden task settings, headless browser) unless the founder explicitly asked to watch it; a popup that grabs focus is a defect (repeated, confirmed founder complaint).
10
10
  Grill the operator once per new goal to lock scope and shared understanding; once scope is locked, execute autonomously end-to-end without re-confirming each step — grilling gates scope, not execution.
11
11
  Never open a git issue by yourself you need to explain the issue with complete context concisely in terms of customer facing functionality so user can take a decision if this is really an issue. User also want you to find out with thorough investigation if this is really an issue as the pending git issues spam is a real problem.
@@ -23,7 +23,7 @@ Be extremely proactive to take up the tasks from our pending list of tasks. Look
23
23
 
24
24
  The main chat model is the founder's choice (`/model`); it is a scarce orchestration and planning resource, so subagents run only on the two roles below, never on the main-chat models.
25
25
 
26
- Roles resolve to model IDs in `~/.claude/models.json` (repo `config/models.json`) — the one place an ID lives; change a role there, then run `agents-cli models apply`, to switch or roll back. Current: worker `claude-sonnet-5-5`, assistant `claude-haiku-5-5` (main-chat models: `claude-opus-5-5`, `claude-fable-5-1`).
26
+ Roles resolve to model IDs in `~/.claude/models.json` (repo `config/models.json`) — the one place an ID lives; change a role there, then run `agents-cli models apply`, to switch or roll back. <!--models-->Current: worker `claude-sonnet-5-5`, assistant `claude-haiku-5-5` (main-chat models: `claude-opus-5-5`, `claude-fable-5-1`)<!--/models-->.
27
27
 
28
28
  | Role | Work | Subagent |
29
29
  |---|---|---|
@@ -37,7 +37,8 @@ Standalone non-Claude subagents (an agent whose entire multi-turn loop runs as a
37
37
 
38
38
  - Fan-out is the standing default, never a per-request instruction: anything not already in context (a new error, screenshot, log, file, ticket, git/AWS state) is looked up by a subagent that returns conclusions and saves them to one-brain; the main loop opens nothing itself except the one line a decision needs.
39
39
  - Dispatch threshold: if the deliverable is > ~30 lines of file content, or > 2 mechanical steps (or any step whose raw output isn't needed verbatim for a decision), it goes to a subagent (worker by default, per the rule above) that returns conclusions only, never raw file dumps. Main loop holds only: reads needed for decisions, dispatch, review, and small edits to decision docs.
40
- - On Agent/Task dispatch without a custom agent, `agent_model_guard.py` injects the model from models.json: types listed in `typeRoles` (`Explore`, `claude-code-guide`, `statusline-setup`) -> `assistant`, every other type -> `worker`; any model outside the worker roles is rewritten, and any dispatch resolving to a main-chat model (opus/fable family) becomes `worker` in every project. A bare `sonnet`/`haiku` alias maps through the config `aliases`. Registered agents carry `role:` (stamped into `model:` by `agents-cli models apply`; the guard injects the live role model and drops any explicit `model` param). The bare `model:` tool parameter is schema-restricted to `sonnet`/`opus`/`haiku`/`fable` for unregistered dispatch types (`Explore`, `general-purpose`, `claude`), so any non-Claude slug there fails tool-schema validation. A non-Claude model needs a REGISTERED project-specific agent whose own frontmatter names it. Custom agents that specify their own model override this table.
40
+ - On Agent/Task dispatch never pass `model` or `effort`: the `agent_model_guard.py` hook and `model-routing` mod set the model from `models.json` (unregistered types -> worker; `Explore`, `claude-code-guide`, `statusline-setup` -> assistant; a requested opus/fable -> worker in every project) and effort defaults to `high`.
41
+ - A registered agent's `role:` (stamped into `model:` by `agents-cli models apply`) governs its model; its own `model:` is respected only if it is not an opus/fable family. A non-Claude model needs a registered agent whose own `model:` names it.
41
42
  - Loop shape: the main chat plans → a subagent executes → the main chat adversarially reviews → return to user or re-instruct subagents.
42
43
 
43
44
  ## Memory-First (every session)
@@ -48,6 +49,8 @@ At the start of every session, before substantive work, call `mcp__claude_ai_one
48
49
 
49
50
  **Surprise logging.** After investigating and due diligence if it is a revelation — log it to one-brain as BOTH `log_episode` and `remember` and also update the relevant PRDs and docs with the information fanning out. Applies whether the underlying task succeeds or fails.
50
51
 
52
+ **Compaction.** When compacting, always preserve: the PRD issue number, the active worktree path and branch, locked scope and grilling answers, pending decisions, and the TODO task list.
53
+
51
54
  ## Codify Over Instruct
52
55
 
53
56
  Prefer code over natural-language rules. Mechanical constraints (paths, formats, naming, validity) belong in hooks/scripts/validators; word instructions are reserved for intent and judgement calls (creative direction, tone, priorities) that code cannot check.
@@ -61,7 +64,7 @@ Prefer code over natural-language rules. Mechanical constraints (paths, formats,
61
64
 
62
65
  ## Web Search Routing
63
66
 
64
- Web search is routed by **code, not this prose**: the `web_search_guard.py` PreToolUse hook denies native `WebSearch` and redirects to the `web-search` skill (Perplexity Sonar via LiteLLM, cited). You don't have to remember to prefer it — the hook enforces it. On a Sonar error, retry `--model litellm_sonar`. Judgment that the hook can't make: send library/framework/API doc lookups to **Context7** first, not web-search.
67
+ Web search is routed by **code, not this prose**: the `web_search_guard.py` PreToolUse hook denies native `WebSearch` and redirects to the `web-search` skill (Perplexity Sonar via LiteLLM, cited). You don't have to remember to prefer it — the hook enforces it. On a Sonar error, retry `--model litellm_sonar`.
65
68
 
66
69
  ## Memory Write Mandate
67
70
 
@@ -73,4 +76,4 @@ Whenever a session adds, edits, or removes an agent (`.agent.md`), a skill (`SKI
73
76
 
74
77
  1. **GitLab issue.** Post an update to the relevant issue. Check for an existing on-topic thread first (e.g. a project's own "Agent Flow"-style issue) and append there; only open a new issue if the change is a genuinely distinct thread, not a continuation of ongoing work.
75
78
  2. **Docs.** Update any project docs (README roster tables, architecture docs) the change affects, so they don't silently go stale relative to the actual code.
76
- 3. **Global vs. local — check my-agents.** `C:/dev/my-agents` is the canonical SOURCE for hooks/agents deployed to `~/.claude/` (e.g. `my-agents/proxy/*.py` → `~/.claude/proxy/*.py`, `my-agents/agents/*.md` → `~/.claude/agents/*.md`) — confirmed by direct diff on 2026-07-05 that these can silently diverge (an entire session's worth of global hook fixes existed only in the deployed copy, never propagated to source, which would be lost on a future reinstall). If the change touched anything under `~/.claude/` (not a project-local `.claude/` directory), it is GLOBAL/shared — the same fix must also land in the matching my-agents source file, or flag explicitly why it doesn't apply there. This is a judgment call (is this change global-shared-infra vs. project-local?), not something a hook can auto-detect — always ask "did I just edit something under `~/.claude/`?" and if yes, check my-agents.
79
+ 3. **Global vs. local — check my-agents.** `C:/dev/my-agents` is the canonical SOURCE for hooks/agents deployed to `~/.claude/` (e.g. `my-agents/proxy/*.py` → `~/.claude/proxy/*.py`, `my-agents/agents/*.md` → `~/.claude/agents/*.md`) — they can silently diverge. If the change touched anything under `~/.claude/` (not a project-local `.claude/` directory), it is GLOBAL/shared — the same fix must also land in the matching my-agents source file, or flag explicitly why it doesn't apply there. This is a judgment call (is this change global-shared-infra vs. project-local?), not something a hook can auto-detect — always ask "did I just edit something under `~/.claude/`?" and if yes, check my-agents.
@@ -0,0 +1,156 @@
1
+ #!/usr/bin/env python3
2
+ """compact_context.py -- SessionStart (matcher "compact"): after a compaction, print a short
3
+ context block of facts the code can derive from disk. Plain stdout of a SessionStart hook is
4
+ added to Claude's context. Fails open: any error or non-compact source prints nothing, exit 0."""
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import os
9
+ import re
10
+ import subprocess
11
+ import sys
12
+ import time
13
+ from concurrent.futures import ThreadPoolExecutor
14
+ from pathlib import Path
15
+
16
+ MAX_CHARS = 1200
17
+ BUDGET_SECS = float(os.environ.get("COMPACT_CONTEXT_BUDGET_SECS", "1.0"))
18
+ STATUS_MAX_LINES = 20
19
+ STATUS_LINE_CHARS = 90
20
+ TASK_MAX = 6
21
+ TASK_SUBJECT_CHARS = 70
22
+ HANDOFF_MAX_AGE_SECS = 24 * 3600
23
+ TASKLIST_HINT = "Open tasks: not readable from disk for this session id; call TaskList to see them."
24
+ OPEN_STATUSES = ("in_progress", "pending")
25
+ SAFE_ID = re.compile(r"^[A-Za-z0-9_.-]+$")
26
+ SECRET = re.compile(
27
+ r"(glpat-[\w-]{10,}|gh[pousr]_[A-Za-z0-9]{20,}|sk-[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16}"
28
+ r"|xox[abprs]-[\w-]{10,}|Bearer\s+[\w.~+/=-]{12,}"
29
+ r"|(?:password|passwd|secret|token|api[_-]?key)\s*[=:]\s*\S+)",
30
+ re.IGNORECASE,
31
+ )
32
+
33
+
34
+ def clip(text: str, limit: int) -> str:
35
+ text = " ".join(text.split())
36
+ return text if len(text) <= limit else text[: limit - 3] + "..."
37
+
38
+
39
+ def git(args: list[str], cwd: str, deadline: float) -> str | None:
40
+ remaining = deadline - time.monotonic()
41
+ if remaining <= 0:
42
+ return None
43
+ flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
44
+ try:
45
+ proc = subprocess.run(
46
+ ["git", "--no-optional-locks", *args],
47
+ cwd=cwd, capture_output=True, text=True, encoding="utf-8", errors="replace",
48
+ timeout=remaining, stdin=subprocess.DEVNULL, creationflags=flags,
49
+ )
50
+ except (OSError, subprocess.SubprocessError):
51
+ return None
52
+ return proc.stdout.strip("\r\n") if proc.returncode == 0 else None
53
+
54
+
55
+ def task_dirs(session_id: str) -> list[Path]:
56
+ root = Path.home() / ".claude" / "tasks"
57
+ names = [os.environ.get("CLAUDE_CODE_TASK_LIST_ID", ""), session_id, f"session-{session_id[:8]}"]
58
+ return [root / n for n in names if n and SAFE_ID.match(n) and (root / n).is_dir()]
59
+
60
+
61
+ def open_tasks(session_id: str) -> list[str] | None:
62
+ directories = task_dirs(session_id)
63
+ if not directories and not os.environ.get("CLAUDE_CODE_TASK_LIST_ID"):
64
+ return None
65
+ for directory in directories:
66
+ found = []
67
+ for path in directory.glob("*.json"):
68
+ try:
69
+ task = json.loads(path.read_text(encoding="utf-8"))
70
+ status, subject = task["status"], task["subject"]
71
+ found.append((int(task["id"]), status, subject))
72
+ except (OSError, ValueError, KeyError, TypeError):
73
+ continue
74
+ rows = sorted(t for t in found if t[1] in OPEN_STATUSES)
75
+ if rows:
76
+ lines = [f"#{i} [{s}] {clip(str(sub), TASK_SUBJECT_CHARS)}" for i, s, sub in rows[:TASK_MAX]]
77
+ if len(rows) > TASK_MAX:
78
+ lines.append(f"+{len(rows) - TASK_MAX} more")
79
+ return lines
80
+ return []
81
+
82
+
83
+ def newest_handoff() -> str | None:
84
+ directory = Path.home() / ".claude" / "handoffs"
85
+ try:
86
+ files = [(p.stat().st_mtime, p) for p in directory.glob("*.md")]
87
+ except OSError:
88
+ return None
89
+ if not files:
90
+ return None
91
+ mtime, path = max(files)
92
+ return path.as_posix() if time.time() - mtime <= HANDOFF_MAX_AGE_SECS else None
93
+
94
+
95
+ def build(payload: dict) -> str:
96
+ deadline = time.monotonic() + BUDGET_SECS
97
+ cwd = payload.get("cwd") or os.getcwd()
98
+ queries = (["rev-parse", "--show-toplevel"], ["branch", "--show-current"],
99
+ ["rev-parse", "--short", "HEAD"], ["status", "--short"])
100
+ with ThreadPoolExecutor(max_workers=len(queries)) as pool:
101
+ top, branch, head, status = pool.map(lambda args: git(args, cwd, deadline), queries)
102
+ lines = ["Context after compaction (read from disk, not from memory):"]
103
+ if top:
104
+ lines.append(f"Worktree: {top}")
105
+ branch = branch or (f"(detached at {head})" if head else None)
106
+ if branch:
107
+ lines.append(f"Branch: {branch}")
108
+ handoff = newest_handoff()
109
+ if handoff:
110
+ lines.append(f"Latest handoff: {handoff}")
111
+ tasks = open_tasks(str(payload.get("session_id") or ""))
112
+ if tasks is None:
113
+ lines.append(TASKLIST_HINT)
114
+ elif tasks:
115
+ lines.append("Open tasks:")
116
+ lines.extend(f" {t}" for t in tasks)
117
+ if len(lines) == 1:
118
+ return ""
119
+ if status:
120
+ rows = status.splitlines()
121
+ lines.append("Git status:")
122
+ used = sum(len(line) + 1 for line in lines)
123
+ shown = 0
124
+ for row in rows[:STATUS_MAX_LINES]:
125
+ entry = " " + clip(row, STATUS_LINE_CHARS)
126
+ if used + len(entry) + 1 > MAX_CHARS - 16:
127
+ break
128
+ lines.append(entry)
129
+ used += len(entry) + 1
130
+ shown += 1
131
+ if len(rows) > shown:
132
+ lines.append(f" +{len(rows) - shown} more")
133
+ elif status is not None:
134
+ lines.append("Git status: clean")
135
+ text = SECRET.sub("[redacted]", "\n".join(lines))
136
+ return text if len(text) <= MAX_CHARS else text[: MAX_CHARS - 3] + "..."
137
+
138
+
139
+ def main() -> int:
140
+ try:
141
+ if os.environ.get("CLAUDE_HOOK_CHILD"):
142
+ return 0
143
+ payload = json.loads(sys.stdin.buffer.read().decode("utf-8", errors="replace"))
144
+ if not isinstance(payload, dict) or payload.get("source") != "compact":
145
+ return 0
146
+ text = build(payload)
147
+ if text:
148
+ sys.stdout.buffer.write((text + "\n").encode("utf-8", errors="replace"))
149
+ sys.stdout.buffer.flush()
150
+ except Exception:
151
+ return 0
152
+ return 0
153
+
154
+
155
+ if __name__ == "__main__":
156
+ sys.exit(main())