@antoneeo/agentic-sdlc-skill 1.52.0 → 1.53.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,29 @@
2
2
 
3
3
  Tutte le modifiche significative a questa skill saranno documentate in questo file.
4
4
 
5
+
6
+ ## [Unreleased]
7
+
8
+ ## [1.53.0] - 2026-11-04
9
+
10
+ ### What's new
11
+
12
+ **Codex can now apply the SDLC guardrails automatically.** On supported local Codex clients, installing or updating this package configures project orientation, the per-request protocol reminder, the pre-edit guide check and constraint recall. Each hook has a descriptive consent title, so you can see its purpose before trusting it. Existing opt-outs and Claude hook behavior are preserved.
13
+
14
+ #### What to do
15
+
16
+ For local Codex users, make Python 3.11 or later available, then:
17
+ 1. Run `npm install -g @antoneeo/agentic-sdlc-skill@latest` and `agentic-sdlc-install-skill`.
18
+ 2. Restart Codex. Open **Review hooks** or **Settings > Hooks** in the desktop app, or `/hooks` in the CLI, and review/trust the four SDLC definitions you want to run. Installation configures definitions; Codex grants trust through this separate review.
19
+ 3. Check that `npm ls -g @antoneeo/agentic-sdlc-skill` shows 1.53.0 and the intended SDLC hooks are enabled and trusted in Codex. Existing disabled or removed hooks stay opted out; see `ENFORCEMENT.md` if you choose to re-enable them.
20
+
21
+ The pre-edit checks cover native `apply_patch` on supported local orchestration. Other write paths keep the skill's written duties. Windows Codex 0.166.0-alpha.6 is the recorded native test environment; other platforms and client versions need their own verification.
22
+
23
+ ### Added
24
+
25
+ - Codex-specific user-level hook wiring, descriptive consent labels, native patch/transcript normalization and conservative configuration diagnostics.
26
+ - Packaged install/upgrade, opt-out, cleanup and Claude-preservation regression evidence.
27
+
5
28
  ## [1.52.0] - 2026-11-01
6
29
 
7
30
  ### What's new
package/README.md CHANGED
@@ -4,23 +4,18 @@
4
4
 
5
5
  <!-- whats-new:begin -->
6
6
  <!-- generated by scripts/whats_new.js from CHANGELOG.md: edit the CHANGELOG, then run node scripts/whats_new.js --write -->
7
- ## What's new in 1.52.0
7
+ ## What's new in 1.53.0
8
8
 
9
- **A session that writes only documents no longer costs you a branch.** When you run several sessions with a coordinator, a session working only on design documents can work in the folder the others already use, instead of a worktree of its own. It writes only its own unit's files, runs no git command that changes the folder, and leaves index regeneration and its closure steps to the coordinator, so you no longer merge one branch per documents-only unit. A session that writes code still holds the code lease, or works in its own worktree.
10
-
11
- **Every file several sessions touch has one writer.** Each session adds only its own rows to the review log. Translation catalogs count as code, so in the shared folder only the session holding the code lease writes them. devPNT's store goes in the Shared section of a commit map.
12
-
13
- **The coordinator survives compaction and changes only when you say so.** After its context is compacted, the coordinator rereads the leases and the shared request record before acting, instead of trusting its summary. A session it starts does not become coordinator. To change coordinator, name the new session: it records your words, tells the previous coordinator, which stops, and sends you anything written in between.
14
-
15
- **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.
9
+ **Codex can now apply the SDLC guardrails automatically.** On supported local Codex clients, installing or updating this package configures project orientation, the per-request protocol reminder, the pre-edit guide check and constraint recall. Each hook has a descriptive consent title, so you can see its purpose before trusting it. Existing opt-outs and Claude hook behavior are preserved.
16
10
 
17
11
  #### What to do
18
12
 
19
- **1. Update (everyone).** The changes arrive only with the update.
20
- 1. Run `npm install -g @antoneeo/agentic-sdlc-skill@latest`, then `agentic-sdlc-install-skill`.
21
- 2. Close and reopen your agent sessions: the new version loads only at startup.
13
+ For local Codex users, make Python 3.11 or later available, then:
14
+ 1. Run `npm install -g @antoneeo/agentic-sdlc-skill@latest` and `agentic-sdlc-install-skill`.
15
+ 2. Restart Codex. Open **Review hooks** or **Settings > Hooks** in the desktop app, or `/hooks` in the CLI, and review/trust the four SDLC definitions you want to run. Installation configures definitions; Codex grants trust through this separate review.
16
+ 3. Check that `npm ls -g @antoneeo/agentic-sdlc-skill` shows 1.53.0 and the intended SDLC hooks are enabled and trusted in Codex. Existing disabled or removed hooks stay opted out; see `ENFORCEMENT.md` if you choose to re-enable them.
22
17
 
23
- To check: `npm ls -g @antoneeo/agentic-sdlc-skill` shows 1.52.0.
18
+ The pre-edit checks cover native `apply_patch` on supported local orchestration. Other write paths keep the skill's written duties. Windows Codex 0.166.0-alpha.6 is the recorded native test environment; other platforms and client versions need their own verification.
24
19
 
25
20
  Full history: [CHANGELOG](https://github.com/Antoneeo/agentic-sdlc-skill/blob/main/CHANGELOG.md)
26
21
  <!-- whats-new:end -->
@@ -149,11 +144,18 @@ skills/agentic-sdlc-skill/
149
144
  The validator is **three files**: `sdlc_check.py` selects the lens, `sdlc_core.py` owns structural checks, and `knowledge.py` adds shared memory and KB integrity. Copy all three; core alone is not equivalent.
150
145
 
151
146
  Installing or updating the npm package wires the session-orientation hook
152
- machine-wide (user-level Claude Code settings; removal is a standing opt-out
147
+ machine-wide (user-level Claude Code settings and Codex hooks.json; removal is a standing opt-out
153
148
  that no update overrides -- ENFORCEMENT.md par.4).
154
149
  It also wires, the same way, the per-turn reminder, the guide-verdict check and
155
150
  the constraint recall (ENFORCEMENT.md par.3); the recall costs about 0.25 s per
156
- edit and adds context only at L3 on a bound file.
151
+ edit on Claude Code and adds context only at L3 on a bound file. Codex adds context on supported native patches; its latency is reported in the test evidence, not inferred from Claude.
152
+
153
+ For Codex, restart a **local** session and review the four definitions with `/hooks`.
154
+ The installer configures hooks; it does not grant trust, enable disabled features or
155
+ override managed policy. Reinstalling/updating keeps existing definitions byte-identical
156
+ and respects removal as opt-out. Local command hooks do not run under cloud orchestration.
157
+ Use the explicit package `scripts/preuninstall.js` before removing it if hook cleanup
158
+ is needed: npm versions that skip lifecycle uninstall callbacks cannot perform that cleanup.
157
159
 
158
160
  ## The family: four lenses, one spine
159
161
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentic-sdlc-skill",
3
- "version": "1.52.0",
3
+ "version": "1.53.0",
4
4
  "description": "Documentation-First SDLC protocol with triage, Vision governance 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/agentic-sdlc-skill",
3
- "version": "1.52.0",
3
+ "version": "1.53.0",
4
4
  "description": "Documentation-First SDLC protocol for Claude Code, Gemini CLI, Google Antigravity and Codex with risk triage, Vision governance, installed support files and optional devPNT integration.",
5
5
  "keywords": [
6
6
  "claude-code",
package/scripts/init.js CHANGED
@@ -3,7 +3,7 @@
3
3
  const fs = require('fs');
4
4
  const path = require('path');
5
5
  const { execSync } = require('child_process');
6
- const { SKILL_SOURCE, INSTALLED_SKILL_NAME, SELF_LENS, SIBLING_LENSES, CLIENTS, clientDetected, skillTarget, wireOrientHook, detectPython, loadTemplates, templateFor } = require('./lib');
6
+ const { SKILL_SOURCE, INSTALLED_SKILL_NAME, SELF_LENS, SIBLING_LENSES, CLIENTS, clientDetected, skillTarget, wireOrientHook, wireGlobalOrientHook, detectPython, loadTemplates, templateFor } = require('./lib');
7
7
 
8
8
  const cwd = process.cwd();
9
9
 
@@ -203,16 +203,16 @@ in the skill's \`routing.md\`: it decides which lens's method and validation rul
203
203
  that unit. L1 never reaches it. Never refer to a document whose meaning differs by lens
204
204
  ("threat model", "vision", \`principles.md\`, \`handoff.md\`) by its bare name.
205
205
 
206
- Select the owning lens by the unit's purpose, then apply only its risk scale.
207
- The project's always-on pointer stays intact: consult the selected skill rather than
208
- merging multiple mandatory ladders. All lenses already carry shared project memory
209
- (\`memory.md\`); another installation is not needed for cross-domain recall.
206
+ Select the owning lens by the unit's purpose, then apply only its risk scale.
207
+ The project's always-on pointer stays intact: consult the selected skill rather than
208
+ merging multiple mandatory ladders. All lenses already carry shared project memory
209
+ (\`memory.md\`); another installation is not needed for cross-domain recall.
210
210
  This file is NOT auto-loaded by any client: it is a note for you, deliberately additive.
211
- Delete this note once the routing pointer is integrated.
211
+ Delete this note once the routing pointer is integrated.
212
212
  `, 'multi-lens routing note');
213
213
  if (wrote && protocolPreexisting) {
214
214
  console.log(' ⚠️ A protocol pointer already existed and was NOT overwritten.');
215
- console.log(' Integrate the routing pointer from AGENTIC_MULTI_LENS.md; keep one risk scale per unit.');
215
+ console.log(' Integrate the routing pointer from AGENTIC_MULTI_LENS.md; keep one risk scale per unit.');
216
216
  }
217
217
  }
218
218
 
@@ -255,7 +255,7 @@ const ignoreLocalSettings = () => {
255
255
  };
256
256
 
257
257
  const claudeClient = detectedClients.find((c) => c.key === 'claude');
258
- const otherClients = detectedClients.filter((c) => c.key !== 'claude');
258
+ const otherClients = detectedClients.filter((c) => !['claude', 'codex'].includes(c.key));
259
259
  if (!claudeClient) {
260
260
  console.log('ℹ️ Claude Code not detected: SessionStart orientation hook not wired.');
261
261
  } else {
@@ -330,6 +330,12 @@ if (!claudeClient) {
330
330
  break;
331
331
  }
332
332
  }
333
+ const codexClient = detectedClients.find(c => c.key === 'codex');
334
+ if (codexClient) {
335
+ const result = wireGlobalOrientHook({client: codexClient, python: detectedPython, cwd});
336
+ console.log(`Codex user orientation: ${result.code}. Review configured hooks with /hooks; trust is not changed.`);
337
+ if (result.code === 'no-validator') console.log('Run agentic-sdlc-install-skill first to configure Codex hooks.');
338
+ }
333
339
  for (const c of otherClients) {
334
340
  // Said out loud rather than skipped in silence: ENFORCEMENT.md §4's manual
335
341
  // snippet is these clients' only route, and a silent skip is what let the
package/scripts/lib.js CHANGED
@@ -5,7 +5,7 @@
5
5
  const fs = require('fs');
6
6
  const path = require('path');
7
7
  const os = require('os');
8
- const { execSync } = require('child_process');
8
+ const { execSync, execFileSync } = require('child_process');
9
9
 
10
10
  const PACKAGE_ROOT = path.resolve(__dirname, '..');
11
11
  const SKILL_SOURCE = path.join(PACKAGE_ROOT, 'skills', 'agentic-sdlc-skill');
@@ -289,6 +289,8 @@ function orientHookCommand(python, validator, hybrid) {
289
289
  // reported broken. Returns null when no token names a validator: the caller must
290
290
  // then say it cannot tell, never that the hook is broken.
291
291
  function orientHookValidator(command) {
292
+ const invocation = decodeHookInvocation(command);
293
+ if (invocation) return invocation.validator;
292
294
  const cmd = String(command || '');
293
295
  const re = /"([^"]*)"|(\S+)/g;
294
296
  let m;
@@ -310,7 +312,9 @@ function findOrientHook(settings) {
310
312
  const inner = Array.isArray(group.hooks) ? group.hooks : [group];
311
313
  for (const h of inner) {
312
314
  const cmd = h && typeof h.command === 'string' ? h.command : '';
313
- if (ORIENT_ENTRY_POINTS.some((n) => cmd.includes(n)) && / orient(\s|$)/.test(cmd)) {
315
+ const invocation = decodeHookInvocation(cmd);
316
+ if ((invocation && invocation.argv[0] === 'orient') ||
317
+ (ORIENT_ENTRY_POINTS.some((n) => cmd.includes(n)) && / orient(\s|$)/.test(cmd))) {
314
318
  return cmd;
315
319
  }
316
320
  }
@@ -348,6 +352,7 @@ function orientSettingsState(target) {
348
352
  // wired | already | broken | unverifiable | malformed
349
353
  // no-validator | no-python | unsafe-path | write-failed
350
354
  function wireOrientHook(options) {
355
+ if (options.client.key === 'codex') return wireGlobalOrientHook(options);
351
356
  const cwd = options.cwd;
352
357
  const client = options.client;
353
358
  const python = options.python;
@@ -524,6 +529,10 @@ function orientMarkerRemove(target) {
524
529
  // file (user level has no local split; the path is machine-local by nature).
525
530
  // Codes follow the wireOrientHook contract, plus `opted-out`.
526
531
  function wireGlobalOrientHook(options) {
532
+ if (options.client.key === 'codex') return wireCodexHook({
533
+ event: 'SessionStart', sub: 'orient', re: / orient(\s|$)/,
534
+ marker: 'orient-hook-wired', timeout: ORIENT_HOOK_TIMEOUT, name: 'session orientation',
535
+ }, options);
527
536
  const client = options.client;
528
537
  const python = options.python;
529
538
 
@@ -603,6 +612,8 @@ function removeGlobalHookEntries(removedRoots, spec) {
603
612
  const targets = [];
604
613
  const claude = CLIENTS.find((c) => c.key === 'claude');
605
614
  if (claude) targets.push(path.join(claude.home, 'settings.json'));
615
+ const codex = CLIENTS.find((c) => c.key === 'codex');
616
+ if (codex) targets.push(path.join(codex.home, 'hooks.json'));
606
617
  for (const t of spec.markerTargets()) {
607
618
  if (!targets.some((x) => pathsEqual(x, t))) targets.push(t);
608
619
  }
@@ -616,7 +627,9 @@ function removeGlobalHookEntries(removedRoots, spec) {
616
627
  let removedHere = false;
617
628
  const ours = (h) => {
618
629
  const cmd = h && typeof h.command === 'string' ? h.command : '';
619
- if (!(ORIENT_ENTRY_POINTS.some((n) => cmd.includes(n)) && spec.re.test(cmd))) return false;
630
+ const invocation = decodeHookInvocation(cmd);
631
+ if (!(invocation ? spec.re.test(' ' + invocation.argv.join(' ')) :
632
+ ORIENT_ENTRY_POINTS.some((n) => cmd.includes(n)) && spec.re.test(cmd))) return false;
620
633
  const tok = orientHookValidator(cmd);
621
634
  if (tok === null || !path.isAbsolute(tok)) return false; // cannot attribute: keep
622
635
  return removedRoots.some((root) => pathInside(tok, root));
@@ -703,7 +716,9 @@ function findCommandHook(settings, spec) {
703
716
  const inner = Array.isArray(group.hooks) ? group.hooks : [group];
704
717
  for (const h of inner) {
705
718
  const cmd = h && typeof h.command === 'string' ? h.command : '';
706
- if (ORIENT_ENTRY_POINTS.some((n) => cmd.includes(n)) && spec.re.test(cmd)) {
719
+ const invocation = decodeHookInvocation(cmd);
720
+ if ((invocation && spec.re.test(' ' + invocation.argv.join(' '))) ||
721
+ (ORIENT_ENTRY_POINTS.some((n) => cmd.includes(n)) && spec.re.test(cmd))) {
707
722
  return cmd;
708
723
  }
709
724
  }
@@ -757,7 +772,7 @@ function remindMarkerAdd(target) { markerAddOf(REMIND_HOOK, target); }
757
772
  // `already`, and only its ABSENCE plus our marker means the user removed it --
758
773
  // a standing opt-out. Marker-first would refuse to re-check a hook someone
759
774
  // still has.
760
- function wireCommandHookInto(spec, target, python, validator) {
775
+ function wireCommandHookInto(spec, target, python, validator, handler = null) {
761
776
  if (!python) return { code: 'no-python' };
762
777
  if (!validator || ORIENT_UNSAFE_IN_PATH.test(validator)) return { code: 'unsafe-path', validator };
763
778
  const state = orientSettingsState(target);
@@ -766,10 +781,10 @@ function wireCommandHookInto(spec, target, python, validator) {
766
781
  const present = findCommandHook(settings, spec);
767
782
  if (present) return { code: 'already', target, command: present };
768
783
  if (markerHasOf(spec, target)) return { code: 'opted-out', target };
769
- const command = commandHookCommand(spec, python, validator);
784
+ const command = handler ? handler.command : commandHookCommand(spec, python, validator);
770
785
  if (!settings.hooks) settings.hooks = {};
771
786
  if (!Array.isArray(settings.hooks[spec.event])) settings.hooks[spec.event] = [];
772
- const group = { hooks: [{ type: 'command', command, timeout: spec.timeout }] };
787
+ const group = { hooks: [handler || { type: 'command', command, timeout: spec.timeout }] };
773
788
  if (spec.matcher) group.matcher = spec.matcher;
774
789
  settings.hooks[spec.event].push(group);
775
790
  try {
@@ -787,6 +802,7 @@ function wireRemindHookInto(target, python, validator) {
787
802
 
788
803
  // The machine-global twins of wireGlobalOrientHook, same target and validator.
789
804
  function wireGlobalCommandHook(spec, options) {
805
+ if (options.client.key === 'codex') return wireCodexHook(spec, options);
790
806
  const client = options.client;
791
807
  const validator = path.join(skillTarget(client), 'scripts', ORIENT_ENTRY_POINT);
792
808
  if (!fs.existsSync(validator)) return { code: 'no-validator', validator };
@@ -796,6 +812,129 @@ function wireGlobalRemindHook(options) { return wireGlobalCommandHook(REMIND_HOO
796
812
  function wireGlobalVerdictHook(options) { return wireGlobalCommandHook(VERDICT_HOOK, options); }
797
813
  function wireGlobalRecallHook(options) { return wireGlobalCommandHook(RECALL_HOOK, options); }
798
814
 
815
+ function wireCodexHook(spec, options) {
816
+ const validator = path.join(skillTarget(options.client), 'scripts', ORIENT_ENTRY_POINT);
817
+ if (!fs.existsSync(validator)) return { code: 'no-validator', validator };
818
+ if (!options.python) return { code: 'no-python', validator };
819
+ if (ORIENT_UNSAFE_IN_PATH.test(validator)) return { code: 'unsafe-path', validator };
820
+ const sources = hookSources(options);
821
+ if (sources.error) return { code: sources.error, target: sources.target };
822
+ for (const source of sources.sources) {
823
+ const groups = source.settings.hooks && source.settings.hooks[spec.event];
824
+ if (groups !== undefined && !Array.isArray(groups)) return { code: 'malformed', target: source.target };
825
+ for (const group of groups || []) {
826
+ for (const handler of (Array.isArray(group.hooks) ? group.hooks : [group])) {
827
+ const command = (process.platform === 'win32' && (handler.commandWindows || handler.command_windows)) || handler.command || '';
828
+ const invocation = decodeHookInvocation(command);
829
+ const matches = invocation ? invocation.argv[0] === spec.sub.split(' ')[0]
830
+ : ORIENT_ENTRY_POINTS.some(n => command.includes(n)) && spec.re.test(command);
831
+ if (!matches) continue;
832
+ if (group.enabled === false || handler.enabled === false) return { code: 'opted-out', target: source.target };
833
+ const found = orientHookValidator(command);
834
+ if (!found || !path.isAbsolute(found)) return { code: 'unverifiable', target: source.target };
835
+ if (!fs.existsSync(found)) return { code: 'broken', target: source.target };
836
+ if (!codexHookEquivalent(spec, group, handler, command, invocation))
837
+ return { code: 'unverifiable', target: source.target };
838
+ markerAddOf(spec, source.target);
839
+ return { code: 'already', target: source.target, command };
840
+ }
841
+ }
842
+ }
843
+ // Absent sources still carry opt-outs (including an entirely deleted TOML file).
844
+ for (const target of sources.targets) {
845
+ if (markerHasOf(spec, target)) return { code: 'opted-out', target };
846
+ }
847
+ const profile = hookProfile(options.client);
848
+ return wireCommandHookInto({...spec, matcher: spec.event === 'PreToolUse' ? '^apply_patch$' : undefined},
849
+ path.join(options.client.home, profile.file), options.python, validator,
850
+ hookHandler(spec, options.client, options.python, validator));
851
+ }
852
+
853
+ function codexHookEquivalent(spec, group, handler, command, invocation) {
854
+ if (handler.type !== 'command') return false;
855
+ const matcher = group.matcher;
856
+ if (spec.event === 'PreToolUse' ? matcher !== '^apply_patch$' : matcher != null && matcher !== '') return false;
857
+ const expected = spec.sub.split(' ');
858
+ if (invocation) return JSON.stringify(invocation.argv) === JSON.stringify(expected);
859
+ // Recognizing a validator is ownership evidence, not proof of equivalent dispatch.
860
+ const tokens = [...command.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map(m => m[1] ?? m[2] ?? m[3]);
861
+ const validator = orientHookValidator(command);
862
+ return tokens.length === expected.length + 2 && tokens[1] === validator &&
863
+ JSON.stringify(tokens.slice(2)) === JSON.stringify(expected);
864
+ }
865
+
866
+ // The legacy Claude builder remains unchanged. Codex normalizes child exit codes
867
+ // without shell-specific `exit` syntax; stdin/stdout are passed through verbatim.
868
+ const 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())";
869
+ function hookProfile(client) {
870
+ return client.key === 'codex' ? {file: 'hooks.json'} : client.key === 'claude' ? {file: 'settings.json'} : null;
871
+ }
872
+ function hookHandler(spec, client, python, validator) {
873
+ const data = Buffer.from(JSON.stringify({client: client.key, validator, argv: spec.sub.split(' ')})).toString('base64');
874
+ const interpreter = /^[\w.-]+$/.test(python) ? python : '"' + python + '"';
875
+ const handler = {type:'command', command: interpreter + ' -c "' + CODEX_HOOK_WRAPPER + '" agentic-sdlc-hook-v1 ' + data,
876
+ timeout:spec.timeout,
877
+ statusMessage: {
878
+ orient: 'SDLC: load project context when the session starts',
879
+ remind: 'SDLC: remind the agent to follow the development protocol',
880
+ verdict: 'SDLC: block edits missing triage or required guide reads',
881
+ constraints: 'SDLC: recall applicable constraints before editing',
882
+ }[spec.sub.split(' ')[0]]};
883
+ if (spec.sub === 'orient') handler.additionalContextLimit = 0; // orient itself caps output at 9,500 chars
884
+ return handler;
885
+ }
886
+ function decodeHookInvocation(command) {
887
+ const middle = ' -c "' + CODEX_HOOK_WRAPPER + '" agentic-sdlc-hook-v1 ';
888
+ const at = String(command || '').indexOf(middle);
889
+ if (at < 1) return null;
890
+ if (!/^[\w.-]+$|^"[^"$`\r\n]+"$/.test(command.slice(0, at))) return null;
891
+ const encoded = command.slice(at + middle.length);
892
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) return null;
893
+ try {
894
+ const data = JSON.parse(Buffer.from(encoded, 'base64').toString('utf8'));
895
+ if (data.client !== 'codex' || typeof data.validator !== 'string' ||
896
+ !Array.isArray(data.argv) || !data.argv.every(x=>typeof x === 'string') ||
897
+ !['orient','remind','verdict','constraints'].includes(data.argv[0])) return null;
898
+ return data;
899
+ } catch (_) { return null; }
900
+ }
901
+ function hookSources(options) {
902
+ const sources = [], targets = [];
903
+ const cwd = options.cwd || process.cwd();
904
+ for (const dir of [options.client.home, path.join(cwd, '.codex')]) {
905
+ for (const name of ['hooks.json', 'config.toml']) {
906
+ const target = path.join(dir, name);
907
+ targets.push(target);
908
+ if (!fs.existsSync(target)) continue;
909
+ try {
910
+ const settings = name.endsWith('.json') ? JSON.parse(fs.readFileSync(target,'utf8').replace(/^\uFEFF/,'')) :
911
+ JSON.parse(execFileSync(options.python,['-c',
912
+ "import json,sys,tomllib;print(json.dumps(tomllib.load(open(sys.argv[1],'rb'))))",target],
913
+ {encoding:'utf8',timeout:5000,stdio:['ignore','pipe','pipe']}));
914
+ if (!settings || typeof settings !== 'object' || Array.isArray(settings) ||
915
+ (settings.hooks !== undefined && (!settings.hooks || typeof settings.hooks !== 'object' || Array.isArray(settings.hooks))))
916
+ return {error:'malformed',target};
917
+ for (const groups of Object.values(settings.hooks || {})) {
918
+ if (!Array.isArray(groups)) return {error:'malformed',target};
919
+ for (const group of groups) {
920
+ if (!group || typeof group !== 'object' || Array.isArray(group) ||
921
+ (group.hooks !== undefined && !Array.isArray(group.hooks))) return {error:'malformed',target};
922
+ for (const handler of group.hooks || [group]) {
923
+ if (!handler || typeof handler !== 'object' || Array.isArray(handler) ||
924
+ ['command','commandWindows','command_windows'].some(key =>
925
+ handler[key] !== undefined && typeof handler[key] !== 'string')) return {error:'malformed',target};
926
+ }
927
+ }
928
+ }
929
+ if ((settings.features && settings.features.hooks === false) || settings.allow_managed_hooks_only === true)
930
+ return {error:'disabled-by-policy',target};
931
+ sources.push({target,settings});
932
+ } catch (_) { return {error:name.endsWith('.toml') ? 'unverifiable' : 'malformed',target}; }
933
+ }
934
+ }
935
+ return {sources,targets};
936
+ }
937
+
799
938
  // Uninstall twin for the constant-command hooks: one {target, event, name} per
800
939
  // removal, so the uninstaller can say what it removed.
801
940
  function removeGlobalCommandHooks(removedRoots) {
@@ -34,10 +34,21 @@ for (const client of CLIENTS) {
34
34
  console.log(`✅ Detected: ${client.label}`);
35
35
  detected = true;
36
36
  const installed = installSkill(client);
37
- // F-042: wire the machine-global orientation hook — the install IS the
38
- // consent, so no question is ever asked. Claude Code only (the one client
39
- // whose hook shape a fixture pins); removal is a standing opt-out the
40
- // marker remembers. A convenience must never fail an npm install: wrapped.
37
+ // F-091 adds definitions for Codex; its separate trust decision stays human.
38
+ // F-042's legacy Claude wiring remains below. Per-hook markers preserve
39
+ // removals, and wiring failures must never abort package installation.
40
+ if (client.key === 'codex' && installed) {
41
+ const python = detectPython();
42
+ for (const [name, wire] of [['orientation', wireGlobalOrientHook], ['reminder', wireGlobalRemindHook],
43
+ ['guide-verdict check', wireGlobalVerdictHook], ['constraint recall', wireGlobalRecallHook]]) {
44
+ try {
45
+ const result = wire({client, python});
46
+ console.log(`Codex ${name}: ${result.code}${result.target ? ' (' + result.target + ')' : ''}.`);
47
+ } catch (_) { console.log(`Codex ${name}: configuration failed; existing settings preserved.`); }
48
+ }
49
+ console.log('Configured Codex hooks require human trust. Check the per-hook results above and review them with /hooks in a local Codex session.');
50
+ console.log('Client policy, disabled hooks or cloud orchestration may prevent execution; no trust or policy setting was changed.');
51
+ }
41
52
  if (client.key === 'claude' && installed) {
42
53
  try {
43
54
  // F-046: the per-turn reminder, wired alongside and never instead of
@@ -159,10 +159,8 @@ Emits the `ai_docs/` orientation to stdout at session start, in the order an arr
159
159
  and a Python interpreter now installs this hook itself — it was a manual step until
160
160
  2026-08-25, and the field result was exactly the defect this level exists to prevent: an
161
161
  agent worked a governed project without ever meeting the router. The snippet below is
162
- the fallback for the cases init declines, and the list is exhaustive: **any client
163
- other than Claude Code** (Codex and Gemini keep the manual snippet — no fixture in the
164
- repository pins their hook schema, and writing one in an unverified shape is how a
165
- wired-but-dead hook is born), no Python, the skill not installed yet, a settings file
162
+ the fallback for the cases init declines, and the list is exhaustive: **a client without an implemented hook profile** (Gemini and Antigravity keep manual
163
+ setup; Codex uses user-global wiring as described below), no Python, the skill not installed yet, a settings file
166
164
  that is not valid JSON or carries a `hooks`/`SessionStart` shape the writer does not
167
165
  recognise (it never rewrites one it cannot read), a validator path holding a character
168
166
  that cannot be placed in a command safely, or a settings file it cannot write. `init`
@@ -248,7 +246,7 @@ Claude Code — in the project's `.claude/settings.json`:
248
246
  }
249
247
  ```
250
248
 
251
- Codex — in `.codex/hooks.json`, the same `SessionStart` → `{"type":"command","command":"… orient"}` shape (this replaces the legacy static-echo protocol some fixtures still carry).
249
+ Codex — use `agentic-sdlc-install-skill` to configure the user-level hooks, then review them with `/hooks`. No new project-relative command is generated; existing manual project sources are inspected before wiring.
252
250
 
253
251
  Gemini CLI — wire the same command into its startup-hook mechanism if present; otherwise the step simply degrades to the manual Phase-1 reads (no capability lost).
254
252
 
@@ -325,3 +323,42 @@ it into CI**. It is the criterion by which future units are judged, and a
325
323
  measurement that can fail a build becomes a target -- a targeted measurement
326
324
  stops measuring. Run it when deciding whether a proposed rule is worth its
327
325
  ceremony, not on every push.
326
+
327
+ ## Codex local hook profile (F-091)
328
+
329
+ The main software package configures four user-level handlers at installation or
330
+ update: SessionStart/orient, UserPromptSubmit/remind, and native apply_patch
331
+ PreToolUse/verdict plus constraints. `CODEX_HOME` selects the configuration home;
332
+ the validator's absolute path comes from the same skill resolver as installation.
333
+ Project init inspects existing sources and configures user-level orientation only
334
+ when needed. Claude's writers, shell commands, settings paths and opt-out rules
335
+ are unchanged. Sibling installers retain their own existing scope.
336
+
337
+ Restart a supported local Codex client and open `/hooks` to inspect/trust the
338
+ exact definitions. The installer never grants trust or changes client feature or
339
+ managed-policy settings. A changed definition can require another review. Hook
340
+ scripts require local orchestration; cloud-orchestrated sessions retain the manual
341
+ skill duties even when some tools execute locally. Configuration inspection alone
342
+ cannot certify native execution, trust or a supported client version.
343
+
344
+ The generated command is a fixed Python stdlib carrier with marker
345
+ `agentic-sdlc-hook-v1` and base64 JSON data (client, absolute validator, argv).
346
+ It forwards stdin/stdout, preserves a JSON denial and normalizes a child's nonzero
347
+ exit code without shell-specific exit syntax. The carrier and legacy commands
348
+ are both recognized for attribution and cleanup. Orientation sets an unlimited
349
+ client context threshold only because the validator itself caps output at 9,500
350
+ characters. Other outputs keep the client's normal limits.
351
+
352
+ No shell write interception is added. Codex read hints recognize bounded literal
353
+ Get-Content/cat commands and supported literal exec wrappers; dynamic scripts,
354
+ unknown transcript formats and inaccessible/oversized inputs remain fail-open.
355
+ Multiple patch targets and both move paths are checked; recall shares 15 lines.
356
+ No hook grants permission. Existing user hooks, opt-out markers, malformed config
357
+ and inline TOML are preserved. Inline configuration inspection needs stdlib
358
+ `tomllib`; when unavailable the installer reports unverified instead of guessing.
359
+
360
+ Removing a generated entry opts out that hook for that target; upgrades do not
361
+ re-add it. To clean up while the package still exists, run its explicit
362
+ `scripts/preuninstall.js` with Node, then uninstall the npm package. Some npm
363
+ versions do not invoke preuninstall automatically. Cleanup removes only entries
364
+ attributable to removed skill roots, and does not edit the Codex trust store.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: agentic-sdlc
3
- version: 1.52.0
3
+ version: 1.53.0
4
4
  description: Documentation-First SDLC protocol with risk-proportional triage, Vision as a guide, a complete Standalone mode and optional symbiosis with devPNT. Use for features, significant bugs, refactors, audits and documented maintenance.
5
5
  author: Antonio Pinto (https://github.com/Antoneeo)
6
6
  copyright: (c) 2026 Antonio Pinto
@@ -52,7 +52,7 @@ The validator now ships as three files: entry point, `sdlc_core.py`, `knowledge.
52
52
 
53
53
  Always classify the request before choosing the process. Declare the chosen level to the user when you start operational work.
54
54
 
55
- **Declare the level WITH the router verdict** (one line, for L2, L3 and Spike — L1 declares the level alone): the result of the guide-router lookup described under `## Operative Guides`, i.e. `Level: L2 · router: no match` or `Level: L3 · router: GUIDE_release.md → read`. The lookup is the consult trigger; making its result a declared output is what keeps it from being skipped — a level declared without a verdict makes "did not look" indistinguishable from "looked, nothing matched". Name the guide you matched, or `no match`; name a second one only when it covers a genuinely distinct concern (typically one operative guide plus the comprehension map of the component you are touching). The verdict is never a listing of the catalogue, and never an excuse to read every guide. On Claude Code with the package's hooks wired, an edit in a project with guides is refused until the session shows a verdict (or `Level: L1`) and has read every guide it names (`ENFORCEMENT.md` §3); other clients keep it a written duty.
55
+ **Declare the level WITH the router verdict** (one line, for L2, L3 and Spike — L1 declares the level alone): the result of the guide-router lookup described under `## Operative Guides`, i.e. `Level: L2 · router: no match` or `Level: L3 · router: GUIDE_release.md → read`. The lookup is the consult trigger; making its result a declared output is what keeps it from being skipped — a level declared without a verdict makes "did not look" indistinguishable from "looked, nothing matched". Name the guide you matched, or `no match`; name a second one only when it covers a genuinely distinct concern (typically one operative guide plus the comprehension map of the component you are touching). The verdict is never a listing of the catalogue, and never an excuse to read every guide. On Claude Code, and on supported local Codex sessions after the user trusts the installed hooks, an edit in a project with guides is refused until the session shows a verdict (or `Level: L1`) and has read every guide it names (`ENFORCEMENT.md` §3). Codex covers native `apply_patch`; unsupported clients, cloud orchestration and other write paths keep the written duty.
56
56
 
57
57
  | Level | Criteria | Required process |
58
58
  |---|---|---|
@@ -34,11 +34,11 @@ proof that it caused this incident.
34
34
  Do not repeat an invalidated hypothesis unless new evidence reopens it.
35
35
 
36
36
  3. **Test and trace the mechanism.** Reproduce and isolate the smallest faithful
37
- failing case when feasible; bisect inputs, paths or changes when informative.
38
- Skip a reproduction already known to omit the incident's causal conditions;
39
- choose a faithful alternative or disclose the gap. Stop diagnostic checks when
40
- further results cannot change the causal or fix decision; this does not replace
41
- the regression and recovery verification in step 5.
37
+ failing case when feasible; bisect inputs, paths or changes when informative.
38
+ Skip a reproduction already known to omit the incident's causal conditions;
39
+ choose a faithful alternative or disclose the gap. Stop diagnostic checks when
40
+ further results cannot change the causal or fix decision; this does not replace
41
+ the regression and recovery verification in step 5.
42
42
  If the incident is intermittent or inaccessible, use captured traces and
43
43
  targeted diagnostic observations instead of declaring investigation impossible.
44
44
  Add minimal instrumentation when evidence is insufficient. Prefer read-only
@@ -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). "
@@ -2700,6 +2801,192 @@ _DECLARATION_RE = re.compile(
2700
2801
  _GUIDE_NAME_RE = re.compile(r"GUIDE_[A-Za-z0-9_-]+\.md")
2701
2802
 
2702
2803
 
2804
+ def _hint_path(value, cwd):
2805
+ if not isinstance(value, str) or not value:
2806
+ return None
2807
+ p = Path(value)
2808
+ if not p.is_absolute():
2809
+ if not cwd or not Path(cwd).is_absolute():
2810
+ return None
2811
+ p = Path(cwd) / p
2812
+ return str(p.resolve())
2813
+
2814
+
2815
+ def hook_edits(payload):
2816
+ """Parse the complete native apply_patch syntax without executing it.
2817
+
2818
+ Unknown or incomplete input yields no partial target set. Move checks both
2819
+ the old and new paths; file membership is evaluated by the existing gate.
2820
+ """
2821
+ command = (payload.get("tool_input") or {}).get("command")
2822
+ if not isinstance(command, str) or len(command.encode("utf-8")) > VERDICT_LINE_MAX:
2823
+ return None
2824
+ lines = command.strip().splitlines()
2825
+ if not lines or lines[0] != "*** Begin Patch" or lines[-1] != "*** End Patch":
2826
+ return None
2827
+ edits, current, mode, changed = [], None, None, False
2828
+ for line in lines[1:-1]:
2829
+ match = re.fullmatch(r"\*\*\* (Add|Update|Delete) File: (.+)", line)
2830
+ if match:
2831
+ if current is not None and mode != "Delete" and not changed:
2832
+ return None
2833
+ mode, value = match.groups()
2834
+ target = _hint_path(value, payload.get("cwd"))
2835
+ if not target:
2836
+ return None
2837
+ current = {"path": target, "new_text": ""}
2838
+ edits.append(current)
2839
+ changed = False
2840
+ elif line.startswith("*** Move to: ") and current is not None and mode == "Update" and not changed:
2841
+ target = _hint_path(line[len("*** Move to: "):], payload.get("cwd"))
2842
+ if not target:
2843
+ return None
2844
+ current = {"path": target, "new_text": ""}
2845
+ edits.append(current)
2846
+ elif current is not None and mode != "Delete" and (
2847
+ line.startswith(("+", "-", " ", "@@")) or line == "*** End of File"):
2848
+ if mode == "Add" and not line.startswith("+"):
2849
+ return None
2850
+ if line.startswith(("+", "-")):
2851
+ changed = True
2852
+ if line.startswith("+"):
2853
+ current["new_text"] += line[1:] + "\n"
2854
+ else:
2855
+ return None
2856
+ if current is not None and mode != "Delete" and not changed:
2857
+ return None
2858
+ return edits or None
2859
+
2860
+
2861
+ def shell_read_paths(command, cwd, workdir=None):
2862
+ """Literal Get-Content/cat reads only: no shell expansion or execution."""
2863
+ if not isinstance(command, str) or re.search(r"[$`\r\n;|&<>\x00]", command):
2864
+ return None
2865
+ token_re = re.compile(r"\s*(?:'([^']*)'|\"([^\"]*)\"|([^\s'\"]+))")
2866
+ tokens, pos = [], 0
2867
+ while pos < len(command.rstrip()):
2868
+ match = token_re.match(command, pos)
2869
+ if not match:
2870
+ return None
2871
+ token = next(x for x in match.groups() if x is not None)
2872
+ tokens.append(token)
2873
+ pos = match.end()
2874
+ if not tokens or tokens[0].lower() not in ("get-content", "cat"):
2875
+ return None
2876
+ paths, i = [], 1
2877
+ while i < len(tokens):
2878
+ token = tokens[i]
2879
+ if tokens[0].lower() == "get-content" and token.lower() in ("-literalpath", "-path", "-raw"):
2880
+ if token.lower() != "-raw" and i + 1 == len(tokens):
2881
+ return None
2882
+ elif tokens[0].lower() == "get-content" and token.lower() == "-totalcount":
2883
+ i += 1
2884
+ if i == len(tokens) or not tokens[i].isdigit():
2885
+ return None
2886
+ elif tokens[0] == "cat" and token == "--":
2887
+ pass
2888
+ elif token.startswith("-") or re.search(r"[*?\[\],]", token):
2889
+ return None
2890
+ else:
2891
+ base = _hint_path(workdir, cwd) if workdir else cwd
2892
+ resolved = _hint_path(token, base)
2893
+ if not resolved:
2894
+ return None
2895
+ paths.append(resolved)
2896
+ i += 1
2897
+ return paths or None
2898
+
2899
+
2900
+ def _codex_literal_calls(code):
2901
+ """Recognize a small non-executable JS carrier grammar, otherwise nothing."""
2902
+ if not isinstance(code, str):
2903
+ return []
2904
+ calls, pos = [], 0
2905
+ pattern = re.compile(r"\s*(?:text\(\s*)?await\s+tools\.exec_command\((\{.*?\})\)\s*\)?\s*;?", re.DOTALL)
2906
+ field = re.compile(r'\s*(?:"(cmd|workdir)"|(cmd|workdir))\s*:\s*("(?:[^"\\]|\\.)*")\s*(,|$)')
2907
+ while pos < len(code.rstrip()):
2908
+ match = pattern.match(code, pos)
2909
+ if not match:
2910
+ return []
2911
+ obj, off, args = match[1][1:-1], 0, {}
2912
+ while off < len(obj.rstrip()):
2913
+ item = field.match(obj, off)
2914
+ if not item or (item[1] or item[2]) in args:
2915
+ return []
2916
+ try:
2917
+ args[item[1] or item[2]] = json.loads(item[3])
2918
+ except ValueError:
2919
+ return []
2920
+ off = item.end()
2921
+ if "cmd" not in args:
2922
+ return []
2923
+ calls.append(args)
2924
+ pos = match.end()
2925
+ return calls
2926
+
2927
+
2928
+ def transcript_events(path):
2929
+ """Yield legacy assistant blocks, plus normalized recognized Codex blocks.
2930
+
2931
+ This is read-only and bounded by the existing transcript limits. Historical
2932
+ cwd is taken from host metadata, never guessed from the present process.
2933
+ """
2934
+ cwd = None
2935
+ with Path(path).open("rb") as fh:
2936
+ for raw in fh:
2937
+ if len(raw) > VERDICT_LINE_MAX:
2938
+ continue
2939
+ try:
2940
+ entry = json.loads(raw.decode("utf-8", errors="replace"))
2941
+ except ValueError:
2942
+ continue
2943
+ if not isinstance(entry, dict):
2944
+ continue
2945
+ if entry.get("type") == "assistant":
2946
+ yield entry
2947
+ continue
2948
+ data = entry.get("payload")
2949
+ if not isinstance(data, dict):
2950
+ continue
2951
+ if entry.get("type") in ("session_meta", "turn_context"):
2952
+ if isinstance(data.get("cwd"), str):
2953
+ cwd = data["cwd"]
2954
+ continue
2955
+ if entry.get("type") != "response_item":
2956
+ continue
2957
+ blocks = []
2958
+ if data.get("type") == "message" and data.get("role") == "assistant":
2959
+ blocks = [{"type": "text", "text": x.get("text", "")}
2960
+ for x in (data.get("content") if isinstance(data.get("content"), list) else []) if isinstance(x, dict) and x.get("type") == "output_text"]
2961
+ elif data.get("type") in ("function_call", "custom_tool_call"):
2962
+ name = data.get("name")
2963
+ calls = []
2964
+ if name in ("exec_command", "Bash"):
2965
+ try:
2966
+ args = json.loads(data.get("arguments", "{}"))
2967
+ except (ValueError, TypeError):
2968
+ args = None
2969
+ if isinstance(args, dict):
2970
+ calls = [args]
2971
+ elif name == "exec":
2972
+ calls = _codex_literal_calls(data.get("input"))
2973
+ elif name == "apply_patch":
2974
+ command = data.get("input")
2975
+ if command is None:
2976
+ try:
2977
+ command = json.loads(data.get("arguments", "{}" )).get("command")
2978
+ except (ValueError, TypeError, AttributeError):
2979
+ pass
2980
+ for edit in hook_edits({"tool_input": {"command": command}, "cwd": cwd}) or []:
2981
+ blocks.append({"type": "tool_use", "name": "Write", "input": {"file_path": edit["path"]}})
2982
+ for args in calls:
2983
+ for target in shell_read_paths(args.get("cmd", args.get("command")), cwd, args.get("workdir")) or []:
2984
+ blocks.append({"type": "tool_use", "name": "Read", "input": {"file_path": target}})
2985
+ if blocks:
2986
+ yield {"type": "assistant", "isSidechain": bool(entry.get("agent_id") or data.get("agent_id")),
2987
+ "message": {"content": blocks}}
2988
+
2989
+
2703
2990
  def transcript_facts(path):
2704
2991
  """What the session transcript shows about the verdict duty, or None when it
2705
2992
  cannot be read within the bounds.
@@ -2714,14 +3001,7 @@ def transcript_facts(path):
2714
3001
  p = Path(path)
2715
3002
  if not p.is_file() or p.stat().st_size > VERDICT_MAX_BYTES:
2716
3003
  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
3004
+ for entry in transcript_events(p):
2725
3005
  if not isinstance(entry, dict) or entry.get("type") != "assistant":
2726
3006
  continue
2727
3007
  content = (entry.get("message") or {}).get("content")
@@ -2755,6 +3035,13 @@ def transcript_facts(path):
2755
3035
  def verdict_reason(payload, root=None, docs_name=None):
2756
3036
  """The refusal line for this edit event, or None when the edit may proceed.
2757
3037
  Without a root, the project is the one holding the edited file (hook_project)."""
3038
+ if payload.get("tool_name") == "apply_patch" and not payload.get("agent_id"):
3039
+ for edit in hook_edits(payload) or []:
3040
+ reason = verdict_reason({**payload, "tool_name": "Edit", "tool_input": {
3041
+ "file_path": edit["path"], "new_string": edit["new_text"]}}, root, docs_name)
3042
+ if reason:
3043
+ return reason
3044
+ return None
2758
3045
  if payload.get("tool_name") not in VERDICT_EDIT_TOOLS or payload.get("agent_id"):
2759
3046
  return None
2760
3047
  tool_input = payload.get("tool_input") or {}
@@ -3113,14 +3400,7 @@ def transcript_work(path):
3113
3400
  p = Path(path)
3114
3401
  if not p.is_file() or p.stat().st_size > VERDICT_MAX_BYTES:
3115
3402
  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
3403
+ for entry in transcript_events(p):
3124
3404
  if not isinstance(entry, dict) or entry.get("type") != "assistant":
3125
3405
  continue
3126
3406
  content = (entry.get("message") or {}).get("content")
@@ -3175,6 +3455,17 @@ def constraints_hook_context(payload, root=None, docs_name=None):
3175
3455
  a subagent, on a file of a project whose open L3 code unit binds it (or the
3176
3456
  unit's own ANALYSIS, about to name a path a P row binds -- UC6), by a session
3177
3457
  that worked on that unit and last declared L3."""
3458
+ if payload.get("tool_name") == "apply_patch" and not payload.get("agent_id"):
3459
+ lines = []
3460
+ for edit in hook_edits(payload) or []:
3461
+ context = constraints_hook_context({**payload, "tool_name": "Edit", "tool_input": {
3462
+ "file_path": edit["path"], "new_string": edit["new_text"]}}, root, docs_name)
3463
+ for line in (context or "").splitlines():
3464
+ if line not in lines:
3465
+ lines.append(line)
3466
+ if len(lines) > CONSTRAINTS_HOOK_LINES:
3467
+ lines = lines[:CONSTRAINTS_HOOK_LINES - 1] + [lines[-1]]
3468
+ return "\n".join(lines) or None
3178
3469
  if payload.get("tool_name") not in VERDICT_EDIT_TOOLS or payload.get("agent_id"):
3179
3470
  return None
3180
3471
  tool_input = payload.get("tool_input") or {}
@@ -3865,6 +4156,10 @@ def cmd_orient(args):
3865
4156
  for client, entries in sorted(orient_wiring(root).items()):
3866
4157
  if len(entries) > 1:
3867
4158
  places = ", ".join(sorted(set(entries.values())))
4159
+ if client == "codex":
4160
+ tail.append(f"[note] Codex has {len(entries)} configured orientation definitions "
4161
+ f"({places}); trust and runtime policy determine delivery. Keep one equivalent definition.")
4162
+ continue
3868
4163
  tail.append(f"[note] session orientation is wired {len(entries)} times for one "
3869
4164
  f"client ({places}): each session receives every copy. Keep one "
3870
4165
  "entry and remove the others.")