chore: add specs and generator script for active_intents.yaml

This commit is contained in:
Sumeyaaaa 2026-02-18 14:01:19 +03:00
parent dedb07ed42
commit 379a61e1c8
11 changed files with 320 additions and 3 deletions

2
.gitignore vendored
View file

@ -6,7 +6,7 @@ node_modules
package-lock.json
coverage/
mock/
TRP1 Challenge Week 1_ Architecting the AI-Native IDE & Intent-Code Traceability.docx
.DS_Store
# IDEs

View file

@ -26,6 +26,8 @@
"knip": "knip --include files",
"evals": "dotenvx run -f packages/evals/.env.development packages/evals/.env.local -- docker compose -f packages/evals/docker-compose.yml --profile server --profile runner up --build --scale runner=0",
"npm:publish:types": "pnpm --filter @roo-code/types npm:publish"
,
"spec:generate": "node scripts/generate-specs.mjs"
},
"devDependencies": {
"@changesets/cli": "^2.27.10",
@ -70,5 +72,8 @@
"@types/react-dom": "^18.3.5",
"zod": "3.25.76"
}
},
"dependencies": {
"yaml": "^2.8.0"
}
}

9
pnpm-lock.yaml generated
View file

@ -19,6 +19,10 @@ overrides:
importers:
.:
dependencies:
yaml:
specifier: ^2.8.0
version: 2.8.0
devDependencies:
'@changesets/cli':
specifier: ^2.27.10
@ -6927,6 +6931,7 @@ packages:
glob@11.1.0:
resolution: {integrity: sha512-vuNwKSaKiqm7g0THUBu2x7ckSs3XJLXE+2ssL7/MfTGPLLcrJQ/4Uq1CjPTtO5cCIiRxqvN6Twy1qOwhL0Xjcw==}
engines: {node: 20 || >=22}
deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
hasBin: true
global-agent@3.0.0:
@ -10101,7 +10106,7 @@ packages:
tar@7.4.3:
resolution: {integrity: sha512-5S7Va8hKfV7W5U6g3aYxXmlPoZVAwUMy9AOKyF2fVuZa2UD3qZjg578OrLRt8PcNN1PleVaL/5/yYATNL0ICUw==}
engines: {node: '>=18'}
deprecated: Old versions of tar are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exhorbitant rates) by contacting i@izs.me
deprecated: Old versions of tar are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
term-size@2.2.1:
resolution: {integrity: sha512-wK0Ri4fOGjv/XPy8SBHZChl8CM7uMc5VML7SqiQ0zG7+J5Vr+RMQDoHa2CNT6KHUnTGIXH34UDMkPzAUyapBZg==}
@ -15073,7 +15078,7 @@ snapshots:
sirv: 3.0.1
tinyglobby: 0.2.14
tinyrainbow: 2.0.0
vitest: 3.2.4(@types/debug@4.1.12)(@types/node@24.2.1)(@vitest/ui@3.2.4)(jiti@2.4.2)(jsdom@26.1.0)(lightningcss@1.30.1)(tsx@4.19.4)(yaml@2.8.0)
vitest: 3.2.4(@types/debug@4.1.12)(@types/node@20.17.57)(@vitest/ui@3.2.4)(jiti@2.4.2)(jsdom@26.1.0)(lightningcss@1.30.1)(tsx@4.19.4)(yaml@2.8.0)
'@vitest/utils@3.2.4':
dependencies:

105
scripts/generate-specs.mjs Normal file
View file

@ -0,0 +1,105 @@
import fs from "node:fs/promises"
import path from "node:path"
import crypto from "node:crypto"
import * as yaml from "yaml"
function sha256(text) {
return crypto.createHash("sha256").update(text).digest("hex")
}
function parseSpecMarkdown(md) {
// Extremely small “SpecKit-like” parser: extracts the 4 sections we need.
// Sections are identified by headings:
// - "## Intent"
// - "## Scope (owned_scope)"
// - "## Constraints"
// - "## Acceptance Criteria"
const getSection = (title) => {
const re = new RegExp(`^##\\s+${title}\\s*$`, "m")
const m = md.match(re)
if (!m) return ""
const start = m.index + m[0].length
const rest = md.slice(start)
const next = rest.search(/^##\s+/m)
return (next === -1 ? rest : rest.slice(0, next)).trim()
}
const intent = getSection("Intent").trim()
const scope = getSection("Scope \\(owned_scope\\)")
.split("\n")
.map((l) => l.trim())
.filter((l) => l.startsWith("- "))
.map((l) => l.slice(2).trim().replace(/^`|`$/g, ""))
const constraints = getSection("Constraints")
.split("\n")
.map((l) => l.trim())
.filter((l) => l.startsWith("- "))
.map((l) => l.slice(2).trim())
const acceptance = getSection("Acceptance Criteria")
.split("\n")
.map((l) => l.trim())
.filter((l) => l.startsWith("- "))
.map((l) => l.slice(2).trim())
return { intent, scope, constraints, acceptance }
}
async function main() {
const repoRoot = process.cwd()
const specsDir = path.join(repoRoot, "specs")
const orchestrationDir = path.join(repoRoot, ".orchestration")
await fs.mkdir(specsDir, { recursive: true })
await fs.mkdir(orchestrationDir, { recursive: true })
const specFiles = (await fs.readdir(specsDir)).filter((f) => f.endsWith(".md"))
if (specFiles.length === 0) {
console.log("No spec files found in ./specs. Add at least one *.md spec and rerun.")
process.exit(1)
}
const activeIntentsPath = path.join(orchestrationDir, "active_intents.yaml")
const existingYaml = await fs.readFile(activeIntentsPath, "utf-8").catch(() => "active_intents: []\n")
const existing = (yaml.parse(existingYaml) ?? {}) || {}
const active_intents = Array.isArray(existing.active_intents) ? existing.active_intents : []
for (const file of specFiles) {
const full = path.join(specsDir, file)
const md = await fs.readFile(full, "utf-8")
const idMatch = file.match(/^(INT-\d+)/i)
const id = idMatch ? idMatch[1].toUpperCase() : `INT-${sha256(file).slice(0, 3).toUpperCase()}`
const name = md.split("\n").find((l) => l.startsWith("# "))?.replace(/^#\s+/, "").trim() || file
const parsed = parseSpecMarkdown(md)
const intentEntry = {
id,
name,
status: "IN_PROGRESS",
owned_scope: parsed.scope,
constraints: parsed.constraints,
acceptance_criteria: parsed.acceptance,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
spec_hash: `sha256:${sha256(md)}`,
spec_file: `specs/${file}`,
}
const i = active_intents.findIndex((x) => x?.id === id)
if (i >= 0) active_intents[i] = intentEntry
else active_intents.push(intentEntry)
}
await fs.writeFile(activeIntentsPath, yaml.stringify({ active_intents }), "utf-8")
console.log(`Updated .orchestration/active_intents.yaml with ${active_intents.length} intent(s).`)
}
main().catch((err) => {
console.error(err)
process.exit(1)
})

View file

@ -0,0 +1,28 @@
# INT-001 — Intent-Code Traceability (Spec)
## Intent
Build an Intent-Code Traceability system for Roo Code that enforces a two-stage reasoning loop and produces durable, auditable traces linking intents to code changes.
## Scope (owned_scope)
- `src/core/assistant-message/**`
- `src/core/tools/**`
- `src/core/hooks/**`
- `src/core/orchestration/**`
- `src/core/prompts/**`
- `.orchestration/**`
## Constraints
- Must enforce **intent selection before any destructive tool** (`write_to_file`, `edit_file`, `apply_diff`, etc.).
- Must keep **privilege separation**: UI emits events; extension host executes privileged actions; hooks are middleware.
- Must log **spatially independent** traces via content hashing.
## Acceptance Criteria
- Agent cannot write code before calling `select_active_intent(intent_id)`.
- When a file is written, a JSONL entry is appended to `.orchestration/agent_trace.jsonl` that includes:
- intent id
- file path
- line range (best-effort)
- `sha256:` content hash of the modified block
- `.orchestration/active_intents.yaml` exists and contains this intent.

View file

@ -0,0 +1,26 @@
# INT-002 — Hook System Implementation
## Intent
Implement a hook system that intercepts tool execution in Roo Code to enforce intent selection and validate AI-generated code before execution.
## Scope (owned_scope)
- `src/core/hooks/**`
- `src/core/assistant-message/presentAssistantMessage.ts`
- `src/core/tools/**`
- `.orchestration/**`
## Constraints
- Must integrate with existing `presentAssistantMessage()` function without breaking current tool execution flow.
- Pre-hooks must run **before** `tool.handle()` is called.
- Post-hooks must run **after** `tool.execute()` completes but before result is returned.
- Hook system must be non-blocking for non-destructive tools (read-only operations).
- Must maintain backward compatibility with existing tools.
## Acceptance Criteria
- `HookEngine` class exists in `src/core/hooks/HookEngine.ts`.
- Pre-hook validates intent selection for destructive tools (`write_to_file`, `edit_file`, `execute_command`, etc.).
- Pre-hook enforces scope validation (file path must be within intent's `owned_scope`).
- Post-hook logs trace entries to `.orchestration/agent_trace.jsonl` for mutating actions.
- `presentAssistantMessage()` integrates `HookEngine` with Pre-Hook and Post-Hook calls.
- All existing tests pass after hook integration.

View file

@ -0,0 +1,24 @@
# INT-003 — Two-Stage Reasoning Loop
## Intent
Implement a two-stage state machine that enforces intent selection before code generation and validates AI output against intent constraints.
## Scope (owned_scope)
- `src/core/hooks/HookEngine.ts`
- `src/core/prompts/sections/tool-use-guidelines.ts`
- `src/core/tools/SelectActiveIntentTool.ts`
- `src/core/task/Task.ts`
## Constraints
- **Stage 1 (Reasoning Intercept):** Agent MUST call `select_active_intent(intent_id)` before any destructive tool.
- **Stage 2 (Contextualized Action):** Agent receives intent context and must include it when making code changes.
- System prompt must enforce this protocol in tool-use guidelines.
- Intent context must be injected into the agent's context before code generation.
## Acceptance Criteria
- System prompt includes instructions requiring `select_active_intent` before code changes.
- `SelectActiveIntentTool` returns XML `<intent_context>` block with scope, constraints, and acceptance criteria.
- Pre-hook blocks destructive tools if no active intent is selected.
- Agent receives intent context in subsequent tool calls.
- Intent context is logged in `agent_trace.jsonl` entries.

View file

@ -0,0 +1,30 @@
# INT-004 — Orchestration Directory Management
## Intent
Implement a robust data model for managing `.orchestration/` directory files with proper initialization, validation, and atomic updates.
## Scope (owned_scope)
- `src/core/orchestration/OrchestrationDataModel.ts`
- `.orchestration/active_intents.yaml`
- `.orchestration/agent_trace.jsonl`
- `.orchestration/intent_map.md`
- `.orchestration/AGENT.md`
## Constraints
- `.orchestration/` directory must be machine-managed (not user-edited directly).
- `active_intents.yaml` must be valid YAML and follow the schema defined in `document.md`.
- `agent_trace.jsonl` must be append-only (no modifications, only appends).
- All file operations must be atomic (write to temp file, then rename).
- Directory and files must be initialized on first use.
## Acceptance Criteria
- `OrchestrationDataModel` class provides methods:
- `initialize()`: Creates directory and initializes files if missing.
- `readActiveIntents()`: Parses and returns active intents.
- `appendAgentTrace()`: Appends trace entry to JSONL file.
- `updateIntentMap()`: Updates intent-to-file mapping.
- `appendAgentKnowledge()`: Appends to AGENT.md.
- All methods handle errors gracefully and log failures.
- Files are created with proper templates if missing.
- YAML parsing validates schema and reports errors clearly.

View file

@ -0,0 +1,33 @@
# INT-005 — Logging & Traceability
## Intent
Implement comprehensive trace logging that links intents to code changes via content hashing, enabling spatial independence and auditability.
## Scope (owned_scope)
- `src/core/hooks/HookEngine.ts` (Post-Hook implementation)
- `src/core/orchestration/OrchestrationDataModel.ts`
- `.orchestration/agent_trace.jsonl`
- `src/utils/git.ts` (for VCS revision tracking)
## Constraints
- Trace entries must include `sha256:` content hash of modified code blocks.
- Line ranges must be best-effort (may be approximate for complex edits).
- Each trace entry must link to:
- Intent ID
- File path (relative to workspace root)
- VCS revision (Git SHA)
- Timestamp
- Model identifier
- Content hashing must be spatially independent (same code block = same hash regardless of file location).
## Acceptance Criteria
- Post-hook computes SHA-256 hash of modified content for file tools.
- Trace entry includes all required fields per `document.md` schema:
- `id` (UUID)
- `timestamp` (ISO 8601)
- `vcs.revision_id` (Git SHA)
- `files[]` with `relative_path`, `conversations[]`, `ranges[]`, `content_hash`
- Trace entries are appended atomically to `agent_trace.jsonl`.
- Content hash format: `sha256:<hex>`.
- Git SHA is retrieved from workspace root (handles non-Git repos gracefully).

View file

@ -0,0 +1,28 @@
# INT-006 — Testing & Validation
## Intent
Create comprehensive test coverage for the Intent-Code Traceability system, including unit tests, integration tests, and end-to-end validation scenarios.
## Scope (owned_scope)
- `src/core/hooks/**/*.test.ts`
- `src/core/orchestration/**/*.test.ts`
- `src/core/tools/SelectActiveIntentTool.test.ts`
- `tests/integration/hook-system.test.ts`
- `tests/e2e/intent-traceability.test.ts`
## Constraints
- Tests must not modify production `.orchestration/` files (use temp directories).
- Tests must be deterministic and isolated (no shared state).
- Integration tests must verify hook system works with real tool execution.
- E2E tests must simulate full agent workflow (intent selection → code change → trace logging).
## Acceptance Criteria
- Unit tests for `HookEngine.preHook()` and `HookEngine.postHook()`.
- Unit tests for `OrchestrationDataModel` file operations.
- Unit tests for `SelectActiveIntentTool` intent loading and context generation.
- Integration test: Verify Pre-Hook blocks destructive tool without intent.
- Integration test: Verify Post-Hook logs trace entry after file write.
- E2E test: Full workflow from intent selection to trace logging.
- All tests pass in CI/CD pipeline.
- Test coverage > 80% for hook and orchestration modules.

View file

@ -0,0 +1,33 @@
# INT-007 — Documentation & Knowledge Base
## Intent
Maintain comprehensive documentation for the Intent-Code Traceability system, including architecture notes, API documentation, and a persistent knowledge base.
## Scope (owned_scope)
- `ARCHITECTURE_NOTES.md`
- `README.md` (Intent-Code Traceability section)
- `.orchestration/AGENT.md`
- `docs/intent-traceability/`
- `CHANGELOG.md` (relevant entries)
## Constraints
- `ARCHITECTURE_NOTES.md` must document all injection points and hook integration.
- `AGENT.md` must be append-only knowledge base for "Lessons Learned".
- Documentation must be kept in sync with code changes.
- API documentation must include examples for each public method.
## Acceptance Criteria
- `ARCHITECTURE_NOTES.md` includes:
- Tool execution flow diagram
- Hook injection points with line numbers
- System prompt modification points
- Data model schemas
- `AGENT.md` includes:
- Lessons learned from implementation
- Common pitfalls and solutions
- Performance optimizations
- Stylistic rules for intent specifications
- README includes setup instructions and usage examples.
- All public APIs are documented with JSDoc comments.
- Documentation is reviewed and updated with each major change.