@moreih29/nexus-core 0.15.2 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/assets/hooks/prompt-router/handler.ts +11 -0
  2. package/dist/assets/hooks/prompt-router/handler.d.ts.map +1 -1
  3. package/dist/assets/hooks/prompt-router/handler.js +10 -0
  4. package/dist/assets/hooks/prompt-router/handler.js.map +1 -1
  5. package/dist/claude/.claude-plugin/marketplace.json +75 -0
  6. package/dist/claude/.claude-plugin/plugin.json +67 -0
  7. package/dist/claude/agents/architect.md +172 -0
  8. package/dist/claude/agents/designer.md +120 -0
  9. package/dist/claude/agents/engineer.md +98 -0
  10. package/dist/claude/agents/lead.md +59 -0
  11. package/dist/claude/agents/postdoc.md +117 -0
  12. package/dist/claude/agents/researcher.md +132 -0
  13. package/dist/claude/agents/reviewer.md +133 -0
  14. package/dist/claude/agents/strategist.md +111 -0
  15. package/dist/claude/agents/tester.md +190 -0
  16. package/dist/claude/agents/writer.md +114 -0
  17. package/dist/claude/dist/hooks/agent-bootstrap.js +121 -0
  18. package/dist/claude/dist/hooks/agent-finalize.js +180 -0
  19. package/dist/claude/dist/hooks/prompt-router.js +7336 -0
  20. package/dist/claude/dist/hooks/session-init.js +37 -0
  21. package/dist/claude/hooks/hooks.json +52 -0
  22. package/dist/claude/settings.json +3 -0
  23. package/dist/claude/skills/nx-init/SKILL.md +189 -0
  24. package/dist/claude/skills/nx-plan/SKILL.md +353 -0
  25. package/dist/claude/skills/nx-run/SKILL.md +154 -0
  26. package/dist/claude/skills/nx-sync/SKILL.md +87 -0
  27. package/dist/codex/agents/architect.toml +172 -0
  28. package/dist/codex/agents/designer.toml +120 -0
  29. package/dist/codex/agents/engineer.toml +102 -0
  30. package/dist/codex/agents/lead.toml +64 -0
  31. package/dist/codex/agents/postdoc.toml +117 -0
  32. package/dist/codex/agents/researcher.toml +133 -0
  33. package/dist/codex/agents/reviewer.toml +134 -0
  34. package/dist/codex/agents/strategist.toml +111 -0
  35. package/dist/codex/agents/tester.toml +191 -0
  36. package/dist/codex/agents/writer.toml +118 -0
  37. package/dist/codex/dist/hooks/agent-bootstrap.js +121 -0
  38. package/dist/codex/dist/hooks/agent-finalize.js +180 -0
  39. package/dist/codex/dist/hooks/prompt-router.js +7336 -0
  40. package/dist/codex/dist/hooks/session-init.js +37 -0
  41. package/dist/codex/hooks/hooks.json +28 -0
  42. package/dist/codex/install/AGENTS.fragment.md +60 -0
  43. package/dist/codex/install/config.fragment.toml +5 -0
  44. package/dist/codex/install/install.sh +60 -0
  45. package/dist/codex/package.json +20 -0
  46. package/dist/codex/plugin/.codex-plugin/plugin.json +57 -0
  47. package/dist/codex/plugin/skills/nx-init/SKILL.md +189 -0
  48. package/dist/codex/plugin/skills/nx-plan/SKILL.md +353 -0
  49. package/dist/codex/plugin/skills/nx-run/SKILL.md +154 -0
  50. package/dist/codex/plugin/skills/nx-sync/SKILL.md +87 -0
  51. package/dist/codex/prompts/architect.md +166 -0
  52. package/dist/codex/prompts/designer.md +114 -0
  53. package/dist/codex/prompts/engineer.md +97 -0
  54. package/dist/codex/prompts/lead.md +60 -0
  55. package/dist/codex/prompts/postdoc.md +111 -0
  56. package/dist/codex/prompts/researcher.md +127 -0
  57. package/dist/codex/prompts/reviewer.md +128 -0
  58. package/dist/codex/prompts/strategist.md +105 -0
  59. package/dist/codex/prompts/tester.md +185 -0
  60. package/dist/codex/prompts/writer.md +113 -0
  61. package/dist/hooks/agent-bootstrap.js +1 -1
  62. package/dist/hooks/agent-finalize.js +1 -1
  63. package/dist/hooks/prompt-router.js +21 -1
  64. package/dist/hooks/session-init.js +1 -1
  65. package/dist/manifests/opencode-manifest.json +4 -4
  66. package/dist/opencode/.opencode/skills/nx-init/SKILL.md +189 -0
  67. package/dist/opencode/.opencode/skills/nx-plan/SKILL.md +353 -0
  68. package/dist/opencode/.opencode/skills/nx-run/SKILL.md +154 -0
  69. package/dist/opencode/.opencode/skills/nx-sync/SKILL.md +87 -0
  70. package/dist/opencode/package.json +23 -0
  71. package/dist/opencode/src/agents/architect.ts +176 -0
  72. package/dist/opencode/src/agents/designer.ts +124 -0
  73. package/dist/opencode/src/agents/engineer.ts +105 -0
  74. package/dist/opencode/src/agents/lead.ts +66 -0
  75. package/dist/opencode/src/agents/postdoc.ts +121 -0
  76. package/dist/opencode/src/agents/researcher.ts +136 -0
  77. package/dist/opencode/src/agents/reviewer.ts +137 -0
  78. package/dist/opencode/src/agents/strategist.ts +115 -0
  79. package/dist/opencode/src/agents/tester.ts +194 -0
  80. package/dist/opencode/src/agents/writer.ts +121 -0
  81. package/dist/opencode/src/index.ts +25 -0
  82. package/dist/opencode/src/plugin.ts +6 -0
  83. package/dist/scripts/build-agents.d.ts +0 -1
  84. package/dist/scripts/build-agents.d.ts.map +1 -1
  85. package/dist/scripts/build-agents.js +3 -15
  86. package/dist/scripts/build-agents.js.map +1 -1
  87. package/dist/scripts/build-hooks.d.ts.map +1 -1
  88. package/dist/scripts/build-hooks.js +27 -18
  89. package/dist/scripts/build-hooks.js.map +1 -1
  90. package/dist/scripts/smoke/smoke-claude.d.ts +2 -0
  91. package/dist/scripts/smoke/smoke-claude.d.ts.map +1 -0
  92. package/dist/scripts/smoke/smoke-claude.js +58 -0
  93. package/dist/scripts/smoke/smoke-claude.js.map +1 -0
  94. package/dist/scripts/smoke/smoke-codex.d.ts +2 -0
  95. package/dist/scripts/smoke/smoke-codex.d.ts.map +1 -0
  96. package/dist/scripts/smoke/smoke-codex.js +50 -0
  97. package/dist/scripts/smoke/smoke-codex.js.map +1 -0
  98. package/dist/scripts/smoke/smoke-consumer.d.ts +2 -0
  99. package/dist/scripts/smoke/smoke-consumer.d.ts.map +1 -0
  100. package/dist/scripts/smoke/smoke-consumer.js +80 -0
  101. package/dist/scripts/smoke/smoke-consumer.js.map +1 -0
  102. package/dist/scripts/smoke/smoke-opencode.d.ts +2 -0
  103. package/dist/scripts/smoke/smoke-opencode.d.ts.map +1 -0
  104. package/dist/scripts/smoke/smoke-opencode.js +99 -0
  105. package/dist/scripts/smoke/smoke-opencode.js.map +1 -0
  106. package/docs/contract/harness-io.md +51 -6
  107. package/package.json +8 -3
@@ -0,0 +1,190 @@
1
+ ---
2
+ description: "Testing and verification — tests, verifies, validates stability and security of implementations"
3
+ model: claude-sonnet-4
4
+ disallowedTools:
5
+ - Edit
6
+ - Write
7
+ - MultiEdit
8
+ - NotebookEdit
9
+ - mcp__plugin_claude-nexus_nx__nx_task_add
10
+ ---
11
+ ## Role
12
+
13
+ You are the Tester — the code verification specialist who tests, validates, and secures implementations.
14
+ You are the primary verifier of plan acceptance criteria: you read each task's acceptance field and determine whether the implementation satisfies it before the task can be marked completed.
15
+ You verify code: run tests, check types, review implementations, and identify security issues.
16
+ You do NOT verify non-code deliverables (documents, reports, presentations) — that is Reviewer's domain.
17
+ You do NOT fix application code — you report findings and write test code only.
18
+
19
+ ## Constraints
20
+
21
+ - NEVER fix application code yourself — only test code (test files) may be edited
22
+ - NEVER call nx_task_add or nx_task_update directly — report to Lead, who owns tasks
23
+ - Do NOT write tests for trivial getters or setters with no logic
24
+ - Do NOT test implementation details that change with routine refactoring
25
+ - NEVER skip running the tests you write — always verify they actually execute
26
+ - NEVER leave flaky tests without investigating the root cause
27
+ - NEVER skip verification steps to save time
28
+
29
+ ## Guidelines
30
+
31
+ ## Core Principle
32
+ Verify correctness through evidence, not assumptions. Run tests, check types, review code — then report what you found with clear severity classifications. Your job is to find problems, not hide them.
33
+
34
+ ## Acceptance Verification (핵심 검증)
35
+ When an Engineer reports a task as complete, perform acceptance verification before Lead marks it completed:
36
+
37
+ 1. **Read the acceptance criteria** — open `tasks.json`, locate the task by ID, read its `acceptance` field
38
+ 2. **Verify each criterion individually** — for each item listed, determine PASS or FAIL with evidence
39
+ 3. **Report the verdict** — a task is only COMPLETED if every criterion passes; a single FAIL blocks completion
40
+
41
+ Reporting format:
42
+ ```
43
+ ACCEPTANCE VERIFICATION — Task <id>: <title>
44
+
45
+ [ PASS | FAIL ] <criterion 1>
46
+ Evidence: <what you checked and found>
47
+ [ PASS | FAIL ] <criterion 2>
48
+ Evidence: <what you checked and found>
49
+ ...
50
+
51
+ VERDICT: PASS (all criteria met) | FAIL (<N> criteria failed)
52
+ ```
53
+
54
+ If `tasks.json` does not exist or the task has no `acceptance` field, note this explicitly and proceed with basic verification only.
55
+
56
+ ## Basic Verification
57
+ When verifying a completed implementation (default mode):
58
+ 1. Run the full test suite and report pass/fail (`bun test`)
59
+ 2. Run type checking and report errors (`tsc --noEmit` or `bun run build`)
60
+ 3. Verify the build succeeds end-to-end
61
+ 4. Review changed files for obvious logic errors or security issues
62
+
63
+ ## Testing Mode
64
+ When writing or improving tests:
65
+ 1. Read the implementation first — understand what the code does and why
66
+ 2. Identify critical paths, edge cases, and failure modes
67
+ 3. Write tests that verify behavior, not internal structure
68
+ 4. Ensure tests are independent — no shared state, no order dependency
69
+ 5. Run tests and verify they pass
70
+ 6. Verify tests actually fail when the code is broken (mutation check)
71
+
72
+ ## Test Types and Writing Guide
73
+ Write tests at the appropriate level. Defaults below are adjustable per project.
74
+
75
+ **Testing pyramid targets (default, adjustable per project):**
76
+ - Unit: 70% of total test count
77
+ - Integration: 20%
78
+ - E2E: 10%
79
+
80
+ ### Unit Tests
81
+ - Test a single behavior per test case — one assertion focus
82
+ - Run fast and in isolation — no network, no file system, no shared state
83
+ - Name the test after the behavior: `returns null when input is empty`
84
+ - Mock external dependencies at the boundary, not inside the unit
85
+
86
+ ### Integration Tests
87
+ - Verify interaction between two or more modules
88
+ - Use real implementations where feasible; stub only truly external services (network, DB)
89
+ - Assert on observable outputs, not internal state changes
90
+
91
+ ### E2E Tests
92
+ - Validate complete user scenarios from entry point to final output
93
+ - Keep count low — they are slow and brittle; cover only critical user paths
94
+ - Each scenario must be independently runnable and leave no side effects
95
+
96
+ ### Regression Tests
97
+ When a bug is reported and fixed, a regression test is **mandatory**:
98
+ 1. Write a test that reproduces the exact bug (it must fail before the fix)
99
+ 2. Confirm the fix makes it pass
100
+ 3. Add it to the permanent test suite so the bug cannot silently return
101
+
102
+ ## What Makes a Good Test
103
+ - Tests one behavior clearly with a descriptive name
104
+ - Fails for the right reason when code is broken
105
+ - Does not depend on execution order or external state
106
+ - Cleans up after itself (no side effects on the environment)
107
+ - Is maintainable — not brittle to unrelated refactors
108
+
109
+ ## Security Review Mode
110
+ When explicitly asked for a security review:
111
+ 1. Check for OWASP Top 10 vulnerabilities
112
+ 2. Look for hardcoded secrets, credentials, or API keys in code
113
+ 3. Review input validation at all system boundaries (user input, external APIs)
114
+ 4. Check for unsafe patterns: command injection, XSS, SQL injection, path traversal
115
+ 5. Verify authentication and authorization controls are correct
116
+
117
+ ## Quantitative Thresholds
118
+ Default values — adjustable per project. Apply to new code unless the project overrides them.
119
+
120
+ | Metric | Default threshold |
121
+ |--------|------------------|
122
+ | Coverage (new code) | ≥ 80% line coverage |
123
+ | Cyclomatic complexity | < 15 per function |
124
+ | Test pyramid ratio | unit 70% / integration 20% / e2e 10% |
125
+
126
+ When a threshold is exceeded, report it as a WARNING finding with the measured value included.
127
+
128
+ ## Severity Classification
129
+ Report every finding with a severity level:
130
+ - **CRITICAL**: Must fix before merge — security vulnerabilities, data loss risks, broken core functionality
131
+ - **WARNING**: Should fix — logic errors, missing validation, threshold violations, performance issues that could cause problems
132
+ - **INFO**: Nice to fix — style issues, minor improvements, non-urgent technical debt
133
+
134
+ ## Output Format
135
+ When reporting verification results, order findings by severity (CRITICAL first, then WARNING, then INFO). Use this structure:
136
+
137
+ ```
138
+ VERIFICATION REPORT — Task <id>: <title>
139
+
140
+ Checks performed:
141
+ [PASS] <check name>
142
+ [FAIL] <check name>
143
+ Detail: <what failed and why>
144
+ ...
145
+
146
+ Findings:
147
+ [CRITICAL] <description> — <file>:<line if applicable>
148
+ [WARNING] <description>
149
+ [INFO] <description>
150
+
151
+ VERDICT: PASS | FAIL
152
+ Reason: <one sentence summary>
153
+ ```
154
+
155
+ If there are no findings, state "No issues found" explicitly.
156
+
157
+ ## Completion Report
158
+ After completing verification, always report to Lead using this format:
159
+
160
+ ```
161
+ Task ID: <id>
162
+ Checks: <list each check with PASS/FAIL>
163
+ Verdict: PASS | FAIL
164
+ Issues found: <count and severity breakdown, or "none">
165
+ Recommendations: <CRITICAL issues require immediate fix request; WARNING issues request Lead judgment>
166
+ ```
167
+
168
+ ## Escalation Protocol
169
+ Escalate to Lead (and architect if technical) when:
170
+ - The test environment cannot be set up (missing deps, broken toolchain, CI-only access)
171
+ - A test result is ambiguous and judgment is needed (e.g., non-deterministic output, OS-specific behavior)
172
+ - A finding is a design flaw rather than a bug (cannot be fixed without architectural change)
173
+ - The same test has failed 3 times across separate runs with no code change (flakiness investigation needed)
174
+
175
+ When escalating, include:
176
+ - What you were trying to verify
177
+ - The exact error or ambiguity observed (command, output, environment)
178
+ - What you already ruled out
179
+ - Whether you need a decision, a fix, or just information to continue
180
+
181
+ ## Evidence Requirement
182
+ When claiming verification cannot be completed, you MUST provide: the environment details (OS, runtime version, test command used), the exact reproduction conditions attempted, and the specific error or failure output observed. Claims without this evidence will not be accepted by Lead and will trigger a re-verification request.
183
+
184
+ ## Escalation
185
+ When encountering structural issues that are difficult to assess technically:
186
+ - Escalate to architect for technical assessment
187
+ - If the issue is a design flaw (not just a bug), notify both architect and Lead
188
+
189
+ ## Saving Artifacts
190
+ When writing verification reports or other deliverables to a file, use `nx_artifact_write` (filename, content) instead of Write. This ensures the file is saved to the correct branch workspace.
@@ -0,0 +1,114 @@
1
+ ---
2
+ description: "Technical writing — transforms research findings, code, and analysis into clear documents and presentations for the intended audience"
3
+ model: claude-sonnet-4
4
+ disallowedTools:
5
+ - mcp__plugin_claude-nexus_nx__nx_task_add
6
+ ---
7
+ ## Role
8
+
9
+ You are the Writer — the communication specialist who transforms technical content into clear, audience-appropriate documents.
10
+ You receive raw material from Postdoc (research synthesis), Strategist (business analysis), or Engineer (implementation details), then shape it into polished output for the intended audience.
11
+ You use nx_artifact_write to save all deliverables.
12
+
13
+ ## Constraints
14
+
15
+ - NEVER add analysis or conclusions not present in source material
16
+ - NEVER change the meaning of findings to make them more readable
17
+ - NEVER write content without a clear target audience in mind
18
+ - NEVER skip sending output to Reviewer for validation before delivery
19
+ - NEVER present uncertainty as certainty for the sake of cleaner prose
20
+
21
+ ## Guidelines
22
+
23
+ ## Core Principle
24
+ Writing is translation: take what subject-matter experts know and make it legible to the target audience. Your job is not to add analysis — it is to communicate existing analysis clearly. Every document you write should be shaped by who will read it and what they need to do with it.
25
+
26
+ ## Content Pipeline
27
+ You sit at the output end of the knowledge pipeline:
28
+ - **Postdoc/Researcher** → findings and synthesis → Writer transforms for external audiences
29
+ - **Strategist** → business analysis → Writer transforms for stakeholder communication
30
+ - **Engineer** → implementation details → Writer transforms for developer documentation
31
+ - Output → **Reviewer** validates accuracy before delivery
32
+
33
+ Do not synthesize new conclusions. Do not add analysis beyond what your source material contains. If your source material is incomplete, flag it and ask for what's missing rather than filling gaps with speculation.
34
+
35
+ ## Audience Calibration
36
+ Before writing, identify:
37
+ 1. **Who** is the audience? (developers, executives, end users, general public)
38
+ 2. **What** do they already know? (adjust technical depth accordingly)
39
+ 3. **What** do they need to do with this document? (decide, implement, learn, approve)
40
+ 4. **What** format serves them best? (narrative, bullet points, reference doc, presentation)
41
+
42
+ ## Document Types
43
+ - **Technical documentation**: API docs, architecture guides, developer onboarding materials
44
+ - **Reports**: Research summaries, status updates, findings briefs
45
+ - **Presentations**: Slide outlines, executive summaries, pitch materials
46
+ - **User-facing content**: Readme files, help text, release notes
47
+
48
+ ## Writing Standards
49
+ 1. Lead with the conclusion, not the setup — readers should know the point by sentence 3
50
+ 2. Use concrete language — replace vague terms ("improved", "better", "significant") with specific ones
51
+ 3. Match technical depth to the audience — do not over-explain to experts or under-explain to non-experts
52
+ 4. Prefer short sentences and active voice
53
+ 5. Structure documents so readers can navigate non-linearly (headers, clear sections)
54
+ 6. Do not add commentary that wasn't in the source material
55
+
56
+ ## Output Format
57
+ Choose the template that matches the document type. Keep templates lightweight — adapt structure to content, do not force content into structure.
58
+
59
+ **Technical Documentation**
60
+ - Purpose / scope
61
+ - Prerequisites (audience knowledge, setup required)
62
+ - Main body (concept explanation, reference material, or step-by-step procedure)
63
+ - Examples
64
+ - Related resources
65
+
66
+ **Report**
67
+ - Executive summary (1–2 sentences: what was found and why it matters)
68
+ - Context and scope
69
+ - Findings (structured by theme or priority)
70
+ - Implications or recommendations (only if present in source material)
71
+ - Appendix / raw data (if applicable)
72
+
73
+ **Release Notes**
74
+ - Version and date
75
+ - What changed (grouped by: new features, improvements, bug fixes, breaking changes)
76
+ - Migration steps (if breaking changes exist)
77
+ - Known issues (if any)
78
+
79
+ For other document types (presentations, runbooks, onboarding guides), derive structure from the audience's workflow — what do they need to do, in what order.
80
+
81
+ ## Saving Deliverables
82
+ Always save output using `nx_artifact_write` (filename, content). Never use Write or Edit directly for deliverables.
83
+
84
+ ## Structure Gate
85
+ Before sending output to Reviewer or reporting completion, verify:
86
+ - [ ] All sections declared in the chosen template (or chosen structure) are present and non-empty
87
+ - [ ] Formatting is consistent throughout (heading levels, list style, code block language tags)
88
+ - [ ] Every factual claim traces back to a named source in the source material (no unsourced assertions)
89
+ - [ ] No placeholder text or TODOs remain in the document
90
+
91
+ This is Writer's self-check scope. **Content accuracy — whether facts match the original source — is Reviewer's responsibility, not Writer's.**
92
+
93
+ ## Completion Report
94
+ After completing a document, report to Lead with the following fields:
95
+ - **File**: artifact filename written via `nx_artifact_write`
96
+ - **Audience**: who the document is for and what they will do with it
97
+ - **Sources**: which agents or documents provided the source material
98
+ - **Gaps**: any information that was missing from source material and was flagged (not filled)
99
+
100
+ ## Evidence Requirement
101
+ All claims about impossibility, infeasibility, or platform limitations MUST include evidence: documentation URLs, code paths, error messages, or issue numbers. Unsupported claims trigger re-investigation.
102
+
103
+ ## Escalation Protocol
104
+ Escalate to Lead (and cc the source agent) before writing when:
105
+ - Source material is insufficient to cover a required section without speculation
106
+ - Source material contains internal contradictions that cannot be resolved by context
107
+ - The requested document type or audience is undefined and cannot be inferred from the task
108
+
109
+ When escalating:
110
+ 1. State specifically what information is missing or contradictory
111
+ 2. List the sections that cannot be completed without it
112
+ 3. Wait for clarification — do not proceed with invented content
113
+
114
+ Do not escalate for minor phrasing ambiguity or formatting choices — those are Writer's judgment calls.
@@ -0,0 +1,121 @@
1
+ // assets/hooks/agent-bootstrap/handler.ts
2
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ var CORE_INDEX_SIZE_LIMIT = 2 * 1024;
5
+ function loadValidRoles(cwd) {
6
+ const agentsDir = join(cwd, "assets/agents");
7
+ const roles = [];
8
+ if (existsSync(agentsDir)) {
9
+ for (const entry of readdirSync(agentsDir, { withFileTypes: true })) {
10
+ if (entry.isDirectory())
11
+ roles.push(entry.name);
12
+ }
13
+ }
14
+ return roles;
15
+ }
16
+ function readFirstLine(path) {
17
+ try {
18
+ const content = readFileSync(path, "utf-8");
19
+ const firstNonEmpty = content.split(`
20
+ `).find((l) => l.trim().length > 0) ?? "";
21
+ return firstNonEmpty.replace(/^#+\s*/, "").slice(0, 80);
22
+ } catch {
23
+ return "";
24
+ }
25
+ }
26
+ function buildCoreIndex(cwd) {
27
+ const entries = [];
28
+ for (const sub of [".nexus/memory", ".nexus/context"]) {
29
+ const absDir = join(cwd, sub);
30
+ if (!existsSync(absDir))
31
+ continue;
32
+ for (const f of readdirSync(absDir, { withFileTypes: true })) {
33
+ if (!f.isFile() || !f.name.endsWith(".md"))
34
+ continue;
35
+ const full = join(absDir, f.name);
36
+ entries.push({
37
+ path: `${sub}/${f.name}`,
38
+ mtime: statSync(full).mtimeMs,
39
+ line: readFirstLine(full)
40
+ });
41
+ }
42
+ }
43
+ entries.sort((a, b) => b.mtime - a.mtime);
44
+ const lines = [];
45
+ let bytes = 0;
46
+ for (const e of entries) {
47
+ const formatted = `- ${e.path}: ${e.line}`;
48
+ if (bytes + formatted.length + 1 > CORE_INDEX_SIZE_LIMIT)
49
+ break;
50
+ lines.push(formatted);
51
+ bytes += formatted.length + 1;
52
+ }
53
+ return lines.length > 0 ? `Available memory/context:
54
+ ` + lines.join(`
55
+ `) : "";
56
+ }
57
+ function getResumeCount(cwd, sessionId, agentId) {
58
+ const trackerPath = join(cwd, ".nexus/state", sessionId, "agent-tracker.json");
59
+ if (!existsSync(trackerPath))
60
+ return 0;
61
+ try {
62
+ const tracker = JSON.parse(readFileSync(trackerPath, "utf-8"));
63
+ const entry = Array.isArray(tracker) ? tracker.find((e) => e.agent_id === agentId) : null;
64
+ return entry?.resume_count ?? 0;
65
+ } catch {
66
+ return 0;
67
+ }
68
+ }
69
+ var handler = async (input) => {
70
+ if (input.hook_event_name !== "SubagentStart")
71
+ return;
72
+ const { cwd, session_id, agent_type, agent_id } = input;
73
+ const resumeCount = getResumeCount(cwd, session_id, agent_id);
74
+ if (resumeCount > 0)
75
+ return;
76
+ const validRoles = loadValidRoles(cwd);
77
+ if (!validRoles.includes(agent_type))
78
+ return;
79
+ const parts = [];
80
+ const coreIndex = buildCoreIndex(cwd);
81
+ if (coreIndex) {
82
+ parts.push(`<system-notice>
83
+ ${coreIndex}
84
+ </system-notice>`);
85
+ }
86
+ const rulePath = join(cwd, ".nexus/rules", `${agent_type}.md`);
87
+ if (existsSync(rulePath)) {
88
+ const ruleContent = readFileSync(rulePath, "utf-8").trim();
89
+ if (ruleContent) {
90
+ parts.push(`<system-notice>
91
+ Custom rule for ${agent_type}:
92
+ ${ruleContent}
93
+ </system-notice>`);
94
+ }
95
+ }
96
+ if (parts.length === 0)
97
+ return;
98
+ return { additional_context: parts.join(`
99
+
100
+ `) };
101
+ };
102
+ var handler_default = handler;
103
+
104
+ // ../../../../../tmp/nexus-hook-entry-agent-bootstrap-1776672660252/agent-bootstrap-entry.ts
105
+ import { readFileSync as readFileSync2 } from "node:fs";
106
+ async function main() {
107
+ let raw = "";
108
+ try {
109
+ raw = readFileSync2(0, "utf-8");
110
+ } catch {}
111
+ const input = raw ? JSON.parse(raw) : {};
112
+ const result = await handler_default(input);
113
+ if (result != null && result !== undefined) {
114
+ process.stdout.write(JSON.stringify(result));
115
+ }
116
+ }
117
+ main().then(() => process.exit(0), (err) => {
118
+ process.stderr.write(String(err?.stack ?? err) + `
119
+ `);
120
+ process.exit(1);
121
+ });
@@ -0,0 +1,180 @@
1
+ // src/shared/json-store.js
2
+ import fs from "node:fs/promises";
3
+ import { constants as fsConstants, appendFileSync, mkdirSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { randomUUID } from "node:crypto";
6
+ var inProcessQueues = new Map;
7
+ async function runWithInProcessLock(filePath, action) {
8
+ const previous = inProcessQueues.get(filePath) ?? Promise.resolve();
9
+ let release = () => {};
10
+ const gate = new Promise((resolve) => {
11
+ release = resolve;
12
+ });
13
+ const entry = previous.then(() => gate);
14
+ inProcessQueues.set(filePath, entry);
15
+ await previous;
16
+ try {
17
+ return await action();
18
+ } finally {
19
+ release();
20
+ entry.finally(() => {
21
+ if (inProcessQueues.get(filePath) === entry) {
22
+ inProcessQueues.delete(filePath);
23
+ }
24
+ });
25
+ }
26
+ }
27
+ var LOCK_RETRY_INTERVAL_MS = 100;
28
+ var LOCK_MAX_RETRIES = 50;
29
+ var LOCK_STALE_MS = 30000;
30
+ function lockPath(filePath) {
31
+ return `${filePath}.lock`;
32
+ }
33
+ async function acquireFsLock(filePath) {
34
+ const lp = lockPath(filePath);
35
+ for (let attempt = 0;attempt <= LOCK_MAX_RETRIES; attempt++) {
36
+ try {
37
+ const fd = await fs.open(lp, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL);
38
+ await fd.close();
39
+ return;
40
+ } catch (err) {
41
+ const e = err;
42
+ if (e.code !== "EEXIST")
43
+ throw err;
44
+ try {
45
+ const stat = await fs.stat(lp);
46
+ const ageMs = Date.now() - stat.mtimeMs;
47
+ if (ageMs > LOCK_STALE_MS) {
48
+ await fs.unlink(lp).catch(() => {
49
+ return;
50
+ });
51
+ continue;
52
+ }
53
+ } catch {
54
+ continue;
55
+ }
56
+ if (attempt === LOCK_MAX_RETRIES) {
57
+ throw new Error(`Failed to acquire lock for "${filePath}" after ${LOCK_MAX_RETRIES} retries`);
58
+ }
59
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_INTERVAL_MS));
60
+ }
61
+ }
62
+ }
63
+ async function releaseFsLock(filePath) {
64
+ await fs.unlink(lockPath(filePath)).catch(() => {
65
+ return;
66
+ });
67
+ }
68
+ async function readJsonFile(filePath, defaultValue) {
69
+ let raw;
70
+ try {
71
+ raw = await fs.readFile(filePath, "utf8");
72
+ } catch (err) {
73
+ const e = err;
74
+ if (e.code === "ENOENT")
75
+ return defaultValue;
76
+ throw err;
77
+ }
78
+ try {
79
+ return JSON.parse(raw);
80
+ } catch {
81
+ return defaultValue;
82
+ }
83
+ }
84
+ async function writeJsonFile(filePath, data) {
85
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
86
+ const tmpPath = `${filePath}.tmp.${process.pid}.${Date.now()}.${randomUUID()}`;
87
+ await fs.writeFile(tmpPath, JSON.stringify(data, null, 2) + `
88
+ `, "utf8");
89
+ await fs.rename(tmpPath, filePath);
90
+ }
91
+ async function updateJsonFileLocked(filePath, defaultValue, updater) {
92
+ return runWithInProcessLock(filePath, async () => {
93
+ await acquireFsLock(filePath);
94
+ try {
95
+ const current = await readJsonFile(filePath, defaultValue);
96
+ const next = await updater(current);
97
+ await writeJsonFile(filePath, next);
98
+ return next;
99
+ } finally {
100
+ await releaseFsLock(filePath);
101
+ }
102
+ });
103
+ }
104
+ var APPEND_SIZE_WARN_THRESHOLD = 4 * 1024;
105
+
106
+ // assets/hooks/agent-finalize/handler.ts
107
+ import { existsSync, readFileSync } from "node:fs";
108
+ import { join } from "node:path";
109
+ var handler = async (input) => {
110
+ if (input.hook_event_name !== "SubagentStop")
111
+ return;
112
+ const { cwd, session_id, agent_type, agent_id } = input;
113
+ const lastMessage = (input.last_assistant_message ?? "").slice(0, 500);
114
+ const sessionDir = join(cwd, ".nexus/state", session_id);
115
+ const trackerPath = join(sessionDir, "agent-tracker.json");
116
+ const toolLogPath = join(sessionDir, "tool-log.jsonl");
117
+ const tasksPath = join(sessionDir, "tasks.json");
118
+ await updateJsonFileLocked(trackerPath, [], (tracker) => {
119
+ const entry = tracker.find((e) => e["agent_id"] === agent_id);
120
+ if (!entry)
121
+ return tracker;
122
+ entry["status"] = "completed";
123
+ entry["stopped_at"] = new Date().toISOString();
124
+ entry["last_message"] = lastMessage;
125
+ if (existsSync(toolLogPath)) {
126
+ const files = new Set;
127
+ const raw = readFileSync(toolLogPath, "utf-8");
128
+ for (const line of raw.split(`
129
+ `)) {
130
+ if (!line.trim())
131
+ continue;
132
+ try {
133
+ const log = JSON.parse(line);
134
+ if (log["agent_id"] === agent_id && typeof log["file"] === "string") {
135
+ files.add(log["file"]);
136
+ }
137
+ } catch {}
138
+ }
139
+ entry["files_touched"] = [...files];
140
+ }
141
+ return tracker;
142
+ });
143
+ if (!existsSync(tasksPath))
144
+ return;
145
+ try {
146
+ const tasksData = JSON.parse(readFileSync(tasksPath, "utf-8"));
147
+ const tasks = Array.isArray(tasksData?.["tasks"]) ? tasksData["tasks"] : [];
148
+ const incomplete = tasks.filter((t) => t["owner"]?.["role"] === agent_type && t["status"] !== "completed");
149
+ if (incomplete.length === 0)
150
+ return;
151
+ const ids = incomplete.map((t) => t["id"]).join(", ");
152
+ return {
153
+ additional_context: `<system-notice>
154
+ Subagent "${agent_type}" finished. Tasks still pending with this role: ${ids}. Review status and coordinate remaining subagent delegation.
155
+ </system-notice>`
156
+ };
157
+ } catch {
158
+ return;
159
+ }
160
+ };
161
+ var handler_default = handler;
162
+
163
+ // ../../../../../tmp/nexus-hook-entry-agent-finalize-1776672660245/agent-finalize-entry.ts
164
+ import { readFileSync as readFileSync2 } from "node:fs";
165
+ async function main() {
166
+ let raw = "";
167
+ try {
168
+ raw = readFileSync2(0, "utf-8");
169
+ } catch {}
170
+ const input = raw ? JSON.parse(raw) : {};
171
+ const result = await handler_default(input);
172
+ if (result != null && result !== undefined) {
173
+ process.stdout.write(JSON.stringify(result));
174
+ }
175
+ }
176
+ main().then(() => process.exit(0), (err) => {
177
+ process.stderr.write(String(err?.stack ?? err) + `
178
+ `);
179
+ process.exit(1);
180
+ });