gemstack-ai 1.1.2 → 1.3.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 (45) hide show
  1. package/.agents/skills/gemstack-plan/SKILL.md +2 -1
  2. package/.agents/skills/gemstack-qa/SKILL.md +3 -0
  3. package/.agents/skills/gemstack-ship/SKILL.md +5 -1
  4. package/.agents/skills/gemstack-spec/SKILL.md +3 -2
  5. package/.agents/skills/gemstack-tasks/SKILL.md +4 -3
  6. package/.gemstack/state.json +7 -8
  7. package/CHANGELOG.md +75 -0
  8. package/README.md +36 -0
  9. package/RELEASE_NOTES.md +61 -0
  10. package/docs/architecture-consistency.md +14 -2
  11. package/docs/spec-driven-development.md +26 -0
  12. package/{gemstack-ai-1.1.2.tgz → gemstack-ai-1.3.0.tgz} +0 -0
  13. package/handoff.md +30 -15
  14. package/package.json +2 -2
  15. package/specs/007-mechanical-test-matrix-closure-evidence/.gemstack.json +5 -0
  16. package/specs/007-mechanical-test-matrix-closure-evidence/closure.json +59 -0
  17. package/specs/007-mechanical-test-matrix-closure-evidence/plan.md +484 -0
  18. package/specs/007-mechanical-test-matrix-closure-evidence/spec.md +597 -0
  19. package/specs/007-mechanical-test-matrix-closure-evidence/tasks.md +536 -0
  20. package/specs/008-cost-provider-safety-gates/.gemstack.json +5 -0
  21. package/specs/008-cost-provider-safety-gates/closure.json +59 -0
  22. package/specs/008-cost-provider-safety-gates/plan.md +456 -0
  23. package/specs/008-cost-provider-safety-gates/spec.md +633 -0
  24. package/specs/008-cost-provider-safety-gates/tasks.md +635 -0
  25. package/specs/009-context-capsule/closure.json +59 -0
  26. package/specs/009-context-capsule/context-capsule.json +428 -0
  27. package/specs/009-context-capsule/plan.md +663 -0
  28. package/specs/009-context-capsule/spec.md +913 -0
  29. package/specs/009-context-capsule/tasks.md +720 -0
  30. package/specs/templates/plan.md +30 -0
  31. package/specs/templates/spec.md +18 -0
  32. package/specs/templates/tasks.md +9 -0
  33. package/src/cli.js +8 -0
  34. package/src/commands/collect.js +340 -0
  35. package/src/commands/context.js +95 -0
  36. package/src/commands/ship.js +79 -0
  37. package/src/commands/verify.js +182 -6
  38. package/src/lib/closure-context.js +453 -0
  39. package/src/lib/context-capsule.js +594 -0
  40. package/src/lib/cost-ledger.js +355 -0
  41. package/src/lib/provider-boundary.js +186 -0
  42. package/src/lib/provider-registry.js +265 -0
  43. package/src/lib/runner-adapters.js +347 -0
  44. package/src/lib/safety-gates.js +277 -0
  45. package/src/lib/test-matrix.js +187 -0
@@ -17,5 +17,6 @@ Invocado mediante `/plan`.
17
17
  5. Detalla el stack y llena la tabla "Complexity Tracking" SÓLO si rompiste alguna regla de la constitución y necesitas justificarlo.
18
18
  6. Opcionalmente, genera los entregables satélites: `data-model.md`, `contracts/` (para APIs/Interfaces), y `quickstart.md`.
19
19
  7. **Herencia y Contratos Aditivos (Upgrade A)**: PLAN hereda automáticamente los contratos declarados en `spec.md`. No contradigas ni alteres los contratos congelados heredados; si requieres contratos técnicos adicionales, decláralos de forma compatible y aditiva en el bloque ````gemstack-contracts ```` de `plan.md`.
20
- 8. Pide aprobación al usuario antes de permitir la ejecución de `/tasks`.
20
+ 8. **Vinculación Física de Pruebas y Gates (Upgrade B)**: Define en `plan.md` los bloques canónicos ````gemstack-test-bindings ```` (asociando cada ID de prueba a un archivo físico y runner) y ````gemstack-closure-gates ```` (especificando scripts de package.json obligatorios).
21
+ 9. Pide aprobación al usuario antes de permitir la ejecución de `/tasks`.
21
22
 
@@ -15,3 +15,6 @@ Invocado mediante `/qa` o `/qa-only`.
15
15
  3. Si la aplicación es visual, recomienda `/browser` o correr tests de Playwright para verificar manualmente la UI.
16
16
  4. Genera un breve reporte indicando si cada Criterio pasó o falló.
17
17
 
18
+
19
+ 5. **Recolección Mecánica de Evidencias (Upgrade B)**: Ejecuta `node src/cli.js collect` para ejecutar los runners de pruebas, gates y reconciliar la matriz mecánica generando `specs/[nombre-feature]/closure.json`.
20
+ 6. Valida que la evidencia esté fresca y en modo lectura con `node src/cli.js verify`.
@@ -12,7 +12,11 @@ Invocado mediante `/ship`.
12
12
  ## Proceso:
13
13
  1. Verifica revisión (`/review`) y validación (`/qa`).
14
14
  2. Confirma validación de seguridad (`/cso`).
15
- 3. Comprueba si los specs se cumplieron.
15
+ 3. **Validación de Evidencia Mecánica de Cierre (Upgrade B)**:
16
+ - Comprueba que exista `specs/[nombre-feature]/closure.json`.
17
+ - Confirma que el estado sea `VERIFIED` o `VERIFIED_WITH_EXCEPTIONS`.
18
+ - Bloquea el ship si el estado es `STALE`, `BLOCKED`, o si falta el archivo (a menos que la feature opere en modo LEGACY).
19
+ - Ejecuta `node src/cli.js ship` para validar compuertas y transicionar el ciclo de vida.
16
20
  4. Genera un PR summary si se pide.
17
21
  5. NO hagas push, merge o deploy sin aprobación explícita.
18
22
  6. Sugiere ejecutar `/handoff` para documentar la entrega en la memoria del proyecto.
@@ -20,6 +20,7 @@ Eres un Product Manager técnico. Tu objetivo es convertir ideas vagas en requis
20
20
  5. **CERO SUPOSICIONES**: Si el usuario omitió detalles, NO adivines. Usa el marcador `[NEEDS CLARIFICATION: tu duda]` en el documento.
21
21
  6. No describas implementación técnica (nada de stacks, bases de datos o APIs). Concéntrate estrictamente en el "Qué" y "Por qué".
22
22
  7. **Contratos Arquitectónicos Congelados (Upgrade A)**: Si la funcionalidad implica decisiones estructurales críticas (estados enum, tuplas de identidad, reglas de procedencia, invariantes booleanas, límites de roadmap o límites boundary), decláralos explícitamente en el bloque canónico ````gemstack-contracts ````. Congela solo decisiones materiales, no texto arbitrario.
23
- 8. Actualiza el archivo `.gemstack/state.json` para reflejar la rama activa y fase: `{"active_spec": "specs/[nombre-feature]/", "current_phase": "spec", "last_update": "<timestamp>"}`.
24
- 9. Una vez finalizado, indica al usuario que puede revisar la especificación y, tras resolver las dudas, ejecutar `/plan`.
23
+ 8. **Matriz Mecánica de Pruebas (Upgrade B)**: Declara la matriz canónica en el bloque ````gemstack-test-matrix ```` de `spec.md`, asignando IDs canónicos estables `TEST-[FEATURE]-[CAT][NUM]`, capas y compuertas (REQUIRED | SUPPLEMENTAL).
24
+ 9. Actualiza el archivo `.gemstack/state.json` para reflejar la rama activa y fase: `{"active_spec": "specs/[nombre-feature]/", "current_phase": "spec", "last_update": "<timestamp>"}`.
25
+ 10. Una vez finalizado, indica al usuario que puede revisar la especificación y, tras resolver las dudas, ejecutar `/plan`.
25
26
 
@@ -13,7 +13,8 @@ Invocado mediante `/tasks`.
13
13
  1. Lee `specs/[nombre-feature]/plan.md` y, si existen, `data-model.md` y la carpeta `contracts/`.
14
14
  2. Convierte los contratos, entidades y el plan en una lista estricta de ejecución en `specs/[nombre-feature]/tasks.md` usando la plantilla `specs/templates/tasks.md`.
15
15
  3. **Herencia de Contratos (Upgrade A)**: TASKS hereda automáticamente los contratos consolidados de SPEC y PLAN. No se requiere declarar un bloque de contratos propio salvo que se agreguen contratos operacionales específicos de tareas.
16
- 4. Aplica Test-First: Las tareas de escribir pruebas (y validarlas) deben ir ANTES que la implementación de código.
17
- 5. Usa el marcador `[P]` para tareas independientes que se puedan paralelizar.
18
- 6. Ofrece al usuario comenzar automáticamente con la primera tarea o delegar a subagentes paralelos si hay múltiples `[P]`.
16
+ 4. **Trazabilidad TASK -> TEST (Upgrade B)**: Para cada tarea, incluye comentarios de metadatos `<!-- gemstack:validation_required=true|false -->`, `<!-- gemstack:tests=... -->`, y `<!-- gemstack:files=... -->`, asegurando que todas las pruebas canónicas requeridas estén mapeadas a al menos una tarea de implementación.
17
+ 5. Aplica Test-First: Las tareas de escribir pruebas (y validarlas) deben ir ANTES que la implementación de código.
18
+ 6. Usa el marcador `[P]` para tareas independientes que se puedan paralelizar.
19
+ 7. Ofrece al usuario comenzar automáticamente con la primera tarea o delegar a subagentes paralelos si hay múltiples `[P]`.
19
20
 
@@ -2,18 +2,17 @@
2
2
  "version": "0.1",
3
3
  "current_phase": "shipped",
4
4
  "status": "SHIPPED",
5
- "stop_reason": "UPGRADE_A_SHIPPED_DONE",
5
+ "stop_reason": "UPGRADE_C_SHIPPED_DONE",
6
6
  "active_spec": null,
7
7
  "completed_phases": [
8
8
  "spec",
9
9
  "plan",
10
- "tasks",
11
- "implement"
10
+ "tasks"
12
11
  ],
13
12
  "phase_hashes": {
14
- "spec": "f5d423eaf508b06b663b39f467fba1d9ceff6db21f01e427500ad739a90c5be8",
15
- "plan": "1ce0e58863427905022a6294f8683b9f508d72b171379c78807db19862c75004",
16
- "tasks": "dfad2484ad112e26ef906ea851b12cf6ea090d6faf244a6fbd2650baee8e0d98"
13
+ "spec": "9241b9e992f687e80ecef388c79731ece7af9aa75ba989dc8f0b1e9b855f7914",
14
+ "plan": "6a2e29e9aeda266a71ab435fa09bca3b18521835a69f6020cd8d9f135643e3aa",
15
+ "tasks": "1697c32a1f6596f317491df68cd1b161e5c77fbbddc74ce3f1e6e00a42619249"
17
16
  },
18
17
  "consistency": {
19
18
  "status": "PASS",
@@ -24,6 +23,6 @@
24
23
  "freeze": false,
25
24
  "allowed_paths": []
26
25
  },
27
- "last_update": "2026-09-11T09:01:18.769Z",
28
- "last_completed_feature": "specs/006-architecture-consistency-engine/"
26
+ "last_update": "2026-09-11T17:38:04.916Z",
27
+ "last_completed_feature": "specs/008-cost-provider-safety-gates"
29
28
  }
package/CHANGELOG.md CHANGED
@@ -2,6 +2,81 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [v1.3.0] - 2026-09-11
6
+
7
+ ### Added
8
+ - **Cost & Provider Safety Gates (Upgrade C)**: Deterministic, fail-closed safety and cost verification framework for commercial, external, and AI provider interactions.
9
+ - `ProviderCapabilityGate`: validates that requested capabilities are declared and supported by the active provider adapter before invocation.
10
+ - `BillableActionGate`: blocks billable actions unless explicit spending authorization tokens are granted.
11
+ - Provider Registry: canonical provider directory with declared capability contracts and deterministic rejection of unknown providers.
12
+ - Cost Ledger (`cost-ledger.json`): auditable schema validating provider cost assumptions, freshness thresholds, and currency units.
13
+ - Fail-Closed Unknown Cost Policy: unclassified or ambiguous operations are strictly treated as commercial rather than defaulted to free.
14
+ - Environment Safety Isolation: prevents accidental commercial provider invocations in `test` and `ci` environments even if ambient credentials exist.
15
+ - Trusted Mock Boundaries: enforces that test mocks execute strictly in memory with zero network escapes.
16
+ - Re-Entrant Fallback Authorization: secondary fallback providers trigger independent gate re-evaluation before execution.
17
+ - Verification Purity: guarantees `gemstack verify` executes offline with zero network sockets and zero ledger file mutations.
18
+ - **Context Capsule / Context Compression (Upgrade D)**: Deterministic, auditable, constraint-lossless context compression architecture for cross-session AI continuation.
19
+ - Deterministic Context Capsule Generation: compiles authoritative sources (`spec.md`, `plan.md`, `tasks.md`, `.gemstack/state.json`, `closure.json`) into `context-capsule.json`.
20
+ - Constraint-Lossless Compression: 100% of normative `MUST` and `MUST NOT` constraints, frozen contracts, and acceptance signatures survive compression.
21
+ - Canonical Authority Precedence: authoritative repository sources unconditionally govern over derived capsule claims (`SPEC` > `PLAN` > `TASKS` > implementation).
22
+ - Provenance & Freshness Hashing: live SHA-256 source digests detect drift or manual tampering immediately (`STALE` / `TAMPERED`).
23
+ - Strict Secrets Defense: automatic regex and property pattern scanner rejects tokens, API keys, private keys, and `.env` references fail-closed.
24
+ - Size Budget Enforcement: 32 KB target budget with deterministic 3-tier condensation and 64 KB fail-closed hard limit.
25
+ - Pure Offline & Atomic Writing: generation and validation execute 100% offline with atomic write semantics (`.tmp` + rename).
26
+ - Read-Only Verification (Stage 5.2): `gemstack verify` inspects context capsule freshness without disk writes or file mutation.
27
+ - New CLI Surface: `gemstack context generate`, `gemstack context show`, and `gemstack context verify`.
28
+ - Progressive Legacy Support: repositories or features lacking capsules operate cleanly with informational notices and zero blockers.
29
+
30
+ ### Changed
31
+ - `gemstack verify` pipeline extended to include Stage 5.2 Context Capsule read-only audit.
32
+ - `package.json` test script updated to explicitly enumerate all 25 physical test suites across Upgrades A, B, C, and D.
33
+ - Closure context resolution (`src/lib/closure-context.js`) incorporates `context-capsule.json` in relevant files hashing.
34
+
35
+ ### Compatibility
36
+ - 100% backward compatible with existing Gemstack repositories and frozen contracts from Upgrades A, B, and C.
37
+ - Zero external runtime npm dependencies added (`package.json` dependencies remain `{}`).
38
+
39
+ ### Validation
40
+ - 20/20 Upgrade C canonical acceptance tests passing (`TEST-COST-A01` through `H01`).
41
+ - 20/20 Upgrade D canonical acceptance tests passing (`TEST-CONTEXT-A01` through `H01`).
42
+ - 85/85 combined canonical acceptance tests passing (25 Upgrade A + 20 Upgrade B + 20 Upgrade C + 20 Upgrade D).
43
+ - 100/100 physical tests passing with 0 failures and 0 regressions.
44
+ - Full CI test matrix (`npm run ci:all`) passing cleanly.
45
+ - `gemstack verify` exit code 0 with 0 errors and 0 open blockers.
46
+ - Context capsule verified: `VALID` and `FRESH` (11,873 bytes < 32 KB budget).
47
+
48
+ ## [v1.2.0] - 2026-09-11
49
+ ### Added
50
+ - **Mechanical Test Matrix & Closure Evidence (Upgrade B)**: Full mechanical closure verification framework eliminating false closure and test discovery hallucinations.
51
+ - Canonical fenced `gemstack-test-matrix` blocks in `spec.md` with 20 canonical acceptance test criteria (`TEST-CLOSURE-A01` through `H01`).
52
+ - Deterministic Acceptance Signature (`acceptanceSignature`): SHA-256 digest calculated across all canonical test definitions ensuring immutable acceptance criteria.
53
+ - Bidirectional Task <-> Test Traceability: strict mapping between `tasks.md` validation blocks and canonical acceptance tests.
54
+ - Zero-Shell Test Runner Adapters: safe, cross-platform `node:test` TAP runner adapter with suite container detection (`kind: 'SUITE'` vs `kind: 'TEST'`).
55
+ - Exact Canonical Reconciliation Arithmetic: verifies `canonical_required = canonical_passed + missing`, `physical_executed = canonical_executed + supporting_executed`, and prevents phantoms and orphans.
56
+ - Mutating Evidence Collector (`gemstack collect`): executes bound test files and required `PACKAGE_SCRIPT` gates to produce `specs/<feature>/closure.json`.
57
+ - Dynamic Closure Context Freshness (`closureContextHash`): binds closure evidence to the repository state (clean/dirty git or non-git), phase hashes, test files, and bounded implementation code.
58
+ - Read-Only Closure Gate in `gemstack verify`: stage 5/6 verifies `closure.json` freshness and acceptance criteria without writing or mutating any files on disk.
59
+ - Lifecycle Ship Enforcement (`gemstack ship`): requires status `VERIFIED` in `closure.json` before transitioning feature lifecycle to `SHIPPED`.
60
+ - Progressive `LEGACY` mode support: features lacking test matrix blocks continue without friction or errors.
61
+
62
+ ### Changed
63
+ - `gemstack verify` upgraded to a 6-stage deterministic verification pipeline with zero-mutation read-only verification.
64
+ - `package.json` test script explicitly enumerates all 11 physical test suites for portable cross-platform execution.
65
+ - Agent skills (`gemstack-spec`, `gemstack-plan`, `gemstack-tasks`, `gemstack-qa`, `gemstack-ship`) and templates updated with Upgrade B canonical workflows.
66
+
67
+ ### Compatibility
68
+ - 100% backward compatible with existing Gemstack repositories and Upgrade A contract blocks.
69
+ - Zero external runtime or development npm dependencies added (`package.json` dependencies remain `{}`).
70
+
71
+ ### Validation
72
+ - 22/22 Upgrade B implementation tasks complete (T001–T022).
73
+ - 20/20 canonical P1 acceptance tests passing.
74
+ - 45/45 combined canonical acceptance tests passing (25 Upgrade A + 20 Upgrade B).
75
+ - 53/53 physical tests passing with 0 regressions.
76
+ - `npm test` exit code 0.
77
+ - `gemstack verify` exit code 0 with 0 open blockers.
78
+ - Self-dogfooded on `specs/007-mechanical-test-matrix-closure-evidence/` with closure status `VERIFIED`.
79
+
5
80
  ## [v1.1.2] - 2026-09-11
6
81
  ### Fixed
7
82
  - Fixed host-dependent normalization of simulated Windows paths in the Architecture Consistency Engine.
package/README.md CHANGED
@@ -95,6 +95,42 @@ Gemstack mechanically prevents AI agents from silently violating or hallucinatin
95
95
  - `gemstack verify` performs strictly read-only verification without mutating or overwriting accepted phase hashes (`VERIFY != FREEZE`).
96
96
  - Existing projects without structured contracts automatically run in **LEGACY** mode without breaking.
97
97
 
98
+
99
+ ## 🧪 Mechanical Test Matrix & Closure Evidence
100
+
101
+ Gemstack Upgrade B guarantees that what was planned is what was physically tested:
102
+ - **Canonical Test Matrix**: `spec.md` declares canonical acceptance tests and cryptographic `acceptanceSignature`.
103
+ - **Physical Test Bindings**: `plan.md` maps canonical IDs 1:1 to physical runner test files.
104
+ - **Task Traceability**: `tasks.md` validates that all required canonical tests have implementation tasks.
105
+ - **Safe Runner Adapters**: Direct zero-shell execution of test suites and package script gates.
106
+ - **`gemstack collect`**: Mutating runner that executes tests and atomically writes `specs/<feature>/closure.json`.
107
+ - **`gemstack verify`**: Strictly read-only 6-stage validator verifying evidence freshness against `closureContextHash`.
108
+ - **`gemstack ship`**: Gatekeeper requiring verified evidence before allowing transition to `SHIPPED`.
109
+ - **Git Optionality & Legacy Support**: Works identically on clean Git, dirty Git, and non-Git projects, with graceful legacy fallback.
110
+
111
+ ## 🛡️ Cost & Provider Safety Gates
112
+
113
+ Gemstack Upgrade C guarantees fail-closed safety for commercial, remote, and AI providers:
114
+ - **`ProviderCapabilityGate`**: Validates provider capability declarations before invocation without network attempts.
115
+ - **`BillableActionGate`**: Enforces strict spending authorization tokens before executing billable operations.
116
+ - **Cost Ledger (`cost-ledger.json`)**: Auditable schema tracking provider cost assumptions, freshness thresholds, and currency units.
117
+ - **Fail-Closed Unknown Cost Policy**: Operations with unclassified or ambiguous costs are strictly blocked.
118
+ - **Environment Safety**: Commercial provider execution is forbidden in `test` and `ci` environments.
119
+ - **Trusted Mock Boundaries**: Test mocks operate strictly in memory with zero network escapes.
120
+ - **Offline Purity**: `gemstack verify` runs 100% offline with zero external network or provider charges.
121
+
122
+ ## 📦 Context Capsule & Compression
123
+
124
+ Gemstack Upgrade D enables deterministic, constraint-lossless context compression for cross-session continuation:
125
+ - **`gemstack context generate`**: Compiles authoritative specifications, plans, tasks, contracts, and closure evidence into `context-capsule.json`.
126
+ - **Constraint Losslessness**: 100% of normative `MUST`/`MUST NOT` constraints, frozen contracts, and acceptance criteria survive compression.
127
+ - **Authority Precedence**: Authoritative repository artifacts unconditionally override derived capsule claims (`SPEC` > `PLAN` > `TASKS` > implementation).
128
+ - **Drift & Tampering Detection**: Live SHA-256 source hashing flags modified or manually tampered capsules as `STALE`.
129
+ - **Secret Defense**: Fail-closed regex scanning strictly blocks credentials, tokens, private keys, and `.env` data.
130
+ - **Size Budgeting**: 32 KB target budget with deterministic priority condensation and 64 KB fail-closed hard cap.
131
+ - **`gemstack context show`**: Displays human-readable continuation context summary or raw JSON.
132
+ - **`gemstack context verify`**: Read-only validation of context capsule freshness and integrity.
133
+
98
134
  ## 🐝 Advanced Autonomy (The WOW Update)
99
135
 
100
136
  Gemstack isn't just passive documents; it actively orchestrates agentic capabilities:
package/RELEASE_NOTES.md CHANGED
@@ -1,5 +1,66 @@
1
1
  # Gemstack Release Notes
2
2
 
3
+ # Gemstack v1.3.0 — Cost & Provider Safety Gates + Context Capsule
4
+
5
+ ## Highlights
6
+
7
+ ### Upgrade C — Cost & Provider Safety Gates
8
+ - **Deterministic Provider & Capability Validation (`ProviderCapabilityGate`)**: Validates requested provider capabilities ahead of invocation and fail-closes on undeclared or unsupported capabilities without network calls.
9
+ - **Spending Authorization Barrier (`BillableActionGate`)**: Enforces the central invariant "NO PROOF = NO EXECUTION"; commercial or billable actions are strictly blocked unless accompanied by valid explicit spending tokens.
10
+ - **Auditable Cost Ledger (`cost-ledger.json`)**: Machine-readable schema establishing strict freshness dates, provider cost classifications, and zero-secrets immunity.
11
+ - **Fail-Closed Unknown Cost Policy**: Unclassified or unknown operations are never assumed free; they are treated fail-closed as commercial risks.
12
+ - **Environment Safety & CI Isolation**: Prevents accidental commercial provider calls during tests and CI builds regardless of ambient developer credentials.
13
+ - **Trusted Mock Enforcement**: Verifies in-memory mocks remain isolated and fail-closed against external network socket leaks.
14
+ - **Re-Entrant Provider Fallback**: Fallback target providers trigger independent gate re-evaluation before execution.
15
+ - **Verification Purity**: Guarantees `gemstack verify` runs strictly offline with zero provider charges and zero file mutations.
16
+
17
+ ### Upgrade D — Context Capsule / Context Compression
18
+ - **Deterministic Context Compression**: Compiles authoritative specification, plan, tasks, lifecycle, and closure artifacts into compact, machine-readable continuation context (`context-capsule.json`).
19
+ - **Constraint-Lossless Compression**: 100% of normative behavioral constraints (`MUST`, `MUST NOT`), frozen architectural contracts, and acceptance criteria survive compression without semantic loss.
20
+ - **Canonical Authority Precedence**: Authoritative repository artifacts unconditionally govern over derived capsule claims (`SPEC` > `PLAN` > `TASKS` > implementation).
21
+ - **Cryptographic Provenance & Drift Detection**: Live SHA-256 source digests detect artifact modifications or tampering immediately (`STALE` / `TAMPERED`).
22
+ - **Strict Secrets Barrier**: Automated regex scanner blocks credential properties (`apiKey`, `token`, `secret`, `clientSecret`), token patterns (`sk-...`, `AIza...`, `ghp_...`), private keys, and `.env` references.
23
+ - **Deterministic Size Budgeting**: 32 KB target budget with prioritized 3-tier condensation and a 64 KB hard fail-closed limit.
24
+ - **Read-Only Verification (Stage 5.2)**: `gemstack verify` inspects context capsule freshness without modifying or rewriting disk state.
25
+ - **CLI Commands**: `gemstack context generate`, `gemstack context show`, and `gemstack context verify`.
26
+ - **Zero Runtime Dependencies**: Native Node.js standard library implementation (`node:crypto`, `node:fs`, `node:path`, `node:test`).
27
+
28
+ ## Acceptance & Regression Baseline
29
+ - 25 Upgrade A canonical acceptance tests passing (`TEST-CONSISTENCY-A01` through `H02`).
30
+ - 20 Upgrade B canonical acceptance tests passing (`TEST-CLOSURE-A01` through `H01`).
31
+ - 20 Upgrade C canonical acceptance tests passing (`TEST-COST-A01` through `H01`).
32
+ - 20 Upgrade D canonical acceptance tests passing (`TEST-CONTEXT-A01` through `H01`).
33
+ - 85 total canonical acceptance tests passing.
34
+ - 100 total physical tests passing across 25 explicitly enumerated suites.
35
+ - Full CI suite (`npm run ci:all`) passing with 0 warnings and 0 errors.
36
+ - Both Upgrade C and Upgrade D closed with closure status `VERIFIED`.
37
+
38
+ ---
39
+
40
+ # Gemstack v1.2.0 — Mechanical Test Matrix & Closure Evidence
41
+
42
+ ## Highlights
43
+ - **Mechanical Test Matrix & Closure Verification (Upgrade B)**: Eliminates false closure and test discovery hallucinations by introducing a deterministic verification pipeline from specification to shipment.
44
+ - **Canonical Test Matrix (`gemstack-test-matrix`)**: Explicit acceptance criteria defined in `spec.md` with deterministic `acceptanceSignature` (SHA-256) ensuring acceptance rules are immutable once approved.
45
+ - **Task ↔ Test Traceability**: Explicit bidirectional binding between implementation tasks in `tasks.md` and canonical acceptance tests.
46
+ - **Safe Zero-Shell Runners**: Pure Node.js `node:test` TAP runner adapter with suite container exclusion (`kind: 'SUITE'` vs `kind: 'TEST'`), ensuring TAP headers/containers are never counted as physical tests.
47
+ - **Exact Canonical Reconciliation Arithmetic**: Mechanical validation proving `canonical_required = canonical_passed + missing` and `physical_executed = canonical_executed + supporting_executed` with zero tolerance for phantoms or orphans.
48
+ - **Mutating Collector (`gemstack collect`)**: Executes bound test suites and required `PACKAGE_SCRIPT` gates to produce `specs/<feature>/closure.json`.
49
+ - **Dynamic Closure Context Freshness (`closureContextHash`)**: Cryptographically binds closure evidence to repository state (clean git, dirty git, or non-git), phase hashes, bound test files, and bounded implementation source files.
50
+ - **Read-Only Verification Pipeline (`gemstack verify`)**: Stage 5/6 inspects closure freshness and gate outcomes in memory with 0 disk mutations.
51
+ - **Ship Gatekeeper (`gemstack ship`)**: Strict gate requiring `status: "VERIFIED"` in `closure.json` before transitioning feature lifecycle to `SHIPPED`.
52
+ - **Progressive LEGACY Mode**: Full backward compatibility for features without test matrices or contract blocks.
53
+ - **Zero-Dependency Architecture**: 100% native Node.js standard library implementation with zero third-party production dependencies.
54
+
55
+ ## Acceptance & Regression Baseline
56
+ - 25 Upgrade A canonical acceptance tests passing (`TEST-CONSISTENCY-A01` through `H02`).
57
+ - 20 Upgrade B canonical acceptance tests passing (`TEST-CLOSURE-A01` through `H01`).
58
+ - 45 total canonical acceptance tests passing.
59
+ - 53 total physical tests passing with 0 regressions.
60
+ - 11 physical test suites explicitly enumerated for cross-platform reliability.
61
+
62
+ ---
63
+
3
64
  # Gemstack v1.1.2 — Architecture Consistency & Phase Freezing
4
65
 
5
66
  ## Recovery Release Note
@@ -130,10 +130,10 @@ Gemstack strictly separates operational state from historical audit trails:
130
130
 
131
131
  ## 9. Verification Integration (`gemstack verify`)
132
132
 
133
- Architectural consistency is embedded as **Step 4/5** in the unified `gemstack verify` command:
133
+ Architectural consistency is embedded as **Step 4/6** in the unified `gemstack verify` command:
134
134
 
135
135
  ```text
136
- [INFO] --- 4/5 Verificación de Consistencia de Arquitectura y Hashes de Fase ---
136
+ [INFO] --- 4/6 Verificación de Consistencia de Arquitectura y Hashes de Fase ---
137
137
  [OK] [STRUCTURED] 5 contrato(s) base declarados en spec.md.
138
138
  [OK] Hash congelado de spec.md verificado: f5d423eaf508...
139
139
  [OK] Hash congelado de plan.md verificado: 1ce0e5886342...
@@ -142,3 +142,15 @@ Architectural consistency is embedded as **Step 4/5** in the unified `gemstack v
142
142
  ```
143
143
 
144
144
  If any contracts contradict, artifacts mutate, or unapproved blockers exist, `gemstack verify` exits with code 1, halting CI/CD pipelines.
145
+
146
+ ---
147
+
148
+ ## 10. Mechanical Test Matrix & Closure Evidence (Upgrade B)
149
+
150
+ Beyond static contract consistency across phase files, Gemstack Upgrade B validates execution evidence against declared requirements:
151
+
152
+ - **`acceptanceSignature`**: Full semantic record SHA-256 digest of the canonical test matrix in `spec.md`.
153
+ - **Authoritative Execution**: Native test runners (such as `node:test`) execute bound tests without shell intermediaries. TAP output is parsed to extract executed canonical test tokens.
154
+ - **Reconciliation & Set Equality**: Proves that all declared required canonical tests were physically executed and passed (`PASS + FAIL + SKIP + TODO + CANCELLED == TOTAL_PHYSICAL`). Detects `PHANTOM_TEST` (claimed but unexecuted) and `ORPHAN_TEST` (executed with unregistered canonical ID).
155
+ - **`closureContextHash`**: Deterministic SHA-256 fingerprint binding repository state, phase hashes, test files, implementation files, and gate definitions. Prevents whole-repository scanning while detecting stale evidence.
156
+ - **Progressive Legacy Compatibility**: Specifications lacking a test matrix operate seamlessly in legacy mode with an informational notice, preserving 100% backward compatibility.
@@ -8,3 +8,29 @@ Inspirado en Spec Kit, Gemstack obliga a pensar antes de teclear.
8
8
 
9
9
  Usa `/specify` para comenzar este ciclo.
10
10
  Una vez que el spec esté aprobado por el usuario, usa `/plan` y luego `/tasks`.
11
+
12
+
13
+ ---
14
+
15
+ ## Mechanical Test Matrix & Closure Evidence (Upgrade B)
16
+
17
+ Gemstack complements Architecture Consistency with mechanical closure verification:
18
+
19
+ 1. **Test Matrix in Spec (`spec.md`)**:
20
+ Declared in a ```gemstack-test-matrix``` block. Defines canonical acceptance tests with unique IDs (`TEST-[FEATURE]-[CAT][NUM]`), verification layers (`UNIT`, `INTEGRATION`, `E2E`, `CLI`), and enforcement gates (`REQUIRED`, `SUPPLEMENTAL`). Produces an immutable `acceptanceSignature`.
21
+
22
+ 2. **Physical Test Bindings in Plan (`plan.md`)**:
23
+ Declared in ```gemstack-test-bindings``` block mapping each canonical test ID 1:1 to a physical runner file (e.g. `tests/example.test.js` with runner `node:test`).
24
+ Also declares mandatory package script gates in ```gemstack-closure-gates```.
25
+
26
+ 3. **Task Traceability in Tasks (`tasks.md`)**:
27
+ Implementation tasks declare metadata:
28
+ `<!-- gemstack:validation_required=true|false -->`
29
+ `<!-- gemstack:tests=TEST-001,TEST-002 -->`
30
+ `<!-- gemstack:files=src/module.js,tests/module.test.js -->`
31
+ Ensures that every required canonical test is bound to at least one implementation task.
32
+
33
+ 4. **Lifecycle: COLLECT vs VERIFY vs SHIP**:
34
+ - `gemstack collect`: Mutating evidence collector. Executes test runners, evaluates package script gates, reconciles counts, computes `closureContextHash`, and generates feature-local `closure.json`.
35
+ - `gemstack verify`: Strictly read-only validator (6 stages). Evaluates existing `closure.json` against in-memory fresh `closureContextHash`. Never writes to disk.
36
+ - `gemstack ship`: Lifecycle gatekeeper. Enforces that `closure.json` is fresh and marked `VERIFIED` (or policy-waived `VERIFIED_WITH_EXCEPTIONS`) before transitioning state to `SHIPPED`.
package/handoff.md CHANGED
@@ -8,25 +8,40 @@ Evolucionar Gemstack incorporando el feedback de producción real de proyectos a
8
8
  4. Comando unificado `gemstack verify` (alias `audit`) para auditoría integral en un solo paso.
9
9
 
10
10
  ## 2. Estado actual
11
- - **Upgrade A (Consistency Core & Phase Freezing)**: CERRADO Y LIBERADO como v1.1.0 (`GEMSTACK UPGRADE A SHIPPED / DONE — ARCHITECTURE CLOSED`).
12
- - 17/17 tareas completadas, 25/25 tests canónicos P1 pasando (33/33 físicos), 0 bloqueadores.
13
- - Reglas `01-gemstack-core.md`, `02-gemstack-constitution.md`, plantillas y skills actualizados y sincronizados en `template/`.
14
- - Motor de consistencia integrado en `gemstack verify` (Paso 4/5).
11
+ - **Upgrade A (Consistency Core & Phase Freezing)**: CERRADO Y PUBLICADO OFICIALMENTE en `v1.1.2`.
12
+ - **Upgrade B (Mechanical Test Matrix & Closure Evidence)**: CERRADO Y PUBLICADO OFICIALMENTE en `v1.2.0`.
13
+ - **Upgrade C (Cost & Provider Safety Gates)**: CERRADO Y VERIFICADO (`closure.json` status `VERIFIED`).
14
+ - 20/20 pruebas canónicas P1 de Upgrade C pasando al 100% en 6 suites dedicadas.
15
+ - Gates `ProviderCapabilityGate` y `BillableActionGate` implementados con fail-closed default deny.
16
+ - Cost ledger (`cost-ledger.json`) validado, offline verification purity garantizada.
17
+ - **Upgrade D (Context Capsule / Context Compression)**: CERRADO Y VERIFICADO (`closure.json` status `VERIFIED`, capsule `VALID` y `FRESH`).
18
+ - 20/20 pruebas canónicas de Upgrade D pasando al 100% en 8 suites dedicadas.
19
+ - Serializador canónico determinista, defensa de secretos fail-closed, presupuesto 32KB/64KB.
20
+ - Comandos CLI `gemstack context` y etapa 5.2 en `gemstack verify`.
21
+ - 100/100 pruebas físicas totales pasando en 25 suites sin dependencias externas.
22
+ - Preparado para release estable `v1.3.0`.
15
23
 
16
24
  ## 3. Archivos y cambios
17
- - `src/lib/contracts.js`: Parser column-0 fenced, esquemas de 6 contratos, resolución de herencia y detección de contradicciones.
18
- - `src/lib/hasher.js`: Hashing canónico SHA-256 (64 hex lowercase) con normalización CRLF->LF y rechazo de BOM UTF-8.
19
- - `src/lib/findings.js`: Fingerprints canónicos SHA-256 de 64 caracteres, display token de 12 caracteres y excepciones con `contextHash`.
20
- - `src/lib/state.js`: Persistencia atómica de `state.json` (solo operativo) y sidecar histórico `.gemstack.json`.
21
- - `src/commands/verify.js`: Paso 4/5 de consistencia arquitectónica y hashes congelados.
22
- - `tests/`: 5 suites unitarias (`contracts.test.js`, `hasher.test.js`, `findings.test.js`, `init.test.js`, `verify.test.js`).
23
- - `docs/architecture-consistency.md`: Referencia técnica integral de consistencia y congelamiento de fases.
24
- - `CHANGELOG.md`, `README.md`, `RELEASE_NOTES.md`, `package.json`: Versión v1.1.0 documentada y preparada para release.
25
+ - `src/lib/test-matrix.js`: Parser de `gemstack-test-matrix`, validación de esquema de 20 tests canónicos y cálculo de `acceptanceSignature` canónico SHA-256.
26
+ - `src/lib/closure-context.js`: Parser de bindings y gates de `plan.md`, metadatos de `tasks.md`, trazabilidad bidireccional, resolución de `RelevantClosureFiles`, `computeContentAggregateHash` y cálculo de `closureContextHash`.
27
+ - `src/lib/runner-adapters.js`: Adaptador nativo seguro de runner `node:test`, parser TAP de resultados, motor de reconciliación aritmética canónica, ejecutor seguro de compuertas `PACKAGE_SCRIPT` y serializador atómico de `closure.json`.
28
+ - `src/commands/collect.js`: Comando mutador dedicado que ejecuta tests y gates para generar `specs/<feature>/closure.json`.
29
+ - `src/commands/ship.js`: Compuerta de transición a `SHIPPED` que exige evidencia de cierre fresca y verificada.
30
+ - `src/commands/verify.js`: Etapa 5/6 agregada de verificación de evidencia mecánica de cierre en modo estrictamente de solo lectura (0 mutaciones en disco).
31
+ - `src/cli.js`: Registro de comandos `collect` y `ship`.
32
+ - `specs/007-mechanical-test-matrix-closure-evidence/`: Artefactos congelados `spec.md`, `plan.md`, `tasks.md` y evidencia de cierre generada `closure.json`.
33
+ - `tests/`: 6 nuevas suites de prueba (`test-matrix.test.js`, `reconciliation.test.js`, `runner-adapter.test.js`, `traceability.test.js`, `closure-manifest.test.js`, `closure-gates.test.js`).
34
+ - `specs/templates/`: Actualizadas plantillas de `spec.md`, `plan.md` y `tasks.md` con bloques canónicos de Upgrade B.
35
+ - `.agents/skills/`: Actualizados skills (`gemstack-spec`, `gemstack-plan`, `gemstack-tasks`, `gemstack-qa`, `gemstack-ship`).
36
+ - `docs/`, `README.md`, `package.json`: Documentación técnica y script de test con enumeración explícita de las 11 suites físicas.
25
37
 
26
38
  ## 4. Intentos fallidos
27
39
  - Se confirmó en proyectos reales que scripts de prueba con sintaxis `2>nul` en `package.json` provocan que PowerShell/Bash enmascaren errores y retornen código de salida 0 con 0 tests ejecutados. Ahora esto es detectado como error por `gemstack verify` y prohibido en la Constitución.
28
- - **2026-09-11**: En el reporte de Upgrade A, se produjo un drift en la nomenclatura y categorización de la matriz P1 canónica (mencionando A04-A06, D03-D04, E03 y sugiriendo incorrectamente merge de múltiples bloques). Se restauró la correlación canónica estricta de 25 tests P1 aprobados (A=3, B=8, C=4, D=2, E=2, F=2, G=2, H=2) y la regla estricta de parser de 2+ bloques -> CONTRACT_PARSE_ERROR.
40
+ - **2026-09-11**: En el reporte de Upgrade A, se produjo un drift en la nomenclatura y categorización de la matriz P1 canónica. Se restauró la correlación canónica estricta de 25 tests P1 aprobados y la regla estricta de parser de 2+ bloques -> CONTRACT_PARSE_ERROR.
41
+ - **Node 20+ Subprocess Recursion**: Al ejecutar `node --test` como subproceso desde un proceso de test runner, `process.env.NODE_TEST_CONTEXT` suprimía la ejecución de archivos hijos con warning de recursión. Se resolvió sanitizando las variables `NODE_TEST_CONTEXT` y `NODE_TEST_WORKER_ID` en el entorno del proceso hijo.
42
+ - **Windows spawn 'npm.cmd' EINVAL**: Node 22+ en Windows genera `EINVAL` al invocar `spawn('npm.cmd', ..., { shell: false })`. Se resolvió ejecutando directamente el binario `npm-cli.js` vía `process.execPath` cuando se detecta en Windows, respetando la regla constitucional de `shell: false`.
43
+ - **Closure Manifest Self-Reference**: Al incluir `specs/<feature>/closure.json` en los archivos de implementación de `tasks.md`, `closureContextHash` cambiaba cada vez que `closure.json` era escrito, provocando que la evidencia se marcara como `STALE` inmediatamente después de recolectarse. Se resolvió excluyendo explícitamente `closure.json` de la agregación de hashes de contexto de implementación (`implementationContextHash`).
29
44
 
30
45
  ## 5. Próximos pasos
31
- 1. Validar el nuevo ruteo semántico en sesiones de desarrollo reales.
32
- 2. Considerar `npx gemstack verify` en los hooks o pipelines de CI de proyectos que consumen Gemstack.
46
+ 1. Completar la publicación y git tag de la versión minor `v1.3.0`.
47
+ 2. Proceder a Upgrade E (SPEC ONLY) una vez autorizada la fase siguiente.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gemstack-ai",
3
- "version": "1.1.2",
3
+ "version": "1.3.0",
4
4
  "description": "Agentic Spec-Driven Development framework for Gemini/Antigravity",
5
5
  "main": "src/cli.js",
6
6
  "bin": {
@@ -10,7 +10,7 @@
10
10
  "node": ">=18.18.0"
11
11
  },
12
12
  "scripts": {
13
- "test": "node --test tests/contracts.test.js tests/hasher.test.js tests/findings.test.js tests/init.test.js tests/verify.test.js",
13
+ "test": "node --test tests/contracts.test.js tests/hasher.test.js tests/findings.test.js tests/init.test.js tests/verify.test.js tests/test-matrix.test.js tests/reconciliation.test.js tests/runner-adapter.test.js tests/traceability.test.js tests/closure-manifest.test.js tests/closure-gates.test.js tests/cost-ledger.test.js tests/environment-provider-safety.test.js tests/provider-capability-gate.test.js tests/billable-action-gate.test.js tests/provider-fallback.test.js tests/verification-purity-cost.test.js tests/context-determinism.test.js tests/context-authority.test.js tests/context-freshness.test.js tests/context-constraints.test.js tests/context-secrets.test.js tests/context-size-budget.test.js tests/context-purity.test.js tests/context-legacy.test.js",
14
14
  "gemstack:verify": "node src/cli.js verify",
15
15
  "pack:dry": "npm pack --dry-run",
16
16
  "ci:frontmatter": "node scripts/ci/check-frontmatter.js",
@@ -0,0 +1,5 @@
1
+ {
2
+ "phase_hashes": {},
3
+ "historical_findings": [],
4
+ "accepted_exceptions": []
5
+ }
@@ -0,0 +1,59 @@
1
+ {
2
+ "schema": "gemstack-closure",
3
+ "version": 1,
4
+ "feature": "specs/007-mechanical-test-matrix-closure-evidence/",
5
+ "generated_at": "2026-09-11T16:47:26.609Z",
6
+ "status": "VERIFIED",
7
+ "closure_context": {
8
+ "closure_context_hash": "d0587bf1f8770e142d2d0bb1bd637426f43794100d6514b2f41f9d004c69c8d8",
9
+ "repository_type": "git",
10
+ "git_commit": "afb384d2bced7ccf08445d9459a9e3211925658b",
11
+ "working_tree_clean": false,
12
+ "relevant_files_digest": "77e03ca88572d0fbbb69df1dd599c9f16e2903db3c4a740f50a0ec4a0459b6ae"
13
+ },
14
+ "acceptance_signature": "d6971eadf2e8238c87fa67fb380e2acd80181906a95168c19a57b3a24bf4d9bb",
15
+ "canonical_summary": {
16
+ "required_total": 20,
17
+ "required_passed": 20,
18
+ "supplemental_total": 0,
19
+ "supplemental_passed": 0
20
+ },
21
+ "physical_summary": {
22
+ "supporting_total": 0,
23
+ "supporting_passed": 0,
24
+ "total_executed": 20,
25
+ "total_passed": 20,
26
+ "total_failed": 0,
27
+ "total_skipped": 0
28
+ },
29
+ "reconciliation": {
30
+ "math_valid": true,
31
+ "phantoms_detected": 0,
32
+ "orphans_detected": 0,
33
+ "missing_canonical_ids": []
34
+ },
35
+ "task_traceability_summary": {
36
+ "tasks_total": 22,
37
+ "tasks_with_validation": 20,
38
+ "tasks_documentation_only": 2,
39
+ "unmapped_canonical_tests": []
40
+ },
41
+ "required_gates": {
42
+ "project-tests": "PASS",
43
+ "gate-ci-frontmatter": "PASS",
44
+ "gate-ci-mojibake": "PASS"
45
+ },
46
+ "supplemental_gates": {},
47
+ "exceptions": [],
48
+ "evidence_sources": [
49
+ {
50
+ "type": "PACKAGE_SCRIPT",
51
+ "script": "test",
52
+ "runner": "node:test",
53
+ "exit_code": 0,
54
+ "duration_ms": 257
55
+ }
56
+ ],
57
+ "blockers": [],
58
+ "warnings": []
59
+ }