@trycore/spec-build-harness 0.1.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.
Files changed (92) hide show
  1. package/.claude-plugin/marketplace.json +21 -0
  2. package/.claude-plugin/plugin.json +28 -0
  3. package/GOVERNANCE.md +48 -0
  4. package/INSTALL.md +295 -0
  5. package/METODOLOGIA.md +360 -0
  6. package/README.md +130 -0
  7. package/VERSION +1 -0
  8. package/agents/build/api-contract-tester.md +32 -0
  9. package/agents/build/build-orchestrator.md +50 -0
  10. package/agents/build/change-epic-coherence.md +41 -0
  11. package/agents/build/coherence-three-way.md +35 -0
  12. package/agents/build/data-consistency-checker.md +48 -0
  13. package/agents/build/dor-dod-gatekeeper.md +46 -0
  14. package/agents/build/security-reviewer.md +46 -0
  15. package/agents/build/simple-design-reviewer.md +33 -0
  16. package/agents/build/stack-guardian.md +41 -0
  17. package/agents/build/ux-krug-reviewer.md +33 -0
  18. package/commands/build/onboard.md +136 -0
  19. package/commands/opsx/apply.md +152 -0
  20. package/commands/opsx/archive.md +157 -0
  21. package/commands/opsx/bulk-archive.md +242 -0
  22. package/commands/opsx/continue.md +114 -0
  23. package/commands/opsx/explore.md +174 -0
  24. package/commands/opsx/ff.md +94 -0
  25. package/commands/opsx/new.md +69 -0
  26. package/commands/opsx/onboard.md +525 -0
  27. package/commands/opsx/sync.md +134 -0
  28. package/commands/opsx/verify.md +164 -0
  29. package/config/stack-allowlist.template.json +12 -0
  30. package/dist/cli.js +105 -0
  31. package/dist/commands/doctor.js +77 -0
  32. package/dist/commands/init.js +129 -0
  33. package/dist/commands/status.js +59 -0
  34. package/dist/commands/uninstall.js +52 -0
  35. package/dist/commands/update.js +11 -0
  36. package/dist/lib/install-engine.js +99 -0
  37. package/dist/lib/markers.js +81 -0
  38. package/dist/lib/paths.js +65 -0
  39. package/dist/lib/settings-merge.js +125 -0
  40. package/dist/lib/stack-prompt.js +69 -0
  41. package/dist/lib/state-seed.js +59 -0
  42. package/docs/agents.md +133 -0
  43. package/docs/commands.md +128 -0
  44. package/docs/customization/mcp-extensions.md +117 -0
  45. package/docs/examples/reference/data-consistency.example.md +61 -0
  46. package/docs/examples/reference/security-foco.example.md +39 -0
  47. package/docs/examples/reference/stack-allowlist.example.json +61 -0
  48. package/docs/getting-started.md +260 -0
  49. package/docs/hooks.md +143 -0
  50. package/hooks/build/build-gate-check.sh +24 -0
  51. package/hooks/build/coherence-flag.sh +23 -0
  52. package/hooks/build/gitflow-guard.sh +65 -0
  53. package/hooks/build/lint-typecheck.sh +33 -0
  54. package/hooks/build/load-build-state.sh +46 -0
  55. package/hooks/build/stack-guard.sh +63 -0
  56. package/hooks/build-harness.json +61 -0
  57. package/internal/skills/auditar-arnes/SKILL.md +29 -0
  58. package/package.json +67 -0
  59. package/scripts/check-agnostic.sh +81 -0
  60. package/scripts/check-state-clean.sh +48 -0
  61. package/scripts/check-version-sync.sh +51 -0
  62. package/scripts/denylist.txt +30 -0
  63. package/skills/building-a-slice/SKILL.md +82 -0
  64. package/skills/building-a-slice/references/data-consistency.md +34 -0
  65. package/skills/building-a-slice/references/dod.md +25 -0
  66. package/skills/building-a-slice/references/dor.md +17 -0
  67. package/skills/building-a-slice/references/gitflow.md +30 -0
  68. package/skills/building-a-slice/references/krug-ux.md +27 -0
  69. package/skills/building-a-slice/references/link-change-epic.md +34 -0
  70. package/skills/building-a-slice/references/mcp-map.md +29 -0
  71. package/skills/building-a-slice/references/newman-tests.md +47 -0
  72. package/skills/building-a-slice/references/simple-design.md +33 -0
  73. package/skills/building-a-slice/references/state-protocol.md +48 -0
  74. package/skills/openspec-apply-change/SKILL.md +156 -0
  75. package/skills/openspec-archive-change/SKILL.md +114 -0
  76. package/skills/openspec-bulk-archive-change/SKILL.md +246 -0
  77. package/skills/openspec-continue-change/SKILL.md +118 -0
  78. package/skills/openspec-explore/SKILL.md +290 -0
  79. package/skills/openspec-ff-change/SKILL.md +101 -0
  80. package/skills/openspec-new-change/SKILL.md +74 -0
  81. package/skills/openspec-onboard/SKILL.md +529 -0
  82. package/skills/openspec-sync-specs/SKILL.md +138 -0
  83. package/skills/openspec-verify-change/SKILL.md +168 -0
  84. package/skills/releasing-a-version/SKILL.md +56 -0
  85. package/skills/releasing-a-version/references/release-dod.md +20 -0
  86. package/state/README.md +56 -0
  87. package/state/build-state.schema.json +111 -0
  88. package/state/build-state.template.json +7 -0
  89. package/templates/CLAUDE.md.template +57 -0
  90. package/templates/newman.collection.template.json +28 -0
  91. package/templates/settings-hooks.template.json +25 -0
  92. package/templates/waivers/WAIVER.template.md +27 -0
@@ -0,0 +1,134 @@
1
+ ---
2
+ name: "OPSX: Sync"
3
+ description: Sync delta specs from a change to main specs
4
+ category: Workflow
5
+ tags: [workflow, specs, experimental]
6
+ ---
7
+
8
+ Sync delta specs from a change to main specs.
9
+
10
+ This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
11
+
12
+ **Input**: Optionally specify a change name after `/opsx:sync` (e.g., `/opsx:sync add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
13
+
14
+ **Steps**
15
+
16
+ 1. **If no change name provided, prompt for selection**
17
+
18
+ Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
19
+
20
+ Show changes that have delta specs (under `specs/` directory).
21
+
22
+ **IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
23
+
24
+ 2. **Find delta specs**
25
+
26
+ Look for delta spec files in `openspec/changes/<name>/specs/*/spec.md`.
27
+
28
+ Each delta spec file contains sections like:
29
+ - `## ADDED Requirements` - New requirements to add
30
+ - `## MODIFIED Requirements` - Changes to existing requirements
31
+ - `## REMOVED Requirements` - Requirements to remove
32
+ - `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
33
+
34
+ If no delta specs found, inform user and stop.
35
+
36
+ 3. **For each delta spec, apply changes to main specs**
37
+
38
+ For each capability with a delta spec at `openspec/changes/<name>/specs/<capability>/spec.md`:
39
+
40
+ a. **Read the delta spec** to understand the intended changes
41
+
42
+ b. **Read the main spec** at `openspec/specs/<capability>/spec.md` (may not exist yet)
43
+
44
+ c. **Apply changes intelligently**:
45
+
46
+ **ADDED Requirements:**
47
+ - If requirement doesn't exist in main spec → add it
48
+ - If requirement already exists → update it to match (treat as implicit MODIFIED)
49
+
50
+ **MODIFIED Requirements:**
51
+ - Find the requirement in main spec
52
+ - Apply the changes - this can be:
53
+ - Adding new scenarios (don't need to copy existing ones)
54
+ - Modifying existing scenarios
55
+ - Changing the requirement description
56
+ - Preserve scenarios/content not mentioned in the delta
57
+
58
+ **REMOVED Requirements:**
59
+ - Remove the entire requirement block from main spec
60
+
61
+ **RENAMED Requirements:**
62
+ - Find the FROM requirement, rename to TO
63
+
64
+ d. **Create new main spec** if capability doesn't exist yet:
65
+ - Create `openspec/specs/<capability>/spec.md`
66
+ - Add Purpose section (can be brief, mark as TBD)
67
+ - Add Requirements section with the ADDED requirements
68
+
69
+ 4. **Show summary**
70
+
71
+ After applying all changes, summarize:
72
+ - Which capabilities were updated
73
+ - What changes were made (requirements added/modified/removed/renamed)
74
+
75
+ **Delta Spec Format Reference**
76
+
77
+ ```markdown
78
+ ## ADDED Requirements
79
+
80
+ ### Requirement: New Feature
81
+ The system SHALL do something new.
82
+
83
+ #### Scenario: Basic case
84
+ - **WHEN** user does X
85
+ - **THEN** system does Y
86
+
87
+ ## MODIFIED Requirements
88
+
89
+ ### Requirement: Existing Feature
90
+ #### Scenario: New scenario to add
91
+ - **WHEN** user does A
92
+ - **THEN** system does B
93
+
94
+ ## REMOVED Requirements
95
+
96
+ ### Requirement: Deprecated Feature
97
+
98
+ ## RENAMED Requirements
99
+
100
+ - FROM: `### Requirement: Old Name`
101
+ - TO: `### Requirement: New Name`
102
+ ```
103
+
104
+ **Key Principle: Intelligent Merging**
105
+
106
+ Unlike programmatic merging, you can apply **partial updates**:
107
+ - To add a scenario, just include that scenario under MODIFIED - don't copy existing scenarios
108
+ - The delta represents *intent*, not a wholesale replacement
109
+ - Use your judgment to merge changes sensibly
110
+
111
+ **Output On Success**
112
+
113
+ ```
114
+ ## Specs Synced: <change-name>
115
+
116
+ Updated main specs:
117
+
118
+ **<capability-1>**:
119
+ - Added requirement: "New Feature"
120
+ - Modified requirement: "Existing Feature" (added 1 scenario)
121
+
122
+ **<capability-2>**:
123
+ - Created new spec file
124
+ - Added requirement: "Another Feature"
125
+
126
+ Main specs are now updated. The change remains active - archive when implementation is complete.
127
+ ```
128
+
129
+ **Guardrails**
130
+ - Read both delta and main specs before making changes
131
+ - Preserve existing content not mentioned in delta
132
+ - If something is unclear, ask for clarification
133
+ - Show what you're changing as you go
134
+ - The operation should be idempotent - running twice should give same result
@@ -0,0 +1,164 @@
1
+ ---
2
+ name: "OPSX: Verify"
3
+ description: Verify implementation matches change artifacts before archiving
4
+ category: Workflow
5
+ tags: [workflow, verify, experimental]
6
+ ---
7
+
8
+ Verify that an implementation matches the change artifacts (specs, tasks, design).
9
+
10
+ **Input**: Optionally specify a change name after `/opsx:verify` (e.g., `/opsx:verify add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
11
+
12
+ **Steps**
13
+
14
+ 1. **If no change name provided, prompt for selection**
15
+
16
+ Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
17
+
18
+ Show changes that have implementation tasks (tasks artifact exists).
19
+ Include the schema used for each change if available.
20
+ Mark changes with incomplete tasks as "(In Progress)".
21
+
22
+ **IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
23
+
24
+ 2. **Check status to understand the schema**
25
+ ```bash
26
+ openspec status --change "<name>" --json
27
+ ```
28
+ Parse the JSON to understand:
29
+ - `schemaName`: The workflow being used (e.g., "spec-driven")
30
+ - Which artifacts exist for this change
31
+
32
+ 3. **Get the change directory and load artifacts**
33
+
34
+ ```bash
35
+ openspec instructions apply --change "<name>" --json
36
+ ```
37
+
38
+ This returns the change directory and context files. Read all available artifacts from `contextFiles`.
39
+
40
+ 4. **Initialize verification report structure**
41
+
42
+ Create a report structure with three dimensions:
43
+ - **Completeness**: Track tasks and spec coverage
44
+ - **Correctness**: Track requirement implementation and scenario coverage
45
+ - **Coherence**: Track design adherence and pattern consistency
46
+
47
+ Each dimension can have CRITICAL, WARNING, or SUGGESTION issues.
48
+
49
+ 5. **Verify Completeness**
50
+
51
+ **Task Completion**:
52
+ - If tasks.md exists in contextFiles, read it
53
+ - Parse checkboxes: `- [ ]` (incomplete) vs `- [x]` (complete)
54
+ - Count complete vs total tasks
55
+ - If incomplete tasks exist:
56
+ - Add CRITICAL issue for each incomplete task
57
+ - Recommendation: "Complete task: <description>" or "Mark as done if already implemented"
58
+
59
+ **Spec Coverage**:
60
+ - If delta specs exist in `openspec/changes/<name>/specs/`:
61
+ - Extract all requirements (marked with "### Requirement:")
62
+ - For each requirement:
63
+ - Search codebase for keywords related to the requirement
64
+ - Assess if implementation likely exists
65
+ - If requirements appear unimplemented:
66
+ - Add CRITICAL issue: "Requirement not found: <requirement name>"
67
+ - Recommendation: "Implement requirement X: <description>"
68
+
69
+ 6. **Verify Correctness**
70
+
71
+ **Requirement Implementation Mapping**:
72
+ - For each requirement from delta specs:
73
+ - Search codebase for implementation evidence
74
+ - If found, note file paths and line ranges
75
+ - Assess if implementation matches requirement intent
76
+ - If divergence detected:
77
+ - Add WARNING: "Implementation may diverge from spec: <details>"
78
+ - Recommendation: "Review <file>:<lines> against requirement X"
79
+
80
+ **Scenario Coverage**:
81
+ - For each scenario in delta specs (marked with "#### Scenario:"):
82
+ - Check if conditions are handled in code
83
+ - Check if tests exist covering the scenario
84
+ - If scenario appears uncovered:
85
+ - Add WARNING: "Scenario not covered: <scenario name>"
86
+ - Recommendation: "Add test or implementation for scenario: <description>"
87
+
88
+ 7. **Verify Coherence**
89
+
90
+ **Design Adherence**:
91
+ - If design.md exists in contextFiles:
92
+ - Extract key decisions (look for sections like "Decision:", "Approach:", "Architecture:")
93
+ - Verify implementation follows those decisions
94
+ - If contradiction detected:
95
+ - Add WARNING: "Design decision not followed: <decision>"
96
+ - Recommendation: "Update implementation or revise design.md to match reality"
97
+ - If no design.md: Skip design adherence check, note "No design.md to verify against"
98
+
99
+ **Code Pattern Consistency**:
100
+ - Review new code for consistency with project patterns
101
+ - Check file naming, directory structure, coding style
102
+ - If significant deviations found:
103
+ - Add SUGGESTION: "Code pattern deviation: <details>"
104
+ - Recommendation: "Consider following project pattern: <example>"
105
+
106
+ 8. **Generate Verification Report**
107
+
108
+ **Summary Scorecard**:
109
+ ```
110
+ ## Verification Report: <change-name>
111
+
112
+ ### Summary
113
+ | Dimension | Status |
114
+ |--------------|------------------|
115
+ | Completeness | X/Y tasks, N reqs|
116
+ | Correctness | M/N reqs covered |
117
+ | Coherence | Followed/Issues |
118
+ ```
119
+
120
+ **Issues by Priority**:
121
+
122
+ 1. **CRITICAL** (Must fix before archive):
123
+ - Incomplete tasks
124
+ - Missing requirement implementations
125
+ - Each with specific, actionable recommendation
126
+
127
+ 2. **WARNING** (Should fix):
128
+ - Spec/design divergences
129
+ - Missing scenario coverage
130
+ - Each with specific recommendation
131
+
132
+ 3. **SUGGESTION** (Nice to fix):
133
+ - Pattern inconsistencies
134
+ - Minor improvements
135
+ - Each with specific recommendation
136
+
137
+ **Final Assessment**:
138
+ - If CRITICAL issues: "X critical issue(s) found. Fix before archiving."
139
+ - If only warnings: "No critical issues. Y warning(s) to consider. Ready for archive (with noted improvements)."
140
+ - If all clear: "All checks passed. Ready for archive."
141
+
142
+ **Verification Heuristics**
143
+
144
+ - **Completeness**: Focus on objective checklist items (checkboxes, requirements list)
145
+ - **Correctness**: Use keyword search, file path analysis, reasonable inference - don't require perfect certainty
146
+ - **Coherence**: Look for glaring inconsistencies, don't nitpick style
147
+ - **False Positives**: When uncertain, prefer SUGGESTION over WARNING, WARNING over CRITICAL
148
+ - **Actionability**: Every issue must have a specific recommendation with file/line references where applicable
149
+
150
+ **Graceful Degradation**
151
+
152
+ - If only tasks.md exists: verify task completion only, skip spec/design checks
153
+ - If tasks + specs exist: verify completeness and correctness, skip design
154
+ - If full artifacts: verify all three dimensions
155
+ - Always note which checks were skipped and why
156
+
157
+ **Output Format**
158
+
159
+ Use clear markdown with:
160
+ - Table for summary scorecard
161
+ - Grouped lists for issues (CRITICAL/WARNING/SUGGESTION)
162
+ - Code references in format: `file.ts:123`
163
+ - Specific, actionable recommendations
164
+ - No vague suggestions like "consider reviewing"
@@ -0,0 +1,12 @@
1
+ {
2
+ "_comment": "TEMPLATE. trycore-build init lo materializa en .claude/config/stack-allowlist.json del consumidor. El hook stack-guard.sh bloquea dependencias fuera de `allow` al editar package.json. Pueblalo con tu stack (o corre /build:onboard).",
3
+ "source": "docs/01-prd/<tu-prd>.md#requisitos-tecnicos",
4
+ "version": "1.0",
5
+ "runtime": {
6
+ "node": ">=18.18",
7
+ "packageManager": "npm|pnpm|yarn"
8
+ },
9
+ "allow": [],
10
+ "deny_examples": [],
11
+ "rationale": {}
12
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env node
2
+ // cli.ts — entry point del CLI `trycore-build`.
3
+ import { Command } from 'commander';
4
+ import { readPackageVersion } from './lib/paths.js';
5
+ import { init } from './commands/init.js';
6
+ import { update } from './commands/update.js';
7
+ import { status } from './commands/status.js';
8
+ import { uninstall } from './commands/uninstall.js';
9
+ import { doctor } from './commands/doctor.js';
10
+ const program = new Command();
11
+ program
12
+ .name('trycore-build')
13
+ .description('Arnés de construcción de Trycore para Claude Code: pipeline de dos loops (slice por épica + release gate) con gates de calidad, estado compartido y OpenSpec.')
14
+ .version(readPackageVersion(), '-v, --version', 'imprime la versión del paquete');
15
+ program
16
+ .command('init')
17
+ .description('Instala el arnés en el directorio actual (o el indicado). Idempotente.')
18
+ .argument('[directory]', 'Directorio donde instalar', '.')
19
+ .option('--copy', 'Copiar archivos en vez de symlinkear (Windows sin admin, sandboxes)')
20
+ .option('--force-init', 'Fuerza modo init incluso si ya hay instalación previa')
21
+ .option('--skip-doctor', 'Omite la verificación de openspec/python3/git (no recomendado)')
22
+ .option('--stack <deps>', 'Dependencias permitidas, coma-separadas (no interactivo)')
23
+ .option('--pkg-manager <pm>', 'Package manager (npm|pnpm|yarn)')
24
+ .option('--runtime <semver>', 'Semver del runtime (ej. ">=18.18")')
25
+ .option('--prd-path <path>', 'Ruta#ancla del PRD técnico (fuente del allowlist)')
26
+ .option('--yes', 'No interactivo: usa defaults para el stack')
27
+ .action(async (directory, opts) => {
28
+ try {
29
+ await init({
30
+ targetDir: directory,
31
+ mode: opts.forceInit ? 'init' : 'auto',
32
+ useCopy: Boolean(opts.copy),
33
+ skipDoctor: Boolean(opts.skipDoctor),
34
+ stackFlags: {
35
+ stack: opts.stack,
36
+ pkgManager: opts.pkgManager,
37
+ runtime: opts.runtime,
38
+ prdPath: opts.prdPath,
39
+ yes: Boolean(opts.yes),
40
+ },
41
+ });
42
+ }
43
+ catch (err) {
44
+ console.error('✗ Error:', err.message);
45
+ process.exit(1);
46
+ }
47
+ });
48
+ program
49
+ .command('update')
50
+ .description('Refresca assets y schema tras actualizar el paquete npm. No pisa estado ni allowlist.')
51
+ .argument('[directory]', 'Directorio del proyecto', '.')
52
+ .option('--copy', 'Copiar archivos en vez de symlinkear')
53
+ .option('--skip-doctor', 'Omite la verificación de requisitos externos')
54
+ .action(async (directory, opts) => {
55
+ try {
56
+ await update({ targetDir: directory, useCopy: Boolean(opts.copy), skipDoctor: Boolean(opts.skipDoctor) });
57
+ }
58
+ catch (err) {
59
+ console.error('✗ Error:', err.message);
60
+ process.exit(1);
61
+ }
62
+ });
63
+ program
64
+ .command('status')
65
+ .description('Muestra el estado de la instalación y la fase del arnés.')
66
+ .argument('[directory]', 'Directorio del proyecto', '.')
67
+ .action(async (directory) => {
68
+ try {
69
+ await status({ targetDir: directory });
70
+ }
71
+ catch (err) {
72
+ console.error('✗ Error:', err.message);
73
+ process.exit(1);
74
+ }
75
+ });
76
+ program
77
+ .command('uninstall')
78
+ .description('Quita el arnés del proyecto. NO toca .claude/state/ ni .claude/config/.')
79
+ .argument('[directory]', 'Directorio del proyecto', '.')
80
+ .action(async (directory) => {
81
+ try {
82
+ await uninstall({ targetDir: directory });
83
+ }
84
+ catch (err) {
85
+ console.error('✗ Error:', err.message);
86
+ process.exit(1);
87
+ }
88
+ });
89
+ program
90
+ .command('doctor')
91
+ .description('Verifica requisitos externos (openspec/python3/git), hooks ejecutables y canales.')
92
+ .argument('[directory]', 'Directorio del proyecto', '.')
93
+ .action(async (directory) => {
94
+ try {
95
+ await doctor({ targetDir: directory });
96
+ }
97
+ catch (err) {
98
+ console.error('✗ Error:', err.message);
99
+ process.exit(1);
100
+ }
101
+ });
102
+ program.parseAsync(process.argv).catch((err) => {
103
+ console.error('✗ Error inesperado:', err);
104
+ process.exit(1);
105
+ });
@@ -0,0 +1,77 @@
1
+ // commands/doctor.ts — diagnóstico de requisitos del arnés.
2
+ // El harness depende de binarios EXTERNOS que el CLI no puede instalar:
3
+ // - openspec → columna vertebral de /opsx:* y skills openspec-* [C2]
4
+ // - python3 → los hooks parsean JSON con python3 [H4]
5
+ // - git → los hooks y gitflow-guard resuelven la raíz con git rev-parse
6
+ // doctor FALLA (exit 1) si falta un requisito duro.
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { spawnSync } from 'node:child_process';
10
+ import { targetPaths } from '../lib/paths.js';
11
+ export function hasBinary(bin) {
12
+ if (process.platform === 'win32') {
13
+ return spawnSync('where', [bin], { stdio: 'ignore' }).status === 0;
14
+ }
15
+ return spawnSync('sh', ['-c', `command -v ${bin}`], { stdio: 'ignore' }).status === 0;
16
+ }
17
+ /** Chequea las dependencias externas duras. */
18
+ export function checkDeps() {
19
+ const git = hasBinary('git');
20
+ const python3 = hasBinary('python3');
21
+ const openspec = hasBinary('openspec');
22
+ const missingHard = [];
23
+ if (!git)
24
+ missingHard.push('git');
25
+ if (!python3)
26
+ missingHard.push('python3');
27
+ if (!openspec)
28
+ missingHard.push('openspec');
29
+ return { git, python3, openspec, missingHard };
30
+ }
31
+ export async function doctor(opts) {
32
+ const targetDir = path.resolve(opts.targetDir);
33
+ const t = targetPaths(targetDir);
34
+ const dep = checkDeps();
35
+ console.log('════════ trycore-build doctor ════════');
36
+ console.log(`Proyecto: ${targetDir}`);
37
+ console.log('');
38
+ console.log('Requisitos externos:');
39
+ console.log(` git: ${dep.git ? '✓' : '✗ FALTA'}`);
40
+ console.log(` python3: ${dep.python3 ? '✓' : '✗ FALTA (los hooks lo necesitan para parsear JSON)'}`);
41
+ console.log(` openspec: ${dep.openspec ? '✓' : '✗ FALTA (npm i -g @fission-ai/openspec — requerido por /opsx:* y skills openspec-*)'}`);
42
+ // Hooks ejecutables
43
+ console.log('');
44
+ console.log('Hooks instalados:');
45
+ if (fs.existsSync(t.hooksBuild)) {
46
+ const scripts = fs.readdirSync(t.hooksBuild).filter((f) => f.endsWith('.sh'));
47
+ let nonExec = 0;
48
+ for (const s of scripts) {
49
+ const p = path.join(t.hooksBuild, s);
50
+ const mode = fs.statSync(p).mode;
51
+ const exec = (mode & 0o111) !== 0;
52
+ if (!exec)
53
+ nonExec++;
54
+ console.log(` ${exec ? '✓' : '✗'} ${s}`);
55
+ }
56
+ if (nonExec > 0)
57
+ console.log(` ⚠ ${nonExec} hook(s) sin bit ejecutable — corre \`trycore-build init --copy\` o \`chmod +x\``);
58
+ }
59
+ else {
60
+ console.log(' — sin hooks instalados (corre `trycore-build init`)');
61
+ }
62
+ // Detección de doble canal (CLI settings.json + plugin) [H3]
63
+ const settingsHasHooks = fs.existsSync(t.settingsFile) &&
64
+ /hooks\/build\//.test(fs.readFileSync(t.settingsFile, 'utf8'));
65
+ if (settingsHasHooks) {
66
+ console.log('');
67
+ console.log('ℹ Hooks del arnés detectados en settings.json (canal CLI).');
68
+ console.log(' Si además instalaste el plugin nativo, la cadena de comando es idéntica:');
69
+ console.log(' Claude Code deduplica y el hook dispara UNA vez. No requiere acción.');
70
+ }
71
+ console.log('═══════════════════════════════════════');
72
+ if (dep.missingHard.length > 0) {
73
+ console.error(`\n✗ Faltan requisitos duros: ${dep.missingHard.join(', ')}. Instálalos antes de operar el arnés.`);
74
+ process.exit(1);
75
+ }
76
+ console.log('\n✓ Requisitos satisfechos.');
77
+ }
@@ -0,0 +1,129 @@
1
+ // commands/init.ts — instala el build harness en el proyecto consumidor.
2
+ // Idempotente: re-correr es seguro. Respeta .claude/, CLAUDE.md y el estado vivo preexistentes.
3
+ //
4
+ // Capa CLI del onboarding [H5,H7,H8]: siembra archivos + captura el stack MECÁNICO.
5
+ // La parametrización SEMÁNTICA (PII, capa IA, capa determinista) y la auto-memory las
6
+ // hace el slash command /build:onboard (Claude), NO este binario.
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { ASSETS, readPackageVersion, targetPaths } from '../lib/paths.js';
10
+ import { linkChildren, countChildren, chmodExec } from '../lib/install-engine.js';
11
+ import { upsertMarkedBlock } from '../lib/markers.js';
12
+ import { seedState, seedConfig } from '../lib/state-seed.js';
13
+ import { mergeHarnessSettings } from '../lib/settings-merge.js';
14
+ import { captureStack, renderAllowlist } from '../lib/stack-prompt.js';
15
+ import { checkDeps } from './doctor.js';
16
+ const BEGIN = '<!-- BEGIN trycore-build-harness ';
17
+ const END = '<!-- END trycore-build-harness -->';
18
+ const GI_BEGIN = '# ── trycore-build-harness (auto)';
19
+ const GI_END = '# ── /trycore-build-harness';
20
+ export async function init(opts) {
21
+ const targetDir = path.resolve(opts.targetDir);
22
+ if (!fs.existsSync(targetDir))
23
+ throw new Error(`Directorio no existe: ${targetDir}`);
24
+ const version = readPackageVersion();
25
+ const linkMode = opts.useCopy ? 'copy' : 'symlink';
26
+ const t = targetPaths(targetDir);
27
+ let mode = opts.mode ?? 'auto';
28
+ if (mode === 'auto')
29
+ mode = fs.existsSync(t.versionFile) ? 'update' : 'init';
30
+ console.log(`▶ trycore-build ${mode}: ${targetDir} (v${version}, ${linkMode})`);
31
+ // 0) Requisitos externos duros [C2,H4]
32
+ if (!opts.skipDoctor) {
33
+ const dep = checkDeps();
34
+ if (dep.missingHard.length > 0) {
35
+ console.error(`\n✗ Faltan requisitos externos: ${dep.missingHard.join(', ')}.`);
36
+ console.error(' openspec: npm i -g @fission-ai/openspec | python3 y git: vía tu gestor del sistema.');
37
+ console.error(' Instálalos y reintenta, o usa --skip-doctor para forzar (los hooks/openspec fallarán en runtime).');
38
+ process.exit(1);
39
+ }
40
+ }
41
+ // 1) Assets en rutas NATIVAS del harness
42
+ linkChildren(ASSETS.agentsBuild, t.agentsBuild, linkMode, (n) => n.endsWith('.md'));
43
+ linkChildren(ASSETS.commandsOpsx, t.commandsOpsx, linkMode, (n) => n.endsWith('.md'));
44
+ linkChildren(ASSETS.commandsBuild, t.commandsBuild, linkMode, (n) => n.endsWith('.md'));
45
+ const nSkills = linkChildren(ASSETS.skills, t.skillsDir, linkMode);
46
+ linkChildren(ASSETS.hooksBuild, t.hooksBuild, linkMode, (n) => n.endsWith('.sh'));
47
+ if (linkMode === 'copy')
48
+ chmodExec(t.hooksBuild); // preserva +x [H1]
49
+ // 2) Estado (schema/README versionados; build-state.json vacío solo si falta) [C1]
50
+ const { stateSeeded } = seedState(targetDir);
51
+ // 3) stack-allowlist.json del consumidor (artefacto del consumidor)
52
+ let allowlist = null;
53
+ if (!fs.existsSync(t.configFile) && mode === 'init') {
54
+ const { cfg, interactive } = await captureStack(opts.stackFlags ?? {});
55
+ allowlist = renderAllowlist(cfg);
56
+ if (!interactive) {
57
+ console.log(' ℹ stack capturado de flags/defaults (no interactivo). Ajusta .claude/config/stack-allowlist.json o corre /build:onboard.');
58
+ }
59
+ }
60
+ const { configSeeded } = seedConfig(targetDir, allowlist);
61
+ // 4) Hooks + permisos mínimos en settings.json (canal CLI) [H3,H11]
62
+ const { addedHooks, addedPerms } = mergeHarnessSettings(t.settingsFile);
63
+ // 5) CLAUDE.md: bloque marcado con {{placeholders}} SIN resolver (los resuelve /build:onboard)
64
+ syncClaudeMdBlock(targetDir, version);
65
+ // 6) .gitignore: lista los assets symlinkeados + estado vivo [H1]
66
+ syncGitignoreBlock(targetDir, linkMode);
67
+ // 7) marca de versión
68
+ fs.writeFileSync(t.versionFile, version + '\n', 'utf8');
69
+ // 8) Resumen
70
+ console.log('');
71
+ console.log(`✓ Build harness instalado en ${targetDir}`);
72
+ console.log(` Agentes: ${countChildren(t.agentsBuild)} en .claude/agents/build/`);
73
+ console.log(` Comandos: ${countChildren(t.commandsOpsx)} /opsx:* + ${countChildren(t.commandsBuild)} /build:*`);
74
+ console.log(` Skills: ${nSkills} en .claude/skills/`);
75
+ console.log(` Hooks: ${countChildren(t.hooksBuild)} en .claude/hooks/build/ (settings.json +${addedHooks} hook(s), +${addedPerms} permiso(s))`);
76
+ console.log(` Estado: ${stateSeeded ? 'build-state.json sembrado (vacío)' : 'build-state.json preservado'}`);
77
+ console.log(` Config: ${configSeeded ? 'stack-allowlist.json sembrado' : 'stack-allowlist.json preservado'}`);
78
+ console.log('');
79
+ console.log('Siguiente paso — abre Claude Code y ejecuta:');
80
+ console.log(' /build:onboard # parametriza el dominio (PII, capa IA, capa determinista) y escribe memoria');
81
+ }
82
+ function syncClaudeMdBlock(targetDir, version) {
83
+ const t = targetPaths(targetDir);
84
+ if (!fs.existsSync(ASSETS.templateClaudeMd)) {
85
+ throw new Error(`Plantilla no encontrada: ${ASSETS.templateClaudeMd}`);
86
+ }
87
+ const template = fs
88
+ .readFileSync(ASSETS.templateClaudeMd, 'utf8')
89
+ .replace(/\{\{BUILD_HARNESS_VERSION\}\}/g, version);
90
+ const lines = template.split('\n');
91
+ const b = lines.findIndex((l) => l.includes(BEGIN));
92
+ const e = lines.findIndex((l) => l.includes(END));
93
+ if (b === -1 || e === -1)
94
+ throw new Error('CLAUDE.md.template sin markers BEGIN/END trycore-build-harness');
95
+ const blockContent = lines.slice(b, e + 1).join('\n');
96
+ if (!fs.existsSync(t.claudeMd)) {
97
+ fs.writeFileSync(t.claudeMd, template, 'utf8');
98
+ console.log(' ✓ CLAUDE.md creado desde template');
99
+ }
100
+ else {
101
+ const action = upsertMarkedBlock({ beginMarker: BEGIN, endMarker: END, blockContent, filePath: t.claudeMd });
102
+ console.log(` ✓ Bloque trycore-build-harness ${action === 'replaced' ? 'actualizado' : 'anexado'} en CLAUDE.md`);
103
+ }
104
+ }
105
+ function syncGitignoreBlock(targetDir, mode) {
106
+ const t = targetPaths(targetDir);
107
+ const isGitRepo = fs.existsSync(path.join(targetDir, '.git'));
108
+ if (!isGitRepo && !fs.existsSync(t.gitignore))
109
+ return;
110
+ const lines = [GI_BEGIN + ' ───────────────────────', '.claude/state/build-state.json'];
111
+ if (mode === 'symlink') {
112
+ // Los symlinks absolutos a node_modules global se rompen en otra máquina si se commitean.
113
+ lines.push('.claude/agents/build/', '.claude/commands/opsx/', '.claude/commands/build/', '.claude/hooks/build/');
114
+ const skillNames = fs.existsSync(ASSETS.skills)
115
+ ? fs.readdirSync(ASSETS.skills, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name)
116
+ : [];
117
+ for (const s of skillNames)
118
+ lines.push(`.claude/skills/${s}/`);
119
+ lines.push('.claude/.build-harness-version');
120
+ }
121
+ lines.push(GI_END + ' ──────────────────────');
122
+ upsertMarkedBlock({
123
+ beginMarker: GI_BEGIN,
124
+ endMarker: GI_END,
125
+ blockContent: lines.join('\n'),
126
+ filePath: t.gitignore,
127
+ });
128
+ console.log(' ✓ .gitignore actualizado');
129
+ }