@inkobytes/nexus 1.0.6 โ 1.0.8
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 +12 -0
- package/README.md +41 -1
- package/bin/nexus.js +8 -1
- package/docs/hooks.md +94 -0
- package/docs/nexus-dynamic-governed-loops.md +135 -0
- package/package.json +2 -1
- package/skills/nexus/SKILL.md +10 -4
- package/src/commands/completion.js +4 -0
- package/src/commands/doctor.js +79 -189
- package/src/commands/hooks.js +305 -0
- package/src/commands/init.js +7 -172
- package/src/commands/install-skill.js +83 -0
- package/src/lib/protocolText.js +196 -0
package/src/commands/doctor.js
CHANGED
|
@@ -10,39 +10,19 @@ import { listLocks } from '../lib/lockManager.js';
|
|
|
10
10
|
import { getConfig } from '../lib/config.js';
|
|
11
11
|
import { AGENT_SCOPE_LIST } from '../lib/agentScopes.js';
|
|
12
12
|
import { DEFAULT_MATRIX, loadPermissions, getChmodPath } from '../lib/permissions.js';
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
'December',
|
|
27
|
-
];
|
|
28
|
-
|
|
29
|
-
const START_MARKER = '<!-- NEXUS-AGENT-PROTOCOL:START -->';
|
|
30
|
-
const END_MARKER = '<!-- NEXUS-AGENT-PROTOCOL:END -->';
|
|
31
|
-
|
|
32
|
-
const CONTINUITY_TEMPLATE = `# CONTINUITY
|
|
33
|
-
Goal: Project setup
|
|
34
|
-
State: Planning
|
|
35
|
-
|
|
36
|
-
Now: Initial Nexus setup
|
|
37
|
-
Next: Confirm first task
|
|
38
|
-
Blockers: None
|
|
39
|
-
Decisions:
|
|
40
|
-
- Nexus manages swarm coordination
|
|
41
|
-
- Continuity and memories are agent-local
|
|
42
|
-
Files:
|
|
43
|
-
- _NEXUS_QUEUE.md
|
|
44
|
-
- _NEXUS_STANDUP.md
|
|
45
|
-
`;
|
|
13
|
+
import {
|
|
14
|
+
CONTINUITY_TEMPLATE,
|
|
15
|
+
END_MARKER,
|
|
16
|
+
MEMORY_INDEX_GUARDRAIL,
|
|
17
|
+
MEMORY_INDEX_TEMPLATE,
|
|
18
|
+
REQUIRED_CONTEXT_READ,
|
|
19
|
+
SKILL_CONTEXT_GUARDRAIL,
|
|
20
|
+
START_MARKER,
|
|
21
|
+
currentMemoryMonthFolder,
|
|
22
|
+
fullEntrypoint,
|
|
23
|
+
protocolBlock,
|
|
24
|
+
} from '../lib/protocolText.js';
|
|
25
|
+
import { HOOK_AGENT_CONFIGS, hookStatus } from './hooks.js';
|
|
46
26
|
|
|
47
27
|
const LOCAL_DECISIONS_TEMPLATE = `# Decisions
|
|
48
28
|
|
|
@@ -53,148 +33,6 @@ const LOCAL_GITIGNORE_LINES = ['DECISIONS.md', 'docs-priv/', '.nexus/presence/']
|
|
|
53
33
|
const STANDUP_FORMAT_GUIDANCE = 'YYYY-MM-DD HH:MM AM/PM @agent [STATUS]: message';
|
|
54
34
|
const STANDUP_RULES_LINE = `*Rules: Append new entries at the bottom. One line per message. Use \`${STANDUP_FORMAT_GUIDANCE}\` so relevance is visible. Use ๐งต for long discussions.*`;
|
|
55
35
|
|
|
56
|
-
const MEMORY_INDEX_TEMPLATE = `# Memory Index
|
|
57
|
-
|
|
58
|
-
Newest first, max 10 visible entries.
|
|
59
|
-
|
|
60
|
-
Format:
|
|
61
|
-
|
|
62
|
-
- YYYY-Month/YYYY-MM-DD-HHMM-topic.md - short session label
|
|
63
|
-
|
|
64
|
-
Entries live in month folders from the start, for example:
|
|
65
|
-
|
|
66
|
-
- \`2026-January/2026-01-15-1030-project-setup.md\`
|
|
67
|
-
- \`2026-February/2026-02-01-0900-debug-session.md\`
|
|
68
|
-
|
|
69
|
-
This keeps monthly review simple: ask an agent to read one month folder and summarize the Markdown files.
|
|
70
|
-
|
|
71
|
-
`;
|
|
72
|
-
|
|
73
|
-
function currentMemoryMonthFolder(now = new Date()) {
|
|
74
|
-
return `${now.getFullYear()}-${MONTH_NAMES[now.getMonth()]}`;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
function protocolBlock(agent) {
|
|
78
|
-
return `${START_MARKER}
|
|
79
|
-
|
|
80
|
-
## Nexus Project Protocol
|
|
81
|
-
|
|
82
|
-
This project uses Nexus for multi-agent coordination.
|
|
83
|
-
|
|
84
|
-
### Start Here
|
|
85
|
-
|
|
86
|
-
1. Read \`_NEXUS_CONSTITUTION.md\`.
|
|
87
|
-
2. Read \`_NEXUS_QUEUE.md\` for executable priorities.
|
|
88
|
-
3. Read \`_NEXUS_STANDUP.md\` for comms, decisions, and completion notes.
|
|
89
|
-
4. Read \`USER.md\` if present for local human preferences.
|
|
90
|
-
5. Read \`${agent.continuity}\` for current session state.
|
|
91
|
-
6. Read \`${agent.memoryIndex}\` and the latest memory entry when resync is needed.
|
|
92
|
-
|
|
93
|
-
### Nexus Rules
|
|
94
|
-
|
|
95
|
-
- Claim before editing shared project files: \`nexus claim <path> @Agent "intent"\`.
|
|
96
|
-
- Nexus is agent-native and file-native, not human-native: optimize for concurrency and rollback, not feature-commit aesthetics.
|
|
97
|
-
- Release each claimed file as soon as it reaches a coherent checkpoint.
|
|
98
|
-
- Never hold claims just to bundle a prettier feature commit; that blocks other agents.
|
|
99
|
-
- Release finished work through Nexus: \`nexus release <path> "commit message"\`.
|
|
100
|
-
- Use \`nexus next @Agent\` for the next safe queue task.
|
|
101
|
-
- Do not free-roam into unassigned or \`Auto-flow: no\` work without user approval.
|
|
102
|
-
- Direct user instruction can override queue order, but not claim/release, data, security, or approval gates.
|
|
103
|
-
- If no safe task remains, announce \`Standby\` with what you are waiting for, then stop until user input, queue change, or explicit assignment.
|
|
104
|
-
|
|
105
|
-
### Current File State
|
|
106
|
-
|
|
107
|
-
- Treat previous chat context, cached model memory, and earlier reads as stale when file contents matter.
|
|
108
|
-
- Before claiming what a file says, making edits, or judging current state, read the file from disk with a fresh command.
|
|
109
|
-
- Treat \`nexus claim\` as the atomic lock-and-read boundary and its output as fresh file state for the claimed path.
|
|
110
|
-
- If you read a shared file before claiming it, treat that read as stale after claim succeeds.
|
|
111
|
-
- If another agent or tool may have touched the file since your last read, re-read it before editing.
|
|
112
|
-
- If a claim appears stale, do not edit through it; run \`nexus status\` or \`nexus doctor\`, then clean only when ownership is clearly abandoned.
|
|
113
|
-
|
|
114
|
-
### Drills
|
|
115
|
-
|
|
116
|
-
Drill guidance is defined in \`_NEXUS_CONSTITUTION.md\`.
|
|
117
|
-
If the situation resembles a drill, use that drill before acting.
|
|
118
|
-
|
|
119
|
-
### Delegated Work
|
|
120
|
-
|
|
121
|
-
- Lead agents own the repo effects of their subagents, tools, and parallel workers.
|
|
122
|
-
- Claim the full path scope before delegating shared-file work.
|
|
123
|
-
- Give subagents the claimed path, intent, non-goals, and boundaries.
|
|
124
|
-
- Re-read affected files after subagent work before final edits, release, or current-state claims.
|
|
125
|
-
- Mention delegated work in release or \`nexus standup\` notes when it affected files, tests, or risk.
|
|
126
|
-
|
|
127
|
-
### Git Write Safety
|
|
128
|
-
|
|
129
|
-
- Before git writes, verify \`pwd\`, repo root, branch/status, and remotes.
|
|
130
|
-
- Stop if they do not match the requested project.
|
|
131
|
-
- Never infer from similar folder names or cached context.
|
|
132
|
-
- Require explicit confirmation before push/force-push, main/master, remote changes, or deletes.
|
|
133
|
-
- To remove private agent files from git, untrack them; do not delete local folders.
|
|
134
|
-
- Agent instruction files are shared protocol files; normal edits require claim/release, while \`nexus doctor --fix\` may update managed protocol blocks after user approval.
|
|
135
|
-
- Agents work inside assigned work zones. If a change crosses work-zone boundaries or alters a shared contract another zone may depend on, announce it in \`_NEXUS_STANDUP.md\` before release and ask if coordination is needed.
|
|
136
|
-
|
|
137
|
-
### Supply-Chain Safety
|
|
138
|
-
|
|
139
|
-
- Do not install third-party packages that have existed for less than 14 days.
|
|
140
|
-
- Before adding a new dependency, verify the package creation date and the specific version publish date.
|
|
141
|
-
- If the package or version is younger than 14 days, or either date cannot be verified, stop and ask the user.
|
|
142
|
-
- Run \`nexus doctor\` before installs; review any Security findings before running package scripts.
|
|
143
|
-
- \`nexus doctor\` is cheap, local, and idempotent.
|
|
144
|
-
- If \`nexus doctor\` reports Security, Package Privacy, Git Privacy, or supply-chain findings, stop and report before fixing or installing.
|
|
145
|
-
- Treat install hooks and scripts with network commands, webhooks, raw sockets, SSH, or secret-looking variables as human-review only.
|
|
146
|
-
- Prefer built-in runtime APIs and existing project dependencies when they fit.
|
|
147
|
-
|
|
148
|
-
### Agent-Local Files
|
|
149
|
-
|
|
150
|
-
\`${agent.continuity}\` and \`${agent.memoryIndex}\` are agent-local handoff files.
|
|
151
|
-
They are exempt from Nexus claim/release unless the user says otherwise.
|
|
152
|
-
|
|
153
|
-
### Memory Flow
|
|
154
|
-
|
|
155
|
-
- On session start, read \`${agent.memoryIndex}\`.
|
|
156
|
-
- If the index has entries, read the newest \`${agent.memoryDir}/YYYY-Month/YYYY-MM-DD-HHMM-topic.md\` entry.
|
|
157
|
-
- Durable architecture and protocol decisions belong in \`DECISIONS.md\`; mention them in \`_NEXUS_STANDUP.md\` only when active agents need to coordinate around them.
|
|
158
|
-
- Memory entries are session handoffs.
|
|
159
|
-
- When writing your own memory entry, create the current month folder under \`${agent.memoryDir}\` if it is missing.
|
|
160
|
-
- Do not create or repair other agents' memory folders manually; use \`nexus doctor --fix\` for broad scaffold repair.
|
|
161
|
-
- On session end, pause, or checkpoint request:
|
|
162
|
-
1. Run \`nexus checkout @${agent.aliases[0]}\` to clear your presence heartbeat.
|
|
163
|
-
2. Create one new memory file: \`${agent.memoryDir}/YYYY-Month/YYYY-MM-DD-HHMM-topic.md\`.
|
|
164
|
-
- Add the newest file to the top of \`${agent.memoryIndex}\`.
|
|
165
|
-
- Keep the index to the 10 newest visible entries.
|
|
166
|
-
- For monthly review, read one month folder such as \`${agent.memoryDir}/2026-January/\` and summarize the Markdown files.
|
|
167
|
-
|
|
168
|
-
Memory entry format:
|
|
169
|
-
|
|
170
|
-
\`\`\`markdown
|
|
171
|
-
# YYYY-MM-DD-HHMM - <topic>
|
|
172
|
-
|
|
173
|
-
## Session Summary
|
|
174
|
-
- What we worked on: [<=50 words]
|
|
175
|
-
- What got done: [bullet list, max 5]
|
|
176
|
-
- Where we stopped: [exact state, <=30 words]
|
|
177
|
-
|
|
178
|
-
## Next Session Needs
|
|
179
|
-
- Immediate next task: [<=20 words]
|
|
180
|
-
- Blockers: [None, or list]
|
|
181
|
-
- Open questions: [if any]
|
|
182
|
-
|
|
183
|
-
## Context to Carry
|
|
184
|
-
- Key decisions made: [max 3 bullets]
|
|
185
|
-
- Files touched: [max 5 paths]
|
|
186
|
-
- Gotchas/warnings: [anything next session should watch for]
|
|
187
|
-
\`\`\`
|
|
188
|
-
|
|
189
|
-
${END_MARKER}
|
|
190
|
-
`;
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
function fullEntrypoint(agent) {
|
|
194
|
-
return `# ${agent.label} Agent Guide
|
|
195
|
-
|
|
196
|
-
${protocolBlock(agent)}`;
|
|
197
|
-
}
|
|
198
36
|
|
|
199
37
|
function upsertProtocolBlock(content, block) {
|
|
200
38
|
const cleanContent = removeUnmanagedProtocolBlock(content);
|
|
@@ -347,6 +185,7 @@ function repairStandupGuidance(content) {
|
|
|
347
185
|
export default function doctor(args) {
|
|
348
186
|
const fix = args.includes('--fix');
|
|
349
187
|
const json = args.includes('--json');
|
|
188
|
+
const checkHooks = args.includes('--hooks');
|
|
350
189
|
const root = cwd();
|
|
351
190
|
const colors = createColors();
|
|
352
191
|
const sections = {
|
|
@@ -361,6 +200,7 @@ export default function doctor(args) {
|
|
|
361
200
|
Memories: [],
|
|
362
201
|
Locks: [],
|
|
363
202
|
'Generated Artifacts': [],
|
|
203
|
+
Hooks: [],
|
|
364
204
|
promptCHMOD: [],
|
|
365
205
|
'Queue Authorship': [],
|
|
366
206
|
};
|
|
@@ -423,6 +263,26 @@ export default function doctor(args) {
|
|
|
423
263
|
sections['Generated Artifacts'].push(issue);
|
|
424
264
|
}
|
|
425
265
|
|
|
266
|
+
if (checkHooks) {
|
|
267
|
+
for (const agent of Object.keys(HOOK_AGENT_CONFIGS)) {
|
|
268
|
+
const status = hookStatus(agent);
|
|
269
|
+
if (status.status === 'current') {
|
|
270
|
+
sections.Hooks.push({
|
|
271
|
+
issue: `${agent} Nexus hook is installed`,
|
|
272
|
+
fix: 'No action needed.',
|
|
273
|
+
ok: true,
|
|
274
|
+
});
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const fixHint = `Run \`nexus hooks install --agent ${agent}\`${status.status === 'foreign' ? ' after reviewing the existing hook, or add `--force` to replace it' : ''}.`;
|
|
279
|
+
sections.Hooks.push({
|
|
280
|
+
issue: `${agent} Nexus hook is ${status.status} at ${status.path}`,
|
|
281
|
+
fix: fixHint,
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
426
286
|
if (!ensureFile(join(root, 'DECISIONS.md'), LOCAL_DECISIONS_TEMPLATE, fix, changes)) {
|
|
427
287
|
sections['Nexus Files'].push({
|
|
428
288
|
issue: 'Missing local DECISIONS.md',
|
|
@@ -992,7 +852,7 @@ function isNexusProductRepo(root) {
|
|
|
992
852
|
}
|
|
993
853
|
|
|
994
854
|
function repairReadmeProtocolDoc(content) {
|
|
995
|
-
|
|
855
|
+
let next = content
|
|
996
856
|
.replace(
|
|
997
857
|
[
|
|
998
858
|
'- [ ] TASK/Codex: Add doctor stale-lock category',
|
|
@@ -1021,10 +881,6 @@ function repairReadmeProtocolDoc(content) {
|
|
|
1021
881
|
' - Notes: Add a doctor section for stale locks with tests and clear fix guidance.',
|
|
1022
882
|
].join('\n'),
|
|
1023
883
|
)
|
|
1024
|
-
.replace(
|
|
1025
|
-
'Keep items dashboard-friendly: include `Id`, `Epic`, `Status`, `Depends on`, `Files`, `Affinity`, `Cost`, `Auto-flow`, and `Notes`. Use `Files` to expose conflict surfaces, `Depends on` for hard blockers, and `Auto-flow: no` when a task needs planning or human approval before an agent grabs it.',
|
|
1026
|
-
'Keep items dashboard-friendly: include `Id`, `Epic`, `Status`, `Depends on`, `Files`, `Affinity`, `Cost`, `Auto-flow`, and `Notes`. Use `Files` to expose conflict surfaces, `Depends on` for hard blockers, and `Auto-flow: no` when a task needs planning or human approval before an agent grabs it. Auto-flow work in `Ready Queue` should also include `Review: approved` and `Approved by: human`, or `doctor` will flag it and `nexus next` may skip it.',
|
|
1027
|
-
)
|
|
1028
884
|
.replace(
|
|
1029
885
|
[
|
|
1030
886
|
'1. Run `nexus start` when entering an existing repo; it does not replace claim/release.',
|
|
@@ -1039,25 +895,39 @@ function repairReadmeProtocolDoc(content) {
|
|
|
1039
895
|
'1. Run `nexus start` when entering an existing repo; it does not replace claim/release.',
|
|
1040
896
|
'2. Read `_NEXUS_CONSTITUTION.md`.',
|
|
1041
897
|
'3. Read `USER.md` when present.',
|
|
1042
|
-
|
|
898
|
+
`4. ${REQUIRED_CONTEXT_READ}`,
|
|
1043
899
|
'5. Read `_NEXUS_QUEUE.md` before taking follow-on work.',
|
|
1044
900
|
'6. Claim before touching shared project files.',
|
|
1045
901
|
'7. Release each claimed tracked file as soon as it reaches a coherent checkpoint.',
|
|
1046
902
|
'8. Use `nexus next @Agent` instead of free-roaming.',
|
|
1047
903
|
].join('\n'),
|
|
1048
904
|
)
|
|
1049
|
-
.replace(
|
|
1050
|
-
'Agent-local continuity and memory files are exempt from claim/release unless the human says otherwise.',
|
|
1051
|
-
'Agent-local continuity and memory files are exempt from claim/release unless the human says otherwise.\n\nNexus is agent-native and file-native, not human-native: optimize for concurrency and rollback, not feature-commit aesthetics. Do not hold claims to bundle related work into prettier feature commits; that blocks other agents waiting on files.',
|
|
1052
|
-
)
|
|
1053
905
|
.replace(
|
|
1054
906
|
'The CLI is the coordination engine. The skill is the lean playbook for this flow: `start -> claim -> release`.',
|
|
1055
907
|
'The CLI is the coordination engine. The skill is the lean playbook for this flow: `start -> claim -> work -> release -> next`.',
|
|
1056
908
|
);
|
|
909
|
+
|
|
910
|
+
const queueReviewReadme = 'Auto-flow work in `Ready Queue` should also include `Review: approved` and `Approved by: human`, or `doctor` will flag it and `nexus next` may skip it.';
|
|
911
|
+
if (!next.includes(queueReviewReadme)) {
|
|
912
|
+
next = next.replace(
|
|
913
|
+
'Keep items dashboard-friendly: include `Id`, `Epic`, `Status`, `Depends on`, `Files`, `Affinity`, `Cost`, `Auto-flow`, and `Notes`. Use `Files` to expose conflict surfaces, `Depends on` for hard blockers, and `Auto-flow: no` when a task needs planning or human approval before an agent grabs it.',
|
|
914
|
+
`Keep items dashboard-friendly: include \`Id\`, \`Epic\`, \`Status\`, \`Depends on\`, \`Files\`, \`Affinity\`, \`Cost\`, \`Auto-flow\`, and \`Notes\`. Use \`Files\` to expose conflict surfaces, \`Depends on\` for hard blockers, and \`Auto-flow: no\` when a task needs planning or human approval before an agent grabs it. ${queueReviewReadme}`,
|
|
915
|
+
);
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
const agentNativeReadme = 'Nexus is agent-native and file-native, not human-native: optimize for concurrency and rollback, not feature-commit aesthetics. Do not hold claims to bundle related work into prettier feature commits; that blocks other agents waiting on files.';
|
|
919
|
+
if (!next.includes(agentNativeReadme)) {
|
|
920
|
+
next = next.replace(
|
|
921
|
+
'Agent-local continuity and memory files are exempt from claim/release unless the human says otherwise.',
|
|
922
|
+
`Agent-local continuity and memory files are exempt from claim/release unless the human says otherwise.\n\n${agentNativeReadme}`,
|
|
923
|
+
);
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
return next;
|
|
1057
927
|
}
|
|
1058
928
|
|
|
1059
929
|
function repairNexusSkillDoc(content) {
|
|
1060
|
-
|
|
930
|
+
let next = content
|
|
1061
931
|
.replace(
|
|
1062
932
|
[
|
|
1063
933
|
'1. Run `nexus start`; set `NEXUS_AGENT` for your CLI, or pass `--agent @agy|@claude|@codex|@gemini`. Start is orientation only, not permission to edit.',
|
|
@@ -1085,13 +955,14 @@ function repairNexusSkillDoc(content) {
|
|
|
1085
955
|
].join('\n'),
|
|
1086
956
|
[
|
|
1087
957
|
'8. Treat claim output as current file state. Ignore cached file memory when contents matter.',
|
|
1088
|
-
'9.
|
|
1089
|
-
'10.
|
|
958
|
+
'9. If a hook blocks access because a path is unclaimed, stop and claim that exact path. Do not work around the hook with another command, cached content, or manual git operation.',
|
|
959
|
+
'10. Work only inside the claimed surface and run focused validation.',
|
|
960
|
+
'11. Release each claimed tracked file through Nexus as soon as it reaches a coherent checkpoint:',
|
|
1090
961
|
].join('\n'),
|
|
1091
962
|
)
|
|
1092
963
|
.replace(
|
|
1093
964
|
'```\\n\\n## Queue Items',
|
|
1094
|
-
'```\\n\\
|
|
965
|
+
'```\\n\\n12. Do not hold claims to bundle related work into a prettier feature commit. Nexus is agent-native and file-native: optimize for file availability, rollback safety, and agent throughput.\\n\\n## Queue Items',
|
|
1095
966
|
)
|
|
1096
967
|
.replace(
|
|
1097
968
|
[
|
|
@@ -1111,6 +982,25 @@ function repairNexusSkillDoc(content) {
|
|
|
1111
982
|
'- `Auto-flow: yes` means an agent can grab it after `nexus next`; use `no` when planning or human approval is needed.\n- `Notes` should carry dashboard-useful context, not a whole design doc.',
|
|
1112
983
|
'- `Auto-flow: yes` means an agent can grab it after `nexus next`; use `no` when planning or human approval is needed.\n- Auto-flow work in `Ready Queue` should include `Review: approved` and `Approved by: human`, or `doctor` will flag it and `nexus next` may skip it.\n- `Notes` should carry dashboard-useful context, not a whole design doc.',
|
|
1113
984
|
);
|
|
985
|
+
|
|
986
|
+
if (!next.includes('Continuity is the compaction-safe session ledger; latest memory is required startup/resume context.')) {
|
|
987
|
+
next = next.replace(
|
|
988
|
+
'- Agent-local continuity and memory files are claim-exempt unless the user says otherwise.',
|
|
989
|
+
`- Agent-local continuity and memory files are claim-exempt unless the user says otherwise.\n- ${SKILL_CONTEXT_GUARDRAIL}\n- ${MEMORY_INDEX_GUARDRAIL}`,
|
|
990
|
+
);
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
const mandatoryNote = 'If the user, repo, or hook says Nexus is active, treat this skill as mandatory workflow. It is not optional advice.';
|
|
994
|
+
if (!next.includes(mandatoryNote)) {
|
|
995
|
+
next = next.replace('## Loop', `${mandatoryNote}\n\n## Loop`);
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
next = next.replace(
|
|
999
|
+
'4. Read continuity and latest memory when present.',
|
|
1000
|
+
`4. ${REQUIRED_CONTEXT_READ}`,
|
|
1001
|
+
);
|
|
1002
|
+
|
|
1003
|
+
return next;
|
|
1114
1004
|
}
|
|
1115
1005
|
|
|
1116
1006
|
const SUSPICIOUS_SCRIPT_PATTERNS = [
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* nexus hooks - install agent-specific local guard hooks
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
|
|
6
|
+
import { dirname, resolve } from 'path';
|
|
7
|
+
import { homedir } from 'os';
|
|
8
|
+
|
|
9
|
+
export const HOOK_AGENT_CONFIGS = {
|
|
10
|
+
'@codex': {
|
|
11
|
+
label: 'Codex',
|
|
12
|
+
defaultTarget: '~/.codex/hooks/pre_tool_use_guard.py',
|
|
13
|
+
},
|
|
14
|
+
'@claude': {
|
|
15
|
+
label: 'Claude',
|
|
16
|
+
defaultTarget: '~/.claude/hooks/nexus_pre_tool_use_guard.py',
|
|
17
|
+
},
|
|
18
|
+
'@gemini': {
|
|
19
|
+
label: 'Gemini',
|
|
20
|
+
defaultTarget: '~/.gemini/hooks/nexus_pre_tool_use_guard.py',
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export const HOOK_FINGERPRINT = 'NEXUS_HOOK_TEMPLATE_V1';
|
|
25
|
+
|
|
26
|
+
const COMMAND_USAGE = 'Usage: nexus hooks install --agent @codex|@claude|@gemini|all [--target <path>] [--force]';
|
|
27
|
+
|
|
28
|
+
function parseArgs(args) {
|
|
29
|
+
if (args[0] !== 'install') throw new Error(COMMAND_USAGE);
|
|
30
|
+
|
|
31
|
+
let agent = '';
|
|
32
|
+
let target = '';
|
|
33
|
+
let force = false;
|
|
34
|
+
|
|
35
|
+
for (let index = 1; index < args.length; index += 1) {
|
|
36
|
+
const arg = args[index];
|
|
37
|
+
if (arg === '--force') {
|
|
38
|
+
force = true;
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (arg === '--agent') {
|
|
43
|
+
const value = args[index + 1];
|
|
44
|
+
if (!value || value.startsWith('--')) throw new Error(COMMAND_USAGE);
|
|
45
|
+
agent = value;
|
|
46
|
+
index += 1;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (arg === '--target') {
|
|
51
|
+
const value = args[index + 1];
|
|
52
|
+
if (!value || value.startsWith('--')) throw new Error(COMMAND_USAGE);
|
|
53
|
+
target = value;
|
|
54
|
+
index += 1;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
throw new Error(COMMAND_USAGE);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const normalizedAgent = agent === '@all' ? 'all' : agent;
|
|
62
|
+
if (normalizedAgent === 'all' && target) throw new Error('Usage: nexus hooks install --agent all [--force]');
|
|
63
|
+
if (normalizedAgent !== 'all' && !HOOK_AGENT_CONFIGS[normalizedAgent]) throw new Error(COMMAND_USAGE);
|
|
64
|
+
return {
|
|
65
|
+
agent: normalizedAgent,
|
|
66
|
+
target: normalizedAgent === 'all' ? '' : target || HOOK_AGENT_CONFIGS[normalizedAgent].defaultTarget,
|
|
67
|
+
force,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function expandHome(path) {
|
|
72
|
+
if (path === '~') return homedir();
|
|
73
|
+
if (path.startsWith('~/')) return resolve(homedir(), path.slice(2));
|
|
74
|
+
return resolve(path);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function hookStatus(agent, target = HOOK_AGENT_CONFIGS[agent]?.defaultTarget) {
|
|
78
|
+
if (!HOOK_AGENT_CONFIGS[agent]) throw new Error(`Unsupported hook agent: ${agent}`);
|
|
79
|
+
const path = expandHome(target);
|
|
80
|
+
if (!existsSync(path)) return { agent, path, status: 'missing' };
|
|
81
|
+
|
|
82
|
+
const content = readFileSync(path, 'utf-8');
|
|
83
|
+
if (!content.includes(HOOK_FINGERPRINT)) return { agent, path, status: 'foreign' };
|
|
84
|
+
if (!content.includes(`NEXUS_AGENT = '${agent}'`)) return { agent, path, status: 'wrong-agent' };
|
|
85
|
+
return { agent, path, status: 'current' };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function hookScriptContent(agent) {
|
|
89
|
+
if (!HOOK_AGENT_CONFIGS[agent]) throw new Error(`Unsupported hook agent: ${agent}`);
|
|
90
|
+
|
|
91
|
+
return `#!/usr/bin/env python3
|
|
92
|
+
"""Nexus PreToolUse guard.
|
|
93
|
+
|
|
94
|
+
${HOOK_FINGERPRINT}
|
|
95
|
+
Blocks writes to Nexus repo files until the exact path is claimed.
|
|
96
|
+
"""
|
|
97
|
+
from __future__ import annotations
|
|
98
|
+
|
|
99
|
+
import json
|
|
100
|
+
import re
|
|
101
|
+
import sys
|
|
102
|
+
from pathlib import Path
|
|
103
|
+
|
|
104
|
+
NEXUS_AGENT = '${agent}'
|
|
105
|
+
ALLOW_WITHOUT_CLAIM = {
|
|
106
|
+
'_NEXUS.md',
|
|
107
|
+
'.codex/CONTINUITY.md',
|
|
108
|
+
'.claude/CONTINUITY.md',
|
|
109
|
+
'.gemini/CONTINUITY.md',
|
|
110
|
+
}
|
|
111
|
+
ALLOW_PREFIXES = (
|
|
112
|
+
'.nexus/',
|
|
113
|
+
'.codex/memories/',
|
|
114
|
+
'.claude/memories/',
|
|
115
|
+
'.gemini/memories/',
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def load_payload() -> dict:
|
|
120
|
+
try:
|
|
121
|
+
raw = sys.stdin.read()
|
|
122
|
+
return json.loads(raw) if raw.strip() else {}
|
|
123
|
+
except Exception:
|
|
124
|
+
return {}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def block(reason: str) -> None:
|
|
128
|
+
print(json.dumps({
|
|
129
|
+
'hookSpecificOutput': {
|
|
130
|
+
'hookEventName': 'PreToolUse',
|
|
131
|
+
'permissionDecision': 'deny',
|
|
132
|
+
'permissionDecisionReason': reason,
|
|
133
|
+
}
|
|
134
|
+
}))
|
|
135
|
+
raise SystemExit(0)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def tool_input(payload: dict) -> dict:
|
|
139
|
+
value = payload.get('tool_input') or {}
|
|
140
|
+
return value if isinstance(value, dict) else {}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def command_text(payload: dict) -> str:
|
|
144
|
+
value = tool_input(payload)
|
|
145
|
+
return str(value.get('command') or value.get('cmd') or '')
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def find_nexus_root(start: Path) -> Path | None:
|
|
149
|
+
current = start if start.is_dir() else start.parent
|
|
150
|
+
for candidate in (current, *current.parents):
|
|
151
|
+
if (candidate / '.nexus').exists() or (candidate / '_NEXUS_CONSTITUTION.md').exists():
|
|
152
|
+
return candidate
|
|
153
|
+
return None
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def repo_relative(path_text: str) -> tuple[Path, str] | None:
|
|
157
|
+
if not path_text:
|
|
158
|
+
return None
|
|
159
|
+
path_text = path_text.strip().strip('"\\'')
|
|
160
|
+
if path_text.startswith('/dev/null'):
|
|
161
|
+
return None
|
|
162
|
+
path = Path(path_text)
|
|
163
|
+
path = (Path.cwd() / path).resolve() if not path.is_absolute() else path.resolve()
|
|
164
|
+
root = find_nexus_root(path) or find_nexus_root(Path.cwd())
|
|
165
|
+
if root is None:
|
|
166
|
+
return None
|
|
167
|
+
try:
|
|
168
|
+
return root, path.relative_to(root).as_posix()
|
|
169
|
+
except ValueError:
|
|
170
|
+
return None
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def needs_claim(rel: str) -> bool:
|
|
174
|
+
if rel in ALLOW_WITHOUT_CLAIM:
|
|
175
|
+
return False
|
|
176
|
+
return not rel.startswith(ALLOW_PREFIXES)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def lock_path(root: Path, rel: str) -> Path:
|
|
180
|
+
return root / '.nexus' / 'locks' / f"{rel.replace('/', '~2F')}.lock" / 'ts'
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def add_path(paths: set[tuple[Path, str]], path_text: str) -> None:
|
|
184
|
+
item = repo_relative(path_text)
|
|
185
|
+
if item:
|
|
186
|
+
paths.add(item)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def patch_paths(command: str) -> set[tuple[Path, str]]:
|
|
190
|
+
paths: set[tuple[Path, str]] = set()
|
|
191
|
+
for line in command.splitlines():
|
|
192
|
+
match = re.match(r"^\\*\\*\\* (?:Update|Add|Delete) File: (.+)$", line.strip())
|
|
193
|
+
if match:
|
|
194
|
+
add_path(paths, match.group(1))
|
|
195
|
+
move = re.match(r"^\\*\\*\\* Move to: (.+)$", line.strip())
|
|
196
|
+
if move:
|
|
197
|
+
add_path(paths, move.group(1))
|
|
198
|
+
return paths
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def input_file_paths(payload: dict) -> set[tuple[Path, str]]:
|
|
202
|
+
paths: set[tuple[Path, str]] = set()
|
|
203
|
+
value = tool_input(payload)
|
|
204
|
+
for key in ('file_path', 'path'):
|
|
205
|
+
if isinstance(value.get(key), str):
|
|
206
|
+
add_path(paths, value[key])
|
|
207
|
+
return paths
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def bash_write_paths(command: str) -> set[tuple[Path, str]]:
|
|
211
|
+
paths: set[tuple[Path, str]] = set()
|
|
212
|
+
patterns = [
|
|
213
|
+
r"\\bmv\\s+([^;&|]+?)\\s+([^;&|]+)",
|
|
214
|
+
r"\\bcp\\s+([^;&|]+?)\\s+([^;&|]+)",
|
|
215
|
+
r">> ?([^;&|\\s]+)",
|
|
216
|
+
r"> ?([^;&|\\s]+)",
|
|
217
|
+
]
|
|
218
|
+
for pattern in patterns:
|
|
219
|
+
for match in re.finditer(pattern, command):
|
|
220
|
+
for group in match.groups():
|
|
221
|
+
if not group:
|
|
222
|
+
continue
|
|
223
|
+
for token in re.split(r"\\s+", group.strip()):
|
|
224
|
+
add_path(paths, token)
|
|
225
|
+
return paths
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def missing_locks(paths: set[tuple[Path, str]]) -> list[tuple[Path, str]]:
|
|
229
|
+
missing = []
|
|
230
|
+
for root, rel in sorted(paths, key=lambda item: (str(item[0]), item[1])):
|
|
231
|
+
if needs_claim(rel) and not lock_path(root, rel).exists():
|
|
232
|
+
missing.append((root, rel))
|
|
233
|
+
return missing
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def claim_required_message(missing: list[tuple[Path, str]]) -> str:
|
|
237
|
+
shown = ', '.join(rel for _, rel in missing[:8]) + (' ...' if len(missing) > 8 else '')
|
|
238
|
+
first_root, first_rel = missing[0]
|
|
239
|
+
multi = '\\nIf multiple files are listed, claim each exact path.' if len(missing) > 1 else ''
|
|
240
|
+
return (
|
|
241
|
+
'โ CLAIM FIRST: '
|
|
242
|
+
+ shown
|
|
243
|
+
+ '\\n'
|
|
244
|
+
+ f'cd {first_root} && nexus claim {first_rel} {NEXUS_AGENT} "Describe the edit"\\n'
|
|
245
|
+
+ 'Retry edit. No workaround.'
|
|
246
|
+
+ multi
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def main() -> None:
|
|
251
|
+
payload = load_payload()
|
|
252
|
+
command = command_text(payload)
|
|
253
|
+
tool_name = str(payload.get('tool_name') or '')
|
|
254
|
+
paths = input_file_paths(payload)
|
|
255
|
+
|
|
256
|
+
if tool_name == 'apply_patch' or command.startswith('*** Begin Patch'):
|
|
257
|
+
paths.update(patch_paths(command))
|
|
258
|
+
else:
|
|
259
|
+
paths.update(bash_write_paths(command))
|
|
260
|
+
|
|
261
|
+
missing = missing_locks(paths)
|
|
262
|
+
if missing:
|
|
263
|
+
block(claim_required_message(missing))
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
if __name__ == '__main__':
|
|
267
|
+
main()
|
|
268
|
+
`;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export default function hooks(args) {
|
|
272
|
+
const { agent, target, force } = parseArgs(args);
|
|
273
|
+
if (agent === 'all') {
|
|
274
|
+
for (const handle of Object.keys(HOOK_AGENT_CONFIGS)) {
|
|
275
|
+
installHook(handle, HOOK_AGENT_CONFIGS[handle].defaultTarget, force);
|
|
276
|
+
}
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
installHook(agent, target, force);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function installHook(agent, target, force) {
|
|
284
|
+
const destination = expandHome(target);
|
|
285
|
+
const current = hookStatus(agent, target);
|
|
286
|
+
|
|
287
|
+
if (current.status === 'current' && !force) {
|
|
288
|
+
console.log(`Nexus ${HOOK_AGENT_CONFIGS[agent].label} hook already current at ${destination}`);
|
|
289
|
+
console.log('Run `nexus hooks install --force` to refresh it.');
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
if (existsSync(destination) && current.status === 'foreign' && !force) {
|
|
294
|
+
console.log(`Hook file already exists at ${destination}`);
|
|
295
|
+
console.log('Run with `--force` after reviewing the existing file.');
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
mkdirSync(dirname(destination), { recursive: true });
|
|
300
|
+
writeFileSync(destination, hookScriptContent(agent), 'utf-8');
|
|
301
|
+
chmodSync(destination, 0o755);
|
|
302
|
+
|
|
303
|
+
console.log(`Installed Nexus ${HOOK_AGENT_CONFIGS[agent].label} hook to ${destination}`);
|
|
304
|
+
console.log('Restart or refresh the agent session so the hook is loaded.');
|
|
305
|
+
}
|