@antoneeo/kb-agentic-skill 1.35.0 → 1.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,35 @@
2
2
 
3
3
  Every significant change to this skill is recorded here.
4
4
 
5
+
6
+ ## [1.36.0] - 2026-11-08
7
+
8
+ ### What's new
9
+
10
+ **With several lenses of the family installed, the per-prompt reminder now names them.** A machine gets one reminder for the whole family, wired by whichever lens was installed first, so a knowledge or marketing task used to see the code lens's line. When other lenses are installed, the line now lists each one with its domain, for example `kb-agentic (knowledge)`, and asks the agent to load the one that governs the work. A single-lens install sees no change. To do this the reminder reads the installed skill names at each prompt (names only), and its length bound rises from 600 to 700 characters (F-093).
11
+
12
+ #### What to do
13
+
14
+ Everyone who has this package installed: run `npm install -g @antoneeo/kb-agentic-skill@latest`, then `kb-agentic-install-skill`, and restart your agent sessions. The install step copies the updated validator into your skills directory and wires the reminder if it is missing; sessions already open keep the old one until restarted. To check it worked, run `npm ls -g @antoneeo/kb-agentic-skill` and look for 1.36.0, then start a session: on a machine with more than one lens of the family installed, the one-line reminder shown at each prompt names the installed lenses with their domains.
15
+
16
+ ### Fixed
17
+
18
+ **Installing this package now wires the per-turn reminder its ENFORCEMENT.md promised.** Until now only the code lens (agentic-sdlc) installed it, so a machine with this lens alone never received the one-line reminder at each prompt. It is wired on Claude Code alongside the session orientation; if another lens of the family already wired its own reminder, that one stays and nothing is added, so a prompt carries one line. Removing the hook entry is still a standing opt-out, and uninstalling removes only this package's own entry (F-093).
19
+
20
+ ## [1.35.1] - 2026-11-04
21
+
22
+ ### What's new
23
+
24
+ **Codex hook checks can recognize the work the agent is doing.** The shared validator recognizes supported native Codex patches and transcript records, and gives more accurate orientation-hook diagnostics when definitions are disabled or cannot be verified. Existing hook setup and opt-outs are preserved.
25
+
26
+ #### What to do
27
+
28
+ Run `npm install -g @antoneeo/kb-agentic-skill@latest`, then `kb-agentic-install-skill`, and restart your agent sessions so they load the updated validator. Check that `npm ls -g @antoneeo/kb-agentic-skill` shows 1.35.1. Any configured Codex hooks still require their normal client trust review.
29
+
30
+ ### Changed
31
+
32
+ - Update the shared validator for Codex event recognition, attributed hook discovery and disabled/unverified configuration handling.
33
+
5
34
  ## [1.35.0] - 2026-11-01
6
35
 
7
36
  ### What's new
package/README.md CHANGED
@@ -6,17 +6,13 @@ The sibling of [`@antoneeo/agentic-sdlc-skill`](https://www.npmjs.com/package/@a
6
6
 
7
7
  <!-- whats-new:begin -->
8
8
  <!-- generated by scripts/whats_new.js from distributions/kb-agentic-skill/CHANGELOG.md: edit the CHANGELOG, then run node scripts/whats_new.js --write -->
9
- ## What's new in 1.35.0
9
+ ## What's new in 1.36.0
10
10
 
11
- **Branches that add review rows merge without a conflict.** When two branches both add rows to the review log and your project has no merge rule for that file, merging them stops on a conflict you resolve by hand. The check the agent runs when it closes a piece of work now notices the missing rule and prints the exact line to add to `.gitattributes`, so the agent sees what to fix while it works, without anyone reading release notes. Nothing changes at session start, and the note never makes a check fail.
11
+ **With several lenses of the family installed, the per-prompt reminder now names them.** A machine gets one reminder for the whole family, wired by whichever lens was installed first, so a knowledge or marketing task used to see the code lens's line. When other lenses are installed, the line now lists each one with its domain, for example `kb-agentic (knowledge)`, and asks the agent to load the one that governs the work. A single-lens install sees no change. To do this the reminder reads the installed skill names at each prompt (names only), and its length bound rises from 600 to 700 characters (F-093).
12
12
 
13
13
  #### What to do
14
14
 
15
- **1. Update (everyone).** The changes arrive only with the update.
16
- 1. Run `npm install -g @antoneeo/kb-agentic-skill@latest`, then `kb-agentic-install-skill`.
17
- 2. Close and reopen your agent sessions: the new version loads only at startup.
18
-
19
- To check: `npm ls -g @antoneeo/kb-agentic-skill` shows 1.35.0.
15
+ Everyone who has this package installed: run `npm install -g @antoneeo/kb-agentic-skill@latest`, then `kb-agentic-install-skill`, and restart your agent sessions. The install step copies the updated validator into your skills directory and wires the reminder if it is missing; sessions already open keep the old one until restarted. To check it worked, run `npm ls -g @antoneeo/kb-agentic-skill` and look for 1.36.0, then start a session: on a machine with more than one lens of the family installed, the one-line reminder shown at each prompt names the installed lenses with their domains.
20
16
 
21
17
  Full history: [CHANGELOG](https://github.com/Antoneeo/agentic-sdlc-skill/blob/main/distributions/kb-agentic-skill/CHANGELOG.md)
22
18
  <!-- whats-new:end -->
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kb-agentic-skill",
3
- "version": "1.35.0",
3
+ "version": "1.36.0",
4
4
  "description": "Knowledge-Base & Document-First protocol with risk triage, Vision governance, signal distillation and optional devPNT integration.",
5
5
  "author": "Antonio Pinto (https://github.com/Antoneeo)"
6
6
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@antoneeo/kb-agentic-skill",
3
- "version": "1.35.0",
3
+ "version": "1.36.0",
4
4
  "description": "Knowledge-Base & Document-First protocol for Claude Code, Gemini CLI, Google Antigravity and Codex with risk triage, Vision governance, signal distillation and optional devPNT integration.",
5
5
  "keywords": [
6
6
  "claude-code",
package/scripts/lib.js CHANGED
@@ -562,10 +562,23 @@ function wireGlobalOrientHook(options) {
562
562
  // already removed the hook, the line stays and the opt-out survives uninstall,
563
563
  // reinstall, and sibling-lens uninstalls.
564
564
  function removeGlobalOrientHooks(removedRoots) {
565
+ return removeGlobalHookEntries(removedRoots, {
566
+ event: 'SessionStart',
567
+ re: / orient(\s|$)/,
568
+ markerTargets: orientMarkerTargets,
569
+ markerRemove: orientMarkerRemove,
570
+ });
571
+ }
572
+
573
+ // The pruning loop shared by every hook this installer wires: only the
574
+ // `spec.event` entries whose command matches `spec.re` AND whose validator
575
+ // token resolves INTO a removed root are ours; the marker line is cleared only
576
+ // when an entry was actually removed. Returns the targets touched.
577
+ function removeGlobalHookEntries(removedRoots, spec) {
565
578
  const targets = [];
566
579
  const claude = CLIENTS.find((c) => c.key === 'claude');
567
580
  if (claude) targets.push(path.join(claude.home, 'settings.json'));
568
- for (const t of orientMarkerTargets()) {
581
+ for (const t of spec.markerTargets()) {
569
582
  if (!targets.some((x) => pathsEqual(x, t))) targets.push(t);
570
583
  }
571
584
  const removedFrom = [];
@@ -574,17 +587,17 @@ function removeGlobalOrientHooks(removedRoots) {
574
587
  const state = orientSettingsState(target);
575
588
  if (!state.ok || !fs.existsSync(target)) continue;
576
589
  const hooks = state.settings.hooks;
577
- if (!hooks || !Array.isArray(hooks.SessionStart)) continue;
590
+ if (!hooks || !Array.isArray(hooks[spec.event])) continue;
578
591
  let removedHere = false;
579
592
  const ours = (h) => {
580
593
  const cmd = h && typeof h.command === 'string' ? h.command : '';
581
- if (!(ORIENT_ENTRY_POINTS.some((n) => cmd.includes(n)) && / orient(\s|$)/.test(cmd))) return false;
594
+ if (!(ORIENT_ENTRY_POINTS.some((n) => cmd.includes(n)) && spec.re.test(cmd))) return false;
582
595
  const tok = orientHookValidator(cmd);
583
596
  if (tok === null || !path.isAbsolute(tok)) return false; // cannot attribute: keep
584
597
  return removedRoots.some((root) => pathInside(tok, root));
585
598
  };
586
599
  const kept = [];
587
- for (const group of hooks.SessionStart) {
600
+ for (const group of hooks[spec.event]) {
588
601
  if (!group || typeof group !== 'object') { kept.push(group); continue; }
589
602
  if (Array.isArray(group.hooks)) {
590
603
  const inner = group.hooks.filter((h) => {
@@ -601,19 +614,122 @@ function removeGlobalOrientHooks(removedRoots) {
601
614
  }
602
615
  }
603
616
  if (!removedHere) continue;
604
- state.settings.hooks.SessionStart = kept;
605
- if (!kept.length) delete state.settings.hooks.SessionStart;
617
+ state.settings.hooks[spec.event] = kept;
618
+ if (!kept.length) delete state.settings.hooks[spec.event];
606
619
  if (state.settings.hooks && !Object.keys(state.settings.hooks).length) {
607
620
  delete state.settings.hooks;
608
621
  }
609
622
  fs.writeFileSync(target, JSON.stringify(state.settings, null, 2) + String.fromCharCode(10), 'utf8');
610
- orientMarkerRemove(target);
623
+ spec.markerRemove(target);
611
624
  removedFrom.push(target);
612
625
  } catch (e) { /* fail-open per target: never abort an uninstall */ }
613
626
  }
614
627
  return removedFrom;
615
628
  }
616
629
 
630
+ // --- Per-turn reminder hook (F-046, wired by this lens since F-093) ----------
631
+ // `orient` fires once and decays; this hook re-arms the lens's constant line
632
+ // every prompt. F-046 wired it from the code lens's installer only, while this
633
+ // lens's ENFORCEMENT.md promised it: a single-lens install got no reminder.
634
+ // Presence is recognized family-wide (any lens's `remind` counts), like the
635
+ // orientation hook, so a multi-lens machine keeps exactly one line per turn
636
+ // (rulings.md r19/r32 price one line). Its own marker: removal is a standing
637
+ // opt-out for this hook only, shared by the family.
638
+ const REMIND_HOOK = {
639
+ event: 'UserPromptSubmit', sub: 'remind', re: / remind(\s|$)/,
640
+ marker: 'remind-hook-wired', timeout: 5,
641
+ };
642
+
643
+ function markerPathOf(spec) {
644
+ const root = process.env.AGENTIC_SDLC_KB_ROOT
645
+ || path.join(os.homedir(), '.agentic-sdlc');
646
+ return path.join(root, spec.marker);
647
+ }
648
+ function markerTargetsOf(spec) {
649
+ try {
650
+ return fs.readFileSync(markerPathOf(spec), 'utf8')
651
+ .split(/\r?\n/).map((x) => x.trim()).filter(Boolean);
652
+ } catch (e) {
653
+ return [];
654
+ }
655
+ }
656
+ function markerHasOf(spec, target) {
657
+ return markerTargetsOf(spec).some((t) => pathsEqual(t, target));
658
+ }
659
+ function markerAddOf(spec, target) {
660
+ try {
661
+ if (markerHasOf(spec, target)) return;
662
+ fs.mkdirSync(path.dirname(markerPathOf(spec)), { recursive: true });
663
+ fs.appendFileSync(markerPathOf(spec), target + String.fromCharCode(10), 'utf8');
664
+ } catch (e) { /* fail-open */ }
665
+ }
666
+ function markerRemoveOf(spec, target) {
667
+ try {
668
+ const rest = markerTargetsOf(spec).filter((t) => !pathsEqual(t, target));
669
+ if (rest.length) {
670
+ fs.writeFileSync(markerPathOf(spec), rest.join(String.fromCharCode(10)) + String.fromCharCode(10), 'utf8');
671
+ } else {
672
+ fs.rmSync(markerPathOf(spec), { force: true });
673
+ }
674
+ } catch (e) { /* fail-open */ }
675
+ }
676
+
677
+ function findCommandHook(settings, spec) {
678
+ const groups = settings && settings.hooks && settings.hooks[spec.event];
679
+ if (!Array.isArray(groups)) return null;
680
+ for (const group of groups) {
681
+ if (!group || typeof group !== 'object') continue;
682
+ const inner = Array.isArray(group.hooks) ? group.hooks : [group];
683
+ for (const h of inner) {
684
+ const cmd = h && typeof h.command === 'string' ? h.command : '';
685
+ if (ORIENT_ENTRY_POINTS.some((n) => cmd.includes(n)) && spec.re.test(cmd)) return cmd;
686
+ }
687
+ }
688
+ return null;
689
+ }
690
+
691
+ // Present is `already`; only ABSENCE plus the marker means the user removed it.
692
+ // Returns a code, never throws: an installer must not die on a settings file.
693
+ function wireGlobalRemindHook(options) {
694
+ const spec = REMIND_HOOK;
695
+ const validator = path.join(skillTarget(options.client), 'scripts', ORIENT_ENTRY_POINT);
696
+ if (!fs.existsSync(validator)) return { code: 'no-validator', validator };
697
+ if (!options.python) return { code: 'no-python' };
698
+ if (ORIENT_UNSAFE_IN_PATH.test(validator)) return { code: 'unsafe-path', validator };
699
+ const target = path.join(options.client.home, 'settings.json');
700
+ const state = orientSettingsState(target);
701
+ if (!state.ok) return { code: 'malformed', target, why: state.why };
702
+ const settings = state.settings;
703
+ // Unrecognised means write nothing (orientSettingsState checks SessionStart only).
704
+ if (settings.hooks && settings.hooks[spec.event] !== undefined && !Array.isArray(settings.hooks[spec.event])) {
705
+ return { code: 'malformed', target, why: 'unexpected-hooks' };
706
+ }
707
+ const present = findCommandHook(settings, spec);
708
+ if (present) return { code: 'already', target, command: present };
709
+ if (markerHasOf(spec, target)) return { code: 'opted-out', target };
710
+ const command = options.python + ' "' + validator + '" ' + spec.sub;
711
+ if (!settings.hooks) settings.hooks = {};
712
+ if (!Array.isArray(settings.hooks[spec.event])) settings.hooks[spec.event] = [];
713
+ settings.hooks[spec.event].push({ hooks: [{ type: 'command', command, timeout: spec.timeout }] });
714
+ try {
715
+ fs.mkdirSync(path.dirname(target), { recursive: true });
716
+ fs.writeFileSync(target, JSON.stringify(settings, null, 2) + String.fromCharCode(10), 'utf8');
717
+ } catch (e) {
718
+ return { code: 'write-failed', target, command, error: e.message };
719
+ }
720
+ markerAddOf(spec, target);
721
+ return { code: 'wired', target, command };
722
+ }
723
+
724
+ function removeGlobalRemindHooks(removedRoots) {
725
+ return removeGlobalHookEntries(removedRoots, {
726
+ event: REMIND_HOOK.event,
727
+ re: REMIND_HOOK.re,
728
+ markerTargets: () => markerTargetsOf(REMIND_HOOK),
729
+ markerRemove: (target) => markerRemoveOf(REMIND_HOOK, target),
730
+ });
731
+ }
732
+
617
733
  module.exports = {
618
734
  PACKAGE_ROOT,
619
735
  SKILL_SOURCE,
@@ -626,6 +742,8 @@ module.exports = {
626
742
  wireOrientHook,
627
743
  wireGlobalOrientHook,
628
744
  removeGlobalOrientHooks,
745
+ wireGlobalRemindHook,
746
+ removeGlobalRemindHooks,
629
747
  detectPython,
630
748
  pathsEqual,
631
749
  orientHookCommand,
@@ -3,7 +3,7 @@
3
3
  const fs = require('fs');
4
4
  const {
5
5
  SKILL_SOURCE, CLIENTS, clientDetected, skillTarget, copyRecursive,
6
- wireGlobalOrientHook, detectPython,
6
+ wireGlobalOrientHook, wireGlobalRemindHook, detectPython,
7
7
  } = require('./lib');
8
8
 
9
9
  function installSkill(client) {
@@ -61,6 +61,18 @@ for (const client of CLIENTS) {
61
61
  // already / opted-out / unverifiable / no-validator: silent — an
62
62
  // install must not nag (the opt-out is the user's standing choice).
63
63
  } catch (e) { /* never fail the install for a convenience */ }
64
+ // F-046/F-093: the per-turn reminder, wired alongside and never instead of
65
+ // the session hook (ENFORCEMENT.md promises it). One line per prompt for
66
+ // the whole family: a sibling lens's reminder already counts. Owner-accepted
67
+ // per-turn cost: rulings.md r19/r32. Removal is a standing opt-out.
68
+ try {
69
+ const rr = wireGlobalRemindHook({ client, python: detectPython() });
70
+ if (rr.code === 'wired') {
71
+ console.log('🔗 Per-turn protocol reminder wired for every project on this machine');
72
+ console.log(` (${rr.target}). One constant line per prompt; remove that hook`);
73
+ console.log(' entry to opt out — it will not be re-added.');
74
+ }
75
+ } catch (e) { /* never fail the install for a convenience */ }
64
76
  }
65
77
  }
66
78
  }
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  const fs = require('fs');
4
- const { CLIENTS, skillTarget, removeGlobalOrientHooks } = require('./lib');
4
+ const { CLIENTS, skillTarget, removeGlobalOrientHooks, removeGlobalRemindHooks } = require('./lib');
5
5
 
6
6
  function removeSkill(client) {
7
7
  const target = skillTarget(client);
@@ -26,5 +26,11 @@ try {
26
26
  console.log(`🧹 Removed the session-orientation hook entry (${target}).`);
27
27
  }
28
28
  } catch (e) { /* never abort an uninstall for a convenience */ }
29
+ // F-093: the per-turn reminder this lens may have wired, same attribution rule.
30
+ try {
31
+ for (const target of removeGlobalRemindHooks(CLIENTS.map(skillTarget))) {
32
+ console.log(`🧹 Removed the per-turn reminder hook entry (${target}).`);
33
+ }
34
+ } catch (e) { /* never abort an uninstall for a convenience */ }
29
35
 
30
36
  CLIENTS.forEach(removeSkill);
@@ -237,9 +237,11 @@ Cost: 531 characters, ~89 tokens per prompt, paid on every turn including
237
237
  trivial ones. That is admissible only because the owner accepted it explicitly
238
238
  (`ai_docs/vision/rulings.md` r19, the "no ceremony ratchet" Non-Goal's second door) --
239
239
  and the acceptance was for a FLAT cost. Hence the contract, guarded by
240
- `scripts/test_remind.py`: the line is **constant and reads nothing** (so nothing repo-
240
+ `scripts/test_remind.py`: the line is **constant per machine and reads nothing repo- or session-controlled** (so nothing repo-
241
241
  or session-controlled rides into the agent's context through it, and the cost cannot
242
- grow with the session), it is **one line under 600 characters** (r32 raised r19's 500 to carry the lens choice), and it **can never
242
+ grow with the session), it is **one line under 600 characters** (r32 raised r19's 500 to carry the lens choice; **700** when sibling lenses are installed,
243
+ because it then names each installed lens and its domain, read each turn from the skills
244
+ directories -- names only, matched against `routing.md`'s table, r44), and it **can never
243
245
  break a prompt** (argv ignored whole, always exit 0). A trivial turn pays a yes/no
244
246
  judgement, never a load.
245
247
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: kb-agentic
3
- version: 1.35.0
3
+ version: 1.36.0
4
4
  description: Knowledge-Base & Document-First protocol with risk-proportional triage, Vision as a guide, Signal Distillation, a complete Standalone mode and optional symbiosis with devPNT. Use for user documentation, knowledge extraction, SOPs, research notes, decision logs, knowledge management — and for answering project questions from the claim ledger and topic graph.
5
5
  author: Antonio Pinto (https://github.com/Antoneeo)
6
6
  copyright: (c) 2026 Antonio Pinto
@@ -35,6 +35,7 @@ but are deprecated: new documents should use the English forms.
35
35
  Standard library only (Python >= 3.8). Windows and POSIX compatible.
36
36
  """
37
37
  import argparse
38
+ import base64
38
39
  import hashlib
39
40
  import json
40
41
  import os
@@ -2317,6 +2318,29 @@ ORIENT_HOOK_CONFIG_CAP = 1024 * 1024 # settings are tiny; cap pathological file
2317
2318
  _ORIENT_HOOK_CMD_RE = re.compile(r" orient(\s|$)")
2318
2319
  _ORIENT_HOOK_TOKEN_RE = re.compile(r'"([^"]*)"|(\S+)')
2319
2320
 
2321
+ # Same fixed, versioned carrier as scripts/lib.js; only JSON data is decoded.
2322
+ _CODEX_HOOK_WRAPPER = "import base64,json,subprocess,sys;d=json.loads(base64.b64decode(sys.argv[2]));subprocess.run([sys.executable,d['validator'],*d['argv']],input=sys.stdin.buffer.read())"
2323
+
2324
+
2325
+ def _decode_hook_invocation(command):
2326
+ middle = ' -c "' + _CODEX_HOOK_WRAPPER + '" agentic-sdlc-hook-v1 '
2327
+ if not isinstance(command, str) or middle not in command:
2328
+ return None
2329
+ prefix, encoded = command.split(middle, 1)
2330
+ if not re.fullmatch(r'[\w.-]+|"[^"$`\r\n]+"', prefix):
2331
+ return None
2332
+ try:
2333
+ data = json.loads(base64.b64decode(encoded, validate=True))
2334
+ if (not isinstance(data, dict) or data.get("client") != "codex"
2335
+ or not isinstance(data.get("validator"), str)
2336
+ or not isinstance(data.get("argv"), list) or not data["argv"]
2337
+ or not all(isinstance(a, str) for a in data["argv"])
2338
+ or data["argv"][0] not in ("orient", "remind", "verdict", "constraints")):
2339
+ return None
2340
+ return data
2341
+ except (ValueError, TypeError):
2342
+ return None
2343
+
2320
2344
 
2321
2345
  def _orient_entries_in(p):
2322
2346
  """Yield the SessionStart commands invoking an orient entry point from ONE
@@ -2327,11 +2351,20 @@ def _orient_entries_in(p):
2327
2351
  try:
2328
2352
  if not p.is_file() or p.stat().st_size > ORIENT_HOOK_CONFIG_CAP:
2329
2353
  return
2330
- data = json.loads(p.read_text(encoding="utf-8-sig"))
2354
+ if p.suffix == ".toml":
2355
+ import tomllib
2356
+ data = tomllib.loads(p.read_text(encoding="utf-8-sig"))
2357
+ else:
2358
+ data = json.loads(p.read_text(encoding="utf-8-sig"))
2331
2359
  except Exception:
2332
2360
  return
2333
2361
  if not isinstance(data, dict):
2334
2362
  return
2363
+ features = data.get("features")
2364
+ if p.name in ("hooks.json", "config.toml") and (
2365
+ isinstance(features, dict) and features.get("hooks") is False
2366
+ or data.get("allow_managed_hooks_only") is True):
2367
+ return
2335
2368
  hooks = data.get("hooks")
2336
2369
  groups = hooks.get("SessionStart") if isinstance(hooks, dict) else None
2337
2370
  if groups is None:
@@ -2341,12 +2374,20 @@ def _orient_entries_in(p):
2341
2374
  for group in groups:
2342
2375
  if not isinstance(group, dict):
2343
2376
  continue
2377
+ codex = p.name in ("hooks.json", "config.toml")
2378
+ if codex and group.get("enabled") is False:
2379
+ continue
2344
2380
  inner = group.get("hooks")
2345
2381
  for h in inner if isinstance(inner, list) else [group]:
2382
+ if codex and (not isinstance(h, dict) or h.get("enabled") is False or h.get("type") != "command"):
2383
+ continue
2346
2384
  cmd = h.get("command") if isinstance(h, dict) else None
2347
- if (isinstance(cmd, str)
2348
- and any(n in cmd for n in ORIENT_HOOK_ENTRY_POINTS)
2349
- and _ORIENT_HOOK_CMD_RE.search(cmd)):
2385
+ if isinstance(h, dict) and p.name in ("hooks.json", "config.toml") and os.name == "nt":
2386
+ cmd = h.get("commandWindows") or h.get("command_windows") or cmd
2387
+ invocation = _decode_hook_invocation(cmd)
2388
+ if ((invocation and invocation["argv"][0] == "orient") or
2389
+ (isinstance(cmd, str) and any(n in cmd for n in ORIENT_HOOK_ENTRY_POINTS)
2390
+ and _ORIENT_HOOK_CMD_RE.search(cmd))):
2350
2391
  yield cmd
2351
2392
 
2352
2393
 
@@ -2365,17 +2406,69 @@ def _orient_user_settings_path():
2365
2406
  return (Path(cfg) if cfg else Path.home() / ".claude") / "settings.json"
2366
2407
 
2367
2408
 
2409
+ def _codex_hook_config(root):
2410
+ """Observable Codex policy across sources; no trust or execution assertion."""
2411
+ home = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex")
2412
+ disabled, unverified, disabled_entries = False, False, False
2413
+ for directory in (home, Path(root) / ".codex"):
2414
+ for name in ("hooks.json", "config.toml"):
2415
+ p = directory / name
2416
+ if not p.exists():
2417
+ continue
2418
+ try:
2419
+ if not p.is_file() or p.stat().st_size > ORIENT_HOOK_CONFIG_CAP:
2420
+ raise ValueError("unreadable configuration")
2421
+ text = p.read_text(encoding="utf-8-sig")
2422
+ if p.suffix == ".toml":
2423
+ import tomllib
2424
+ data = tomllib.loads(text)
2425
+ else:
2426
+ data = json.loads(text)
2427
+ if not isinstance(data, dict):
2428
+ raise ValueError("unknown configuration shape")
2429
+ features = data.get("features", {})
2430
+ hooks = data.get("hooks", {})
2431
+ if not isinstance(features, dict) or not isinstance(hooks, dict):
2432
+ raise ValueError("unknown policy or hooks shape")
2433
+ disabled |= features.get("hooks") is False or data.get("allow_managed_hooks_only") is True
2434
+ groups = hooks.get("SessionStart", data.get("SessionStart", []))
2435
+ if not isinstance(groups, list):
2436
+ raise ValueError("unknown hook groups")
2437
+ for group in groups:
2438
+ if not isinstance(group, dict):
2439
+ raise ValueError("unknown hook group")
2440
+ inner = group.get("hooks", [group])
2441
+ if not isinstance(inner, list) or not all(isinstance(h, dict) for h in inner):
2442
+ raise ValueError("unknown handlers")
2443
+ disabled_entries |= group.get("enabled") is False or any(h.get("enabled") is False for h in inner)
2444
+ except Exception:
2445
+ unverified = True
2446
+ policy = "disabled-by-policy" if disabled else "unverified" if unverified else "enabled"
2447
+ return {"policy": policy, "disabled_entries": disabled_entries}
2448
+
2449
+
2368
2450
  def _orient_hook_commands(root):
2369
2451
  """Yield (command, at_user_level, place) across every known client config:
2370
2452
  the three project-relative files, then the machine-global user settings --
2371
2453
  the file the installer wires (F-042), without which a fixed machine's
2372
2454
  projects would read as unwired forever. `place` is a display label, never a
2373
2455
  home path (F-075 prints it)."""
2456
+ codex_policy = _codex_hook_config(root)["policy"]
2374
2457
  for rel in ORIENT_HOOK_CONFIG_FILES:
2458
+ if rel.startswith(".codex/") and codex_policy != "enabled":
2459
+ continue
2375
2460
  for cmd in _orient_entries_in(Path(root) / rel):
2376
2461
  yield cmd, False, rel
2377
2462
  for cmd in _orient_entries_in(_orient_user_settings_path()):
2378
2463
  yield cmd, True, "user settings"
2464
+ if codex_policy != "enabled":
2465
+ return
2466
+ home = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex")
2467
+ for name in ("hooks.json", "config.toml"):
2468
+ for cmd in _orient_entries_in(home / name):
2469
+ yield cmd, True, "codex user " + name
2470
+ for cmd in _orient_entries_in(Path(root) / ".codex" / name) if name == "config.toml" else ():
2471
+ yield cmd, False, ".codex/" + name
2379
2472
 
2380
2473
 
2381
2474
  def _orient_entry_live(root, cmd, at_user_level):
@@ -2386,7 +2479,8 @@ def _orient_entry_live(root, cmd, at_user_level):
2386
2479
  tokens resolve against the project root (the vendored-validator
2387
2480
  convention); a USER-level relative token has no cwd to resolve against and
2388
2481
  is treated as cannot-tell."""
2389
- token = None
2482
+ invocation = _decode_hook_invocation(cmd)
2483
+ token = invocation["validator"] if invocation else None
2390
2484
  for m in _ORIENT_HOOK_TOKEN_RE.finditer(cmd):
2391
2485
  tok = m.group(1) if m.group(1) is not None else m.group(2)
2392
2486
  if any(tok.endswith(n) for n in ORIENT_HOOK_ENTRY_POINTS):
@@ -2413,7 +2507,7 @@ def orient_wiring(root):
2413
2507
  for cmd, at_user_level, place in _orient_hook_commands(root):
2414
2508
  if not _orient_entry_live(root, cmd, at_user_level):
2415
2509
  continue
2416
- client = "codex" if place.startswith(".codex") else "claude"
2510
+ client = "codex" if place.startswith((".codex", "codex ")) else "claude"
2417
2511
  out.setdefault(client, {}).setdefault(cmd.strip(), place)
2418
2512
  return out
2419
2513
 
@@ -2447,6 +2541,13 @@ def print_orient_hook_note(root):
2447
2541
  does): the note is check-layer behaviour, whoever owns the check."""
2448
2542
  try:
2449
2543
  state = orient_hook_state(root)
2544
+ codex = _codex_hook_config(root)
2545
+ if codex["policy"] != "enabled" or codex["disabled_entries"]:
2546
+ detail = codex["policy"] if codex["policy"] != "enabled" else "disabled definitions present"
2547
+ print(f"[note] Codex hook configuration: {detail}. Disabled or unverified "
2548
+ "definitions are excluded from wiring counts; trust and native delivery are not verified.")
2549
+ if state == "unwired":
2550
+ return
2450
2551
  if state == "unwired":
2451
2552
  print("[note] agent sessions start without automatic orientation on this "
2452
2553
  "machine (no session-orientation hook found at project or user level). "
@@ -2552,7 +2653,9 @@ def print_check_notes(root):
2552
2653
  #
2553
2654
  # The carrier is kb's (F-041 item B), lifted here so all three lenses share one
2554
2655
  # machine instead of two that do the same thing. Its contract is kept: the line
2555
- # is CONSTANT and reads NOTHING -- nothing repo- or session-controlled may ride
2656
+ # is CONSTANT and reads NOTHING repo- or session-controlled (F-093 / r44: it does
2657
+ # read which family lenses the machine has installed, names only) -- nothing
2658
+ # repo- or session-controlled may ride
2556
2659
  # text injected every turn, and zero reads is what keeps the per-turn cost flat.
2557
2660
  # What changed is the payload's first duty and the wiring. First duty: decide
2558
2661
  # whether the skill governs this work and, if it does, read it once -- an
@@ -2573,16 +2676,40 @@ REMIND_FALLBACK = (
2573
2676
  REMIND_LENS_SUFFIX = (" Above L1, with sibling lenses installed: choose the lens with "
2574
2677
  "routing.md and declare it.")
2575
2678
 
2679
+ # F-093: the family wires ONE shared reminder, the first installer's, so its
2680
+ # own text led a knowledge task to the code lens. With siblings installed the
2681
+ # suffix names every installed lens and its domain. The owner accepted the cost
2682
+ # (REQUEST_family_hook_wiring.md R3, rulings r19/r32 amended): the skills
2683
+ # directories are read each turn, names only, filtered by routing.md's table.
2684
+ REMIND_LENS_NAMED = (" Installed lenses: {lenses}. Above L1, choose the one that "
2685
+ "governs this work with routing.md, load it and declare it.")
2686
+
2687
+
2688
+ def remind_lens_suffix():
2689
+ """The lens-choice suffix: the constant one on a single-lens install, the
2690
+ named one when a sibling lens is installed. Never raises."""
2691
+ try:
2692
+ siblings = installed_sibling_lenses()
2693
+ if not siblings:
2694
+ return REMIND_LENS_SUFFIX
2695
+ family = lens_table()
2696
+ names = sorted(set(siblings) | {profile()["skill_name"]})
2697
+ return REMIND_LENS_NAMED.format(lenses=", ".join(
2698
+ f"{n} ({family[n]})" if n in family else n for n in names))
2699
+ except Exception:
2700
+ return REMIND_LENS_SUFFIX
2701
+
2576
2702
 
2577
2703
  def cmd_remind(args):
2578
- """UserPromptSubmit hook: print the lens's constant per-turn line. Always 0.
2704
+ """UserPromptSubmit hook: print the lens's per-turn line. Always 0.
2579
2705
 
2580
- argv is ignored whole and nothing is read: a hook surface must not fail, and
2581
- a flag typo must not cost a turn's context."""
2706
+ argv is ignored whole and nothing repo- or session-controlled is read: a
2707
+ hook surface must not fail, and a flag typo must not cost a turn's context.
2708
+ The one input is which family lenses this machine has installed (F-093)."""
2582
2709
  try:
2583
2710
  prof = profile()
2584
2711
  line = prof.get("remind_line") or REMIND_FALLBACK.format(skill=prof["skill_name"])
2585
- print(f"{prof['skill_name']}: {line}{REMIND_LENS_SUFFIX}")
2712
+ print(f"{prof['skill_name']}: {line}{remind_lens_suffix()}")
2586
2713
  except Exception:
2587
2714
  pass
2588
2715
  return 0
@@ -2700,6 +2827,192 @@ _DECLARATION_RE = re.compile(
2700
2827
  _GUIDE_NAME_RE = re.compile(r"GUIDE_[A-Za-z0-9_-]+\.md")
2701
2828
 
2702
2829
 
2830
+ def _hint_path(value, cwd):
2831
+ if not isinstance(value, str) or not value:
2832
+ return None
2833
+ p = Path(value)
2834
+ if not p.is_absolute():
2835
+ if not cwd or not Path(cwd).is_absolute():
2836
+ return None
2837
+ p = Path(cwd) / p
2838
+ return str(p.resolve())
2839
+
2840
+
2841
+ def hook_edits(payload):
2842
+ """Parse the complete native apply_patch syntax without executing it.
2843
+
2844
+ Unknown or incomplete input yields no partial target set. Move checks both
2845
+ the old and new paths; file membership is evaluated by the existing gate.
2846
+ """
2847
+ command = (payload.get("tool_input") or {}).get("command")
2848
+ if not isinstance(command, str) or len(command.encode("utf-8")) > VERDICT_LINE_MAX:
2849
+ return None
2850
+ lines = command.strip().splitlines()
2851
+ if not lines or lines[0] != "*** Begin Patch" or lines[-1] != "*** End Patch":
2852
+ return None
2853
+ edits, current, mode, changed = [], None, None, False
2854
+ for line in lines[1:-1]:
2855
+ match = re.fullmatch(r"\*\*\* (Add|Update|Delete) File: (.+)", line)
2856
+ if match:
2857
+ if current is not None and mode != "Delete" and not changed:
2858
+ return None
2859
+ mode, value = match.groups()
2860
+ target = _hint_path(value, payload.get("cwd"))
2861
+ if not target:
2862
+ return None
2863
+ current = {"path": target, "new_text": ""}
2864
+ edits.append(current)
2865
+ changed = False
2866
+ elif line.startswith("*** Move to: ") and current is not None and mode == "Update" and not changed:
2867
+ target = _hint_path(line[len("*** Move to: "):], payload.get("cwd"))
2868
+ if not target:
2869
+ return None
2870
+ current = {"path": target, "new_text": ""}
2871
+ edits.append(current)
2872
+ elif current is not None and mode != "Delete" and (
2873
+ line.startswith(("+", "-", " ", "@@")) or line == "*** End of File"):
2874
+ if mode == "Add" and not line.startswith("+"):
2875
+ return None
2876
+ if line.startswith(("+", "-")):
2877
+ changed = True
2878
+ if line.startswith("+"):
2879
+ current["new_text"] += line[1:] + "\n"
2880
+ else:
2881
+ return None
2882
+ if current is not None and mode != "Delete" and not changed:
2883
+ return None
2884
+ return edits or None
2885
+
2886
+
2887
+ def shell_read_paths(command, cwd, workdir=None):
2888
+ """Literal Get-Content/cat reads only: no shell expansion or execution."""
2889
+ if not isinstance(command, str) or re.search(r"[$`\r\n;|&<>\x00]", command):
2890
+ return None
2891
+ token_re = re.compile(r"\s*(?:'([^']*)'|\"([^\"]*)\"|([^\s'\"]+))")
2892
+ tokens, pos = [], 0
2893
+ while pos < len(command.rstrip()):
2894
+ match = token_re.match(command, pos)
2895
+ if not match:
2896
+ return None
2897
+ token = next(x for x in match.groups() if x is not None)
2898
+ tokens.append(token)
2899
+ pos = match.end()
2900
+ if not tokens or tokens[0].lower() not in ("get-content", "cat"):
2901
+ return None
2902
+ paths, i = [], 1
2903
+ while i < len(tokens):
2904
+ token = tokens[i]
2905
+ if tokens[0].lower() == "get-content" and token.lower() in ("-literalpath", "-path", "-raw"):
2906
+ if token.lower() != "-raw" and i + 1 == len(tokens):
2907
+ return None
2908
+ elif tokens[0].lower() == "get-content" and token.lower() == "-totalcount":
2909
+ i += 1
2910
+ if i == len(tokens) or not tokens[i].isdigit():
2911
+ return None
2912
+ elif tokens[0] == "cat" and token == "--":
2913
+ pass
2914
+ elif token.startswith("-") or re.search(r"[*?\[\],]", token):
2915
+ return None
2916
+ else:
2917
+ base = _hint_path(workdir, cwd) if workdir else cwd
2918
+ resolved = _hint_path(token, base)
2919
+ if not resolved:
2920
+ return None
2921
+ paths.append(resolved)
2922
+ i += 1
2923
+ return paths or None
2924
+
2925
+
2926
+ def _codex_literal_calls(code):
2927
+ """Recognize a small non-executable JS carrier grammar, otherwise nothing."""
2928
+ if not isinstance(code, str):
2929
+ return []
2930
+ calls, pos = [], 0
2931
+ pattern = re.compile(r"\s*(?:text\(\s*)?await\s+tools\.exec_command\((\{.*?\})\)\s*\)?\s*;?", re.DOTALL)
2932
+ field = re.compile(r'\s*(?:"(cmd|workdir)"|(cmd|workdir))\s*:\s*("(?:[^"\\]|\\.)*")\s*(,|$)')
2933
+ while pos < len(code.rstrip()):
2934
+ match = pattern.match(code, pos)
2935
+ if not match:
2936
+ return []
2937
+ obj, off, args = match[1][1:-1], 0, {}
2938
+ while off < len(obj.rstrip()):
2939
+ item = field.match(obj, off)
2940
+ if not item or (item[1] or item[2]) in args:
2941
+ return []
2942
+ try:
2943
+ args[item[1] or item[2]] = json.loads(item[3])
2944
+ except ValueError:
2945
+ return []
2946
+ off = item.end()
2947
+ if "cmd" not in args:
2948
+ return []
2949
+ calls.append(args)
2950
+ pos = match.end()
2951
+ return calls
2952
+
2953
+
2954
+ def transcript_events(path):
2955
+ """Yield legacy assistant blocks, plus normalized recognized Codex blocks.
2956
+
2957
+ This is read-only and bounded by the existing transcript limits. Historical
2958
+ cwd is taken from host metadata, never guessed from the present process.
2959
+ """
2960
+ cwd = None
2961
+ with Path(path).open("rb") as fh:
2962
+ for raw in fh:
2963
+ if len(raw) > VERDICT_LINE_MAX:
2964
+ continue
2965
+ try:
2966
+ entry = json.loads(raw.decode("utf-8", errors="replace"))
2967
+ except ValueError:
2968
+ continue
2969
+ if not isinstance(entry, dict):
2970
+ continue
2971
+ if entry.get("type") == "assistant":
2972
+ yield entry
2973
+ continue
2974
+ data = entry.get("payload")
2975
+ if not isinstance(data, dict):
2976
+ continue
2977
+ if entry.get("type") in ("session_meta", "turn_context"):
2978
+ if isinstance(data.get("cwd"), str):
2979
+ cwd = data["cwd"]
2980
+ continue
2981
+ if entry.get("type") != "response_item":
2982
+ continue
2983
+ blocks = []
2984
+ if data.get("type") == "message" and data.get("role") == "assistant":
2985
+ blocks = [{"type": "text", "text": x.get("text", "")}
2986
+ for x in (data.get("content") if isinstance(data.get("content"), list) else []) if isinstance(x, dict) and x.get("type") == "output_text"]
2987
+ elif data.get("type") in ("function_call", "custom_tool_call"):
2988
+ name = data.get("name")
2989
+ calls = []
2990
+ if name in ("exec_command", "Bash"):
2991
+ try:
2992
+ args = json.loads(data.get("arguments", "{}"))
2993
+ except (ValueError, TypeError):
2994
+ args = None
2995
+ if isinstance(args, dict):
2996
+ calls = [args]
2997
+ elif name == "exec":
2998
+ calls = _codex_literal_calls(data.get("input"))
2999
+ elif name == "apply_patch":
3000
+ command = data.get("input")
3001
+ if command is None:
3002
+ try:
3003
+ command = json.loads(data.get("arguments", "{}" )).get("command")
3004
+ except (ValueError, TypeError, AttributeError):
3005
+ pass
3006
+ for edit in hook_edits({"tool_input": {"command": command}, "cwd": cwd}) or []:
3007
+ blocks.append({"type": "tool_use", "name": "Write", "input": {"file_path": edit["path"]}})
3008
+ for args in calls:
3009
+ for target in shell_read_paths(args.get("cmd", args.get("command")), cwd, args.get("workdir")) or []:
3010
+ blocks.append({"type": "tool_use", "name": "Read", "input": {"file_path": target}})
3011
+ if blocks:
3012
+ yield {"type": "assistant", "isSidechain": bool(entry.get("agent_id") or data.get("agent_id")),
3013
+ "message": {"content": blocks}}
3014
+
3015
+
2703
3016
  def transcript_facts(path):
2704
3017
  """What the session transcript shows about the verdict duty, or None when it
2705
3018
  cannot be read within the bounds.
@@ -2714,14 +3027,7 @@ def transcript_facts(path):
2714
3027
  p = Path(path)
2715
3028
  if not p.is_file() or p.stat().st_size > VERDICT_MAX_BYTES:
2716
3029
  return None
2717
- with p.open("rb") as fh:
2718
- for raw in fh:
2719
- if len(raw) > VERDICT_LINE_MAX or b'"assistant"' not in raw:
2720
- continue
2721
- try:
2722
- entry = json.loads(raw.decode("utf-8", errors="replace"))
2723
- except ValueError:
2724
- continue
3030
+ for entry in transcript_events(p):
2725
3031
  if not isinstance(entry, dict) or entry.get("type") != "assistant":
2726
3032
  continue
2727
3033
  content = (entry.get("message") or {}).get("content")
@@ -2755,6 +3061,13 @@ def transcript_facts(path):
2755
3061
  def verdict_reason(payload, root=None, docs_name=None):
2756
3062
  """The refusal line for this edit event, or None when the edit may proceed.
2757
3063
  Without a root, the project is the one holding the edited file (hook_project)."""
3064
+ if payload.get("tool_name") == "apply_patch" and not payload.get("agent_id"):
3065
+ for edit in hook_edits(payload) or []:
3066
+ reason = verdict_reason({**payload, "tool_name": "Edit", "tool_input": {
3067
+ "file_path": edit["path"], "new_string": edit["new_text"]}}, root, docs_name)
3068
+ if reason:
3069
+ return reason
3070
+ return None
2758
3071
  if payload.get("tool_name") not in VERDICT_EDIT_TOOLS or payload.get("agent_id"):
2759
3072
  return None
2760
3073
  tool_input = payload.get("tool_input") or {}
@@ -3113,14 +3426,7 @@ def transcript_work(path):
3113
3426
  p = Path(path)
3114
3427
  if not p.is_file() or p.stat().st_size > VERDICT_MAX_BYTES:
3115
3428
  return None
3116
- with p.open("rb") as fh:
3117
- for raw in fh:
3118
- if len(raw) > VERDICT_LINE_MAX or b'"assistant"' not in raw:
3119
- continue
3120
- try:
3121
- entry = json.loads(raw.decode("utf-8", errors="replace"))
3122
- except ValueError:
3123
- continue
3429
+ for entry in transcript_events(p):
3124
3430
  if not isinstance(entry, dict) or entry.get("type") != "assistant":
3125
3431
  continue
3126
3432
  content = (entry.get("message") or {}).get("content")
@@ -3175,6 +3481,17 @@ def constraints_hook_context(payload, root=None, docs_name=None):
3175
3481
  a subagent, on a file of a project whose open L3 code unit binds it (or the
3176
3482
  unit's own ANALYSIS, about to name a path a P row binds -- UC6), by a session
3177
3483
  that worked on that unit and last declared L3."""
3484
+ if payload.get("tool_name") == "apply_patch" and not payload.get("agent_id"):
3485
+ lines = []
3486
+ for edit in hook_edits(payload) or []:
3487
+ context = constraints_hook_context({**payload, "tool_name": "Edit", "tool_input": {
3488
+ "file_path": edit["path"], "new_string": edit["new_text"]}}, root, docs_name)
3489
+ for line in (context or "").splitlines():
3490
+ if line not in lines:
3491
+ lines.append(line)
3492
+ if len(lines) > CONSTRAINTS_HOOK_LINES:
3493
+ lines = lines[:CONSTRAINTS_HOOK_LINES - 1] + [lines[-1]]
3494
+ return "\n".join(lines) or None
3178
3495
  if payload.get("tool_name") not in VERDICT_EDIT_TOOLS or payload.get("agent_id"):
3179
3496
  return None
3180
3497
  tool_input = payload.get("tool_input") or {}
@@ -3865,6 +4182,10 @@ def cmd_orient(args):
3865
4182
  for client, entries in sorted(orient_wiring(root).items()):
3866
4183
  if len(entries) > 1:
3867
4184
  places = ", ".join(sorted(set(entries.values())))
4185
+ if client == "codex":
4186
+ tail.append(f"[note] Codex has {len(entries)} configured orientation definitions "
4187
+ f"({places}); trust and runtime policy determine delivery. Keep one equivalent definition.")
4188
+ continue
3868
4189
  tail.append(f"[note] session orientation is wired {len(entries)} times for one "
3869
4190
  f"client ({places}): each session receives every copy. Keep one "
3870
4191
  "entry and remove the others.")