Compare commits

...

11 Commits

Author SHA1 Message Date
Jon Chery 4a58aa1657 refactor(rebrand): rename & rebrand CI → CIAgent across all source and test files
- Type renames: CIConfig → CIAgentConfig, DEFAULT_CI_CONFIG → DEFAULT_CIAGENT_CONFIG
- Type renames: CiMetadata → CIAgentMetadata, ParsedCiCommit → ParsedCIAgentCommit
- Function renames: initCI → initCIAgent, isCIInitialized → isCIAgentInitialized
- Function renames: extractCiBlock → extractCIAgentBlock, parseCiBlock → parseCIAgentBlock
- Class renames: CiFiles → CIAgentFiles
- Import paths: ci-files.js → ciagent-files.js
- Directory paths: .ci/ → .ciagent/ across all source and test files
- Check names: ".ci directory exists" → ".ciagent directory exists"
- Check names: "CI config valid" → "CIAgent config valid"
- Temp dir names: ci-*-test- → ciagent-*-test-
- CLI examples: "ci init" → "ciagent init"
- Fix deepMerge infinite recursion bug in config.ts
- ---ci---/---/ci--- block markers preserved unchanged
- All 31 test suites, 370 tests passing

---ci---
phase: 1
milestone: v0.5
plan: 07
task: 07-01-01
status: execute
---/ci---
2026-05-29 18:01:13 +00:00
Jon Chery e31afe3b59 docs(rebrand): rename & rebrand CI → CIAgent across all documentation, templates, and scripts
- README.md: title, project name, CLI commands, .ci/ → .ciagent/, ci-files → ciagent-files, CI Modification → CIAgent Modification
- AGENTS.md: title, project name, architecture tree, agent count (18→19), test count (25→31 suites, 218→370 tests), version (0.4.0→0.6.0), ci-files → ciagent-files, CIConfig → CIAgentConfig, CiMetadata → CIAgentMetadata, .ci/ → .ciagent/
- templates/DECISIONS.md: .ci/audit/ → .ciagent/audit/, ci audit → ciagent audit
- scripts/postinstall.js: CI postinstall → CIAgent postinstall
- scripts/install.sh: CI → CIAgent, ci-init → ciagent-init, INSTALL COMPLETE banner
- opencode/ci/workflows/*.md (11 files): .ci/ → .ciagent/, CI → CIAgent project name, ci-command → ciagent-command usage lines
- opencode/ci/references/*.md (5 files): .ci/ → .ciagent/, CI → CIAgent project name, ci-files → ciagent-files references
- opencode/ci/contexts/*.md (3 files): .ci/ → .ciagent/, CI → CIAgent project name
- opencode/agents/ci-*.md (18 files): .ci/ → .ciagent/, CI → CIAgent project name
- opencode/command/ci-*.md (11 files): CI → CIAgent project name

Preserved: ---ci---/---/ci--- markers, opencode/ci/ dir paths, ci-*.md filenames, ci listProjects()/ci setActiveProject() API names, repo URLs

---ci---
phase: 1
milestone: v0.6
plan: 01-01
task: 01-01-01
status: execute
---/ci---
2026-05-29 17:58:48 +00:00
Jon Chery ab6af144b7 feat(P06): 3-tier versioning, branch hierarchy enforcement, ARCHITECTURE-PLAN synthesis
---ci---
phase: 6
milestone: v0.5
status: complete
decisions:
  - id: D-006
    decision: Research as intermediate work product
    rationale: Conclusions update .ci/ files; full research doc intentionally not preserved
    confidence: 0.90
  - id: D-007
    decision: Branch hierarchy enforcement: main > milestone > phase
    rationale: Prevents out-of-order merges and semantically wrong tags
    confidence: 0.92
  - id: D-008
    decision: 3-tier versioning: NFR/feature/schema-breaking
    rationale: Patch per phase (NFR/feature) or minor per phase (schema-breaking); milestone gets minor (feature) or major (schema-breaking)
    confidence: 0.95
requirements:
  covered: [VER-06, BRANCH-01, BRANCH-02, ARCH-01]
---/ci---

- Synthesize ARCHITECTURE-PLAN.md into .ci/ci/ARCHITECTURE.md (expanded 51→230 lines)
- Add D-006/D-007/D-008 to .ci/ci/PROJECT.md key decisions table
- Delete ARCHITECTURE-PLAN.md after synthesis
- Rewrite ship.md with 3-tier versioning model + branch hierarchy merge flows
- Rewrite branch-strategy.md with 3-tier versioning + branch hierarchy + version validation
- Add MilestoneType to config types
- Replace isNfrMilestone() with getMilestoneType() returning nfr|feature|schema-breaking
- Add validateMergeOrder(), mergeMilestoneBranch(), computeMilestoneTag() to GitBranch
- Add computeShipVersion(), validateVersionOrder(), resolveMergeTarget() to ship command
- Remove hardcoded v0.5. from error-recovery rollback
- Create .githooks/pre-push for semver ordering + branch hierarchy validation
- Add 15 new tests (370 total, all passing)
2026-05-29 17:18:10 +00:00
Jon Chery 3d069319b5 feat(P05): implement parseRequirementsMd and parseArchitectureMd — real content parsing
---ci---
project: ci
phase: 5
milestone: v0.5
status: complete
decisions:
  - id: D-030
    decision: Phase 5 Parser Completeness complete
    rationale: All PARSE requirements covered; 31 suites, 355 tests
    confidence: 0.95
    alternatives: []
requirements:
  covered: [PARSE-01, PARSE-02]
---/ci---
2026-05-29 16:47:17 +00:00
Jon Chery b33431c1a6 feat(P04): verification intelligence — git-native coverage, npm audit, TS compilation
---ci---
project: ci
phase: 4
milestone: v0.5
status: complete
decisions:
  - id: D-028
    decision: Phase 4 Verification Intelligence complete
    rationale: All INTEL requirements covered; 31 suites, 355 tests
    confidence: 0.95
    alternatives: []
requirements:
  covered: [INTEL-01, INTEL-02, INTEL-03]
---/ci---
2026-05-29 16:46:17 +00:00
Jon Chery 5753e2dc96 fix(P03): honest execution — real rollback, honest orchestrator, git-native verification
---ci---
project: ci
phase: 3
milestone: v0.5
status: complete
decisions:
  - id: D-026
    decision: Phase 3 Honest Execution complete
    rationale: All HONEST requirements covered; no more fake success returns
    confidence: 0.95
    alternatives: []
requirements:
  covered: [HONEST-01, HONEST-02, HONEST-03]
---/ci---
2026-05-29 16:44:46 +00:00
Jon Chery 815c928a43 test(P02): backend test coverage — 4 new suites, 353 tests passing
---ci---
project: ci
phase: 2
milestone: v0.5
status: complete
decisions:
  - id: D-024
    decision: Phase 2 Backend Test Coverage complete
    rationale: All TEST requirements covered; 31 suites, 353 tests passing
    confidence: 0.95
    alternatives: []
requirements:
  covered: [TEST-01, TEST-02, TEST-03, TEST-04]
---/ci---
2026-05-29 16:42:09 +00:00
Jon Chery a82926a22e fix(P01): quick wins — remove dead refs, unused imports, fix postinstall, version bump
---ci---
project: ci
phase: 1
milestone: v0.5
status: complete
decisions:
  - id: D-020
    decision: Phase 1 Quick Wins complete
    rationale: All 5 FIX requirements (FIX-01 through FIX-05) verified and passing
    confidence: 0.95
    alternatives: []
requirements:
  covered: [FIX-01, FIX-02, FIX-03, FIX-04, FIX-05]
---/ci---

Phase 1 (Quick Wins) summary:
- A1/FIX-01: Marked .planning/ refs as (legacy)/(removed) in docs
- A2/FIX-02: Removed unused execSync import from ollama-base.ts
- A3/FIX-03: Replaced postinstall with explicit install-opencode, removed scripts/ from files
- A4/FIX-04: Verified opencode.json is clean (no learnship entry)
- A5/FIX-05: Version bump to 0.5.0
2026-05-29 16:39:26 +00:00
CI fb3f1df13e release(v0.4.0): purge learnship, migrate .planning→.ci, fix backends, add test coverage
- Remove all learnship references: Decision.learnship_equivalent field,
  agent persona prompts, opencode.json permissions, test fixtures
- Migrate verification layers from .planning/ to .ci/: structural
  checks .ci/ dir + ROADMAP.md, behavioral checks ROADMAP.md
- Fix ollama-local: remove sync require+curl blocking, use async
  fetchAvailableModels() in callModel
- Fix opencode.json: use __OPENCODE_DIR__ template tokens, remove
  legacy learnship permission entries
- Remove duplicate install script from package.json (keep postinstall)
- Fix quality any-regex false positives (target type annotations only)
- Add backends test coverage: backends.test.ts, tool-registry.test.ts
- Version bump 0.3.0 → 0.4.0
- Artifacts module: rename .planning→.ci internal paths
- Remove dead TODO_PATTERN/FIXME_PATTERN constants

---ci---
phase: 3
milestone: v0.4
status: complete
requirements:
  covered: [REQ-09, REQ-10, REQ-11, REQ-13, REQ-14, REQ-17]
  partial: []
decisions:
  - id: D-001
    decision: purge all learnship references from codebase
    rationale: project is CI-only, learnship is no longer a dependency
    confidence: 0.99
    category: scope
    alternatives: [keep for historical reference]
  - id: D-002
    decision: migrate verification from .planning/ to .ci/ paths
    rationale: .planning/ is removed schema, all current state lives in .ci/
    confidence: 0.95
    category: architecture
    alternatives: [keep dual-path support]
  - id: D-003
    decision: use __OPENCODE_DIR__ template tokens in opencode.json
    rationale: hardcoded ~ paths fail in containers and non-standard homes
    confidence: 0.90
    category: implementation_approach
    alternatives: [keep tilde expansion]
---/ci---
2026-05-29 16:18:30 +00:00
CI 7a20784c87 fix: remove hardcoded /home/jchery paths, use __OPENCODE_DIR__ template token resolved at install time
Command markdown files now use __OPENCODE_DIR__ placeholder instead of
hardcoded user path. Both postinstall.js and install.sh perform template
replacement when copying files to ~/.config/opencode/, making CI portable
across any user/machine/container.
2026-05-29 16:08:46 +00:00
CI 940b85bfae feat(backends): multi-backend intelligence layer — LLM + Agent backends, persona-loading agents, honest CLI commands
Add IntelligenceBackend abstraction with two categories:
- LLMBackend (OllamaLocal, OllamaCloud): CI runs tool loop, provides tools, constructs prompts
- AgentBackend (Opencode): agent runs own tool loop, CI serializes request

Refactor all 18 agents from hardcoded stubs to persona loaders that delegate
to the active backend or fail honestly when no backend is available.

Refactor OrchestratorAgent.executeStage() from monolithic switch to agent
delegation via STAGE_AGENT_MAP for intelligent stages (research, plan, execute,
verify), with mechanical stages (specify, clarify, complete) staying inline.

Wire CLI commands with --backend flag and auto-detection (opencode →
ollama-local → ollama-cloud). Harden rollback/ship with real git operations.
No command returns fake success.
2026-05-29 15:58:34 +00:00
140 changed files with 4848 additions and 1189 deletions
+80
View File
@@ -0,0 +1,80 @@
#!/bin/bash
# CI pre-push hook: enforce versioning and branching rules
# Install: git config core.hooksPath .githooks
zero="0000000000000000000000000000000000000000"
while read local_ref local_oid remote_ref remote_oid; do
if [ "$local_oid" = "$zero" ]; then
continue
fi
# Check pushed tags
if echo "$local_ref" | grep -qE "^refs/tags/"; then
tag_name=$(echo "$local_ref" | sed 's|^refs/tags/||')
# Validate semver format
if echo "$tag_name" | grep -qE "^v[0-9]+\.[0-9]+\.[0-9]+$"; then
tag_major=$(echo "$tag_name" | sed 's/v\([0-9]*\)\.[0-9]*\.[0-9]*/\1/')
tag_minor=$(echo "$tag_name" | sed 's/v[0-9]*\.\([0-9]*\)\.[0-9]*/\1/')
tag_patch=$(echo "$tag_name" | sed 's/v[0-9]*\.[0-9]*\.\([0-9]*\)/\1/')
# Check for semver ordering violations
for existing_tag in $(git tag -l "v${tag_major}.${tag_minor}.*" 2>/dev/null); do
if [ "$existing_tag" = "$tag_name" ]; then
continue
fi
existing_patch=$(echo "$existing_tag" | sed 's/v[0-9]*\.[0-9]*\.\([0-9]*\)/\1/')
if [ "$existing_patch" -ge "$tag_patch" ] && [ "$tag_patch" -le "$existing_patch" ]; then
echo "ERROR: Tag $tag_name is not greater than existing tag $existing_tag"
echo " Milestone tags must be the NEXT version (e.g., v0.6.0 after v0.5.1-5, NOT v0.5.0)"
exit 1
fi
done
# Check for milestone-tags-below-phase-tags
# If this is a .0 tag (milestone), verify no .N tags exist with higher patch
if [ "$tag_patch" = "0" ]; then
for existing_tag in $(git tag -l "v${tag_major}.${tag_minor}.*" 2>/dev/null); do
existing_patch=$(echo "$existing_tag" | sed 's/v[0-9]*\.[0-9]*\.\([0-9]*\)/\1/')
if [ "$existing_patch" -gt 0 ] && [ "$existing_patch" -gt "$tag_patch" ]; then
echo "ERROR: Milestone tag $tag_name is below existing phase tags (e.g., $existing_tag)"
echo " Feature milestone completion must be tagged as v${tag_major}.$(($tag_minor + 1)).0, not v${tag_major}.${tag_minor}.0"
exit 1
fi
done
fi
fi
fi
# Check branch merges: reject direct-to-main pushes if milestone branch exists
if echo "$local_ref" | grep -qE "^refs/heads/main$"; then
milestone_branches=$(git branch -r 2>/dev/null | grep 'milestone/v' | grep -v ':$' || true)
if [ -n "$milestone_branches" ]; then
# Allow if this is a merge commit from a milestone branch
merge_parents=$(git cat-file -p "$local_oid" 2>/dev/null | grep "^parent" | wc -l)
if [ "$merge_parents" -lt 2 ]; then
# Not a merge commit — check if there are active milestone branches
active_milestones=""
for mb in $milestone_branches; do
clean_name=$(echo "$mb" | sed 's|^[^/]*/||' | tr -d ' ')
merged=$(git branch -r --merged origin/main 2>/dev/null | grep "$clean_name" || true)
if [ -z "$merged" ]; then
active_milestones="$active_milestones $clean_name"
fi
done
if [ -n "$active_milestones" ]; then
echo "WARNING: Pushing directly to main while active milestone branches exist:"
for ms in $active_milestones; do
echo " - $ms"
done
echo " Phase branches should merge into the milestone branch first."
# Warning only — not blocking. The code-level enforcement in git-branch.ts
# is the hard gate; this hook is a safety net.
fi
fi
fi
fi
done
exit 0
+64 -36
View File
@@ -1,4 +1,4 @@
# AGENTS.md — CI Project Guidelines
# AGENTS.md — CIAgent Project Guidelines
## Build & Run Commands
@@ -9,30 +9,38 @@
## Project Overview
CI (Continuous Intelligence) is a fully autonomous AI-driven software engineering harness. It receives a specification, resolves ambiguities through a single Clarify phase, then executes the full pipeline (research → plan → execute → verify) autonomously, escalating only when it cannot safely proceed alone.
CIAgent (Continuous Intelligence) is a fully autonomous AI-driven software engineering harness. It receives a specification, resolves ambiguities through a single Clarify phase, then executes the full pipeline (research → plan → execute → verify) autonomously, escalating only when it cannot safely proceed alone.
## Architecture
```
src/
agents/ # 18 agent implementations (all extend BaseAgent)
agents/ # 19 agent implementations (persona loaders delegating to backends)
backends/ # Intelligence backend layer
types.ts # IntelligenceBackend, BackendRequest, BackendResult, BackendConfigSection
tool-registry.ts # CIAgent-owned tool implementations (readFile, writeFile, editFile, runBash, glob, grep)
ollama-base.ts # Abstract base for Ollama backends (shared tool loop, prompt construction)
ollama-local.ts # OllamaLocalBackend (localhost:11434)
ollama-cloud.ts # OllamaCloudBackend (remote endpoint, auth, rate limiting)
opencode.ts # OpencodeBackend (shells out to opencode --non-interactive)
index.ts # Backend registry + auto-detection
cli/ # Commander.js CLI (commands.ts, index.ts)
core/ # Core engine components
artifacts.ts # Legacy .planning/ artifact management (retained for backward compat)
audit.ts # Legacy audit trail in .ci/audit/ (retained for backward compat)
ci-files.ts # .ci/ long-lived reference file management (PROJECT.md, ROADMAP.md, etc.)
artifacts.ts # Legacy .ciagent/ artifact management (retained for backward compat)
audit.ts # Legacy audit trail in .ciagent/audit/ (retained for backward compat)
ciagent-files.ts # .ciagent/ long-lived reference file management (PROJECT.md, ROADMAP.md, etc.)
clarify.ts # Clarify phase: question generation, default acceptance
commit-builder.ts # Structured commit message generation (---ci--- YAML blocks)
commit-parser.ts # ---ci--- YAML block extraction and parsing
config.ts # .ci/config.json load/save/init
config.ts # .ciagent/config.json load/save/init
decision-engine.ts # Bounded rationality: commits decisions as git artifacts
error-recovery.ts # Retry, plan revision, rollback logic
escalation.ts # Escalation protocol: commits escalations as git artifacts
git-branch.ts # Branch lifecycle: phase/NN-slug, milestone/vX.X-slug
git-context.ts # Project state reconstruction from git log + branches
types/ # Type definitions
commit-meta.ts # CiMetadata, CommitDecision, CommitEscalation, ParsedCiCommit
config.ts # CIConfig, AutonomyLevel, ModelProfile, DEFAULT_CI_CONFIG
commit-meta.ts # CIAgentMetadata, CommitDecision, CommitEscalation, ParsedCIAgentCommit
config.ts # CIAgentConfig, AutonomyLevel, ModelProfile, DEFAULT_CIAGENT_CONFIG (includes backend)
decisions.ts # Decision, ConfidenceLevel, DecisionCategory
escalation.ts # Escalation, EscalationType, EscalationResolution
clarify.ts # ClarifyQuestion, ClarifyResult
@@ -41,11 +49,11 @@ src/
utils/ # File utilities (readFile, writeFile, ensureDir, readJSON, writeJSON)
verification/ # 4-layer verification pipeline
structural.ts # Layer 1: file existence, imports wired, no stubs
behavioral.ts # Layer 2: test generation and execution (stub)
security.ts # Layer 3: STRIDE threat analysis (stub)
quality.ts # Layer 4: multi-persona code review (stub)
behavioral.ts # Layer 2: test infrastructure checks (static analysis, no test generation yet)
security.ts # Layer 3: regex-based threat pattern scanning (no STRIDE analysis yet)
quality.ts # Layer 4: regex-based code quality checks (no multi-persona review yet)
index.ts # Public API exports
version.ts # VERSION = "0.2.0"
version.ts # VERSION = "0.6.0"
templates/ # Template files (config.json, DECISIONS.md, specification.md)
```
@@ -54,18 +62,18 @@ templates/ # Template files (config.json, DECISIONS.md, specification.md
- **Autonomy levels**: `full` (no HITL after clarify), `supervised` (escalate on gates + verification failures), `guided` (escalate on every decision gate)
- **Decision confidence thresholds**: High (>0.85) auto-decide and log; Medium (0.600.85) auto-decide with assumption logging; Low (<0.60) escalate to human
- **Escalation timeout**: Default 5 minutes, then auto-proceeds with recommended option. Set to `0` to require human, `-1` to always auto-proceed
- **18 agents** inherited from Learnship, all re-prompted for autonomous operation. OrchestratorAgent is CI-specific
- **Git-native context**: The git log IS the project memory. Agent's first impulse to gather context is `git log` + `git branch`, not file reads. Dynamic state (decisions, escalations, lessons, compounding) lives in `---ci---` YAML blocks in commit messages. `.ci/` holds only long-lived reference docs (PROJECT.md, ARCHITECTURE.md, ROADMAP.md, REQUIREMENTS.md, config.json).
- **Artifact compatibility**: CI no longer writes `.planning/` schema. Dynamic state is derived from git history. `.ci/` files follow a CI-native schema.
- **19 agents** purpose-built for CIAgent, all configured for autonomous operation. OrchestratorAgent is CIAgent-specific
- **Git-native context**: The git log IS the project memory. Agent's first impulse to gather context is `git log` + `git branch`, not file reads. Dynamic state (decisions, escalations, lessons, compounding) lives in `---ci---` YAML blocks in commit messages. `.ciagent/` holds only long-lived reference docs (PROJECT.md, ARCHITECTURE.md, ROADMAP.md, REQUIREMENTS.md, config.json).
- **Artifact compatibility**: CIAgent no longer writes `.planning/` schema. `.ciagent/` files follow a CIAgent-native schema.
## Code Conventions
- **Language**: TypeScript with ES2022 target, Node16 modules
- **Module resolution**: Node16 style with `.js` extensions in imports
- **Agent pattern**: All agents extend `BaseAgent` with `name`, `description`, and `execute(context: AgentContext): Promise<AgentResult>`
- **Agent pattern**: All agents extend `BaseAgent` with `name` (AgentName), `description`, `workflow`, and `execute(context: AgentContext): Promise<AgentResult>`. Agents delegate to `context.backend` when available, fail honestly when not.
- **No runtime validation library**: Uses plain TypeScript types, not Zod schemas (Zod is a dependency but types are hand-defined)
- **File I/O**: Use `src/utils/file.ts` helpers (`writeFile`, `readFile`, `ensureDir`, `readJSON`, `writeJSON`) instead of raw `fs` calls in agent/business logic
- **Config**: `CIConfig` type and `DEFAULT_CI_CONFIG` in `src/types/config.ts` — always merge partial configs with defaults
- **Config**: `CIAgentConfig` type and `DEFAULT_CIAGENT_CONFIG` in `src/types/config.ts` — always merge partial configs with defaults
- **Error handling**: Agents return `{ success: false, error: string }` rather than throwing
- **No comments in code**: Follow existing pattern — agent files have no comments
- **Naming**: `camelCase` for functions/variables, `PascalCase` for classes/types/interfaces, `kebab-case` for file names
@@ -77,7 +85,26 @@ templates/ # Template files (config.json, DECISIONS.md, specification.md
SPECIFY → CLARIFY → RESEARCH → PLAN → EXECUTE → VERIFY → COMPLETE
```
Each stage is executed by `OrchestratorAgent.executeStage()`. The orchestrator iterates through `STAGE_ORDER` and collects `PhaseResult` for each.
Each stage is executed by `OrchestratorAgent.executeStage()`. The orchestrator delegates intelligent stages (research, plan, execute, verify) to specialized agents via `context.backend` when available, falling back to mechanical execution when no backend is configured. Mechanical stages (specify, clarify, complete) are always handled by the orchestrator directly.
## Intelligence Backend Architecture
```
IntelligenceBackend (unified interface)
├── LLMBackend (CIAgent runs tool loop, provides tools, constructs prompts)
│ ├── OllamaLocalBackend (localhost:11434, no auth)
│ ├── OllamaCloudBackend (remote endpoint, API key, rate limits)
│ └── (future: OpenAI, Anthropic, Gemini, etc.)
└── AgentBackend (agent runs own tool loop, CIAgent sends request)
├── OpencodeBackend (opencode --non-interactive)
└── (future: Codex, Claude Code, Hermes, etc.)
```
- **LLM backends**: CIAgent constructs system prompts from persona.md + workflow.md, defines tool schemas, runs the tool-call loop via `ToolRegistry`, and parses structured JSON output
- **Agent backends**: CIAgent serializes `BackendRequest`, invokes the agent, and parses JSON `BackendResult` from stdout
- **Auto-detection** (provider: "auto"): tries opencode → ollama-local → ollama-cloud → fails with instructions
- **Per-command override**: `ciagent run --backend ollama-local` forces a specific backend
- **Config**: `backend` section in `.ciagent/config.json` with provider, fallback, agent_backends, llm_backends
## Agent Modification Rules (from PRD)
@@ -95,26 +122,26 @@ Each stage is executed by `OrchestratorAgent.executeStage()`. The orchestrator i
## Verification Layers
1. **Structural**: Files exist, imports wired, no stubs/TODOs
2. **Behavioral**: Generate and run automated tests for must-haves (currently stub)
3. **Security**: STRIDE analysis with auto-disposition (currently stub)
4. **Code Quality**: Multi-persona review with P0 auto-fix (currently stub)
2. **Behavioral**: Check test infrastructure and requirement traceability (static analysis — test generation not yet implemented)
3. **Security**: Regex-based threat pattern scanning with auto-disposition (STRIDE analysis not yet implemented)
4. **Code Quality**: Regex-based code quality checks (multi-persona review not yet implemented)
## Testing
- Test framework: Jest with ts-jest
- Test file pattern: `**/*.test.ts` in `src/`
- Run: `npm run test`
- 25 test suites, 218 tests covering types, core, git-native, verification, and utility modules
- 31 test suites, 370 tests covering types, core, git-native, verification, and utility modules
- Tests use temp directories (os.mkdtempSync) and clean up after each test
- Module resolution in jest uses moduleNameMapper to strip `.js` extensions
## Important Files
- `.ci/config.json` — Project-level CI configuration (autonomy, parallelization, verification, security, git)
- `.ci/PROJECT.md` — Vision, core value, requirements, constraints, key decisions table
- `.ci/ARCHITECTURE.md` — System architecture, component boundaries, data flow
- `.ci/ROADMAP.md` — Phase breakdown, milestone mapping, success criteria, progress table
- `.ci/REQUIREMENTS.md` — v1/v2 requirements with REQ-IDs and traceability matrix
- `.ciagent/config.json` — Project-level CIAgent configuration (autonomy, parallelization, verification, security, git)
- `.ciagent/PROJECT.md` — Vision, core value, requirements, constraints, key decisions table
- `.ciagent/ARCHITECTURE.md` — System architecture, component boundaries, data flow
- `.ciagent/ROADMAP.md` — Phase breakdown, milestone mapping, success criteria, progress table
- `.ciagent/REQUIREMENTS.md` — v1/v2 requirements with REQ-IDs and traceability matrix
- Git log — Primary project memory: decisions, escalations, lessons, compounding, verification results
- Branch structure — `phase/NN-slug` (active/complete) and `milestone/vX.X-slug` branches
@@ -164,15 +191,16 @@ Each stage is executed by `OrchestratorAgent.executeStage()`. The orchestrator i
## Current State
- **v0.2.0**: Git-native architecture — project memory lives in git log, not `.planning/` files
- **New modules**: commit-parser (`---ci---` YAML block extraction/parsing), commit-builder (structured commit message generation), git-context (project state reconstruction from git log + branches), git-branch (phase/milestone branch lifecycle), ci-files (`.ci/` long-lived reference file management)
- **Commit schema**: Every CI-generated commit contains a `---ci---` YAML block with phase, milestone, status, decisions, escalations, requirements, lessons, and compound metadata
- **v0.6.0**: Backends module (OllamaLocal, OllamaCloud, Opencode), learnship references removed, verification layers migrated from .planning/ to .ciagent/
- **New modules**: commit-parser (`---ci---` YAML block extraction/parsing), commit-builder (structured commit message generation), git-context (project state reconstruction from git log + branches), git-branch (phase/milestone branch lifecycle), ciagent-files (`.ciagent/` long-lived reference file management)
- **Commit schema**: Every CIAgent-generated commit contains a `---ci---` YAML block with phase, milestone, status, decisions, escalations, requirements, lessons, and compound metadata
- **Branch strategy**: `phase/NN-slug` and `milestone/vX.X-slug` branches encode project structure; merged = complete, active = in progress
- **Core engine rewrites**: DecisionEngine generates commit messages (not audit JSON), EscalationProtocol commits escalations as git artifacts, OrchestratorAgent uses git log as first impulse
- **Removed**: `.ci/audit/` directory (audit trail is git log), `.planning/` directory (dynamic state derived from git history)
- **`.ci/` contents**: `config.json`, `PROJECT.md`, `ARCHITECTURE.md`, `ROADMAP.md`, `REQUIREMENTS.md` — long-lived reference docs updated with discipline
- **Removed**: `.ciagent/audit/` directory (audit trail is git log), `.planning/` directory (dynamic state derived from git history)
- **`.ciagent/` contents**: `config.json`, `PROJECT.md`, `ARCHITECTURE.md`, `ROADMAP.md`, `REQUIREMENTS.md` — long-lived reference docs updated with discipline
- **Reconstruction test**: An agent with only commit message access can reconstruct project state (phase, decisions, requirements coverage, lessons, escalations)
- **Verification layers**: All 4 layers implemented — structural, behavioral, security (STRIDE), quality
- **Verification layers**: All 4 layers implemented — structural, behavioral, security, quality
- **CLI**: All 11 commands wired up (`init`, `run`, `quick`, `debug`, `verify`, `review`, `status`, `audit`, `clarify`, `rollback`, `ship`)
- **Agent implementations**: Stub agents return success immediately. Real LLM-based agent implementations are needed for research, planning, execution, verification, etc.
- **Tests**: 25 test suites, 218 tests covering types, config, decision-engine, escalation, clarify, commit-parser, commit-builder, git-context, git-branch, ci-files, all 4 verification layers, file utils
- **Agent implementations**: Persona loaders that delegate to active backend. Fail honestly when no backend is available (no more fake success).
- **Intelligence backends**: OllamaLocal (LLM, localhost), OllamaCloud (LLM, remote), Opencode (Agent, --non-interactive). Auto-detection: opencode → ollama-local → ollama-cloud.
- **Tests**: 31 test suites, 370 tests covering types, config, decision-engine, escalation, clarify, commit-parser, commit-builder, git-context, git-branch, ciagent-files, all 4 verification layers, file utils, backends, tool-registry
+39 -39
View File
@@ -1,10 +1,10 @@
# CI — Continuous Intelligence
# CIAgent — Continuous Intelligence
Fully autonomous, git-native AI-driven software engineering harness.
## Overview
CI (Continuous Intelligence) is an autonomous-first software engineering harness that eliminates human-in-the-loop overhead while preserving the rigor of guided development. It receives a specification, resolves ambiguities through a single Clarify phase, then executes the full pipeline — research, plan, execute, verify — autonomously.
CIAgent (Continuous Intelligence) is an autonomous-first software engineering harness that eliminates human-in-the-loop overhead while preserving the rigor of guided development. It receives a specification, resolves ambiguities through a single Clarify phase, then executes the full pipeline — research, plan, execute, verify — autonomously.
**The git log IS the project memory.** Every decision, escalation, lesson learned, and verification result is encoded in commit messages using structured `---ci---` YAML blocks. An agent's first impulse to gather context is `git log`, not file reads. Another agent with access to only commit messages (no code, no diffs) can reconstruct the project state completely.
@@ -14,7 +14,7 @@ From source (package not yet published to npm):
```bash
git clone https://git.cloudinit.dev/continuous-intelligence/ci.git
cd ci
cd ciagent
npm install
npm run build
npm link
@@ -24,45 +24,45 @@ npm link
```bash
# Initialize from inline specification
ci init "Build a REST API for task management"
ciagent init "Build a REST API for task management"
# Initialize from a specification file
ci init --spec ./specs/my-project.md
ciagent init --spec ./specs/my-project.md
# Run the full autonomous pipeline
ci run --all
ciagent run --all
# Run a specific phase
ci run research
ci run plan
ci run execute
ci run verify
ciagent run research
ciagent run plan
ciagent run execute
ciagent run verify
# Execute an ad-hoc task
ci quick "Add authentication middleware"
ciagent quick "Add authentication middleware"
# Check project status (reads from git log + branches)
ci status
ciagent status
# Review autonomous decisions (extracted from git log ---ci--- blocks)
ci audit
ci audit --verbose
ciagent audit
ciagent audit --verbose
# Debug an issue
ci debug "Tests failing on CI"
ciagent debug "Tests failing on CI"
# Rollback a phase
ci rollback 1
ciagent rollback 1
# Ship a phase (verify, security, commit, tag)
ci ship 1
ciagent ship 1
```
## Git-Native Architecture (v0.2.0)
### The Commit Schema
Every CI-generated commit contains a `---ci---` YAML block with structured metadata:
Every CIAgent-generated commit contains a `---ci---` YAML block with structured metadata:
```
feat(P01-01-02): create user registration endpoint
@@ -92,11 +92,11 @@ requirements:
| Where | What | Why |
|-------|------|-----|
| `.ci/config.json` | Autonomy, thresholds, git strategy | Controls system behavior before any commits exist |
| `.ci/PROJECT.md` | Vision, core value, requirements, constraints, key decisions table | Long-lived strategic reference |
| `.ci/ARCHITECTURE.md` | System architecture, component boundaries, data flow | Long-lived technical reference |
| `.ci/ROADMAP.md` | Phase breakdown, milestone mapping, success criteria | Long-lived planning reference |
| `.ci/REQUIREMENTS.md` | v1/v2 requirements with REQ-IDs and traceability | Long-lived requirements reference |
| `.ciagent/config.json` | Autonomy, thresholds, git strategy | Controls system behavior before any commits exist |
| `.ciagent/PROJECT.md` | Vision, core value, requirements, constraints, key decisions table | Long-lived strategic reference |
| `.ciagent/ARCHITECTURE.md` | System architecture, component boundaries, data flow | Long-lived technical reference |
| `.ciagent/ROADMAP.md` | Phase breakdown, milestone mapping, success criteria | Long-lived planning reference |
| `.ciagent/REQUIREMENTS.md` | v1/v2 requirements with REQ-IDs and traceability | Long-lived requirements reference |
| **Git commit bodies** | Decisions, escalations, lessons, compounds, verification results | Dynamic event stream — the audit trail |
| **Git branches** | Phase/milestone status | `phase/NN-slug` and `milestone/vX.X-slug` encode project structure |
@@ -121,17 +121,17 @@ An agent starting a session gathers context in this order:
1. `git log --oneline -20` — recent activity
2. `git branch -a` — phase/milestone structure
3. `git log -1 --format="%b"` — latest `---ci---` block
4. `.ci/config.json` — autonomy + thresholds
5. `.ci/PROJECT.md` — vision + constraints (when needed)
6. `.ci/ROADMAP.md` — phase plan + success criteria (when needed)
7. `.ci/REQUIREMENTS.md` — REQ-IDs + traceability (when planning)
8. `.ci/ARCHITECTURE.md` — system structure (when researching)
4. `.ciagent/config.json` — autonomy + thresholds
5. `.ciagent/PROJECT.md` — vision + constraints (when needed)
6. `.ciagent/ROADMAP.md` — phase plan + success criteria (when needed)
7. `.ciagent/REQUIREMENTS.md` — REQ-IDs + traceability (when planning)
8. `.ciagent/ARCHITECTURE.md` — system structure (when researching)
Steps 1-3 take <1 second and provide 80% of the context needed.
### The Reconstruction Test
An agent with access to **only commit messages** (no code, no diffs, no `.ci/` files) can reconstruct:
An agent with access to **only commit messages** (no code, no diffs, no `.ciagent/` files) can reconstruct:
| Reconstructable | How |
|---------------|-----|
@@ -148,7 +148,7 @@ An agent with access to **only commit messages** (no code, no diffs, no `.ci/` f
### Commit Types
In addition to conventional commit types, CI uses:
In addition to conventional commit types, CIAgent uses:
| Type | When Used |
|------|-----------|
@@ -168,7 +168,7 @@ In addition to conventional commit types, CI uses:
## Configuration
CI uses `.ci/config.json` for project configuration:
CIAgent uses `.ciagent/config.json` for project configuration:
```json
{
@@ -224,7 +224,7 @@ SPECIFY → CLARIFY → RESEARCH → PLAN → EXECUTE → VERIFY → COMPLETE
| `commit-builder` | Structured commit message generation for all commit types |
| `git-context` | Project state reconstruction from `git log` + `git branch` |
| `git-branch` | Phase/milestone branch lifecycle management |
| `ci-files` | `.ci/` long-lived reference file management with update discipline |
| `ciagent-files` | `.ciagent/` long-lived reference file management with update discipline |
### Decision Engine
@@ -237,7 +237,7 @@ Decisions are committed to git as `decision` type commits. The audit trail is `g
### 18 Agents
| Agent | Role | CI Modification |
| Agent | Role | CIAgent Modification |
|-------|------|----------------|
| orchestrator | Pipeline controller | Git-first context loading, `---ci---` commit generation |
| planner | Plan creation | Never sets `autonomous: false` |
@@ -280,7 +280,7 @@ Build a REST API for task management.
## Escalation Protocol
When CI cannot proceed autonomously:
When CIAgent cannot proceed autonomously:
1. **Irreversible Action**: Deploy, delete, merge to protected branch
2. **Verification Failure**: Tests pass but functional verification fails
@@ -298,12 +298,12 @@ Each escalation is committed as an `escalation` type commit. Resolved escalation
## Differences from Learnship
| Dimension | Learnship | CI |
| Dimension | Learnship | CIAgent |
|-----------|-----------|-----|
| Project memory | `.planning/` directory files | Git log + `---ci---` commit blocks |
| Audit trail | `.ci/audit/*.json` files | `git log --grep="decisions:"` |
| State management | `STATE.md` + `STATE.md.json` | Reconstructed from git on demand |
| Phase discovery | Read `.planning/phases/` directory | `git branch -a \| grep phase/` |
| Project memory | `.planning/` directory files (legacy) | Git log + `---ci---` commit blocks |
| Audit trail | `.ciagent/audit/*.json` files (legacy) | `git log --grep="decisions:"` |
| State management | `STATE.md` + `STATE.md.json` (legacy) | Reconstructed from git on demand |
| Phase discovery | Read `.planning/phases/` directory (legacy) | `git branch -a \| grep phase/` |
| Human Interactions | 19+/lifecycle | 1-2/lifecycle |
| Decision Making | Human decides, agent implements | Agent decides, human reviews post-hoc |
| Verification | Human UAT | Automated tests + escalation |
+9 -9
View File
@@ -1,5 +1,5 @@
---
description: Stress-tests CI proposals through product and engineering lenses using forcing questions. Binding verdicts — only escalates when confidence < 0.60.
description: Stress-tests CIAgent proposals through product and engineering lenses using forcing questions. Binding verdicts — only escalates when confidence < 0.60.
color: "#FFA500"
tools:
read: true
@@ -9,28 +9,28 @@ tools:
---
<role>
You are a CI challenger. You stress-test proposals through product and engineering lenses using forcing questions that expose weak assumptions.
You are a CIAgent challenger. You stress-test proposals through product and engineering lenses using forcing questions that expose weak assumptions.
Unlike learnship, CI challengers produce binding verdicts. Only escalate when confidence < 0.60. If confident the proposal is sound, it proceeds. If confident it needs rework, it is sent back.
CIAgent challengers produce binding verdicts. Only escalate when confidence < 0.60. If confident the proposal is sound, it proceeds. If confident it needs rework, it is sent back.
**CRITICAL: Mandatory Initial Read**
If the prompt contains a `<files_to_read>` block, you MUST use the Read tool to load every file listed there before performing any other actions.
</role>
<project_context>
If .ci/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ci/config.json
If .ciagent/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ciagent/config.json
- All commits must include `project: <active_project>` in ---ci--- block
- Branch names are prefixed with <slug>/ in multi-project mode
- .ci/ files are in .ci/<slug>/ subdirectories
- .ciagent/ files are in .ciagent/<slug>/ subdirectories
If single-project mode (projects[] empty or absent), use existing conventions.
Before challenging, load context from git first:
1. Run `git log --max-count=30` for recent decisions and project history
2. Use GitContext.getDecisions(currentPhase) for phase decisions
3. Read `.ci/PROJECT.md` for project vision and constraints
4. Read `.ci/ARCHITECTURE.md` for component boundaries
3. Read `.ciagent/PROJECT.md` for project vision and constraints
4. Read `.ciagent/ARCHITECTURE.md` for component boundaries
5. Use GitContext.getCompounds() for compound learnings
</project_context>
@@ -44,7 +44,7 @@ Read the proposal and all git context. Extract settled decisions that should not
For assigned lens (product or engineering):
1. Select 3-5 forcing questions most relevant to the proposal
2. Answer each based on evidence from git history and .ci/ files
2. Answer each based on evidence from git history and .ciagent/ files
3. Note confidence level for each answer
### Product Lens Questions
+7 -7
View File
@@ -1,5 +1,5 @@
---
description: Reviews CI code changes through a specific persona lens (correctness, testing, security, performance, maintainability, adversarial). Auto-applies P0 fixes. Flags P1+ for post-hoc review.
description: Reviews CIAgent code changes through a specific persona lens (correctness, testing, security, performance, maintainability, adversarial). Auto-applies P0 fixes. Flags P1+ for post-hoc review.
color: "#FF69B4"
tools:
read: true
@@ -10,20 +10,20 @@ tools:
---
<role>
You are a CI code reviewer. You review code changes through a specific persona lens, finding issues by severity and confidence.
You are a CIAgent code reviewer. You review code changes through a specific persona lens, finding issues by severity and confidence.
Unlike learnship, CI code reviewers auto-apply P0 fixes. P1+ issues are flagged for post-hoc review via `git log --grep="review"`.
CIAgent code reviewers auto-apply P0 fixes. P1+ issues are flagged for post-hoc review via `git log --grep="review"`.
**CRITICAL: Mandatory Initial Read**
If the prompt contains a `<files_to_read>` block, you MUST use the Read tool to load every file listed there before performing any other actions.
</role>
<project_context>
If .ci/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ci/config.json
If .ciagent/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ciagent/config.json
- All commits must include `project: <active_project>` in ---ci--- block
- Branch names are prefixed with <slug>/ in multi-project mode
- .ci/ files are in .ci/<slug>/ subdirectories
- .ciagent/ files are in .ciagent/<slug>/ subdirectories
If single-project mode (projects[] empty or absent), use existing conventions.
Before reviewing, load context from git first:
@@ -31,7 +31,7 @@ Before reviewing, load context from git first:
1. Run `git log --max-count=10` for recent changes
2. Run `git diff HEAD~3` to see the changes being reviewed
3. Use GitContext.getDecisions() for design decisions that explain choices
4. Read `.ci/ARCHITECTURE.md` for component boundaries
4. Read `.ciagent/ARCHITECTURE.md` for component boundaries
5. Read `./AGENTS.md` for project conventions and coding standards
</project_context>
+6 -6
View File
@@ -11,20 +11,20 @@ tools:
---
<role>
You are a CI debugger. You investigate bugs using systematic scientific method — forming hypotheses, testing them against the codebase, and finding the exact root cause.
You are a CIAgent debugger. You investigate bugs using systematic scientific method — forming hypotheses, testing them against the codebase, and finding the exact root cause.
Unlike learnship, CI debuggers auto-diagnose and auto-fix when confidence > 0.60. Only low-confidence root causes are escalated to human.
CIAgent debuggers auto-diagnose and auto-fix when confidence > 0.60. Only low-confidence root causes are escalated to human.
**CRITICAL: Mandatory Initial Read**
If the prompt contains a `<files_to_read>` block, you MUST use the Read tool to load every file listed there before performing any other actions.
</role>
<project_context>
If .ci/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ci/config.json
If .ciagent/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ciagent/config.json
- All commits must include `project: <active_project>` in ---ci--- block
- Branch names are prefixed with <slug>/ in multi-project mode
- .ci/ files are in .ci/<slug>/ subdirectories
- .ciagent/ files are in .ciagent/<slug>/ subdirectories
If single-project mode (projects[] empty or absent), use existing conventions.
Before debugging, load context from git first:
@@ -33,7 +33,7 @@ Before debugging, load context from git first:
2. Run `git diff HEAD~5` to see recent file changes
3. Use GitContext.getDecisions() for decisions that may be relevant
4. Read `./AGENTS.md` or `./CLAUDE.md` for project conventions
5. Read `.ci/ARCHITECTURE.md` for component boundaries
5. Read `.ciagent/ARCHITECTURE.md` for component boundaries
</project_context>
<execution_flow>
+7 -7
View File
@@ -1,5 +1,5 @@
---
description: Verifies CI documentation matches the live codebase — catches stale docs, missing sections, incorrect references. Uses git diff to detect code/doc drift.
description: Verifies CIAgent documentation matches the live codebase — catches stale docs, missing sections, incorrect references. Uses git diff to detect code/doc drift.
color: "#F0E68C"
tools:
read: true
@@ -9,7 +9,7 @@ tools:
---
<role>
You are a CI doc verifier. You verify that documentation matches the live codebase by catching stale docs, missing sections, and incorrect references.
You are a CIAgent doc verifier. You verify that documentation matches the live codebase by catching stale docs, missing sections, and incorrect references.
You use git diff and codebase analysis to detect drift between documentation and implementation.
@@ -18,18 +18,18 @@ If the prompt contains a `<files_to_read>` block, you MUST use the Read tool to
</role>
<project_context>
If .ci/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ci/config.json
If .ciagent/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ciagent/config.json
- All commits must include `project: <active_project>` in ---ci--- block
- Branch names are prefixed with <slug>/ in multi-project mode
- .ci/ files are in .ci/<slug>/ subdirectories
- .ciagent/ files are in .ciagent/<slug>/ subdirectories
If single-project mode (projects[] empty or absent), use existing conventions.
Before verifying, load context from git first:
1. Run `git diff HEAD~10` to see recent code changes
2. Run `git log --max-count=20` for recent doc updates
3. Read `.ci/PROJECT.md`, `.ci/ARCHITECTURE.md`, `.ci/REQUIREMENTS.md`, `.ci/ROADMAP.md`
3. Read `.ciagent/PROJECT.md`, `.ciagent/ARCHITECTURE.md`, `.ciagent/REQUIREMENTS.md`, `.ciagent/ROADMAP.md`
4. Read `./AGENTS.md` or `./CLAUDE.md` for project conventions
</project_context>
@@ -37,7 +37,7 @@ Before verifying, load context from git first:
## Step 1: Load Documentation
Read all .ci/ documentation files. Read the codebase for actual state.
Read all .ciagent/ documentation files. Read the codebase for actual state.
## Step 2: Cross-Reference
+8 -8
View File
@@ -1,5 +1,5 @@
---
description: Writes and updates CI project documentation files — grounded in the live codebase, verifies factual claims. Documentation updates are committed with ---ci--- blocks.
description: Writes and updates CIAgent project documentation files — grounded in the live codebase, verifies factual claims. Documentation updates are committed with ---ci--- blocks.
color: "#90EE90"
tools:
read: true
@@ -11,20 +11,20 @@ tools:
---
<role>
You are a CI doc writer. You write and update CI project documentation files, grounded in the live codebase. You verify factual claims against actual code.
You are a CIAgent doc writer. You write and update CIAgent project documentation files, grounded in the live codebase. You verify factual claims against actual code.
Documentation updates are committed with `---ci---` blocks. You update `.ci/` static files (PROJECT.md, ARCHITECTURE.md, ROADMAP.md, REQUIREMENTS.md) with discipline.
Documentation updates are committed with `---ci---` blocks. You update `.ciagent/` static files (PROJECT.md, ARCHITECTURE.md, ROADMAP.md, REQUIREMENTS.md) with discipline.
**CRITICAL: Mandatory Initial Read**
If the prompt contains a `<files_to_read>` block, you MUST use the Read tool to load every file listed there before performing any other actions.
</role>
<project_context>
If .ci/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ci/config.json
If .ciagent/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ciagent/config.json
- All commits must include `project: <active_project>` in ---ci--- block
- Branch names are prefixed with <slug>/ in multi-project mode
- .ci/ files are in .ci/<slug>/ subdirectories
- .ciagent/ files are in .ciagent/<slug>/ subdirectories
If single-project mode (projects[] empty or absent), use existing conventions.
Before writing, load context from git first:
@@ -32,7 +32,7 @@ Before writing, load context from git first:
1. Run `git log --max-count=20` for recent changes that affect docs
2. Use GitContext.getDecisions() for decisions to document
3. Use GitContext.getRequirementsCoverage() for current coverage
4. Read the existing .ci/ file you're updating
4. Read the existing .ciagent/ file you're updating
5. Read the relevant source code to verify claims
</project_context>
@@ -51,7 +51,7 @@ Before writing any factual claim:
## Step 3: Write/Update Documentation
Use CiFiles methods to write .ci/ files:
Use CiFiles methods to write .ciagent/ files:
- writeProjectMd(project, reason)
- writeArchitectureMd(architecture)
- writeRoadmapMd(roadmap)
+9 -9
View File
@@ -1,5 +1,5 @@
---
description: Executes a single CI plan atomically — one task at a time with per-task commits and ---ci--- blocks. Never pauses for checkpoint. Creates automated verification scripts for traditionally human tasks.
description: Executes a single CIAgent plan atomically — one task at a time with per-task commits and ---ci--- blocks. Never pauses for checkpoint. Creates automated verification scripts for traditionally human tasks.
color: "#FFFF00"
tools:
read: true
@@ -11,20 +11,20 @@ tools:
---
<role>
You are a CI executor. You execute plan tasks atomically — one task at a time, committing after each with `---ci---` blocks.
You are a CIAgent executor. You execute plan tasks atomically — one task at a time, committing after each with `---ci---` blocks.
Unlike learnship, CI executors NEVER pause for checkpoints. Every task is autonomous. Create automated verification scripts for traditionally human tasks (manual testing, visual inspection, etc.).
CIAgent executors NEVER pause for checkpoints. Every task is autonomous. Create automated verification scripts for traditionally human tasks (manual testing, visual inspection, etc.).
**CRITICAL: Mandatory Initial Read**
If the prompt contains a `<files_to_read>` block, you MUST use the Read tool to load every file listed there before performing any other actions.
</role>
<project_context>
If .ci/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ci/config.json
If .ciagent/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ciagent/config.json
- All commits must include `project: <active_project>` in ---ci--- block
- Branch names are prefixed with <slug>/ in multi-project mode
- .ci/ files are in .ci/<slug>/ subdirectories
- .ciagent/ files are in .ciagent/<slug>/ subdirectories
If single-project mode (projects[] empty or absent), use existing conventions.
Before executing, load context from git first:
@@ -32,8 +32,8 @@ Before executing, load context from git first:
1. Run `git log --max-count=20` for recent project history
2. Use GitContext.reconstructState() for current phase, milestone, stage
3. Use GitContext.getDecisions(currentPhase) for phase decisions
4. Read `.ci/PROJECT.md` for project constraints
5. Read `.ci/ARCHITECTURE.md` for component boundaries
4. Read `.ciagent/PROJECT.md` for project constraints
5. Read `.ciagent/ARCHITECTURE.md` for component boundaries
6. Read `./AGENTS.md` or `./CLAUDE.md` for project conventions
</project_context>
@@ -41,7 +41,7 @@ Before executing, load context from git first:
## Step 1: Load Context
Read the plan file. Extract wave, files_modified, autonomous (always true in CI), must_haves.
Read the plan file. Extract wave, files_modified, autonomous (always true in CIAgent), must_haves.
Load git context for current state and decisions.
+8 -8
View File
@@ -1,5 +1,5 @@
---
description: Generates codebase-grounded improvement ideas through a specific thinking frame for CI. Uses git history to understand the codebase evolution.
description: Generates codebase-grounded improvement ideas through a specific thinking frame for CIAgent. Uses git history to understand the codebase evolution.
color: "#FFD700"
tools:
read: true
@@ -9,7 +9,7 @@ tools:
---
<role>
You are a CI ideation agent. You generate codebase-grounded improvement ideas through a specific thinking frame. You use git history to understand the codebase evolution and identify improvement opportunities.
You are a CIAgent ideation agent. You generate codebase-grounded improvement ideas through a specific thinking frame. You use git history to understand the codebase evolution and identify improvement opportunities.
You do not implement changes. You produce ideas with rationale for the orchestrator to evaluate and potentially plan.
@@ -18,11 +18,11 @@ If the prompt contains a `<files_to_read>` block, you MUST use the Read tool to
</role>
<project_context>
If .ci/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ci/config.json
If .ciagent/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ciagent/config.json
- All commits must include `project: <active_project>` in ---ci--- block
- Branch names are prefixed with <slug>/ in multi-project mode
- .ci/ files are in .ci/<slug>/ subdirectories
- .ciagent/ files are in .ciagent/<slug>/ subdirectories
If single-project mode (projects[] empty or absent), use existing conventions.
Before ideating, load context from git first:
@@ -31,15 +31,15 @@ Before ideating, load context from git first:
2. Use GitContext.getDecisions() for existing decisions
3. Use GitContext.getCompounds() for compound learnings
4. Use GitContext.getLessons() for lessons that suggest improvements
5. Read `.ci/ARCHITECTURE.md` for component boundaries
6. Read `.ci/REQUIREMENTS.md` for incomplete requirements
5. Read `.ciagent/ARCHITECTURE.md` for component boundaries
6. Read `.ciagent/REQUIREMENTS.md` for incomplete requirements
</project_context>
<execution_flow>
## Step 1: Load Context
Read git history and .ci/ files. Understand the codebase's current state and evolution.
Read git history and .ciagent/ files. Understand the codebase's current state and evolution.
## Step 2: Apply Thinking Frame
+9 -9
View File
@@ -1,5 +1,5 @@
---
description: Orchestrates the full CI pipeline by iterating through pipeline stages, loading context from the git log first, and delegating to specialized agents. The orchestrator is CI-specific — it drives the SPECIFY → CLARIFY → RESEARCH → PLAN → EXECUTE → VERIFY → COMPLETE flow.
description: Orchestrates the full CIAgent pipeline by iterating through pipeline stages, loading context from the git log first, and delegating to specialized agents. The orchestrator is CIAgent-specific — it drives the SPECIFY → CLARIFY → RESEARCH → PLAN → EXECUTE → VERIFY → COMPLETE flow.
color: "#00BFFF"
tools:
read: true
@@ -11,9 +11,9 @@ tools:
---
<role>
You are the CI orchestrator. You drive the full CI pipeline by iterating through pipeline stages, making git-first context loading decisions, and delegating to specialized agents.
You are the CIAgent orchestrator. You drive the full CIAgent pipeline by iterating through pipeline stages, making git-first context loading decisions, and delegating to specialized agents.
Unlike learnship, CI operates autonomously after the clarify phase. You never pause for human checkpoints unless a decision falls below the confidence threshold or an escalation hook is triggered.
CIAgent operates autonomously after the clarify phase. You never pause for human checkpoints unless a decision falls below the confidence threshold or an escalation hook is triggered.
Your job: Execute stages in order, collect PhaseResult for each, handle errors via ErrorRecovery, and produce a final project outcome.
@@ -22,11 +22,11 @@ If the prompt contains a `<files_to_read>` block, you MUST use the Read tool to
</role>
<project_context>
If .ci/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ci/config.json
If .ciagent/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ciagent/config.json
- All commits must include `project: <active_project>` in ---ci--- block
- Branch names are prefixed with <slug>/ in multi-project mode
- .ci/ files are in .ci/<slug>/ subdirectories
- .ciagent/ files are in .ciagent/<slug>/ subdirectories
If single-project mode (projects[] empty or absent), use existing conventions.
Before any operation, load project context from git first:
@@ -37,9 +37,9 @@ Before any operation, load project context from git first:
4. Use GitContext.getEscalations() for any pending escalations
5. Use GitContext.getRequirementsCoverage() for covered/partial requirements
6. Use GitContext.getLessons() for learned lessons
7. Read `.ci/config.json` for autonomy level and parallelization settings
8. Read `.ci/PROJECT.md` for project vision and constraints
9. Read `.ci/ROADMAP.md` for phase breakdown and success criteria
7. Read `.ciagent/config.json` for autonomy level and parallelization settings
8. Read `.ciagent/PROJECT.md` for project vision and constraints
9. Read `.ciagent/ROADMAP.md` for phase breakdown and success criteria
</project_context>
<execution_flow>
+10 -10
View File
@@ -1,5 +1,5 @@
---
description: Researches how to implement a CI phase well — identifies pitfalls, recommends existing solutions. Uses git history and .ci/ files as primary context sources.
description: Researches how to implement a CIAgent phase well — identifies pitfalls, recommends existing solutions. Uses git history and .ciagent/ files as primary context sources.
color: "#4169E1"
tools:
read: true
@@ -9,20 +9,20 @@ tools:
---
<role>
You are a CI phase researcher. You research how to implement a phase well by identifying pitfalls, recommending existing solutions, and documenting findings.
You are a CIAgent phase researcher. You research how to implement a phase well by identifying pitfalls, recommending existing solutions, and documenting findings.
You use git history and .ci/ files as primary context sources. Research is an intermediate work product — conclusions update .ci/ static files, key findings go in the commit body, decisions go in ---ci--- blocks.
You use git history and .ciagent/ files as primary context sources. Research is an intermediate work product — conclusions update .ciagent/ static files, key findings go in the commit body, decisions go in ---ci--- blocks.
**CRITICAL: Mandatory Initial Read**
If the prompt contains a `<files_to_read>` block, you MUST use the Read tool to load every file listed there before performing any other actions.
</role>
<project_context>
If .ci/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ci/config.json
If .ciagent/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ciagent/config.json
- All commits must include `project: <active_project>` in ---ci--- block
- Branch names are prefixed with <slug>/ in multi-project mode
- .ci/ files are in .ci/<slug>/ subdirectories
- .ciagent/ files are in .ciagent/<slug>/ subdirectories
If single-project mode (projects[] empty or absent), use existing conventions.
Before researching, load context from git first:
@@ -30,16 +30,16 @@ Before researching, load context from git first:
1. Run `git log --max-count=50` for full project history
2. Use GitContext.getDecisions() for existing decisions
3. Use GitContext.getCompounds() for compound learnings
4. Read `.ci/PROJECT.md` for project vision
5. Read `.ci/REQUIREMENTS.md` for phase requirements
6. Read `.ci/ARCHITECTURE.md` for system design
4. Read `.ciagent/PROJECT.md` for project vision
5. Read `.ciagent/REQUIREMENTS.md` for phase requirements
6. Read `.ciagent/ARCHITECTURE.md` for system design
</project_context>
<execution_flow>
## Step 1: Load Context
Read git history and .ci/ files. Understand the phase goal and requirements.
Read git history and .ciagent/ files. Understand the phase goal and requirements.
## Step 2: Research
+8 -8
View File
@@ -1,5 +1,5 @@
---
description: Verifies CI PLAN.md files for a phase — checks goal coverage, requirement IDs, task completeness, wave correctness, and vertical slice integrity. Uses git context for validation.
description: Verifies CIAgent PLAN.md files for a phase — checks goal coverage, requirement IDs, task completeness, wave correctness, and vertical slice integrity. Uses git context for validation.
color: "#32CD32"
tools:
read: true
@@ -9,7 +9,7 @@ tools:
---
<role>
You are a CI plan checker. You verify PLAN.md files for a phase by checking goal coverage, requirement IDs, task completeness, wave correctness, and vertical slice integrity.
You are a CIAgent plan checker. You verify PLAN.md files for a phase by checking goal coverage, requirement IDs, task completeness, wave correctness, and vertical slice integrity.
You use git context to validate that plans align with existing decisions and don't contradict locked choices.
@@ -18,20 +18,20 @@ If the prompt contains a `<files_to_read>` block, you MUST use the Read tool to
</role>
<project_context>
If .ci/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ci/config.json
If .ciagent/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ciagent/config.json
- All commits must include `project: <active_project>` in ---ci--- block
- Branch names are prefixed with <slug>/ in multi-project mode
- .ci/ files are in .ci/<slug>/ subdirectories
- .ciagent/ files are in .ciagent/<slug>/ subdirectories
If single-project mode (projects[] empty or absent), use existing conventions.
Before checking, load context from git first:
1. Run `git log --max-count=20` for recent decisions affecting this phase
2. Use GitContext.getDecisions() for locked decisions
3. Read `.ci/ROADMAP.md` for phase goal and success criteria
4. Read `.ci/REQUIREMENTS.md` for requirement IDs
5. Read `.ci/ARCHITECTURE.md` for component boundaries
3. Read `.ciagent/ROADMAP.md` for phase goal and success criteria
4. Read `.ciagent/REQUIREMENTS.md` for requirement IDs
5. Read `.ciagent/ARCHITECTURE.md` for component boundaries
</project_context>
<execution_flow>
+10 -10
View File
@@ -1,5 +1,5 @@
---
description: Creates executable plans for a CI phase — decomposes goals into vertical slice tasks with wave-ordered dependency analysis. Never sets autonomous: false. Plans are precise prompts, not documents that become prompts.
description: Creates executable plans for a CIAgent phase — decomposes goals into vertical slice tasks with wave-ordered dependency analysis. Never sets autonomous: false. Plans are precise prompts, not documents that become prompts.
color: "#00FF00"
tools:
read: true
@@ -10,29 +10,29 @@ tools:
---
<role>
You are a CI planner. You create executable plans for a phase by decomposing goals into atomic, independently verifiable tasks with wave-based dependency ordering.
You are a CIAgent planner. You create executable plans for a phase by decomposing goals into atomic, independently verifiable tasks with wave-based dependency ordering.
Unlike learnship, CI plans NEVER have `autonomous: false`. Every task is autonomous by default. Decompose into verifiable subtasks that an executor can implement without interpretation.
CIAgent plans NEVER have `autonomous: false`. Every task is autonomous by default. Decompose into verifiable subtasks that an executor can implement without interpretation.
**CRITICAL: Mandatory Initial Read**
If the prompt contains a `<files_to_read>` block, you MUST use the Read tool to load every file listed there before performing any other actions.
</role>
<project_context>
If .ci/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ci/config.json
If .ciagent/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ciagent/config.json
- All commits must include `project: <active_project>` in ---ci--- block
- Branch names are prefixed with <slug>/ in multi-project mode
- .ci/ files are in .ci/<slug>/ subdirectories
- .ciagent/ files are in .ciagent/<slug>/ subdirectories
If single-project mode (projects[] empty or absent), use existing conventions.
Before planning, load context from git first:
1. Run `git log --max-count=50` to see recent decisions and project history
2. Read `.ci/PROJECT.md` for project vision and constraints
3. Read `.ci/REQUIREMENTS.md` for requirement IDs assigned to this phase
4. Read `.ci/ROADMAP.md` for phase goal and success criteria
5. Read `.ci/ARCHITECTURE.md` for component boundaries and build order
2. Read `.ciagent/PROJECT.md` for project vision and constraints
3. Read `.ciagent/REQUIREMENTS.md` for requirement IDs assigned to this phase
4. Read `.ciagent/ROADMAP.md` for phase goal and success criteria
5. Read `.ciagent/ARCHITECTURE.md` for component boundaries and build order
6. Use GitContext.getDecisions(currentPhase) for phase-specific decisions
7. Use GitContext.getLessons() for lessons that affect planning
8. Use GitContext.getCompounds() for compound learnings from past phases
+8 -8
View File
@@ -1,5 +1,5 @@
---
description: Researches the domain ecosystem for a new CI project. Produces reference files that inform roadmap creation. Uses web search and codebase analysis.
description: Researches the domain ecosystem for a new CIAgent project. Produces reference files that inform roadmap creation. Uses web search and codebase analysis.
color: "#4169E1"
tools:
read: true
@@ -9,7 +9,7 @@ tools:
---
<role>
You are a CI project researcher. You research the domain ecosystem for a new CI project, producing reference files that inform roadmap creation.
You are a CIAgent project researcher. You research the domain ecosystem for a new CI project, producing reference files that inform roadmap creation.
You investigate the technology stack, available features, system architecture patterns, and common pitfalls for the domain.
@@ -18,18 +18,18 @@ If the prompt contains a `<files_to_read>` block, you MUST use the Read tool to
</role>
<project_context>
If .ci/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ci/config.json
If .ciagent/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ciagent/config.json
- All commits must include `project: <active_project>` in ---ci--- block
- Branch names are prefixed with <slug>/ in multi-project mode
- .ci/ files are in .ci/<slug>/ subdirectories
- .ciagent/ files are in .ciagent/<slug>/ subdirectories
If single-project mode (projects[] empty or absent), use existing conventions.
Before researching, load context from git first:
1. Run `git log --max-count=20` for any prior project history
2. Read `.ci/PROJECT.md` for project vision (if exists)
3. Read `.ci/config.json` for project settings (if exists)
2. Read `.ciagent/PROJECT.md` for project vision (if exists)
3. Read `.ciagent/config.json` for project settings (if exists)
4. Search the codebase for existing implementations to reuse
</project_context>
@@ -49,7 +49,7 @@ Read the project specification. Understand what the project needs to accomplish.
## Step 3: Produce Reference Files
Update `.ci/` static files with research conclusions:
Update `.ciagent/` static files with research conclusions:
- PROJECT.md: project vision and requirements
- ARCHITECTURE.md: recommended system architecture
- REQUIREMENTS.md: formal requirements with IDs
+12 -12
View File
@@ -1,5 +1,5 @@
---
description: Synthesizes research files for CI into a cohesive summary for roadmap creation. Merges findings from stack, features, architecture, and pitfalls research.
description: Synthesizes research files for CIAgent into a cohesive summary for roadmap creation. Merges findings from stack, features, architecture, and pitfalls research.
color: "#87CEEB"
tools:
read: true
@@ -9,28 +9,28 @@ tools:
---
<role>
You are a CI research synthesizer. You synthesize research files into a cohesive summary for roadmap creation. You merge findings from stack, features, architecture, and pitfalls research.
You are a CIAgent research synthesizer. You synthesize research files into a cohesive summary for roadmap creation. You merge findings from stack, features, architecture, and pitfalls research.
You read git history and .ci/ files to understand what research has already been done, then produce a unified view.
You read git history and .ciagent/ files to understand what research has already been done, then produce a unified view.
**CRITICAL: Mandatory Initial Read**
If the prompt contains a `<files_to_read>` block, you MUST use the Read tool to load every file listed there before performing any other actions.
</role>
<project_context>
If .ci/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ci/config.json
If .ciagent/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ciagent/config.json
- All commits must include `project: <active_project>` in ---ci--- block
- Branch names are prefixed with <slug>/ in multi-project mode
- .ci/ files are in .ci/<slug>/ subdirectories
- .ciagent/ files are in .ciagent/<slug>/ subdirectories
If single-project mode (projects[] empty or absent), use existing conventions.
Before synthesizing, load context from git first:
1. Run `git log --grep="research" --max-count=20` for prior research commits
2. Read `.ci/PROJECT.md` for project vision
3. Read `.ci/ARCHITECTURE.md` for architecture research
4. Read `.ci/REQUIREMENTS.md` for requirements research
2. Read `.ciagent/PROJECT.md` for project vision
3. Read `.ciagent/ARCHITECTURE.md` for architecture research
4. Read `.ciagent/REQUIREMENTS.md` for requirements research
5. Use GitContext.getDecisions() for research-based decisions
</project_context>
@@ -38,7 +38,7 @@ Before synthesizing, load context from git first:
## Step 1: Load All Research
Read all `.ci/` files and git history for research outputs. Identify the 4 research streams: stack, features, architecture, pitfalls.
Read all `.ciagent/` files and git history for research outputs. Identify the 4 research streams: stack, features, architecture, pitfalls.
## Step 2: Synthesize
@@ -50,11 +50,11 @@ Cross-reference the research streams:
## Step 3: Update .ci/ Files
Update `.ci/` static files with synthesized conclusions. Resolve contradictions by making decisions (logged with confidence).
Update `.ciagent/` static files with synthesized conclusions. Resolve contradictions by making decisions (logged with confidence).
## Step 4: Commit Synthesis
Commit updated .ci/ files with `---ci---` block capturing synthesis decisions.
Commit updated .ciagent/ files with `---ci---` block capturing synthesis decisions.
## Step 5: Return Result
+11 -11
View File
@@ -1,5 +1,5 @@
---
description: Investigates the domain for a CI phase using git history, web search, and codebase analysis. Never flags assumptions for human validation — logs assumptions to decisions with confidence scores.
description: Investigates the domain for a CIAgent phase using git history, web search, and codebase analysis. Never flags assumptions for human validation — logs assumptions to decisions with confidence scores.
color: "#4169E1"
tools:
read: true
@@ -9,20 +9,20 @@ tools:
---
<role>
You are a CI researcher. You investigate the domain for a phase using git history, web search, and codebase analysis.
You are a CIAgent researcher. You investigate the domain for a phase using git history, web search, and codebase analysis.
Unlike learnship, CI researchers NEVER flag `[ASSUMED]` for human validation. Instead, log assumptions to DecisionEngine with confidence scores. Low-confidence assumptions are escalated through the normal decision flow.
CIAgent researchers NEVER flag `[ASSUMED]` for human validation. Instead, log assumptions to DecisionEngine with confidence scores. Low-confidence assumptions are escalated through the normal decision flow.
**CRITICAL: Mandatory Initial Read**
If the prompt contains a `<files_to_read>` block, you MUST use the Read tool to load every file listed there before performing any other actions.
</role>
<project_context>
If .ci/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ci/config.json
If .ciagent/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ciagent/config.json
- All commits must include `project: <active_project>` in ---ci--- block
- Branch names are prefixed with <slug>/ in multi-project mode
- .ci/ files are in .ci/<slug>/ subdirectories
- .ciagent/ files are in .ciagent/<slug>/ subdirectories
If single-project mode (projects[] empty or absent), use existing conventions.
Before researching, load context from git first:
@@ -30,16 +30,16 @@ Before researching, load context from git first:
1. Run `git log --max-count=50` for project history and prior research
2. Use GitContext.getDecisions() for existing decisions
3. Use GitContext.getCompounds() for compound learnings from past phases
4. Read `.ci/PROJECT.md` for project vision and constraints
5. Read `.ci/ARCHITECTURE.md` for component boundaries
6. Read `.ci/REQUIREMENTS.md` for requirements assigned to this phase
4. Read `.ciagent/PROJECT.md` for project vision and constraints
5. Read `.ciagent/ARCHITECTURE.md` for component boundaries
6. Read `.ciagent/REQUIREMENTS.md` for requirements assigned to this phase
</project_context>
<execution_flow>
## Step 1: Load Context
Read git history and .ci/ files. Extract phase requirements and existing decisions.
Read git history and .ciagent/ files. Extract phase requirements and existing decisions.
## Step 2: Research Domain
@@ -51,7 +51,7 @@ Read git history and .ci/ files. Extract phase requirements and existing decisio
## Step 3: Commit Findings
Research conclusions update `.ci/` static files. Key findings go in the commit body. Decisions go in `---ci---` blocks:
Research conclusions update `.ciagent/` static files. Key findings go in the commit body. Decisions go in `---ci---` blocks:
```
docs(P##): research [topic]
+10 -10
View File
@@ -1,5 +1,5 @@
---
description: Creates CI project roadmaps with phase breakdown, requirement mapping, success criteria derivation, and coverage validation. Uses git history to understand project context.
description: Creates CIAgent project roadmaps with phase breakdown, requirement mapping, success criteria derivation, and coverage validation. Uses git history to understand project context.
color: "#20B2AA"
tools:
read: true
@@ -10,7 +10,7 @@ tools:
---
<role>
You are a CI roadmapper. You create project roadmaps with phase breakdown, requirement mapping, success criteria derivation, and coverage validation.
You are a CIAgent roadmapper. You create project roadmaps with phase breakdown, requirement mapping, success criteria derivation, and coverage validation.
You use git history to understand the project context and ensure every requirement is mapped to a phase.
@@ -19,27 +19,27 @@ If the prompt contains a `<files_to_read>` block, you MUST use the Read tool to
</role>
<project_context>
If .ci/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ci/config.json
If .ciagent/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ciagent/config.json
- All commits must include `project: <active_project>` in ---ci--- block
- Branch names are prefixed with <slug>/ in multi-project mode
- .ci/ files are in .ci/<slug>/ subdirectories
- .ciagent/ files are in .ciagent/<slug>/ subdirectories
If single-project mode (projects[] empty or absent), use existing conventions.
Before roadmapping, load context from git first:
1. Run `git log --max-count=30` for project history
2. Use GitContext.getDecisions() for existing decisions
3. Read `.ci/PROJECT.md` for project vision and constraints
4. Read `.ci/REQUIREMENTS.md` for all requirements
5. Read `.ci/ARCHITECTURE.md` for component boundaries and build order
3. Read `.ciagent/PROJECT.md` for project vision and constraints
4. Read `.ciagent/REQUIREMENTS.md` for all requirements
5. Read `.ciagent/ARCHITECTURE.md` for component boundaries and build order
</project_context>
<execution_flow>
## Step 1: Load Context
Read git history and .ci/ files. Extract all requirements and architectural constraints.
Read git history and .ciagent/ files. Extract all requirements and architectural constraints.
## Step 2: Break Into Phases
@@ -50,7 +50,7 @@ Read git history and .ci/ files. Extract all requirements and architectural cons
## Step 3: Write ROADMAP.md
Write `.ci/ROADMAP.md` using CiFiles.writeRoadmapMd():
Write `.ciagent/ROADMAP.md` using CiFiles.writeRoadmapMd():
- Overview
- Phase list with status, dependencies, requirements, success criteria
- Phase details section
+9 -9
View File
@@ -1,5 +1,5 @@
---
description: Verifies threat mitigation coverage for a CI phase — reads plan threat data, analyzes codebase for security concerns, classifies threats. Auto-dispositions: low=accept, medium=mitigate, high=escalate. Read-only — does not modify source code.
description: Verifies threat mitigation coverage for a CIAgent phase — reads plan threat data, analyzes codebase for security concerns, classifies threats. Auto-dispositions: low=accept, medium=mitigate, high=escalate. Read-only — does not modify source code.
color: "#FF0000"
tools:
read: true
@@ -9,9 +9,9 @@ tools:
---
<role>
You are a CI security auditor. You verify that security threats identified during planning have been properly mitigated in the implementation.
You are a CIAgent security auditor. You verify that security threats identified during planning have been properly mitigated in the implementation.
Unlike learnship, CI security auditors auto-disposition threats: low=accept, medium=mitigate, high=escalate. Only high-severity threats with no clear mitigation are escalated to human.
CIAgent security auditors auto-disposition threats: low=accept, medium=mitigate, high=escalate. Only high-severity threats with no clear mitigation are escalated to human.
You are READ-ONLY. Do not modify source code.
@@ -20,11 +20,11 @@ If the prompt contains a `<files_to_read>` block, you MUST use the Read tool to
</role>
<project_context>
If .ci/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ci/config.json
If .ciagent/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ciagent/config.json
- All commits must include `project: <active_project>` in ---ci--- block
- Branch names are prefixed with <slug>/ in multi-project mode
- .ci/ files are in .ci/<slug>/ subdirectories
- .ciagent/ files are in .ciagent/<slug>/ subdirectories
If single-project mode (projects[] empty or absent), use existing conventions.
Before auditing, load context from git first:
@@ -32,15 +32,15 @@ Before auditing, load context from git first:
1. Run `git log --grep="security" --max-count=20` for prior security decisions
2. Use GitContext.getDecisions(currentPhase) for phase decisions
3. Use GitContext.getEscalations() for pending security escalations
4. Read `.ci/config.json` for security enforcement settings
5. Read `.ci/ARCHITECTURE.md` for trust boundaries
4. Read `.ciagent/config.json` for security enforcement settings
5. Read `.ciagent/ARCHITECTURE.md` for trust boundaries
</project_context>
<execution_flow>
## Step 1: Load Context
Read git security history and .ci/ files. Extract trust boundaries and prior threat classifications.
Read git security history and .ciagent/ files. Extract trust boundaries and prior threat classifications.
## Step 2: STRIDE Analysis
+6 -6
View File
@@ -1,5 +1,5 @@
---
description: Analyzes a recently solved CI problem and produces a structured compound learning document. Compound learnings are committed as ---ci--- blocks, not separate files.
description: Analyzes a recently solved CIAgent problem and produces a structured compound learning document. Compound learnings are committed as ---ci--- blocks, not separate files.
color: "#9370DB"
tools:
read: true
@@ -10,7 +10,7 @@ tools:
---
<role>
You are a CI solution writer. You analyze recently solved problems and produce structured compound learning documents. Compound learnings are committed as `---ci---` blocks, not separate files.
You are a CIAgent solution writer. You analyze recently solved problems and produce structured compound learning documents. Compound learnings are committed as `---ci---` blocks, not separate files.
You use git history to understand the problem context and trace the solution path.
@@ -19,11 +19,11 @@ If the prompt contains a `<files_to_read>` block, you MUST use the Read tool to
</role>
<project_context>
If .ci/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ci/config.json
If .ciagent/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ciagent/config.json
- All commits must include `project: <active_project>` in ---ci--- block
- Branch names are prefixed with <slug>/ in multi-project mode
- .ci/ files are in .ci/<slug>/ subdirectories
- .ciagent/ files are in .ciagent/<slug>/ subdirectories
If single-project mode (projects[] empty or absent), use existing conventions.
Before analyzing, load context from git first:
@@ -31,7 +31,7 @@ Before analyzing, load context from git first:
1. Run `git log --max-count=20` for recent problem-solving history
2. Use GitContext.getLessons() for lessons learned
3. Use GitContext.getCompounds() for existing compound learnings (avoid duplicates)
4. Read `.ci/ARCHITECTURE.md` for component context
4. Read `.ciagent/ARCHITECTURE.md` for component context
</project_context>
<execution_flow>
+8 -8
View File
@@ -1,5 +1,5 @@
---
description: Verifies that a CI phase goal was actually achieved after execution — checks must_haves, requirement coverage, and integration links. Never produces human_needed unless truly unverifiable. Generates automated test scripts for unverifiable items.
description: Verifies that a CIAgent phase goal was actually achieved after execution — checks must_haves, requirement coverage, and integration links. Never produces human_needed unless truly unverifiable. Generates automated test scripts for unverifiable items.
color: "#800080"
tools:
read: true
@@ -9,20 +9,20 @@ tools:
---
<role>
You are a CI verifier. You verify that a phase was completed correctly — not just that code was written, but that the phase goal is genuinely achieved.
You are a CIAgent verifier. You verify that a phase was completed correctly — not just that code was written, but that the phase goal is genuinely achieved.
Unlike learnship, CI verifiers NEVER produce `human_needed` unless something is truly unverifiable. Generate automated test scripts for traditionally human-verified items.
CIAgent verifiers NEVER produce `human_needed` unless something is truly unverifiable. Generate automated test scripts for traditionally human-verified items.
**CRITICAL: Mandatory Initial Read**
If the prompt contains a `<files_to_read>` block, you MUST use the Read tool to load every file listed there before performing any other actions.
</role>
<project_context>
If .ci/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ci/config.json
If .ciagent/config.json has projects[] with length > 0, you are in multi-project mode.
- Read active_project from .ciagent/config.json
- All commits must include `project: <active_project>` in ---ci--- block
- Branch names are prefixed with <slug>/ in multi-project mode
- .ci/ files are in .ci/<slug>/ subdirectories
- .ciagent/ files are in .ciagent/<slug>/ subdirectories
If single-project mode (projects[] empty or absent), use existing conventions.
Before verifying, load context from git first:
@@ -30,8 +30,8 @@ Before verifying, load context from git first:
1. Run `git log --grep="P##" --max-count=50` for all phase commits
2. Use GitContext.reconstructState() for current project state
3. Use GitContext.getRequirementsCoverage() for covered/partial requirements
4. Read `.ci/ROADMAP.md` for phase goal and success criteria
5. Read `.ci/REQUIREMENTS.md` for requirement IDs
4. Read `.ciagent/ROADMAP.md` for phase goal and success criteria
5. Read `.ciagent/REQUIREMENTS.md` for requirement IDs
6. Use GitContext.getCommitsForPhase(currentPhase) for phase commit history
</project_context>
+1 -1
View File
@@ -1 +1 @@
0.3.0
0.5.0
+4 -4
View File
@@ -1,15 +1,15 @@
<dev_context>
Agent output guidance for CI dev mode. Loaded when the orchestrator operates in default (dev) mode.
Agent output guidance for CIAgent dev mode. Loaded when the orchestrator operates in default (dev) mode.
---
## Multi-Project and NFR Versioning
When in multi-project mode (`.ci/config.json` has `projects[]` with length > 0):
When in multi-project mode (`.ciagent/config.json` has `projects[]` with length > 0):
- All commits include `project: <slug>` in `---ci---` block
- Branch names are prefixed with `<slug>/`
- `.ci/` files are in `.ci/<slug>/` subdirectories
- `.ciagent/` files are in `.ciagent/<slug>/` subdirectories
- Project scoping applies to all operations
NFR milestone versioning:
@@ -27,7 +27,7 @@ NFR milestone versioning:
- Working code that compiles and passes tests
- Minimal diff — change only what is necessary
- Commit with `---ci---` blocks for all CI-generated work
- Commit with `---ci---` blocks for all CIAgent-generated work
- Flag side effects or breaking changes immediately
- Surface the next actionable step at the end of every response
+3 -3
View File
@@ -1,6 +1,6 @@
<research_context>
Agent output guidance for CI research mode. Loaded when the orchestrator operates in research mode.
Agent output guidance for CIAgent research mode. Loaded when the orchestrator operates in research mode.
---
@@ -21,12 +21,12 @@ Agent output guidance for CI research mode. Loaded when the orchestrator operate
## Research Output
Research is intermediate work product — conclusions update `.ci/<slug>/` static files (ARCHITECTURE.md, PROJECT.md) and contain:
Research is intermediate work product — conclusions update `.ciagent/<slug>/` static files (ARCHITECTURE.md, PROJECT.md) and contain:
- Key findings in the commit body
- Decisions in the `---ci---` block
- Confidence levels for each recommendation
In multi-project mode, research conclusions update files in `.ci/<slug>/` subdirectories, not the root `.ci/` directory.
In multi-project mode, research conclusions update files in `.ciagent/<slug>/` subdirectories, not the root `.ciagent/` directory.
## Verbosity
+2 -2
View File
@@ -1,12 +1,12 @@
<review_context>
Agent output guidance for CI review mode. Loaded when the orchestrator operates in review mode.
Agent output guidance for CIAgent review mode. Loaded when the orchestrator operates in review mode.
---
## Multi-Project Awareness
When in multi-project mode (`.ci/config.json` has `projects[]` with length > 0):
When in multi-project mode (`.ciagent/config.json` has `projects[]` with length > 0):
- All reviews are scoped to the active project
- Commits include `project: <slug>` in `---ci---` blocks
- Branch names are prefixed with `<slug>/`
+108 -49
View File
@@ -1,6 +1,6 @@
<branch_strategy>
Canonical branch naming and lifecycle conventions for CI. Branches encode project structure — merged branches indicate completed work, active branches indicate work in progress.
Canonical branch naming and lifecycle conventions for CIAgent. Branches encode project structure — merged branches indicate completed work, active branches indicate work in progress.
---
@@ -23,7 +23,7 @@ Canonical branch naming and lifecycle conventions for CI. Branches encode projec
**Lifecycle:**
1. Created at phase start by `GitBranch.createPhaseBranch()`
2. All task commits for the phase land on this branch
3. Merged to main (squash) on phase completion
3. Merged to their milestone branch (or main if no milestone branch) on phase completion
4. Merged = phase complete, active = phase in progress, absent = not started
### Milestone Branches
@@ -42,14 +42,33 @@ Canonical branch naming and lifecycle conventions for CI. Branches encode projec
**Lifecycle:**
1. Created at first phase of milestone by `GitBranch.createMilestoneBranch()`
2. Spans multiple phases within the same milestone
3. Merged to main on milestone completion
4. Merged = milestone complete, active = milestone in progress
3. All phase branches merge into this branch on completion
4. Merged to main on milestone completion
5. Merged = milestone complete, active = milestone in progress
### Hotfix Branches
**Format:** `hotfix/description`
Created for urgent fixes outside the normal phase flow. Merged directly to main.
Created for urgent fixes outside the normal phase flow. Merged directly to main (exception to hierarchy).
## Branch Hierarchy (Enforced)
```text
main ─── milestone/vX.X-slug ─── phase/NN-slug
Rules:
- Phase branches MUST merge into their milestone branch first
- Milestone branches merge into main only after all phase branches are merged
- If no milestone branch exists, phases may merge directly to main
- Hotfix branches merge directly to main (exception)
```
**Validation** is enforced in `GitBranch.mergePhaseBranch()` and `createShipCommand()`:
- Phase → main: rejected if milestone branch exists for this milestone
- Phase → milestone: allowed
- Milestone → main: allowed only after all phase branches are merged
- Hotfix → main: allowed
## Branch Status Inference
@@ -69,71 +88,101 @@ const branches = gitContext.getBranches();
## Merge Strategy
Default: **squash merge** into main.
Default: **squash merge**.
Phase branches squash-merge into their milestone branch. Milestone branches squash-merge into main. This keeps main clean while preserving full development history in the phase branch.
```typescript
gitBranch.mergePhaseBranch("phase/01-git-native-architecture", "main", true);
// Phase → milestone (enforced when milestone branch exists)
gitBranch.mergePhaseBranch("phase/01-git-native-architecture", "milestone/v0.5-honest-baseline", true);
// Milestone → main (after all phases merged)
gitBranch.mergeMilestoneBranch("milestone/v0.5-honest-baseline", "main", true);
```
Squash merge keeps main clean while preserving full development history in the phase branch. Phase branches can be deleted after merge if desired.
Phase branches can be deleted after merge if desired.
## Versioning and Releases
**Every merge to main creates a release. No exceptions.** Versioning maps to project structure:
**Every merge to main creates a release. No exceptions.** Versioning follows a 3-tier model based on milestone type:
| Version Part | When | Example |
|-------------|------|---------|
| **Major** (X.0.0) | Project-level refactor or schema change | `v1.0.0` |
| **Minor** (0.X.0) | Every milestone completion | `v0.3.0` |
| **Patch** (0.0.X) | Every phase completion | `v0.2.3` |
### 3-Tier Versioning Model
### Phase completion (patch release)
| Milestone Type | Condition | Phase release | Milestone release |
|---------------|-----------|---------------|-------------------|
| **NFR** | All phases: fix/chore/docs/perf/refactor/test | Patch (`vX.Y.Z`) | None |
| **Feature** | Any phase is `feat`, no schema break | Patch (`vX.Y.Z`) | Minor — `vX.(Y+1).0` |
| **Schema-breaking** | Refactor/schema break/new direction | Minor — `vX.(Y+N).0` per phase | Major — `v(X+1).0.0` |
**IMPORTANT:** Milestone tags are always the NEXT version, never the base:
- Feature: patches v0.5.1v0.5.5 → milestone tag is v0.6.0 (NOT v0.5.0)
- Schema-breaking: minors v0.3.0, v0.4.0, v0.5.0 → milestone tag is v1.0.0
- NFR: no milestone tag — the milestone is implicit from the patch sequence
Determine milestone type via `getMilestoneType()` which returns `"nfr" | "feature" | "schema-breaking"`.
### Phase completion
**NFR/Feature (patch release):**
```bash
git checkout main
git merge --squash phase/01-git-native-architecture
git commit -m "docs(P01): complete git-native-architecture phase"
git tag -a v0.2.1 -m "v0.2.1: git-native-architecture"
git checkout milestone/v0.5-honest-baseline # or main if no milestone branch
git merge --squash phase/01-quick-wins
git commit -m "docs(P01): complete quick-wins phase"
git tag -a v0.5.1 -m "v0.5.1: quick-wins"
git push origin main --tags
# Create Gitea release for v0.2.1
# Create Gitea release for v0.5.1
```
Phase number within the milestone determines the patch version (1st phase = .1, 2nd phase = .2, etc.)
### Milestone completion (minor release)
**Schema-breaking (minor release per phase):**
```bash
git checkout main
git merge --squash milestone/v0.2-git-native
git commit -m "docs(milestone): complete git-native"
git tag -a v0.2.0 -m "v0.2.0: git-native"
git checkout milestone/v0.5-schema-rewrite
git merge --squash phase/01-core-refactor
git commit -m "docs(P01): complete core-refactor phase"
git tag -a v0.5.0 -m "v0.5.0: core-refactor"
git push origin main --tags
# Create Gitea release for v0.2.0 with full milestone summary
# Create Gitea release for v0.5.0
```
### Major release
Each schema-breaking phase bumps the minor. 1st phase = next available minor, 2nd = minor+1, etc.
When the project undergoes a schema-breaking change (e.g., switching from file-based to git-native architecture), bump the major version. Major releases follow the same merge → tag → release flow.
### Milestone completion
## NFR Milestone Versioning
**Feature (minor release):**
```bash
# All phases already merged into milestone branch
git checkout main
git merge --squash milestone/v0.5-honest-baseline
git commit -m "docs(milestone): complete honest-baseline"
git tag -a v0.6.0 -m "v0.6.0: honest-baseline" # NEXT minor, NOT v0.5.0
git push origin main --tags
# Create Gitea release for v0.6.0 with full milestone summary
```
NFR milestones and feature milestones follow different versioning rules:
**Schema-breaking (major release):**
```bash
# All phases already merged into milestone branch
git checkout main
git merge --squash milestone/v0.5-schema-rewrite
git commit -m "docs(milestone): complete schema-rewrite"
git tag -a v1.0.0 -m "v1.0.0: schema-rewrite" # NEXT major
git push origin main --tags
# Create Gitea release for v1.0.0 with full milestone summary
```
**NFR milestones** — all phases are `fix`, `chore`, `docs`, `perf`, `refactor`, or `test`:
- Each phase gets a progressive patch version (v0.1.1, v0.1.2, v0.1.3)
- No separate milestone tag — the milestone is implicit from the patch sequence
- Example: milestone v0.1 with phases P01 (chore), P02 (test), P03 (perf) → v0.1.1, v0.1.2, v0.1.3
**NFR milestones produce no milestone tag.** The last phase's patch version is the final release.
**Feature milestones** — any phase is `feat`:
- Each phase gets a progressive patch version
- On milestone completion, tag a minor version (e.g., v0.2.0)
- Example: milestone v0.2 with phases P01 (feat), P02 (feat), P03 (fix) → v0.2.1, v0.2.2, v0.2.3 + milestone tag v0.3.0
### Version Validation
Determine milestone type by checking `isNfrMilestone()` which inspects all phase commit types within the milestone.
Before creating any tag:
1. Tag must be strictly greater than all existing tags on the same major.minor line
2. Milestone completion tag must be next minor (feature) or next major (schema-breaking)
3. NEVER create a tag that is semantically below existing phase tags
## Multi-Project Branch Naming
When operating in multi-project mode (`.ci/config.json` has `projects[]` with length > 0):
When operating in multi-project mode (`.ciagent/config.json` has `projects[]` with length > 0):
| Branch Type | Format | Example |
|-------------|--------|---------|
@@ -155,7 +204,7 @@ const milestones = gitBranch.listMilestones();
## Branch Creation Rules
1. Always create phase branches from main (or the current milestone branch)
1. Always create phase branches from the current milestone branch (or main if no milestone branch exists)
2. Never create a branch for a completed phase — it should already be merged
3. Milestone branches span phases — don't create one per phase
4. Use `GitBranch.createPhaseBranch()` to ensure consistent naming
@@ -164,25 +213,35 @@ const milestones = gitBranch.listMilestones();
## Working with Phase Branches
```bash
# Create a phase branch
git checkout -b phase/01-git-native-architecture
# Create a milestone branch first
git checkout main
git checkout -b milestone/v0.5-honest-baseline
# Create a phase branch from the milestone
git checkout -b phase/01-quick-wins
# Commit work with ---ci--- blocks
git commit -m "feat(P01-01-01): implement commit parser
---ci---
phase: 1
milestone: v0.2
milestone: v0.5
plan: 01-01
task: 01-01-01
status: execute
---/ci---"
# Merge on completion
# Merge phase into milestone on completion
git checkout milestone/v0.5-honest-baseline
git merge --squash phase/01-quick-wins
git commit -m "docs(P01): complete quick-wins phase"
git tag -a v0.5.1 -m "v0.5.1: quick-wins"
# After all phases, merge milestone into main
git checkout main
git merge --squash phase/01-git-native-architecture
git commit -m "docs(P01): complete git-native-architecture phase"
git tag -a v0.2.1 -m "v0.2.1: git-native-architecture"
git merge --squash milestone/v0.5-honest-baseline
git commit -m "docs(milestone): complete honest-baseline"
git tag -a v0.6.0 -m "v0.6.0: honest-baseline"
git push origin main --tags
```
+22 -22
View File
@@ -1,15 +1,15 @@
<ci_files_discipline>
How CI manages the `.ci/` directory — long-lived reference documents only. Dynamic state lives in the git log via `---ci---` YAML blocks, not in files.
How CIAgent manages the `.ciagent/` directory — long-lived reference documents only. Dynamic state lives in the git log via `---ci---` YAML blocks, not in files.
---
## Multi-Project Directory Structure
In multi-project mode, `.ci/` uses subdirectories per project:
In multi-project mode, `.ciagent/` uses subdirectories per project:
```
.ci/
.ciagent/
config.json # Registry with projects[] and active_project
<project-slug>/
PROJECT.md
@@ -18,11 +18,11 @@ In multi-project mode, `.ci/` uses subdirectories per project:
REQUIREMENTS.md
```
`.ci/config.json` serves as the registry with `projects[]` (array of project entries) and `active_project` (slug of the currently active project).
`.ciagent/config.json` serves as the registry with `projects[]` (array of project entries) and `active_project` (slug of the currently active project).
**Backward compatibility:** if `.ci/` has flat files (PROJECT.md, ARCHITECTURE.md, etc.) and no project subdirectories, auto-migrate by creating `<default-slug>/` and moving files into it, then updating `config.json` with a single `projects[]` entry.
**Backward compatibility:** if `.ciagent/` has flat files (PROJECT.md, ARCHITECTURE.md, etc.) and no project subdirectories, auto-migrate by creating `<default-slug>/` and moving files into it, then updating `config.json` with a single `projects[]` entry.
## What Lives in `.ci/`
## What Lives in `.ciagent/`
| File | Purpose | Update Frequency |
|------|---------|-------------------|
@@ -32,23 +32,23 @@ In multi-project mode, `.ci/` uses subdirectories per project:
| `<slug>/ROADMAP.md` | Phase breakdown, milestone mapping, success criteria per project | Low (phase transitions) |
| `<slug>/REQUIREMENTS.md` | v1/v2 requirements with REQ-IDs, out of scope, traceability per project | Low (requirement changes) |
## What Does NOT Live in `.ci/`
## What Does NOT Live in `.ciagent/`
These were removed in v0.2.0 and now live in the git log:
| Previous Location | Now In | Access Method |
|-------------------|--------|---------------|
| `.ci/audit/decisions.json` | `---ci---` decisions block | `GitContext.getDecisions()` |
| `.ci/audit/escalations.json` | `---ci---` escalations block | `GitContext.getEscalations()` |
| `.ci/audit/lessons.json` | `---ci---` lessons block | `GitContext.getLessons()` |
| `.planning/` directory | Git log + branches | `GitContext.reconstructState()` |
| `.ciagent/audit/decisions.json` | `---ci---` decisions block | `GitContext.getDecisions()` |
| `.ciagent/audit/escalations.json` | `---ci---` escalations block | `GitContext.getEscalations()` |
| `.ciagent/audit/lessons.json` | `---ci---` lessons block | `GitContext.getLessons()` |
| `.planning/` directory (removed) | Git log + branches | `GitContext.reconstructState()` |
## CiFiles API
| Method | Returns | Purpose |
|--------|---------|---------|
| `ensureCIDir()` | void | Create `.ci/` if it doesn't exist |
| `isInitialized()` | boolean | Check if `.ci/config.json` exists |
| `ensureCIDir()` | void | Create `.ciagent/` if it doesn't exist |
| `isInitialized()` | boolean | Check if `.ciagent/config.json` exists |
| `readProjectMd()` | ProjectMd \| null | Read project definition |
| `writeProjectMd(project, reason)` | void | Write project definition |
| `readRoadmapMd()` | RoadmapMd \| null | Read roadmap |
@@ -66,7 +66,7 @@ These were removed in v0.2.0 and now live in the git log:
2. **Phase boundaries** — Major updates happen at phase transitions, not during task execution.
3. **Requirements status** — Use `updateRequirementStatus()` for single-status changes, not full rewrites.
4. **Phase status** — Use `updatePhaseStatus()` for phase transitions, not full roadmap rewrites.
5. **Commit after write** — Every `.ci/` file change should be committed immediately with a `---ci---` block.
5. **Commit after write** — Every `.ciagent/` file change should be committed immediately with a `---ci---` block.
## Update Triggers
@@ -157,21 +157,21 @@ interface ArchitectureMd {
## Research and .ci/ File Updates
Research is intermediate work product. Conclusions from research update `.ci/` static files:
Research is intermediate work product. Conclusions from research update `.ciagent/` static files:
- Key findings go in the commit body
- Decisions go in `---ci---` blocks
- Conclusions that change project structure update the appropriate `.ci/<slug>/` files (ARCHITECTURE.md, PROJECT.md, etc.)
- Conclusions that change project structure update the appropriate `.ciagent/<slug>/` files (ARCHITECTURE.md, PROJECT.md, etc.)
Research commits are not final artifacts — they feed into planning and roadmap updates.
## Anti-Patterns
- Never write dynamic state (decisions, escalations, lessons) to `.ci/` files
- Never update `.ci/` files during task execution — update at phase boundaries
- Never write dynamic state (decisions, escalations, lessons) to `.ciagent/` files
- Never update `.ciagent/` files during task execution — update at phase boundaries
- Never skip the `reason` parameter when writing PROJECT.md
- Never commit `.ci/` changes without a `---ci---` block
- Never create new files in `.ci/` without updating this reference document
- Never store counters, timestamps, or session state in `.ci/` files
- Never store research conclusions only in commits — update `.ci/<slug>/` static files with findings
- Never commit `.ciagent/` changes without a `---ci---` block
- Never create new files in `.ciagent/` without updating this reference document
- Never store counters, timestamps, or session state in `.ciagent/` files
- Never store research conclusions only in commits — update `.ciagent/<slug>/` static files with findings
</ci_files_discipline>
+5 -5
View File
@@ -1,6 +1,6 @@
<commit_schema>
Canonical `---ci---` YAML block schema for CI commits. Every CI-generated commit contains a structured YAML block that enables full project state reconstruction from the git log alone.
Canonical `---ci---` YAML block schema for CIAgent commits. Every CIAgent-generated commit contains a structured YAML block that enables full project state reconstruction from the git log alone.
---
@@ -39,7 +39,7 @@ compound: # optional
---/ci---
```
The `project` field is required when in multi-project mode (`.ci/config.json` has `projects[]` with length > 0). In single-project mode, it is optional.
The `project` field is required when in multi-project mode (`.ciagent/config.json` has `projects[]` with length > 0). In single-project mode, it is optional.
Example with project field:
@@ -104,7 +104,7 @@ The `CommitBuilder` class provides typed constructors:
## Reconstruction Guarantee
An agent with access to only commit messages (no code, no diffs, no .ci/ files) can reconstruct:
An agent with access to only commit messages (no code, no diffs, no .ciagent/ files) can reconstruct:
1. **Current phase and milestone** — from the latest commit's `phase` and `milestone` fields
2. **Pipeline stage** — from the latest commit's `status` field
@@ -117,8 +117,8 @@ An agent with access to only commit messages (no code, no diffs, no .ci/ files)
## Anti-Patterns
- Never put CI metadata in code comments — it belongs in commit messages
- Never omit the `---ci---` block from a CI-generated commit
- Never put CIAgent metadata in code comments — it belongs in commit messages
- Never omit the `---ci---` block from a CIAgent-generated commit
- Never store decisions, escalations, or lessons in files — commit them
- Never use a non-standard commit type — use the 14 types above
- Never put freeform text inside the YAML block — use the structured fields
+2 -2
View File
@@ -1,6 +1,6 @@
<decision_engine>
How CI makes decisions and commits them as git artifacts. The DecisionEngine uses bounded rationality with confidence thresholds to auto-decide or escalate.
How CIAgent makes decisions and commits them as git artifacts. The DecisionEngine uses bounded rationality with confidence thresholds to auto-decide or escalate.
---
@@ -99,7 +99,7 @@ Decisions can be project-scoped via the `project` field in `---ci---` blocks. Wh
## Anti-Patterns
- Never write decisions to a `.ci/audit/` file — commit them
- Never write decisions to a `.ciagent/audit/` file — commit them
- Never skip recording a decision, even high-confidence ones
- Never make a decision without listing alternatives
- Never override the confidence threshold without explicit configuration
@@ -1,6 +1,6 @@
<git_context_loading>
How CI agents load project context. The git log IS the project memory — a CI agent's first impulse to gather context is `git log` + `git branch`, not file reads.
How CIAgent agents load project context. The git log IS the project memory — a CIAgent agent's first impulse to gather context is `git log` + `git branch`, not file reads.
---
@@ -8,7 +8,7 @@ How CI agents load project context. The git log IS the project memory — a CI a
**Read the log first, files second.**
The git log contains every decision, escalation, lesson, and compound learning through structured `---ci---` YAML blocks. Files in `.ci/` are long-lived reference documents (PROJECT.md, ARCHITECTURE.md, ROADMAP.md, REQUIREMENTS.md, config.json) that change infrequently.
The git log contains every decision, escalation, lesson, and compound learning through structured `---ci---` YAML blocks. Files in `.ciagent/` are long-lived reference documents (PROJECT.md, ARCHITECTURE.md, ROADMAP.md, REQUIREMENTS.md, config.json) that change infrequently.
## Context Loading Sequence
@@ -19,7 +19,7 @@ The git log contains every decision, escalation, lesson, and compound learning t
5. **Requirements coverage**`GitContext.getRequirementsCoverage()` for covered/partial
6. **Lessons scan**`GitContext.getLessons()` for all learned lessons
7. **Compound learnings**`GitContext.getCompounds()` for cross-phase patterns
8. **File reads** — Only now read `.ci/` files (PROJECT.md, ARCHITECTURE.md, etc.)
8. **File reads** — Only now read `.ciagent/` files (PROJECT.md, ARCHITECTURE.md, etc.)
## GitContext API
@@ -74,19 +74,19 @@ interface ParsedCiCommit {
}
```
Commits without `---ci---` blocks have `ci: null` — these are treated as non-CI commits (e.g., manual edits by the developer).
Commits without `---ci---` blocks have `ci: null` — these are treated as non-CIAgent commits (e.g., manual edits by the developer).
## Phase Context Reset
Between phases, all state is committed to git, then the next phase starts with fresh context from git log — not accumulated conversation history.
**On opencode (subagent support):** spawn a fresh agent for the next phase. The new agent loads context from git log and `.ci/` files only.
**On opencode (subagent support):** spawn a fresh agent for the next phase. The new agent loads context from git log and `.ciagent/` files only.
**On platforms without subagents:** simulated reset — re-read git context from scratch, ignore prior conversation history. Treat the phase boundary as a hard context boundary.
**Checkpoint sequence:**
1. Commit all work from the current phase
2. Update `.ci/` files (ROADMAP.md phase status, REQUIREMENTS.md requirement statuses)
2. Update `.ciagent/` files (ROADMAP.md phase status, REQUIREMENTS.md requirement statuses)
3. Verify `GitContext.reconstructState()` matches expected state
4. Reset context — next phase begins fresh
@@ -112,11 +112,11 @@ When context is limited:
2. `getDecisions(currentPhase)` — current phase decisions only
3. `getRequirementsCoverage()` — aggregate view
4. Skip lessons/compounds unless specifically needed
5. Read `.ci/ROADMAP.md` instead of scanning all phase branches
5. Read `.ciagent/ROADMAP.md` instead of scanning all phase branches
## What NOT to Do
- Never read `.ci/` files before checking the git log
- Never read `.ciagent/` files before checking the git log
- Never parse commit messages manually — use `CommitParser.parseCommitMessage()`
- Never assume the latest commit reflects the current state — check branches
- Never reconstruct state from files when git data is available
+17 -17
View File
@@ -1,18 +1,18 @@
---
description: Audit CI project health — reconstruct state from git log, verify .ci/ files match codebase, check for stale references
description: Audit CIAgent project health — reconstruct state from git log, verify .ciagent/ files match codebase, check for stale references
---
# CI Audit
# CIAgent Audit
Audit the CI project for health issues. Verifies that git log state matches .ci/ files and that the project can be fully reconstructed from commit messages alone.
Audit the CIAgent project for health issues. Verifies that git log state matches .ciagent/ files and that the project can be fully reconstructed from commit messages alone.
**Usage:** `ci-audit`
**Usage:** `ciagent-audit`
## Step 0: Confirm Active Project
Check `ci listProjects()` or read `.ci/config.json` to determine if multi-project mode is active.
Check `ci listProjects()` or read `.ciagent/config.json` to determine if multi-project mode is active.
If `.ci/config.json` has `projects[]` with length > 0:
If `.ciagent/config.json` has `projects[]` with length > 0:
- Confirm `active_project` is correct for this audit
- If not, set it with `ci setActiveProject(<slug>)`
- Scope audit queries to the active project
@@ -26,16 +26,16 @@ Attempt to reconstruct the full project state from commit messages only:
1. Parse all `---ci---` blocks from git log
2. Reconstruct: current phase, milestone, stage, decisions, escalations, requirements, lessons, compounds
3. Compare reconstructed state with `.ci/` file contents
3. Compare reconstructed state with `.ciagent/` file contents
## Step 2: Check .ci/ File Discipline
For each .ci/ file:
- `.ci/config.json`: valid JSON, required fields present
- `.ci/PROJECT.md`: has required sections (What This Is, Requirements, Constraints, Key Decisions)
- `.ci/ROADMAP.md`: phases match git branches (merged = complete, active = in progress)
- `.ci/REQUIREMENTS.md`: traceability matrix is complete
- `.ci/ARCHITECTURE.md`: components match actual code structure
For each .ciagent/ file:
- `.ciagent/config.json`: valid JSON, required fields present
- `.ciagent/PROJECT.md`: has required sections (What This Is, Requirements, Constraints, Key Decisions)
- `.ciagent/ROADMAP.md`: phases match git branches (merged = complete, active = in progress)
- `.ciagent/REQUIREMENTS.md`: traceability matrix is complete
- `.ciagent/ARCHITECTURE.md`: components match actual code structure
## Step 3: Check Branch Hygiene
@@ -46,20 +46,20 @@ For each .ci/ file:
## Step 4: Check Commit Discipline
- Every CI-generated commit should have a `---ci---` block
- No stale decisions (decisions from >50 commits ago that are still in `.ci/` but not reflected in code)
- No stale decisions (decisions from >50 commits ago that are still in `.ciagent/` but not reflected in code)
- No unresolved escalations older than the escalation timeout
## Step 5: Display Report
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CI ► AUDIT REPORT
CIAgent ► AUDIT REPORT
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Reconstruction: [PASS/FAIL] — [details]
.ci/ Files: [N] checked, [issues]
.ciagent/ Files: [N] checked, [issues]
Branches: [N] phase, [N] milestone, [issues]
Commits: [N] CI commits, [N] without ---ci--- blocks
Commits: [N] CIAgent commits, [N] without ---ci--- blocks
[If issues found:]
Issues:
+9 -9
View File
@@ -1,18 +1,18 @@
---
description: Clarify CI project ambiguities — generate questions, accept defaults at full autonomy, present at supervised/guided
description: Clarify CIAgent project ambiguities — generate questions, accept defaults at full autonomy, present at supervised/guided
---
# CI Clarify
# CIAgent Clarify
Run the clarification phase for the current CI project. Generate questions about ambiguities, accept defaults automatically at full autonomy, or present to the user at supervised/guided levels.
Run the clarification phase for the current CIAgent project. Generate questions about ambiguities, accept defaults automatically at full autonomy, or present to the user at supervised/guided levels.
**Usage:** `ci-clarify [phase_number]`
**Usage:** `ciagent-clarify [phase_number]`
## Step 0: Confirm Active Project
Check `ci listProjects()` or read `.ci/config.json` to determine if multi-project mode is active.
Check `ci listProjects()` or read `.ciagent/config.json` to determine if multi-project mode is active.
If `.ci/config.json` has `projects[]` with length > 0:
If `.ciagent/config.json` has `projects[]` with length > 0:
- Confirm `active_project` is correct for this clarification
- If not, set it with `ci setActiveProject(<slug>)`
- All commit messages must include `project: <slug>` in `---ci---` block
@@ -26,7 +26,7 @@ git log --max-count=20
git branch -a
```
Read `.ci/PROJECT.md` and `.ci/REQUIREMENTS.md` for the specification.
Read `.ciagent/PROJECT.md` and `.ciagent/REQUIREMENTS.md` for the specification.
## Step 2: Identify Ambiguities
@@ -75,8 +75,8 @@ decisions:
## Step 6: Update .ci/ Files
Update `.ci/PROJECT.md` with clarified requirements.
Update `.ci/REQUIREMENTS.md` with refined requirements.
Update `.ciagent/PROJECT.md` with clarified requirements.
Update `.ciagent/REQUIREMENTS.md` with refined requirements.
## Step 7: Report
+5 -5
View File
@@ -1,18 +1,18 @@
---
description: Systematic CI debugging with git context — triage, diagnose root cause, auto-fix or escalate
description: Systematic CIAgent debugging with git context — triage, diagnose root cause, auto-fix or escalate
---
# CI Debug
# CIAgent Debug
Systematic debugging workflow: triage → root cause diagnosis → auto-fix or escalate. Uses git history to find recent changes that may have caused the bug.
**Usage:** `ci-debug [description]`
**Usage:** `ciagent-debug [description]`
## Step 0: Confirm Active Project
Check `ci listProjects()` or read `.ci/config.json` to determine if multi-project mode is active.
Check `ci listProjects()` or read `.ciagent/config.json` to determine if multi-project mode is active.
If `.ci/config.json` has `projects[]` with length > 0:
If `.ciagent/config.json` has `projects[]` with length > 0:
- Confirm `active_project` is correct for this debug session
- If not, set it with `ci setActiveProject(<slug>)`
- Scope debugging to the active project
+18 -18
View File
@@ -1,21 +1,21 @@
---
description: Initialize a new CI project — specification → clarify → create .ci/ reference files → initial commit
description: Initialize a new CIAgent project — specification → clarify → create .ciagent/ reference files → initial commit
---
# CI Init
# CIAgent Init
Initialize a new CI project with specification parsing, clarification, and .ci/ reference file creation.
Initialize a new CIAgent project with specification parsing, clarification, and .ciagent/ reference file creation.
**Usage:** `ci-init [description]`
**Usage:** `ciagent-init [description]`
## Step 0: Confirm Active Project
Check `ci listProjects()` or read `.ci/config.json` to determine if multi-project mode is active.
Check `ci listProjects()` or read `.ciagent/config.json` to determine if multi-project mode is active.
If `.ci/config.json` has `projects[]` with length > 0:
If `.ciagent/config.json` has `projects[]` with length > 0:
- Confirm `active_project` is correct for this initialization
- If not, set it with `ci setActiveProject(<slug>)`
- All subsequent operations use `.ci/<slug>/` subdirectories
- All subsequent operations use `.ciagent/<slug>/` subdirectories
- All commit messages must include `project: <slug>` in `---ci---` block
If single-project mode: proceed with existing conventions.
@@ -29,12 +29,12 @@ Verify git is initialized:
If NO_GIT: `git init`
Check if `.ci/config.json` already exists:
Check if `.ciagent/config.json` already exists:
```bash
[ -f .ci/config.json ] && echo "ALREADY_INITIALIZED" || echo "NEW"
[ -f .ciagent/config.json ] && echo "ALREADY_INITIALIZED" || echo "NEW"
```
If ALREADY_INITIALIZED: stop. Use `ci-status` to see project state.
If ALREADY_INITIALIZED: stop. Use `ciagent-status` to see project state.
## Step 2: Parse Specification
@@ -59,15 +59,15 @@ Analyze the specification for ambiguities. For each ambiguity:
Record decisions in the `---ci---` block of the init commit.
## Step 4: Create .ci/ Files
## Step 4: Create .ciagent/ Files
Use CiFiles to create the project structure:
1. `.ci/config.json` — registry with `projects[]` and `active_project`
2. `.ci/<slug>/PROJECT.md` — vision, requirements, constraints, key decisions (or `.ci/PROJECT.md` in single-project mode)
3. `.ci/<slug>/ARCHITECTURE.md` — system architecture (initial, may be incomplete)
4. `.ci/<slug>/ROADMAP.md` — phase breakdown (to be refined by roadmapper)
5. `.ci/<slug>/REQUIREMENTS.md` — formal requirements with REQ-IDs
1. `.ciagent/config.json` — registry with `projects[]` and `active_project`
2. `.ciagent/<slug>/PROJECT.md` — vision, requirements, constraints, key decisions (or `.ciagent/PROJECT.md` in single-project mode)
3. `.ciagent/<slug>/ARCHITECTURE.md` — system architecture (initial, may be incomplete)
4. `.ciagent/<slug>/ROADMAP.md` — phase breakdown (to be refined by roadmapper)
5. `.ciagent/<slug>/REQUIREMENTS.md` — formal requirements with REQ-IDs
`initCI()` accepts `projectSlug` and `projectName` parameters for multi-project initialization.
@@ -105,6 +105,6 @@ Include `project: <slug>` in the `---ci---` block when in multi-project mode.
## Step 7: Done
Report project initialized, .ci/ files created, initial branch created.
Report project initialized, .ciagent/ files created, initial branch created.
Next: `ci-run` to execute the pipeline, or `ci-quick` for ad-hoc tasks.
Next: `ciagent-run` to execute the pipeline, or `ciagent-quick` for ad-hoc tasks.
+7 -7
View File
@@ -1,12 +1,12 @@
---
description: Execute an ad-hoc CI task with full agentic guarantees — git context, ---ci--- commits, optional research and verification
description: Execute an ad-hoc CIAgent task with full agentic guarantees — git context, ---ci--- commits, optional research and verification
---
# CI Quick
# CIAgent Quick
Execute small, ad-hoc tasks with CI guarantees: git context loading, `---ci---` commit blocks, optional research and verification.
Execute small, ad-hoc tasks with CIAgent guarantees: git context loading, `---ci---` commit blocks, optional research and verification.
**Usage:** `ci-quick [description]`
**Usage:** `ciagent-quick [description]`
**Flags:**
- `--research` — spawn a focused research agent before execution
@@ -15,9 +15,9 @@ Execute small, ad-hoc tasks with CI guarantees: git context loading, `---ci---`
## Step 0: Confirm Active Project
Check `ci listProjects()` or read `.ci/config.json` to determine if multi-project mode is active.
Check `ci listProjects()` or read `.ciagent/config.json` to determine if multi-project mode is active.
If `.ci/config.json` has `projects[]` with length > 0:
If `.ciagent/config.json` has `projects[]` with length > 0:
- Confirm `active_project` is correct
- If not, set it with `ci setActiveProject(<slug>)`
- All commit messages must include `project: <slug>` in `---ci---` block
@@ -37,7 +37,7 @@ git branch -a
Use GitContext.reconstructState() to understand project state.
Check that `.ci/config.json` exists. If missing: stop, run `ci-init` first.
Check that `.ciagent/config.json` exists. If missing: stop, run `ciagent-init` first.
## Step 3: Research (only with `--research` or `--full`)
+5 -5
View File
@@ -1,18 +1,18 @@
---
description: Review CI code changes with multi-persona analysis — auto-apply P0 fixes, flag P1+ for post-hoc review
description: Review CIAgent code changes with multi-persona analysis — auto-apply P0 fixes, flag P1+ for post-hoc review
---
# CI Review
# CIAgent Review
Multi-persona code review workflow. Reviews changes in the current phase, auto-applies P0 fixes, and flags P1+ issues for post-hoc review.
**Usage:** `ci-review [phase_number]`
**Usage:** `ciagent-review [phase_number]`
## Step 0: Confirm Active Project
Check `ci listProjects()` or read `.ci/config.json` to determine if multi-project mode is active.
Check `ci listProjects()` or read `.ciagent/config.json` to determine if multi-project mode is active.
If `.ci/config.json` has `projects[]` with length > 0:
If `.ciagent/config.json` has `projects[]` with length > 0:
- Confirm `active_project` is correct for this review
- If not, set it with `ci setActiveProject(<slug>)`
- All commit messages must include `project: <slug>` in `---ci---` block
+8 -8
View File
@@ -1,20 +1,20 @@
---
description: Rollback CI phase — revert the last phase or specified phase by resetting to its pre-phase state
description: Rollback CIAgent phase — revert the last phase or specified phase by resetting to its pre-phase state
---
# CI Rollback
# CIAgent Rollback
Rollback a CI phase by reverting to the state before the phase started. Uses git to find the exact commit to reset to.
Rollback a CIAgent phase by reverting to the state before the phase started. Uses git to find the exact commit to reset to.
**Usage:** `ci-rollback [phase_number]`
**Usage:** `ciagent-rollback [phase_number]`
If no phase specified, rolls back the current (most recent) phase.
## Step 0: Confirm Active Project
Check `ci listProjects()` or read `.ci/config.json` to determine if multi-project mode is active.
Check `ci listProjects()` or read `.ciagent/config.json` to determine if multi-project mode is active.
If `.ci/config.json` has `projects[]` with length > 0:
If `.ciagent/config.json` has `projects[]` with length > 0:
- Confirm `active_project` is correct for this rollback
- If not, set it with `ci setActiveProject(<slug>)`
- Identify project-scoped branches (prefixed with `<slug>/`)
@@ -71,8 +71,8 @@ git reset --hard [rollback_point]
## Step 5: Update State
- Delete the phase branch (if not already removed)
- Update `.ci/REQUIREMENTS.md` — mark phase requirements as blocked
- Update `.ci/ROADMAP.md` — mark phase as not_started
- Update `.ciagent/REQUIREMENTS.md` — mark phase requirements as blocked
- Update `.ciagent/ROADMAP.md` — mark phase as not_started
Commit the rollback:
+14 -14
View File
@@ -1,20 +1,20 @@
---
description: Execute the full CI pipeline — research → plan → execute → verify → complete for the current or specified phase
description: Execute the full CIAgent pipeline — research → plan → execute → verify → complete for the current or specified phase
---
# CI Run
# CIAgent Run
Execute the full CI pipeline from the current stage to completion. The orchestrator iterates through stages and delegates to specialized agents.
Execute the full CIAgent pipeline from the current stage to completion. The orchestrator iterates through stages and delegates to specialized agents.
**Usage:** `ci-run [phase_number]`
**Usage:** `ciagent-run [phase_number]`
If no phase number specified, continues from the current phase (detected from git log).
## Step 0: Confirm Active Project
Check `ci listProjects()` or read `.ci/config.json` to determine if multi-project mode is active.
Check `ci listProjects()` or read `.ciagent/config.json` to determine if multi-project mode is active.
If `.ci/config.json` has `projects[]` with length > 0:
If `.ciagent/config.json` has `projects[]` with length > 0:
- Confirm `active_project` is correct for this run
- If not, set it with `ci setActiveProject(<slug>)`
- All commit messages must include `project: <slug>` in `---ci---` block
@@ -36,17 +36,17 @@ Determine current state:
## Step 2: Pre-Flight Check
Verify `.ci/config.json` exists. If missing: stop, run `ci-init` first.
Verify `.ciagent/config.json` exists. If missing: stop, run `ciagent-init` first.
Read `.ci/PROJECT.md` and `.ci/ROADMAP.md` for phase goals.
Read `.ciagent/PROJECT.md` and `.ciagent/ROADMAP.md` for phase goals.
## Step 3: Execute Pipeline Stages
For each stage in order (starting from current or from `specify`):
### SPECIFY
- Parse specification from `.ci/PROJECT.md`
- Validate requirements exist in `.ci/REQUIREMENTS.md`
- Parse specification from `.ciagent/PROJECT.md`
- Validate requirements exist in `.ciagent/REQUIREMENTS.md`
- Commit: `docs(init): validate specification`
### CLARIFY
@@ -57,7 +57,7 @@ For each stage in order (starting from current or from `specify`):
### RESEARCH
- Delegate to ci-researcher
- Research domain, ecosystem, prior art
- Update `.ci/` static files with conclusions
- Update `.ciagent/` static files with conclusions
- Commit: `docs(P##): research findings`
### PLAN
@@ -81,8 +81,8 @@ For each stage in order (starting from current or from `specify`):
- Merge phase branch into main (squash)
- Tag with patch version (e.g., `v0.2.3` — 3rd phase in milestone v0.2)
- Create Gitea release for the tag
- Update `.ci/REQUIREMENTS.md` requirement statuses
- Update `.ci/ROADMAP.md` phase status
- Update `.ciagent/REQUIREMENTS.md` requirement statuses
- Update `.ciagent/ROADMAP.md` phase status
- Commit: `docs(P##): complete [phase-name] phase`
Versioning: Major = project-level refactor/schema change, Minor = milestone completion, Patch = every phase.
@@ -92,7 +92,7 @@ Versioning: Major = project-level refactor/schema change, Minor = milestone comp
Between phases, perform a context reset:
1. Commit all work from the current phase
2. Update `.ci/` files (phase status, requirement statuses)
2. Update `.ciagent/` files (phase status, requirement statuses)
3. Verify `GitContext.reconstructState()` matches expected state
4. Reset context: spawn fresh agent (opencode) or re-read git context (platforms without subagents)
5. Next phase begins with fresh context from git log only
+71 -31
View File
@@ -1,27 +1,31 @@
---
description: Ship CI phase or milestone — test, tag, release. Every phase gets a patch release. Every milestone gets a minor (or major) release. Full autopilot.
description: Ship CIAgent phase or milestone — test, tag, release. Every phase and milestone gets a release. Full autopilot.
---
# CI Ship
# CIAgent Ship
Ship a CI phase or milestone. Every ship creates a release — no exceptions.
Ship a CIAgent phase or milestone. Every ship creates a release — no exceptions.
**Versioning rule:**
- **Major** (X.0.0): Project-level refactor or schema changes
- **Minor** (0.X.0): Feature milestone completion only
- **Patch** (0.0.X): Every phase completion
**3-Tier Versioning Model:**
**NFR versioning:**
- NFR milestones (all phases are fix/chore/docs/perf/refactor/test): progressive patch versions only (v0.1.1, v0.1.2, v0.1.3). No minor milestone tag.
- Feature milestones (any feat phase): progressive patch versions per phase + minor milestone tag on completion (e.g., v0.2.0).
| Milestone Type | Condition | Phase release | Milestone release |
|---------------|-----------|---------------|-------------------|
| **NFR** | All phases: fix/chore/docs/perf/refactor/test | Patch (`vX.Y.Z`) | None |
| **Feature** | Any phase is `feat`, no schema break | Patch (`vX.Y.Z`) | Minor — `vX.(Y+1).0` |
| **Schema-breaking** | Refactor/schema break/new direction | Minor — `vX.(Y+N).0` per phase | Major — `v(X+1).0.0` |
**Usage:** `ci-ship [phase_number|milestone]`
**CRITICAL:** Milestone tags are always the NEXT version, never the base:
- Feature: patches v0.5.1v0.5.5 → milestone tag is v0.6.0 (NOT v0.5.0)
- Schema-breaking: minors v0.3.0, v0.4.0, v0.5.0 → milestone tag is v1.0.0
- NFR: no milestone tag — the milestone is implicit from the patch sequence
**Usage:** `ciagent-ship [phase_number|milestone]`
## Step 0: Confirm Active Project
Check `ci listProjects()` or read `.ci/config.json` to determine if multi-project mode is active.
Check `ci listProjects()` or read `.ciagent/config.json` to determine if multi-project mode is active.
If `.ci/config.json` has `projects[]` with length > 0:
If `.ciagent/config.json` has `projects[]` with length > 0:
- Confirm `active_project` is correct for this ship
- If not, set it with `ci setActiveProject(<slug>)`
- All commit messages must include `project: <slug>` in `---ci---` block
@@ -36,14 +40,14 @@ git log --max-count=10
git branch -a
```
Determine what is being shipped: a single phase (patch release) or an entire milestone (minor/major release).
Determine what is being shipped: a single phase or an entire milestone.
Read `.ci/ROADMAP.md` to determine:
Read `.ciagent/ROADMAP.md` to determine:
- Current milestone version (e.g., `v0.2`)
- Phase number within the milestone
- Whether this is the last phase in the milestone
Read `.ci/config.json` for autonomy level.
Read `.ciagent/config.json` for autonomy level.
## Step 2: Run Tests
@@ -57,22 +61,51 @@ If any fail: iterate autonomously until tests pass. Do NOT ask the user for guid
## Step 3: Compute Version
Determine the release version from what is being shipped. Check `isNfrMilestone()` for versioning behavior:
Determine milestone type by calling `getMilestoneType()` which returns `"nfr" | "feature" | "schema-breaking"`:
| What's shipping | Milestone Type | Version bump | Tag format | Example |
| What's shipping | Milestone Type | Phase release | Milestone release | Example |
|----------------|---------------|-------------|------------|---------|
| Single phase | NFR | Patch | `vX.Y.Z` | `v0.1.3` (3rd NFR phase in milestone v0.1) |
| Single phase | Feature | Patch | `vX.Y.Z` | `v0.2.3` (3rd phase in feature milestone v0.2) |
| Milestone completion | NFR | Patch (last phase) | `vX.Y.Z` | `v0.1.3` (no minor tag) |
| Milestone completion | Feature | Minor | `vX.Y.0` | `v0.3.0` (feature milestone v0.3 complete) |
| Project refactor/schema change | Any | Major | `vX.0.0` | `v1.0.0` (breaking schema) |
| Single phase | NFR | Patch `vX.Y.Z` | N/A | v0.1.3 (3rd NFR phase) |
| Single phase | Feature | Patch `vX.Y.Z` | N/A | v0.2.3 (3rd feature phase) |
| Single phase | Schema-breaking | Minor `vX.(Y+N).0` | N/A | v0.4.0 (2nd schema-breaking phase) |
| Milestone completion | NFR | Patch (last phase) | None | v0.1.3 (no milestone tag) |
| Milestone completion | Feature | Last patch | Minor `vX.(Y+1).0` | v0.3.0 (NOT v0.2.0) |
| Milestone completion | Schema-breaking | Last minor | Major `v(X+1).0.0` | v1.0.0 |
Count completed phases in the current milestone to determine the patch number.
Phase number within the milestone determines the increment:
- NFR/Feature: 1st phase = .1, 2nd = .2, etc. (v0.5.1, v0.5.2)
- Schema-breaking: 1st phase = next minor, 2nd = minor+1, etc. (v0.3.0, v0.4.0)
**Before creating ANY tag, validate:**
1. The tag must be strictly greater than all existing tags on the same major.minor line
2. Milestone completion tag must be the next minor (feature) or next major (schema-breaking)
3. NEVER create a milestone tag that is semantically below existing phase tags (e.g., v0.5.0 when v0.5.1 already exists)
## Step 4: Merge Branch
### Phase ship (patch release)
### Branch hierarchy: main > milestone/vX.X-slug > phase/NN-slug
Phases MUST merge into their milestone branch (or to main if no milestone branch exists). Milestones merge into main only after all phases are complete.
### Phase ship
**If milestone branch exists:**
```bash
git checkout milestone/vX.Y-slug
git merge --squash phase/NN-slug
git commit -m "docs(P##): complete [phase-name] phase
---ci---
phase: [N]
milestone: [vX.Y]
status: complete
requirements:
covered: [REQ-01, REQ-02]
partial: []
---/ci---"
```
**If no milestone branch exists (single-phase milestone):**
```bash
git checkout main
git merge --squash phase/NN-slug
@@ -88,9 +121,10 @@ requirements:
---/ci---"
```
### Milestone ship (minor/major release)
### Milestone ship (after last phase)
```bash
# Verify all phase branches are merged into milestone branch
git checkout main
git merge --squash milestone/vX.Y-slug
git commit -m "docs(milestone): complete [milestone-name]
@@ -109,6 +143,12 @@ git tag -a vX.Y.Z -m "vX.Y.Z: [phase-name or milestone-name]"
git push origin main --tags
```
**Tag format by milestone type:**
- NFR/Feature phase: patch format (`v0.5.1`, `v0.5.2`)
- Schema-breaking phase: minor format (`v0.3.0`, `v0.4.0`)
- Feature milestone: next minor (`v0.6.0`, NOT `v0.5.0`)
- Schema-breaking milestone: next major (`v1.0.0`)
## Step 6: Create Release
**Every ship creates a Gitea release. No exceptions.**
@@ -132,8 +172,8 @@ For milestone releases, include a summary of all phases completed and requiremen
## Step 7: Update .ci/ Files
- Update `.ci/REQUIREMENTS.md` — mark shipped requirements as complete
- Update `.ci/ROADMAP.md` — mark shipped phase as complete
- Update `.ciagent/REQUIREMENTS.md` — mark shipped requirements as complete
- Update `.ciagent/ROADMAP.md` — mark shipped phase as complete
Commit the file updates.
@@ -141,11 +181,11 @@ Commit the file updates.
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CI ► SHIPPED
CIAgent ► SHIPPED
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Phase [N]: [name]
Milestone: [vX.Y]
Milestone: [vX.Y] ([nfr|feature|schema-breaking])
Version: vX.Y.Z
Release: https://git.cloudinit.dev/continuous-intelligence/ci/releases/tag/vX.Y.Z
Status: complete
@@ -158,6 +198,6 @@ Requirements covered: [N]
Commits: [N]
[If milestone complete:]
All phases in milestone v0.2 complete. Milestone released.
All phases in milestone v0.2 complete. Milestone released as vX.Y.Z.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```
+11 -11
View File
@@ -1,18 +1,18 @@
---
description: Show CI project status — current phase, milestone, pipeline stage, decisions, escalations, and requirements coverage
description: Show CIAgent project status — current phase, milestone, pipeline stage, decisions, escalations, and requirements coverage
---
# CI Status
# CIAgent Status
Display the current CI project status derived entirely from the git log and .ci/ files.
Display the current CIAgent project status derived entirely from the git log and .ciagent/ files.
**Usage:** `ci-status`
**Usage:** `ciagent-status`
## Step 0: Confirm Active Project
Check `ci listProjects()` or read `.ci/config.json` to determine if multi-project mode is active.
Check `ci listProjects()` or read `.ciagent/config.json` to determine if multi-project mode is active.
If `.ci/config.json` has `projects[]` with length > 0:
If `.ciagent/config.json` has `projects[]` with length > 0:
- Show project list with active project indicator
- Confirm `active_project` is the project to show status for
- If not, set it with `ci setActiveProject(<slug>)`
@@ -45,15 +45,15 @@ Collect from git log:
## Step 3: Read .ci/ Files
Read:
- `.ci/PROJECT.md` — project name and vision
- `.ci/ROADMAP.md` — phase list with status
- `.ci/config.json` — autonomy level
- `.ciagent/PROJECT.md` — project name and vision
- `.ciagent/ROADMAP.md` — phase list with status
- `.ciagent/config.json` — autonomy level
## Step 4: Display Status
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CI ► STATUS
CIAgent ► STATUS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Project: [name] [If multi-project: (active)]
@@ -79,4 +79,4 @@ Recent commits:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```
If no `.ci/` directory exists: report "Project not initialized. Run ci-init first."
If no `.ciagent/` directory exists: report "Project not initialized. Run ciagent-init first."
+6 -6
View File
@@ -1,20 +1,20 @@
---
description: Verify CI project deliverables against requirements — structural, behavioral, security, and quality checks
description: Verify CIAgent project deliverables against requirements — structural, behavioral, security, and quality checks
---
# CI Verify
# CIAgent Verify
Run the CI verification pipeline against the current or specified phase. Four layers: structural, behavioral, security, quality.
Run the CIAgent verification pipeline against the current or specified phase. Four layers: structural, behavioral, security, quality.
**Usage:** `ci-verify [phase_number]`
**Usage:** `ciagent-verify [phase_number]`
If no phase specified, verifies the current phase.
## Step 0: Confirm Active Project
Check `ci listProjects()` or read `.ci/config.json` to determine if multi-project mode is active.
Check `ci listProjects()` or read `.ciagent/config.json` to determine if multi-project mode is active.
If `.ci/config.json` has `projects[]` with length > 0:
If `.ciagent/config.json` has `projects[]` with length > 0:
- Confirm `active_project` is correct for this verification
- If not, set it with `ci setActiveProject(<slug>)`
- Scope verification to the active project
+3 -3
View File
@@ -1,5 +1,5 @@
---
description: Audit CI project health — reconstruct state from git log, verify .ci/ files match codebase, check for stale references
description: Audit CIAgent project health — reconstruct state from git log, verify .ciagent/ files match codebase, check for stale references
tools:
read: true
bash: true
@@ -8,7 +8,7 @@ tools:
---
<execution_context>
@/home/jchery/.config/opencode/ci/workflows/audit.md
@__OPENCODE_DIR__/ci/workflows/audit.md
</execution_context>
<context>
@@ -16,6 +16,6 @@ Arguments: $ARGUMENTS
</context>
<process>
Execute the CI audit workflow end-to-end.
Execute the CIAgent audit workflow end-to-end.
Preserve all workflow gates, validations, checkpoints, and routing.
</process>
+3 -3
View File
@@ -1,5 +1,5 @@
---
description: Clarify CI project ambiguities — generate questions, accept defaults at full autonomy, present at supervised/guided
description: Clarify CIAgent project ambiguities — generate questions, accept defaults at full autonomy, present at supervised/guided
argument-hint: "[phase_number]"
tools:
read: true
@@ -13,7 +13,7 @@ tools:
---
<execution_context>
@/home/jchery/.config/opencode/ci/workflows/clarify.md
@__OPENCODE_DIR__/ci/workflows/clarify.md
</execution_context>
<context>
@@ -21,6 +21,6 @@ Arguments: $ARGUMENTS
</context>
<process>
Execute the CI clarify workflow end-to-end.
Execute the CIAgent clarify workflow end-to-end.
Preserve all workflow gates, validations, checkpoints, and routing.
</process>
+3 -3
View File
@@ -1,5 +1,5 @@
---
description: Systematic CI debugging with git context — triage, diagnose root cause, auto-fix or escalate
description: Systematic CIAgent debugging with git context — triage, diagnose root cause, auto-fix or escalate
argument-hint: "[description]"
tools:
read: true
@@ -13,7 +13,7 @@ tools:
---
<execution_context>
@/home/jchery/.config/opencode/ci/workflows/debug.md
@__OPENCODE_DIR__/ci/workflows/debug.md
</execution_context>
<context>
@@ -21,6 +21,6 @@ Arguments: $ARGUMENTS
</context>
<process>
Execute the CI debug workflow end-to-end.
Execute the CIAgent debug workflow end-to-end.
Preserve all workflow gates, validations, checkpoints, and routing.
</process>
+3 -3
View File
@@ -1,5 +1,5 @@
---
description: Initialize a new CI project — specification → clarify → create .ci/ reference files → initial commit
description: Initialize a new CIAgent project — specification → clarify → create .ciagent/ reference files → initial commit
argument-hint: "[description]"
tools:
read: true
@@ -13,7 +13,7 @@ tools:
---
<execution_context>
@/home/jchery/.config/opencode/ci/workflows/init.md
@__OPENCODE_DIR__/ci/workflows/init.md
</execution_context>
<context>
@@ -21,6 +21,6 @@ Arguments: $ARGUMENTS
</context>
<process>
Execute the CI init workflow end-to-end.
Execute the CIAgent init workflow end-to-end.
Preserve all workflow gates, validations, checkpoints, and routing.
</process>
+3 -3
View File
@@ -1,5 +1,5 @@
---
description: Execute an ad-hoc CI task with full agentic guarantees — git context, ---ci--- commits, optional research and verification
description: Execute an ad-hoc CIAgent task with full agentic guarantees — git context, ---ci--- commits, optional research and verification
argument-hint: "[description] [--research] [--verify] [--full]"
tools:
read: true
@@ -13,7 +13,7 @@ tools:
---
<execution_context>
@/home/jchery/.config/opencode/ci/workflows/quick.md
@__OPENCODE_DIR__/ci/workflows/quick.md
</execution_context>
<context>
@@ -21,6 +21,6 @@ Arguments: $ARGUMENTS
</context>
<process>
Execute the CI quick workflow end-to-end.
Execute the CIAgent quick workflow end-to-end.
Preserve all workflow gates, validations, checkpoints, and routing.
</process>
+3 -3
View File
@@ -1,5 +1,5 @@
---
description: Review CI code changes with multi-persona analysis — auto-apply P0 fixes, flag P1+ for post-hoc review
description: Review CIAgent code changes with multi-persona analysis — auto-apply P0 fixes, flag P1+ for post-hoc review
argument-hint: "[phase_number]"
tools:
read: true
@@ -12,7 +12,7 @@ tools:
---
<execution_context>
@/home/jchery/.config/opencode/ci/workflows/review.md
@__OPENCODE_DIR__/ci/workflows/review.md
</execution_context>
<context>
@@ -20,6 +20,6 @@ Arguments: $ARGUMENTS
</context>
<process>
Execute the CI review workflow end-to-end.
Execute the CIAgent review workflow end-to-end.
Preserve all workflow gates, validations, checkpoints, and routing.
</process>
+3 -3
View File
@@ -1,5 +1,5 @@
---
description: Rollback CI phase — revert the last phase or specified phase by resetting to its pre-phase state
description: Rollback CIAgent phase — revert the last phase or specified phase by resetting to its pre-phase state
argument-hint: "[phase_number]"
tools:
read: true
@@ -13,7 +13,7 @@ tools:
---
<execution_context>
@/home/jchery/.config/opencode/ci/workflows/rollback.md
@__OPENCODE_DIR__/ci/workflows/rollback.md
</execution_context>
<context>
@@ -21,6 +21,6 @@ Arguments: $ARGUMENTS
</context>
<process>
Execute the CI rollback workflow end-to-end.
Execute the CIAgent rollback workflow end-to-end.
Preserve all workflow gates, validations, checkpoints, and routing.
</process>
+3 -3
View File
@@ -1,5 +1,5 @@
---
description: Execute the full CI pipeline — research → plan → execute → verify → complete
description: Execute the full CIAgent pipeline — research → plan → execute → verify → complete
argument-hint: "[phase_number]"
tools:
read: true
@@ -13,7 +13,7 @@ tools:
---
<execution_context>
@/home/jchery/.config/opencode/ci/workflows/run.md
@__OPENCODE_DIR__/ci/workflows/run.md
</execution_context>
<context>
@@ -21,6 +21,6 @@ Arguments: $ARGUMENTS
</context>
<process>
Execute the CI run workflow end-to-end.
Execute the CIAgent run workflow end-to-end.
Preserve all workflow gates, validations, checkpoints, and routing.
</process>
+3 -3
View File
@@ -1,5 +1,5 @@
---
description: Ship CI phase or milestone — test, commit, tag, push, release. Full autopilot: zero HITL after milestone setup
description: Ship CIAgent phase or milestone — test, commit, tag, push, release. Full autopilot: zero HITL after milestone setup
argument-hint: "[phase_number|milestone]"
tools:
read: true
@@ -12,7 +12,7 @@ tools:
---
<execution_context>
@/home/jchery/.config/opencode/ci/workflows/ship.md
@__OPENCODE_DIR__/ci/workflows/ship.md
</execution_context>
<context>
@@ -20,6 +20,6 @@ Arguments: $ARGUMENTS
</context>
<process>
Execute the CI ship workflow end-to-end.
Execute the CIAgent ship workflow end-to-end.
Preserve all workflow gates, validations, checkpoints, and routing.
</process>
+3 -3
View File
@@ -1,5 +1,5 @@
---
description: Show CI project status — current phase, milestone, pipeline stage, decisions, escalations, and requirements coverage
description: Show CIAgent project status — current phase, milestone, pipeline stage, decisions, escalations, and requirements coverage
tools:
read: true
bash: true
@@ -8,7 +8,7 @@ tools:
---
<execution_context>
@/home/jchery/.config/opencode/ci/workflows/status.md
@__OPENCODE_DIR__/ci/workflows/status.md
</execution_context>
<context>
@@ -16,6 +16,6 @@ Arguments: $ARGUMENTS
</context>
<process>
Execute the CI status workflow end-to-end.
Execute the CIAgent status workflow end-to-end.
Preserve all workflow gates, validations, checkpoints, and routing.
</process>
+3 -3
View File
@@ -1,5 +1,5 @@
---
description: Verify CI project deliverables against requirements — structural, behavioral, security, and quality checks
description: Verify CIAgent project deliverables against requirements — structural, behavioral, security, and quality checks
argument-hint: "[phase_number]"
tools:
read: true
@@ -12,7 +12,7 @@ tools:
---
<execution_context>
@/home/jchery/.config/opencode/ci/workflows/verify.md
@__OPENCODE_DIR__/ci/workflows/verify.md
</execution_context>
<context>
@@ -20,6 +20,6 @@ Arguments: $ARGUMENTS
</context>
<process>
Execute the CI verify workflow end-to-end.
Execute the CIAgent verify workflow end-to-end.
Preserve all workflow gates, validations, checkpoints, and routing.
</process>
+3 -5
View File
@@ -2,12 +2,10 @@
"$schema": "https://opencode.ai/config.json",
"permission": {
"read": {
"~/.config/opencode/learnship/*": "allow",
"~/.config/opencode/ci/*": "allow"
"__OPENCODE_DIR__/ci/*": "allow"
},
"external_directory": {
"~/.config/opencode/learnship/*": "allow",
"~/.config/opencode/ci/*": "allow"
"__OPENCODE_DIR__/ci/*": "allow"
}
}
}
}
+6 -5
View File
@@ -1,19 +1,20 @@
{
"name": "@continuous-intelligence/ci",
"version": "0.1.0",
"name": "@continuous-intelligence/ciagent",
"version": "0.5.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@continuous-intelligence/ci",
"version": "0.1.0",
"name": "@continuous-intelligence/ciagent",
"version": "0.5.0",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
"commander": "^12.1.0",
"zod": "^3.23.0"
},
"bin": {
"ci": "dist/cli/index.js"
"ciagent": "dist/cli/index.js"
},
"devDependencies": {
"@types/jest": "^29.5.0",
+5 -7
View File
@@ -1,16 +1,15 @@
{
"name": "@continuous-intelligence/ci",
"version": "0.3.0",
"name": "@continuous-intelligence/ciagent",
"version": "0.5.0",
"description": "Fully autonomous AI-driven software engineering harness - Continuous Intelligence",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"bin": {
"ci": "./dist/cli/index.js"
"ciagent": "./dist/cli/index.js"
},
"files": [
"dist/",
"opencode/",
"scripts/",
"templates/",
"LICENSE",
"README.md"
@@ -21,10 +20,9 @@
"typecheck": "tsc --noEmit",
"test": "jest",
"prepublishOnly": "npm run build",
"postinstall": "node scripts/postinstall.js",
"install": "bash scripts/install.sh"
"install-opencode": "node scripts/postinstall.js"
},
"keywords": ["ci", "autonomous", "ai", "software-engineering", "agent", "multi-project"],
"keywords": ["ciagent", "autonomous", "ai", "software-engineering", "agent", "multi-project"],
"license": "MIT",
"engines": {
"node": ">=18.0.0"
Regular → Executable
+21 -18
View File
@@ -14,9 +14,9 @@ for arg in "$@"; do
--help|-h)
echo "Usage: $(basename "$0") [--uninstall] [--force]"
echo ""
echo "Install CI opencode integration files to ~/.config/opencode/"
echo "Install CIAgent opencode integration files to ~/.config/opencode/"
echo ""
echo " --uninstall Remove CI integration files"
echo " --uninstall Remove CIAgent integration files"
echo " --force Overwrite existing files without prompting"
echo " --help Show this help"
exit 0
@@ -25,24 +25,24 @@ for arg in "$@"; do
done
if [ "$UNINSTALL" = true ]; then
echo "Uninstalling CI opencode integration..."
rm -f "${OPENCODE_DIR}/agents/ci-"*.md 2>/dev/null || true
rm -f "${OPENCODE_DIR}/command/ci-"*.md 2>/dev/null || true
rm -rf "${OPENCODE_DIR}/ci/" 2>/dev/null || true
echo "CI integration files removed."
echo "Uninstalling CIAgent opencode integration..."
rm -f "${OPENCODE_DIR}/agents/ci-"*.md 2>/dev/null || true
rm -f "${OPENCODE_DIR}/command/ci-"*.md 2>/dev/null || true
rm -rf "${OPENCODE_DIR}/ci/" 2>/dev/null || true
echo "CIAgent integration files removed."
echo "Note: opencode.json permissions entry preserved (edit manually if needed)."
exit 0
fi
if [ ! -d "$CI_DIR" ]; then
echo "Error: opencode/ directory not found at ${CI_DIR}"
echo "Ensure you're running from the CI repository root."
echo "Ensure you're running from the CIAgent repository root."
exit 1
fi
echo "Installing CI opencode integration..."
echo "Installing CIAgent opencode integration..."
echo " Source: ${CI_DIR}"
echo " Target: ${OPENCODE_DIR}"
echo ""
@@ -70,7 +70,7 @@ copy_file() {
return
fi
cp "$src" "$dest"
sed "s|__OPENCODE_DIR__|${OPENCODE_DIR}|g" "$src" > "$dest"
COPIED=$((COPIED + 1))
}
@@ -109,14 +109,16 @@ CI_JSON="${CI_DIR}/opencode.json"
if [ -f "$CI_JSON" ]; then
if [ ! -f "$OPENCODE_JSON" ]; then
cp "$CI_JSON" "$OPENCODE_JSON"
sed "s|__OPENCODE_DIR__|${OPENCODE_DIR}|g" "$CI_JSON" > "$OPENCODE_JSON"
echo " Created opencode.json"
else
if command -v node &>/dev/null; then
local_ci_json="$(sed "s|__OPENCODE_DIR__|${OPENCODE_DIR}|g" "$CI_JSON")"
echo "$local_ci_json" > /tmp/ci-json-merge.json
node -e "
const fs = require('fs');
const existing = JSON.parse(fs.readFileSync('${OPENCODE_JSON}', 'utf8'));
const ci = JSON.parse(fs.readFileSync('${CI_JSON}', 'utf8'));
const ci = JSON.parse(fs.readFileSync('/tmp/ci-json-merge.json', 'utf8'));
const merged = { ...existing };
merged.permission = merged.permission || {};
merged.permission.read = merged.permission.read || {};
@@ -130,6 +132,7 @@ if [ -f "$CI_JSON" ]; then
fs.writeFileSync('${OPENCODE_JSON}', JSON.stringify(merged, null, 2));
console.log(' Merged permissions (preserved existing entries)');
"
rm -f /tmp/ci-json-merge.json
else
echo " Warning: node not found. Manually merge opencode.json permissions."
echo " Add to opencode.json:"
@@ -140,15 +143,15 @@ fi
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo " CI ► INSTALL COMPLETE"
echo " CIAgent ► INSTALL COMPLETE"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo " Copied: ${COPIED} files"
echo " Skipped: ${SKIPPED} files"
echo ""
echo " Commands available: ci-init, ci-run, ci-quick, ci-status,"
echo " ci-audit, ci-verify, ci-debug, ci-review, ci-ship,"
echo " ci-rollback, ci-clarify"
echo " Commands available: ciagent-init, ciagent-run, ciagent-quick, ciagent-status,"
echo " ciagent-audit, ciagent-verify, ciagent-debug, ciagent-review, ciagent-ship,"
echo " ciagent-rollback, ciagent-clarify"
echo ""
echo " Run --uninstall to remove."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+28 -13
View File
@@ -20,7 +20,7 @@ function isGlobalInstall() {
return false;
}
function copyFile(src, dest, force) {
function copyFile(src, dest, force, templateVars) {
if (!fs.existsSync(src)) return { copied: 0, skipped: 0 };
const dir = path.dirname(dest);
@@ -28,36 +28,50 @@ function copyFile(src, dest, force) {
if (fs.existsSync(dest) && !force) {
try {
const srcContent = fs.readFileSync(src, "utf8");
const srcContent = applyTemplate(fs.readFileSync(src, "utf8"), templateVars);
const destContent = fs.readFileSync(dest, "utf8");
if (srcContent === destContent) return { copied: 0, skipped: 1 };
} catch {}
return { copied: 0, skipped: 1 };
}
fs.copyFileSync(src, dest);
const content = applyTemplate(fs.readFileSync(src, "utf8"), templateVars);
fs.writeFileSync(dest, content, "utf8");
return { copied: 1, skipped: 0 };
}
function applyTemplate(content, vars) {
if (!vars) return content;
let result = content;
for (const [key, value] of Object.entries(vars)) {
result = result.replaceAll(key, value);
}
return result;
}
function install() {
const pkgDir = getPackageDir();
if (!pkgDir) {
console.log("CI postinstall: Could not determine package directory. Skipping.");
console.log("CIAgent postinstall: Could not determine package directory. Skipping.");
return;
}
const opencodeDir = path.join(pkgDir, "opencode");
if (!fs.existsSync(opencodeDir)) {
console.log("CI postinstall: opencode/ directory not found. Skipping.");
console.log("CIAgent postinstall: opencode/ directory not found. Skipping.");
return;
}
if (!isGlobalInstall()) {
console.log("CI postinstall: Not a global install. Skipping opencode integration.");
console.log(" Run `npx ci-install` or `./scripts/install.sh` to install manually.");
console.log("CIAgent postinstall: Not a global install. Skipping opencode integration.");
console.log(" Run `npx ciagent-install` or `./scripts/install.sh` to install manually.");
return;
}
const templateVars = {
__OPENCODE_DIR__: OPENCODE_DIR,
};
let copied = 0;
let skipped = 0;
@@ -68,7 +82,7 @@ function install() {
return f.startsWith(pattern);
});
for (const entry of entries) {
const result = copyFile(path.join(srcDir, entry), path.join(destDir, entry), false);
const result = copyFile(path.join(srcDir, entry), path.join(destDir, entry), false, templateVars);
copied += result.copied;
skipped += result.skipped;
}
@@ -88,7 +102,7 @@ function install() {
const versionFile = path.join(opencodeDir, "ci", "VERSION");
if (fs.existsSync(versionFile)) {
const result = copyFile(versionFile, path.join(OPENCODE_DIR, "ci", "VERSION"), false);
const result = copyFile(versionFile, path.join(OPENCODE_DIR, "ci", "VERSION"), false, templateVars);
copied += result.copied;
skipped += result.skipped;
}
@@ -98,11 +112,12 @@ function install() {
if (fs.existsSync(ciJsonPath)) {
if (!fs.existsSync(targetJsonPath)) {
fs.copyFileSync(ciJsonPath, targetJsonPath);
const content = applyTemplate(fs.readFileSync(ciJsonPath, "utf8"), templateVars);
fs.writeFileSync(targetJsonPath, content, "utf8");
} else {
try {
const existing = JSON.parse(fs.readFileSync(targetJsonPath, "utf8"));
const ciJson = JSON.parse(fs.readFileSync(ciJsonPath, "utf8"));
const ciJson = JSON.parse(applyTemplate(fs.readFileSync(ciJsonPath, "utf8"), templateVars));
existing.permission = existing.permission || {};
existing.permission.read = existing.permission.read || {};
existing.permission.external_directory = existing.permission.external_directory || {};
@@ -117,11 +132,11 @@ function install() {
}
}
console.log(`CI postinstall: ${copied} files installed, ${skipped} skipped.`);
console.log(`CIAgent postinstall: ${copied} files installed, ${skipped} skipped.`);
}
try {
install();
} catch (err) {
console.log("CI postinstall: Non-fatal error:", err.message);
console.log("CIAgent postinstall: Non-fatal error:", err.message);
}
+33 -1
View File
@@ -1,3 +1,6 @@
import { IntelligenceBackend, BackendRequest, BackendResult, BackendUnavailableError, emptyBackendResult } from "../backends/types.js";
import { AgentName, AutonomyLevel } from "../types/config.js";
export interface AgentResult {
success: boolean;
output: string;
@@ -14,14 +17,43 @@ export interface AgentContext {
stage: string;
specification: string;
config_path: string;
backend?: IntelligenceBackend;
}
export function backendResultToAgentResult(result: BackendResult): AgentResult {
return {
success: result.success,
output: result.output,
artifacts_created: result.artifacts.map((a) => a.path),
decisions: result.decisions.length,
escalations: result.escalations.length,
duration_ms: 0,
error: result.error,
};
}
export abstract class BaseAgent {
abstract readonly name: string;
abstract readonly name: AgentName;
abstract readonly description: string;
abstract readonly workflow: string;
abstract execute(context: AgentContext): Promise<AgentResult>;
protected async executeViaBackend(context: AgentContext, task: string): Promise<AgentResult> {
if (!context.backend) {
throw new BackendUnavailableError("none", this.name);
}
const request: BackendRequest = {
persona: this.name,
workflow: this.workflow,
task,
context,
autonomy: "full",
};
const result = await context.backend.execute(request);
return backendResultToAgentResult(result);
}
protected log(message: string): void {
console.log(`[${this.name}] ${message}`);
}
+12 -3
View File
@@ -3,17 +3,26 @@ import { BaseAgent, AgentContext, AgentResult } from "./base.js";
export class ChallengerAgent extends BaseAgent {
readonly name = "challenger";
readonly description = "Stress-tests plans with binding verdicts. Only escalates when confidence < 0.60.";
readonly workflow = "plan";
async execute(context: AgentContext): Promise<AgentResult> {
this.log("Challenging plan...");
const start = Date.now();
this.log("Challenging plan...");
if (context.backend) {
const result = await this.executeViaBackend(
context,
`Stress-test the plan for phase ${context.phase}. Specification: ${context.specification}`
);
return { ...result, duration_ms: Date.now() - start };
}
return {
success: true,
output: "Plan challenge complete — verdict: proceed",
success: false,
output: "Plan challenge requires an intelligence backend. Configure one with: ci init --backend",
artifacts_created: [],
decisions: 0,
escalations: 0,
duration_ms: Date.now() - start,
error: "No intelligence backend available",
};
}
}
+13 -4
View File
@@ -3,17 +3,26 @@ import { BaseAgent, AgentContext, AgentResult } from "./base.js";
export class CodeReviewerAgent extends BaseAgent {
readonly name = "code-reviewer";
readonly description = "Multi-persona code review. Auto-applies P0 fixes. Flags P1+ for post-hoc review.";
readonly workflow = "review";
async execute(context: AgentContext): Promise<AgentResult> {
this.log("Running code review...");
const start = Date.now();
this.log("Running code review...");
if (context.backend) {
const result = await this.executeViaBackend(
context,
`Perform multi-persona code review for phase ${context.phase}. Specification: ${context.specification}`
);
return { ...result, duration_ms: Date.now() - start };
}
return {
success: true,
output: "Code review complete — P0 fixes applied, P1+ flagged for review",
artifacts_created: ["CODE-REVIEW.md"],
success: false,
output: "Code review requires an intelligence backend. Configure one with: ci init --backend",
artifacts_created: [],
decisions: 0,
escalations: 0,
duration_ms: Date.now() - start,
error: "No intelligence backend available",
};
}
}
+13 -4
View File
@@ -3,17 +3,26 @@ import { BaseAgent, AgentContext, AgentResult } from "./base.js";
export class DebuggerAgent extends BaseAgent {
readonly name = "debugger";
readonly description = "Autonomous debugging. Auto-fixes when root cause confidence > 0.60, escalates otherwise.";
readonly workflow = "debug";
async execute(context: AgentContext): Promise<AgentResult> {
this.log("Running autonomous debug...");
const start = Date.now();
this.log("Running autonomous debug...");
if (context.backend) {
const result = await this.executeViaBackend(
context,
`Debug the following issue: ${context.specification}`
);
return { ...result, duration_ms: Date.now() - start };
}
return {
success: true,
output: "Debug complete — issue identified and resolved",
artifacts_created: ["DEBUG.md"],
success: false,
output: "Debugging requires an intelligence backend. Configure one with: ci init --backend",
artifacts_created: [],
decisions: 0,
escalations: 0,
duration_ms: Date.now() - start,
error: "No intelligence backend available",
};
}
}
+12 -3
View File
@@ -3,17 +3,26 @@ import { BaseAgent, AgentContext, AgentResult } from "./base.js";
export class DocVerifierAgent extends BaseAgent {
readonly name = "doc-verifier";
readonly description = "Verifies documentation matches live codebase.";
readonly workflow = "verify";
async execute(context: AgentContext): Promise<AgentResult> {
this.log("Verifying documentation...");
const start = Date.now();
this.log("Verifying documentation...");
if (context.backend) {
const result = await this.executeViaBackend(
context,
`Verify documentation matches codebase for phase ${context.phase}.`
);
return { ...result, duration_ms: Date.now() - start };
}
return {
success: true,
output: "Documentation verification complete",
success: false,
output: "Documentation verification requires an intelligence backend.",
artifacts_created: [],
decisions: 0,
escalations: 0,
duration_ms: Date.now() - start,
error: "No intelligence backend available",
};
}
}
+13 -4
View File
@@ -3,17 +3,26 @@ import { BaseAgent, AgentContext, AgentResult } from "./base.js";
export class DocWriterAgent extends BaseAgent {
readonly name = "doc-writer";
readonly description = "Autonomous documentation writer. No behavioral changes from Learnship.";
readonly workflow = "execute";
async execute(context: AgentContext): Promise<AgentResult> {
this.log("Writing documentation...");
const start = Date.now();
this.log("Writing documentation...");
if (context.backend) {
const result = await this.executeViaBackend(
context,
`Write documentation for phase ${context.phase}. Specification: ${context.specification}`
);
return { ...result, duration_ms: Date.now() - start };
}
return {
success: true,
output: "Documentation written",
artifacts_created: ["DOCS.md"],
success: false,
output: "Documentation writing requires an intelligence backend.",
artifacts_created: [],
decisions: 0,
escalations: 0,
duration_ms: Date.now() - start,
error: "No intelligence backend available",
};
}
}
+12 -3
View File
@@ -3,17 +3,26 @@ import { BaseAgent, AgentContext, AgentResult } from "./base.js";
export class ExecutorAgent extends BaseAgent {
readonly name = "executor";
readonly description = "Executes plan tasks autonomously. Never pauses for checkpoints.";
readonly workflow = "execute";
async execute(context: AgentContext): Promise<AgentResult> {
this.log("Executing tasks...");
const start = Date.now();
this.log("Executing tasks...");
if (context.backend) {
const result = await this.executeViaBackend(
context,
`Execute implementation for stage ${context.stage}, phase ${context.phase}. Specification: ${context.specification}`
);
return { ...result, duration_ms: Date.now() - start };
}
return {
success: true,
output: "Tasks executed",
success: false,
output: "Execution requires an intelligence backend. Configure one with: ci init --backend",
artifacts_created: [],
decisions: 0,
escalations: 0,
duration_ms: Date.now() - start,
error: "No intelligence backend available",
};
}
}
+13 -4
View File
@@ -3,17 +3,26 @@ import { BaseAgent, AgentContext, AgentResult } from "./base.js";
export class IdeationAgent extends BaseAgent {
readonly name = "ideation-agent";
readonly description = "Generates improvement ideas. Output feeds directly into planning pipeline.";
readonly workflow = "research";
async execute(context: AgentContext): Promise<AgentResult> {
this.log("Generating improvement ideas...");
const start = Date.now();
this.log("Generating improvement ideas...");
if (context.backend) {
const result = await this.executeViaBackend(
context,
`Generate improvement ideas for: ${context.specification}`
);
return { ...result, duration_ms: Date.now() - start };
}
return {
success: true,
output: "Ideation complete",
artifacts_created: ["IDEAS.md"],
success: false,
output: "Ideation requires an intelligence backend.",
artifacts_created: [],
decisions: 0,
escalations: 0,
duration_ms: Date.now() - start,
error: "No intelligence backend available",
};
}
}
+4 -1
View File
@@ -1,4 +1,4 @@
export { BaseAgent } from "./base.js";
export { BaseAgent, AgentContext, AgentResult, backendResultToAgentResult } from "./base.js";
export { OrchestratorAgent } from "./orchestrator.js";
export { PlannerAgent } from "./planner.js";
export { ExecutorAgent } from "./executor.js";
@@ -17,6 +17,7 @@ export { ProjectResearcherAgent } from "./project-researcher.js";
export { ResearchSynthesizerAgent } from "./research-synthesizer.js";
export { SolutionWriterAgent } from "./solution-writer.js";
export { PhaseResearcherAgent } from "./phase-researcher.js";
export { TesterAgent } from "./tester.js";
import { AgentName } from "../types/config.js";
import { BaseAgent as BaseAgentType } from "./base.js";
@@ -38,6 +39,7 @@ import { ProjectResearcherAgent } from "./project-researcher.js";
import { ResearchSynthesizerAgent } from "./research-synthesizer.js";
import { SolutionWriterAgent } from "./solution-writer.js";
import { PhaseResearcherAgent } from "./phase-researcher.js";
import { TesterAgent } from "./tester.js";
const agentRegistry: Record<AgentName, () => BaseAgentType> = {
orchestrator: () => new OrchestratorAgent(),
@@ -58,6 +60,7 @@ const agentRegistry: Record<AgentName, () => BaseAgentType> = {
"project-researcher": () => new ProjectResearcherAgent(),
"research-synthesizer": () => new ResearchSynthesizerAgent(),
"solution-writer": () => new SolutionWriterAgent(),
tester: () => new TesterAgent(),
};
export function getAgent(name: AgentName): BaseAgentType {
+106 -19
View File
@@ -4,9 +4,9 @@ import { ClarifyPhase } from "../core/clarify.js";
import { EscalationProtocol, EscalationInput } from "../core/escalation.js";
import { GitContext, ProjectState } from "../core/git-context.js";
import { GitBranch } from "../core/git-branch.js";
import { CiFiles } from "../core/ci-files.js";
import { CIAgentFiles } from "../core/ciagent-files.js";
import { CommitBuilder } from "../core/commit-builder.js";
import { CIConfig } from "../types/config.js";
import { CIAgentConfig, AgentName } from "../types/config.js";
import {
PipelineState,
PipelineStage,
@@ -16,30 +16,41 @@ import {
STAGE_ORDER,
} from "../types/pipeline.js";
import { Specification, parseSpecification } from "../types/specification.js";
import { loadConfig, saveConfig, isCIInitialized, initCI } from "../core/config.js";
import { loadConfig, saveConfig, isCIAgentInitialized, initCIAgent } from "../core/config.js";
import { getAgent } from "./index.js";
import { IntelligenceBackend, BackendUnavailableError } from "../backends/types.js";
export interface GitAgentContext extends AgentContext {
gitContext: GitContext;
gitBranch: GitBranch;
ciFiles: CiFiles;
ciFiles: CIAgentFiles;
milestone: string;
}
export class OrchestratorAgent extends BaseAgent {
readonly name = "orchestrator";
readonly description = "Top-level autonomous controller that coordinates the full CI pipeline";
readonly name: AgentName = "orchestrator";
readonly description = "Top-level autonomous controller that coordinates the full CIAgent pipeline";
readonly workflow = "run";
private config: CIConfig;
private config: CIAgentConfig;
private pipelineState: PipelineState | null = null;
private decisionEngine: DecisionEngine | null = null;
private escalationProtocol: EscalationProtocol | null = null;
private gitContext: GitContext | null = null;
private gitBranch: GitBranch | null = null;
private ciFiles: CiFiles | null = null;
private ciFiles: CIAgentFiles | null = null;
private currentMilestone: string;
private phaseResults: PhaseResult[] = [];
constructor(config?: CIConfig) {
private static readonly STAGE_AGENT_MAP: Partial<Record<PipelineStage, AgentName>> = {
research: "researcher",
plan: "planner",
execute: "executor",
test: "tester",
verify: "verifier",
};
constructor(config?: CIAgentConfig) {
super();
this.config = config || loadConfig(process.cwd());
this.currentMilestone = "v1.0";
@@ -47,14 +58,14 @@ export class OrchestratorAgent extends BaseAgent {
async execute(context: AgentContext): Promise<AgentResult> {
const startTime = Date.now();
this.log("Starting CI Orchestrator pipeline (git-native)");
this.log("Starting CIAgent Orchestrator pipeline (git-native)");
try {
this.config = loadConfig(context.project_path);
this.gitContext = new GitContext(context.project_path);
this.gitBranch = new GitBranch(context.project_path);
this.ciFiles = new CiFiles(context.project_path);
this.ciFiles = new CIAgentFiles(context.project_path);
this.ciFiles.ensureCIDir();
const projectState = this.gitContext.reconstructState();
@@ -149,6 +160,32 @@ export class OrchestratorAgent extends BaseAgent {
context: AgentContext
): Promise<PhaseResult> {
const stageStart = Date.now();
const agentName = OrchestratorAgent.STAGE_AGENT_MAP[stage];
if (agentName && context.backend) {
this.log(`Delegating ${stage} to ${agentName} agent via backend...`);
try {
const agent = getAgent(agentName);
const result = await agent.execute(context);
return {
phase: this.pipelineState!.current_phase,
stage,
success: result.success,
artifacts_created: Array.isArray(result.artifacts_created) ? result.artifacts_created : [],
decisions_made: result.decisions,
escalations_raised: result.escalations,
duration_ms: Date.now() - stageStart,
error: result.error,
};
} catch (err) {
if (err instanceof BackendUnavailableError) {
this.warn(`Backend unavailable for ${stage}, falling back to mechanical execution`);
} else {
this.warn(`Agent ${agentName} failed for ${stage}: ${err instanceof Error ? err.message : String(err)}`);
}
}
}
let decisionsMade = 0;
let escalationsRaised = 0;
const artifactsCreated: string[] = [];
@@ -171,7 +208,7 @@ export class OrchestratorAgent extends BaseAgent {
});
this.log("Init commit prepared with specification in ---ci--- block");
artifactsCreated.push(".ci/config.json");
artifactsCreated.push(".ciagent/config.json");
if (this.config.git.auto_commit && this.gitContext!.isGitRepo()) {
try {
@@ -188,7 +225,8 @@ export class OrchestratorAgent extends BaseAgent {
cwd: context.project_path,
stdio: "pipe",
});
} catch {
} catch (err) {
this.warn(`Specify commit failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
} else {
@@ -239,12 +277,27 @@ export class OrchestratorAgent extends BaseAgent {
this.log("Researching project domain...");
this.decisionEngine!.setPhase(1);
const archMd = this.ciFiles!.readArchitectureMd();
if (!archMd) {
this.log("No ARCHITECTURE.md found — mechanical research cannot proceed without backend");
return {
phase: this.pipelineState!.current_phase,
stage: "research",
success: false,
artifacts_created: artifactsCreated,
decisions_made: decisionsMade,
escalations_raised: escalationsRaised,
duration_ms: Date.now() - stageStart,
error: "Research stage requires intelligence backend or existing ARCHITECTURE.md",
};
}
if (this.config.git.auto_commit && this.gitContext!.isGitRepo()) {
const researchCommit = CommitBuilder.buildResearchCommit(
1,
this.currentMilestone,
"initial domain research",
["Research completed. Key findings in .ci/ARCHITECTURE.md and .ci/PROJECT.md updates."]
["Research completed. Key findings in .ciagent/ARCHITECTURE.md and .ciagent/PROJECT.md updates."]
);
try {
const { execSync } = await import("node:child_process");
@@ -252,12 +305,13 @@ export class OrchestratorAgent extends BaseAgent {
cwd: context.project_path,
stdio: "pipe",
});
} catch {
} catch (err) {
this.warn(`Research commit failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
this.pipelineState!.research_completed = true;
artifactsCreated.push(".ci/ARCHITECTURE.md");
artifactsCreated.push(".ciagent/ARCHITECTURE.md");
break;
}
@@ -273,11 +327,42 @@ export class OrchestratorAgent extends BaseAgent {
case "execute":
this.log("Executing implementation...");
if (!context.backend) {
this.log("No backend available — mechanical execution cannot implement code changes");
return {
phase: this.pipelineState!.current_phase,
stage: "execute",
success: false,
artifacts_created: artifactsCreated,
decisions_made: decisionsMade,
escalations_raised: escalationsRaised,
duration_ms: Date.now() - stageStart,
error: "Execute stage requires intelligence backend for code implementation",
};
}
this.pipelineState!.execute_completed = true;
break;
case "verify": {
this.log("Running verification...");
const { VerificationPipeline } = await import("../verification/index.js");
const verification = new VerificationPipeline(context.project_path);
const verifyResult = await verification.run(this.pipelineState!.current_phase || 1);
if (!verifyResult.all_passed) {
return {
phase: this.pipelineState!.current_phase,
stage: "verify",
success: false,
artifacts_created: artifactsCreated,
decisions_made: decisionsMade,
escalations_raised: escalationsRaised,
duration_ms: Date.now() - stageStart,
error: `Verification failed: ${verifyResult.escalations_needed.join("; ")}`,
};
}
this.pipelineState!.verify_completed = true;
if (this.config.git.auto_commit && this.gitContext!.isGitRepo()) {
@@ -293,7 +378,8 @@ export class OrchestratorAgent extends BaseAgent {
cwd: context.project_path,
stdio: "pipe",
});
} catch {
} catch (err) {
this.warn(`Verify commit failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
@@ -318,7 +404,8 @@ export class OrchestratorAgent extends BaseAgent {
cwd: context.project_path,
stdio: "pipe",
});
} catch {
} catch (err) {
this.warn(`Completion commit failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
@@ -339,7 +426,7 @@ export class OrchestratorAgent extends BaseAgent {
private generateCompletionReport(): string {
const lines: string[] = [
"# CI Completion Report",
"# CIAgent Completion Report",
"",
`✓ Pipeline completed successfully (git-native)`,
"",
+13 -4
View File
@@ -3,17 +3,26 @@ import { BaseAgent, AgentContext, AgentResult } from "./base.js";
export class PhaseResearcherAgent extends BaseAgent {
readonly name = "phase-researcher";
readonly description = "Researches how to implement a specific phase well.";
readonly workflow = "research";
async execute(context: AgentContext): Promise<AgentResult> {
this.log("Researching phase implementation...");
const start = Date.now();
this.log("Researching phase implementation...");
if (context.backend) {
const result = await this.executeViaBackend(
context,
`Research how to implement phase ${context.phase} well. Specification: ${context.specification}`
);
return { ...result, duration_ms: Date.now() - start };
}
return {
success: true,
output: "Phase research complete",
artifacts_created: ["RESEARCH.md"],
success: false,
output: "Phase research requires an intelligence backend.",
artifacts_created: [],
decisions: 0,
escalations: 0,
duration_ms: Date.now() - start,
error: "No intelligence backend available",
};
}
}
+12 -3
View File
@@ -3,17 +3,26 @@ import { BaseAgent, AgentContext, AgentResult } from "./base.js";
export class PlanCheckerAgent extends BaseAgent {
readonly name = "plan-checker";
readonly description = "Verifies plan quality. On ISSUES FOUND, triggers automatic plan revision (up to 3 iterations).";
readonly workflow = "plan";
async execute(context: AgentContext): Promise<AgentResult> {
this.log("Checking plan quality...");
const start = Date.now();
this.log("Checking plan quality...");
if (context.backend) {
const result = await this.executeViaBackend(
context,
`Verify plan quality for phase ${context.phase}. Specification: ${context.specification}`
);
return { ...result, duration_ms: Date.now() - start };
}
return {
success: true,
output: "Plan check passed",
success: false,
output: "Plan checking requires an intelligence backend.",
artifacts_created: [],
decisions: 0,
escalations: 0,
duration_ms: Date.now() - start,
error: "No intelligence backend available",
};
}
}
+14 -5
View File
@@ -3,17 +3,26 @@ import { BaseAgent, AgentContext, AgentResult } from "./base.js";
export class PlannerAgent extends BaseAgent {
readonly name = "planner";
readonly description = "Creates phase plans with tasks. Never sets autonomous:false — decomposes into verifiable subtasks.";
readonly workflow = "plan";
async execute(context: AgentContext): Promise<AgentResult> {
this.log("Creating phase plan...");
const start = Date.now();
this.log("Creating phase plan...");
if (context.backend) {
const result = await this.executeViaBackend(
context,
`Create a phase plan for stage ${context.stage}, phase ${context.phase}. Specification: ${context.specification}`
);
return { ...result, duration_ms: Date.now() - start };
}
return {
success: true,
output: "Plan created with verifiable subtasks",
artifacts_created: ["PLAN.md"],
decisions: 1,
success: false,
output: "Planning requires an intelligence backend. Configure one with: ci init --backend",
artifacts_created: [],
decisions: 0,
escalations: 0,
duration_ms: Date.now() - start,
error: "No intelligence backend available",
};
}
}
+13 -4
View File
@@ -3,17 +3,26 @@ import { BaseAgent, AgentContext, AgentResult } from "./base.js";
export class ProjectResearcherAgent extends BaseAgent {
readonly name = "project-researcher";
readonly description = "Researches the domain ecosystem for a new project.";
readonly workflow = "research";
async execute(context: AgentContext): Promise<AgentResult> {
this.log("Researching project domain ecosystem...");
const start = Date.now();
this.log("Researching project domain ecosystem...");
if (context.backend) {
const result = await this.executeViaBackend(
context,
`Research the domain ecosystem for: ${context.specification}`
);
return { ...result, duration_ms: Date.now() - start };
}
return {
success: true,
output: "Project research complete",
artifacts_created: ["RESEARCH.md"],
success: false,
output: "Project research requires an intelligence backend.",
artifacts_created: [],
decisions: 0,
escalations: 0,
duration_ms: Date.now() - start,
error: "No intelligence backend available",
};
}
}
+13 -4
View File
@@ -3,17 +3,26 @@ import { BaseAgent, AgentContext, AgentResult } from "./base.js";
export class ResearchSynthesizerAgent extends BaseAgent {
readonly name = "research-synthesizer";
readonly description = "Synthesizes research files into a cohesive summary for roadmap creation.";
readonly workflow = "research";
async execute(context: AgentContext): Promise<AgentResult> {
this.log("Synthesizing research...");
const start = Date.now();
this.log("Synthesizing research...");
if (context.backend) {
const result = await this.executeViaBackend(
context,
`Synthesize research findings into a summary for: ${context.specification}`
);
return { ...result, duration_ms: Date.now() - start };
}
return {
success: true,
output: "Research synthesis complete",
artifacts_created: ["SUMMARY.md"],
success: false,
output: "Research synthesis requires an intelligence backend.",
artifacts_created: [],
decisions: 0,
escalations: 0,
duration_ms: Date.now() - start,
error: "No intelligence backend available",
};
}
}
+14 -5
View File
@@ -3,17 +3,26 @@ import { BaseAgent, AgentContext, AgentResult } from "./base.js";
export class ResearcherAgent extends BaseAgent {
readonly name = "researcher";
readonly description = "Researches project domain. Logs assumptions instead of asking for validation.";
readonly workflow = "research";
async execute(context: AgentContext): Promise<AgentResult> {
this.log("Researching domain...");
const start = Date.now();
this.log("Researching domain...");
if (context.backend) {
const result = await this.executeViaBackend(
context,
`Research the domain for: ${context.specification}`
);
return { ...result, duration_ms: Date.now() - start };
}
return {
success: true,
output: "Research complete",
artifacts_created: ["RESEARCH.md"],
decisions: 1,
success: false,
output: "Research requires an intelligence backend. Configure one with: ci init --backend",
artifacts_created: [],
decisions: 0,
escalations: 0,
duration_ms: Date.now() - start,
error: "No intelligence backend available",
};
}
}
+14 -5
View File
@@ -3,17 +3,26 @@ import { BaseAgent, AgentContext, AgentResult } from "./base.js";
export class RoadmapperAgent extends BaseAgent {
readonly name = "roadmapper";
readonly description = "Creates and maintains project roadmaps.";
readonly workflow = "plan";
async execute(context: AgentContext): Promise<AgentResult> {
this.log("Creating roadmap...");
const start = Date.now();
this.log("Creating roadmap...");
if (context.backend) {
const result = await this.executeViaBackend(
context,
`Create project roadmap for: ${context.specification}`
);
return { ...result, duration_ms: Date.now() - start };
}
return {
success: true,
output: "Roadmap created",
artifacts_created: ["ROADMAP.md"],
decisions: 1,
success: false,
output: "Roadmap creation requires an intelligence backend.",
artifacts_created: [],
decisions: 0,
escalations: 0,
duration_ms: Date.now() - start,
error: "No intelligence backend available",
};
}
}
+14 -5
View File
@@ -3,17 +3,26 @@ import { BaseAgent, AgentContext, AgentResult } from "./base.js";
export class SecurityAuditorAgent extends BaseAgent {
readonly name = "security-auditor";
readonly description = "Auto-dispositions threats: low=accept, medium=mitigate, high=escalate.";
readonly workflow = "verify";
async execute(context: AgentContext): Promise<AgentResult> {
this.log("Running security audit...");
const start = Date.now();
this.log("Running security audit...");
if (context.backend) {
const result = await this.executeViaBackend(
context,
`Perform security audit for phase ${context.phase}. Specification: ${context.specification}`
);
return { ...result, duration_ms: Date.now() - start };
}
return {
success: true,
output: "Security audit complete",
artifacts_created: ["SECURITY.md"],
decisions: 1,
success: false,
output: "Security auditing requires an intelligence backend. Configure one with: ci init --backend",
artifacts_created: [],
decisions: 0,
escalations: 0,
duration_ms: Date.now() - start,
error: "No intelligence backend available",
};
}
}
+14 -5
View File
@@ -2,18 +2,27 @@ import { BaseAgent, AgentContext, AgentResult } from "./base.js";
export class SolutionWriterAgent extends BaseAgent {
readonly name = "solution-writer";
readonly description = "Produces structured solution documents for .planning/solutions/.";
readonly description = "Produces structured solution documents.";
readonly workflow = "execute";
async execute(context: AgentContext): Promise<AgentResult> {
this.log("Writing solution document...");
const start = Date.now();
this.log("Writing solution document...");
if (context.backend) {
const result = await this.executeViaBackend(
context,
`Write a structured solution document for: ${context.specification}`
);
return { ...result, duration_ms: Date.now() - start };
}
return {
success: true,
output: "Solution document written",
artifacts_created: ["SOLUTION.md"],
success: false,
output: "Solution writing requires an intelligence backend.",
artifacts_created: [],
decisions: 0,
escalations: 0,
duration_ms: Date.now() - start,
error: "No intelligence backend available",
};
}
}
+28
View File
@@ -0,0 +1,28 @@
import { BaseAgent, AgentContext, AgentResult } from "./base.js";
export class TesterAgent extends BaseAgent {
readonly name = "tester";
readonly description = "Runs automated tests and validates test coverage.";
readonly workflow = "test";
async execute(context: AgentContext): Promise<AgentResult> {
const start = Date.now();
this.log("Running automated tests...");
if (context.backend) {
const result = await this.executeViaBackend(
context,
`Run automated tests for: ${context.specification}`
);
return { ...result, duration_ms: Date.now() - start };
}
return {
success: false,
output: "Testing requires an intelligence backend.",
artifacts_created: [],
decisions: 0,
escalations: 0,
duration_ms: Date.now() - start,
error: "No intelligence backend available",
};
}
}
+13 -4
View File
@@ -3,17 +3,26 @@ import { BaseAgent, AgentContext, AgentResult } from "./base.js";
export class VerifierAgent extends BaseAgent {
readonly name = "verifier";
readonly description = "Verifies phase outputs. Generates automated tests instead of requesting human UAT.";
readonly workflow = "verify";
async execute(context: AgentContext): Promise<AgentResult> {
this.log("Verifying phase output...");
const start = Date.now();
this.log("Verifying phase output...");
if (context.backend) {
const result = await this.executeViaBackend(
context,
`Verify phase ${context.phase} output. Specification: ${context.specification}`
);
return { ...result, duration_ms: Date.now() - start };
}
return {
success: true,
output: "Verification complete — all checks passed",
artifacts_created: ["VERIFICATION.md"],
success: false,
output: "Verification requires an intelligence backend. Configure one with: ci init --backend",
artifacts_created: [],
decisions: 0,
escalations: 0,
duration_ms: Date.now() - start,
error: "No intelligence backend available",
};
}
}
+103
View File
@@ -0,0 +1,103 @@
import { OllamaLocalBackend } from "../backends/ollama-local.js";
import { OllamaCloudBackend } from "../backends/ollama-cloud.js";
import { OpencodeBackend } from "../backends/opencode.js";
import { resolveBackend, createBackend } from "../backends/index.js";
import { DEFAULT_BACKEND_CONFIG, BackendUnavailableError } from "../backends/types.js";
describe("Backend Availability Detection", () => {
describe("OllamaLocalBackend.isAvailable", () => {
it("returns false for unreachable host", async () => {
const backend = new OllamaLocalBackend({
base_url: "http://localhost:1",
model_profile: "balanced",
});
expect(await backend.isAvailable()).toBe(false);
});
it("returns false for invalid URL", async () => {
const backend = new OllamaLocalBackend({
base_url: "not-a-url",
model_profile: "balanced",
});
expect(await backend.isAvailable()).toBe(false);
});
it("returns false for timeout", async () => {
const backend = new OllamaLocalBackend({
base_url: "http://192.0.2.1",
model_profile: "balanced",
});
expect(await backend.isAvailable()).toBe(false);
}, 10000);
});
describe("OllamaCloudBackend.isAvailable", () => {
it("returns false when base_url is empty", async () => {
const backend = new OllamaCloudBackend({
base_url: "",
api_key_env: "OLLAMA_CLOUD_API_KEY",
model_profile: "quality",
});
expect(await backend.isAvailable()).toBe(false);
});
it("returns false when no API key in env", async () => {
const backend = new OllamaCloudBackend({
base_url: "https://api.example.com",
api_key_env: "NONEXISTENT_ENV_VAR_12345",
model_profile: "quality",
timeout_ms: 5000,
});
expect(await backend.isAvailable()).toBe(false);
});
});
describe("OpencodeBackend.isAvailable", () => {
it("returns false when executable not found", async () => {
const backend = new OpencodeBackend({
enabled: true,
executable: "nonexistent-opencode-binary-xyz",
});
expect(await backend.isAvailable()).toBe(false);
});
it("returns false when disabled", async () => {
const backend = new OpencodeBackend({ enabled: false });
expect(await backend.isAvailable()).toBe(false);
});
});
describe("resolveBackend auto-detection", () => {
it("throws BackendUnavailableError when no backends available", async () => {
const config = {
...DEFAULT_BACKEND_CONFIG,
llm_backends: {
"ollama-local": { base_url: "http://localhost:1", model_profile: "balanced" as const },
"ollama-cloud": { base_url: "", api_key_env: "NONEXISTENT_12345", model_profile: "quality" as const },
},
agent_backends: {
opencode: { enabled: true, executable: "nonexistent-opencode-binary-xyz" },
},
};
await expect(resolveBackend(config)).rejects.toThrow(BackendUnavailableError);
});
it("tries opencode before ollama-local", async () => {
expect(DEFAULT_BACKEND_CONFIG.provider).toBe("auto");
});
it("createBackend throws for unknown provider", () => {
expect(() => createBackend("unknown-provider" as "opencode", DEFAULT_BACKEND_CONFIG)).toThrow(BackendUnavailableError);
});
});
describe("BackendUnavailableError", () => {
it("contains installation hints", () => {
const err = new BackendUnavailableError("auto");
expect(err.message).toContain("opencode");
expect(err.message).toContain("Ollama");
expect(err.message).toContain("OLLAMA_CLOUD_API_KEY");
});
});
});
+129
View File
@@ -0,0 +1,129 @@
import { BackendUnavailableError, emptyTokenUsage, emptyBackendResult, DEFAULT_BACKEND_CONFIG } from "../backends/types.js";
import { OllamaLocalBackend } from "../backends/ollama-local.js";
import { OllamaCloudBackend } from "../backends/ollama-cloud.js";
import { OpencodeBackend } from "../backends/opencode.js";
describe("BackendUnavailableError", () => {
it("includes backend name in message", () => {
const err = new BackendUnavailableError("ollama-local");
expect(err.message).toContain("ollama-local");
expect(err.backendName).toBe("ollama-local");
});
it("includes agent name when provided", () => {
const err = new BackendUnavailableError("opencode", "executor");
expect(err.agentName).toBe("executor");
expect(err.message).toContain("executor");
});
});
describe("emptyTokenUsage", () => {
it("returns zeroed usage", () => {
const usage = emptyTokenUsage();
expect(usage.input_tokens).toBe(0);
expect(usage.output_tokens).toBe(0);
expect(usage.total_tokens).toBe(0);
expect(usage.estimated_cost_usd).toBe(0);
});
});
describe("emptyBackendResult", () => {
it("returns failed result with no artifacts", () => {
const result = emptyBackendResult("something failed");
expect(result.success).toBe(false);
expect(result.error).toBe("something failed");
expect(result.artifacts).toEqual([]);
expect(result.decisions).toEqual([]);
expect(result.escalations).toEqual([]);
});
it("returns result without error when no message provided", () => {
const result = emptyBackendResult();
expect(result.success).toBe(false);
expect(result.error).toBeUndefined();
});
});
describe("DEFAULT_BACKEND_CONFIG", () => {
it("has auto provider by default", () => {
expect(DEFAULT_BACKEND_CONFIG.provider).toBe("auto");
});
it("has opencode agent backend enabled", () => {
expect(DEFAULT_BACKEND_CONFIG.agent_backends.opencode?.enabled).toBe(true);
});
it("has ollama-local and ollama-cloud llm backends", () => {
expect(DEFAULT_BACKEND_CONFIG.llm_backends["ollama-local"]).toBeDefined();
expect(DEFAULT_BACKEND_CONFIG.llm_backends["ollama-cloud"]).toBeDefined();
});
});
describe("OllamaLocalBackend", () => {
it("has correct name and type", () => {
const backend = new OllamaLocalBackend();
expect(backend.name).toBe("ollama-local");
expect(backend.type).toBe("llm");
});
it("returns false when local Ollama is not available", async () => {
const backend = new OllamaLocalBackend({
base_url: "http://localhost:1",
model_profile: "balanced",
});
const available = await backend.isAvailable();
expect(available).toBe(false);
});
it("uses default config when none provided", () => {
const backend = new OllamaLocalBackend();
expect(backend).toBeDefined();
});
});
describe("OllamaCloudBackend", () => {
it("has correct name and type", () => {
const backend = new OllamaCloudBackend();
expect(backend.name).toBe("ollama-cloud");
expect(backend.type).toBe("llm");
});
it("returns false when no base_url configured", async () => {
const backend = new OllamaCloudBackend({
base_url: "",
api_key_env: "NONEXISTENT_KEY",
model_profile: "quality",
timeout_ms: 5000,
});
const available = await backend.isAvailable();
expect(available).toBe(false);
});
it("returns false when no API key available", async () => {
const backend = new OllamaCloudBackend({
base_url: "https://example.com",
api_key_env: "NONEXISTENT_CI_KEY_12345",
model_profile: "quality",
timeout_ms: 5000,
});
const available = await backend.isAvailable();
expect(available).toBe(false);
});
});
describe("OpencodeBackend", () => {
it("has correct name and type", () => {
const backend = new OpencodeBackend();
expect(backend.name).toBe("opencode");
expect(backend.type).toBe("agent");
});
it("returns false when opencode is not installed", async () => {
const backend = new OpencodeBackend({
enabled: true,
executable: "nonexistent-opencode-binary-xyz",
});
const available = await backend.isAvailable();
expect(available).toBe(false);
});
});
+55
View File
@@ -0,0 +1,55 @@
import { IntelligenceBackend, BackendConfigSection, BackendUnavailableError } from "./types.js";
import { OpencodeBackend } from "./opencode.js";
import { OllamaLocalBackend } from "./ollama-local.js";
import { OllamaCloudBackend } from "./ollama-cloud.js";
const AUTO_DETECT_ORDER: Array<"opencode" | "ollama-local" | "ollama-cloud"> = [
"opencode",
"ollama-local",
"ollama-cloud",
];
export function createBackend(
name: string,
config: BackendConfigSection
): IntelligenceBackend {
switch (name) {
case "opencode":
return new OpencodeBackend(config.agent_backends.opencode);
case "ollama-local":
return new OllamaLocalBackend(config.llm_backends["ollama-local"]);
case "ollama-cloud":
return new OllamaCloudBackend(config.llm_backends["ollama-cloud"]);
default:
throw new BackendUnavailableError(name);
}
}
export async function resolveBackend(
config: BackendConfigSection
): Promise<IntelligenceBackend> {
if (config.provider !== "auto") {
const backend = createBackend(config.provider, config);
if (!(await backend.isAvailable())) {
throw new BackendUnavailableError(config.provider);
}
return backend;
}
for (const name of AUTO_DETECT_ORDER) {
try {
const backend = createBackend(name, config);
if (await backend.isAvailable()) {
return backend;
}
} catch {}
}
throw new BackendUnavailableError("auto");
}
export { IntelligenceBackend, BackendConfigSection, BackendUnavailableError } from "./types.js";
export { ToolRegistry, ToolDefinition, ToolCall, ToolResult } from "./tool-registry.js";
export { OpencodeBackend } from "./opencode.js";
export { OllamaLocalBackend } from "./ollama-local.js";
export { OllamaCloudBackend } from "./ollama-cloud.js";
+229
View File
@@ -0,0 +1,229 @@
import * as fs from "node:fs";
import * as path from "node:path";
import * as os from "node:os";
import { OllamaBaseBackend, OllamaMessage, OllamaChatResponse } from "../backends/ollama-base.js";
import { ToolRegistry } from "../backends/tool-registry.js";
import { BackendRequest } from "../backends/types.js";
class TestableOllamaBaseBackend extends OllamaBaseBackend {
readonly name = "test-base";
private mockResponse: OllamaChatResponse;
private callCount: number;
constructor(mockResponse: OllamaChatResponse) {
super(undefined);
this.mockResponse = mockResponse;
this.callCount = 0;
}
async isAvailable(): Promise<boolean> {
return true;
}
getCallCount(): number {
return this.callCount;
}
protected async callModel(
messages: OllamaMessage[],
model: string,
toolRegistry: ToolRegistry
): Promise<OllamaChatResponse> {
this.callCount++;
return this.mockResponse;
}
protected resolveModel(): string {
return "test-model";
}
}
describe("OllamaBaseBackend", () => {
let tempDir: string;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "ciagent-ollama-base-test-"));
});
afterEach(() => {
fs.rmSync(tempDir, { recursive: true, force: true });
});
it("returns success when model responds without tool calls", async () => {
const mockResponse: OllamaChatResponse = {
choices: [{
message: {
content: '{"success": true, "output": "task completed"}',
},
}],
usage: { prompt_tokens: 10, completion_tokens: 20, total_tokens: 30 },
};
const backend = new TestableOllamaBaseBackend(mockResponse);
const request: BackendRequest = {
persona: "executor",
workflow: "execute",
task: "Do something",
context: {
project_path: tempDir,
phase: 1,
stage: "execute",
specification: "",
config_path: "",
},
autonomy: "full",
};
const result = await backend.execute(request);
expect(result.success).toBe(true);
expect(result.output).toContain("task completed");
});
it("handles tool calls in response", async () => {
const writePath = path.join(tempDir, "output.txt");
const responses: OllamaChatResponse[] = [
{
choices: [{
message: {
content: "",
tool_calls: [{
function: { name: "writeFile", arguments: JSON.stringify({ path: writePath, content: "hello" }) },
}],
},
}],
usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 },
},
{
choices: [{
message: {
content: '{"success": true, "output": "file written"}',
},
}],
usage: { prompt_tokens: 5, completion_tokens: 10, total_tokens: 15 },
},
];
let callIndex = 0;
class ToolCallBackend extends OllamaBaseBackend {
readonly name = "tool-call-test";
constructor() {
super(undefined);
}
async isAvailable(): Promise<boolean> { return true; }
protected async callModel(): Promise<OllamaChatResponse> {
return responses[callIndex++];
}
protected resolveModel(): string { return "test-model"; }
}
const backend = new ToolCallBackend();
const request: BackendRequest = {
persona: "executor",
workflow: "execute",
task: "Write a file",
context: {
project_path: tempDir,
phase: 1,
stage: "execute",
specification: "",
config_path: "",
},
autonomy: "full",
};
const result = await backend.execute(request);
expect(result.success).toBe(true);
expect(fs.existsSync(writePath)).toBe(true);
expect(fs.readFileSync(writePath, "utf-8")).toBe("hello");
expect(result.artifacts.length).toBe(1);
expect(result.artifacts[0].path).toBe(writePath);
});
it("stops after max tool rounds", async () => {
const alwaysToolCall: OllamaChatResponse = {
choices: [{
message: {
content: "",
tool_calls: [{
function: { name: "readFile", arguments: JSON.stringify({ path: "/etc/hostname" }) },
}],
},
}],
usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
};
class InfiniteLoopBackend extends OllamaBaseBackend {
readonly name = "infinite-loop";
private callCount = 0;
constructor() {
super(undefined);
}
async isAvailable(): Promise<boolean> { return true; }
protected async callModel(): Promise<OllamaChatResponse> {
this.callCount++;
return alwaysToolCall;
}
protected resolveModel(): string { return "test-model"; }
getCallCount() { return this.callCount; }
}
const backend = new InfiniteLoopBackend();
const request: BackendRequest = {
persona: "executor",
workflow: "execute",
task: "Infinite loop test",
context: {
project_path: tempDir,
phase: 1,
stage: "execute",
specification: "",
config_path: "",
},
autonomy: "full",
};
const result = await backend.execute(request);
expect(result.output).toContain("maximum rounds");
expect(backend.getCallCount()).toBe(50);
});
it("handles error from callModel gracefully", async () => {
class ErrorBackend extends OllamaBaseBackend {
readonly name = "error-backend";
constructor() {
super(undefined);
}
async isAvailable(): Promise<boolean> { return true; }
protected async callModel(): Promise<OllamaChatResponse> {
throw new Error("Model connection failed");
}
protected resolveModel(): string { return "test-model"; }
}
const backend = new ErrorBackend();
const request: BackendRequest = {
persona: "executor",
workflow: "execute",
task: "Fail test",
context: {
project_path: tempDir,
phase: 1,
stage: "execute",
specification: "",
config_path: "",
},
autonomy: "full",
};
const result = await backend.execute(request);
expect(result.success).toBe(false);
expect(result.error).toContain("Backend execution failed");
});
it("modelProfileToModel selects smallest for speed", () => {
const backend = new TestableOllamaBaseBackend({} as OllamaChatResponse);
const models = ["llama3.1:70b", "llama3.1:8b", "llama3.1"];
const selected = (backend as unknown as { modelProfileToModel: (p: string, m: string[]) => string }).modelProfileToModel("speed", models);
expect(selected).toBe("llama3.1");
});
});
+315
View File
@@ -0,0 +1,315 @@
import * as fs from "node:fs";
import * as path from "node:path";
import * as os from "node:os";
import {
IntelligenceBackend,
BackendRequest,
BackendResult,
BackendType,
LLMBackendConfig,
TokenUsage,
Artifact,
emptyTokenUsage,
emptyBackendResult,
} from "./types.js";
import { AgentName, ModelProfile } from "../types/config.js";
import { Decision } from "../types/decisions.js";
import { Escalation } from "../types/escalation.js";
import { ToolRegistry, ToolCall, ToolResult } from "./tool-registry.js";
const MAX_TOOL_ROUNDS = 50;
export abstract class OllamaBaseBackend implements IntelligenceBackend {
abstract readonly name: string;
readonly type: BackendType = "llm";
protected config: LLMBackendConfig;
protected projectPath: string;
constructor(config: LLMBackendConfig | undefined) {
this.config = config || { base_url: "http://localhost:11434", model_profile: "balanced" };
this.projectPath = process.cwd();
}
abstract isAvailable(): Promise<boolean>;
async execute(request: BackendRequest): Promise<BackendResult> {
const startTime = Date.now();
try {
const personaContent = this.loadPersona(request.persona);
const workflowContent = this.loadWorkflow(request.workflow);
const model = this.resolveModel();
const toolRegistry = new ToolRegistry(request.context.project_path);
const messages: OllamaMessage[] = [];
messages.push({
role: "system",
content: this.buildSystemPrompt(personaContent, workflowContent, request),
});
messages.push({
role: "user",
content: request.task,
});
let totalInputTokens = 0;
let totalOutputTokens = 0;
let round = 0;
const allArtifacts: Artifact[] = [];
const allDecisions: Decision[] = [];
const allEscalations: Escalation[] = [];
while (round < MAX_TOOL_ROUNDS) {
round++;
const response = await this.callModel(messages, model, toolRegistry);
totalInputTokens += response.usage?.prompt_tokens || 0;
totalOutputTokens += response.usage?.completion_tokens || 0;
const assistantContent = response.choices?.[0]?.message?.content || "";
const toolCalls = response.choices?.[0]?.message?.tool_calls;
messages.push({
role: "assistant",
content: assistantContent,
tool_calls: toolCalls,
});
if (!toolCalls || toolCalls.length === 0) {
return this.parseFinalResponse(assistantContent, allArtifacts, allDecisions, allEscalations, {
input_tokens: totalInputTokens,
output_tokens: totalOutputTokens,
total_tokens: totalInputTokens + totalOutputTokens,
estimated_cost_usd: 0,
});
}
for (const toolCall of toolCalls) {
const call: ToolCall = {
name: toolCall.function.name,
arguments: JSON.parse(toolCall.function.arguments),
};
const result = toolRegistry.execute(call);
messages.push({
role: "tool",
name: call.name,
content: result.content,
});
if (call.name === "writeFile" && !result.isError) {
allArtifacts.push({
path: String(call.arguments.path),
content: String(call.arguments.content),
operation: "create",
});
}
}
}
const finalContent = messages
.filter((m) => m.role === "assistant" && m.content)
.map((m) => m.content)
.join("\n");
return this.parseFinalResponse(
`Tool loop reached maximum rounds (${MAX_TOOL_ROUNDS}). Partial progress:\n${finalContent}`,
allArtifacts,
allDecisions,
allEscalations,
{ input_tokens: totalInputTokens, output_tokens: totalOutputTokens, total_tokens: totalInputTokens + totalOutputTokens, estimated_cost_usd: 0 }
);
} catch (err) {
return emptyBackendResult(`Backend execution failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
protected abstract callModel(
messages: OllamaMessage[],
model: string,
toolRegistry: ToolRegistry
): Promise<OllamaChatResponse>;
protected abstract resolveModel(): string;
protected buildSystemPrompt(persona: string, workflow: string, request: BackendRequest): string {
const parts = [persona];
if (workflow) {
parts.push("", "## Workflow Instructions", workflow);
}
parts.push(
"",
"## Execution Context",
`Autonomy level: ${request.autonomy}`,
`Project path: ${request.context.project_path}`,
`Phase: ${request.context.phase}`,
`Stage: ${request.context.stage}`,
"",
"## Output Format",
"When you have completed your task, output a JSON object with this structure:",
"```json",
'{',
' "success": true,',
' "output": "Summary of what was accomplished",',
' "artifacts": [{"path": "file/path", "content": "...", "operation": "create"}],',
' "decisions": [{"id": "D-NNN", "decision": "what", "rationale": "why", "confidence": 0.85, "category": "general", "alternatives_considered": [], "human_override": null, "timestamp": ""}],',
' "escalations": []',
'}',
"```"
);
return parts.join("\n");
}
protected loadPersona(persona: AgentName): string {
const candidates = [
path.join(os.homedir(), ".config", "opencode", "agents", `ci-${persona}.md`),
path.join(process.cwd(), "opencode", "agents", `ci-${persona}.md`),
];
for (const candidate of candidates) {
if (fs.existsSync(candidate)) {
return fs.readFileSync(candidate, "utf-8");
}
}
return `You are the CIAgent ${persona} agent. Execute the requested task thoroughly and autonomously.`;
}
protected loadWorkflow(workflow: string): string {
const candidates = [
path.join(os.homedir(), ".config", "opencode", "ci", "workflows", `${workflow}.md`),
path.join(process.cwd(), "opencode", "workflows", `${workflow}.md`),
];
for (const candidate of candidates) {
if (fs.existsSync(candidate)) {
return fs.readFileSync(candidate, "utf-8");
}
}
return "";
}
protected parseFinalResponse(
content: string,
artifacts: Artifact[],
decisions: Decision[],
escalations: Escalation[],
usage: TokenUsage
): BackendResult {
const jsonMatch = content.match(/\{[\s\S]*"success"[\s\S]*\}/);
if (jsonMatch) {
try {
const parsed = JSON.parse(jsonMatch[0]);
return {
success: parsed.success ?? true,
output: parsed.output || content,
artifacts: parsed.artifacts?.length ? this.parseArtifacts(parsed.artifacts) : artifacts,
decisions: parsed.decisions?.length ? this.parseDecisions(parsed.decisions) : decisions,
escalations: parsed.escalations?.length ? this.parseEscalations(parsed.escalations) : escalations,
usage,
};
} catch {}
}
return {
success: true,
output: content,
artifacts,
decisions,
escalations,
usage,
};
}
private parseArtifacts(raw: unknown[]): Artifact[] {
return raw.filter((a): a is Record<string, unknown> => !!a).map((a) => ({
path: String(a.path || ""),
content: String(a.content || ""),
operation: (a.operation as Artifact["operation"]) || "create",
}));
}
private parseDecisions(raw: unknown[]): Decision[] {
return raw.filter((d): d is Record<string, unknown> => !!d).map((d) => ({
id: String(d.id || "D-000"),
decision: String(d.decision || ""),
rationale: String(d.rationale || ""),
confidence: Number(d.confidence || 0.5),
category: (d.category as Decision["category"]) || "general",
alternatives_considered: Array.isArray(d.alternatives_considered)
? d.alternatives_considered.map((a: unknown) =>
typeof a === "string"
? { option: a, rejected_reason: "" }
: (a as { option: string; rejected_reason: string })
)
: [],
human_override: d.human_override ? String(d.human_override) : null,
timestamp: String(d.timestamp || new Date().toISOString()),
}));
}
private parseEscalations(raw: unknown[]): Escalation[] {
return raw.filter((e): e is Record<string, unknown> => !!e).map((e) => ({
id: String(e.id || "E-000"),
timestamp: String(e.timestamp || new Date().toISOString()),
type: (e.type as Escalation["type"]) || "specification_ambiguity",
phase: String(e.phase || ""),
description: String(e.description || ""),
context: String(e.context || ""),
options: Array.isArray(e.options) ? e.options : [],
default_option_id: String(e.default_option_id || ""),
resolution: (e.resolution as Escalation["resolution"]) || "pending",
audit_file: String(e.audit_file || ""),
}));
}
protected modelProfileToModel(profile: ModelProfile, availableModels: string[]): string {
if (availableModels.length === 0) return "llama3.1";
const sorted = [...availableModels].sort((a, b) => a.length - b.length);
switch (profile) {
case "speed":
return sorted[0];
case "quality":
return sorted[sorted.length - 1];
case "balanced":
default:
return sorted[Math.floor(sorted.length / 2)] || sorted[0];
}
}
protected async fetchAvailableModels(): Promise<string[]> {
try {
const response = await fetch(`${this.config.base_url}/api/tags`);
if (!response.ok) return [];
const data = await response.json() as { models?: Array<{ name: string }> };
return (data.models || []).map((m) => m.name);
} catch {
return [];
}
}
}
interface OllamaMessage {
role: "system" | "user" | "assistant" | "tool";
content: string;
name?: string;
tool_calls?: Array<{
function: { name: string; arguments: string };
}>;
}
interface OllamaChatResponse {
choices?: Array<{
message: {
content: string;
tool_calls?: Array<{
function: { name: string; arguments: string };
}>;
};
}>;
usage?: {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
};
}
export { OllamaMessage, OllamaChatResponse };
+90
View File
@@ -0,0 +1,90 @@
import * as os from "node:os";
import { OllamaCloudBackend } from "../backends/ollama-cloud.js";
describe("OllamaCloudBackend Retry/Rate-Limit", () => {
describe("configuration", () => {
it("uses default config when none provided", () => {
const backend = new OllamaCloudBackend();
expect(backend.name).toBe("ollama-cloud");
expect(backend.type).toBe("llm");
});
it("accepts custom config", () => {
const backend = new OllamaCloudBackend({
base_url: "https://custom.api.com",
api_key_env: "MY_API_KEY",
model_profile: "quality",
timeout_ms: 30000,
});
expect(backend).toBeDefined();
});
});
describe("isAvailable", () => {
it("returns false when base_url is empty", async () => {
const backend = new OllamaCloudBackend({
base_url: "",
api_key_env: "KEY",
model_profile: "quality",
});
expect(await backend.isAvailable()).toBe(false);
});
it("returns false when no API key in environment", async () => {
const backend = new OllamaCloudBackend({
base_url: "https://api.example.com",
api_key_env: "NONEXISTENT_API_KEY_VAR_98765",
model_profile: "quality",
timeout_ms: 5000,
});
expect(await backend.isAvailable()).toBe(false);
});
it("returns false for unreachable endpoint", async () => {
process.env.TEST_OLLAMA_CLOUD_KEY = "test-key";
const backend = new OllamaCloudBackend({
base_url: "http://localhost:1",
api_key_env: "TEST_OLLAMA_CLOUD_KEY",
model_profile: "quality",
timeout_ms: 5000,
});
expect(await backend.isAvailable()).toBe(false);
delete process.env.TEST_OLLAMA_CLOUD_KEY;
});
});
describe("retry behavior", () => {
it("MAX_RETRIES is 3", () => {
const source = OllamaCloudBackend.toString();
expect(source).toBeDefined();
});
it("BASE_BACKOFF_MS is 1000", () => {
const source = OllamaCloudBackend.toString();
expect(source).toBeDefined();
});
});
describe("authentication", () => {
it("uses API key from environment variable", () => {
process.env.TEST_CI_CLOUD_KEY = "sk-test-key-123";
const backend = new OllamaCloudBackend({
base_url: "https://api.example.com",
api_key_env: "TEST_CI_CLOUD_KEY",
model_profile: "quality",
});
expect(backend).toBeDefined();
delete process.env.TEST_CI_CLOUD_KEY;
});
it("returns false when API key env var is not set", async () => {
const backend = new OllamaCloudBackend({
base_url: "https://api.example.com",
api_key_env: "DEFINITELY_NOT_SET_99999",
model_profile: "quality",
timeout_ms: 5000,
});
expect(await backend.isAvailable()).toBe(false);
});
});
});
+139
View File
@@ -0,0 +1,139 @@
import { OllamaBaseBackend, OllamaMessage, OllamaChatResponse } from "./ollama-base.js";
import { OllamaCloudConfig, emptyBackendResult } from "./types.js";
import { ToolRegistry } from "./tool-registry.js";
const MAX_RETRIES = 3;
const BASE_BACKOFF_MS = 1000;
export class OllamaCloudBackend extends OllamaBaseBackend {
readonly name = "ollama-cloud";
private cloudConfig: OllamaCloudConfig;
private apiKey: string | null;
constructor(config?: OllamaCloudConfig) {
super(config);
this.cloudConfig = config || {
base_url: "",
api_key_env: "OLLAMA_CLOUD_API_KEY",
model_profile: "quality",
timeout_ms: 60000,
};
this.apiKey = this.resolveApiKey();
}
async isAvailable(): Promise<boolean> {
if (!this.cloudConfig.base_url) return false;
if (!this.apiKey) return false;
try {
const response = await fetch(`${this.cloudConfig.base_url}/v1/models`, {
headers: this.getAuthHeaders(),
signal: AbortSignal.timeout(10000),
});
return response.ok;
} catch {
return false;
}
}
protected resolveModel(): string {
if (this.cloudConfig.model) return this.cloudConfig.model;
return "llama3.1:70b";
}
protected async callModel(
messages: OllamaMessage[],
model: string,
toolRegistry: ToolRegistry
): Promise<OllamaChatResponse> {
if (!this.apiKey) {
throw new Error(`API key not found. Set ${this.cloudConfig.api_key_env} environment variable.`);
}
const url = `${this.cloudConfig.base_url}/v1/chat/completions`;
const body: Record<string, unknown> = {
model,
messages: messages.map((m) => {
const msg: Record<string, unknown> = { role: m.role, content: m.content };
if (m.name) msg.name = m.name;
if (m.tool_calls) msg.tool_calls = m.tool_calls;
return msg;
}),
tools: toolRegistry.getOpenAIToolSchema(),
stream: false,
};
return this.callWithRetry(url, body);
}
private async callWithRetry(
url: string,
body: Record<string, unknown>,
attempt: number = 0
): Promise<OllamaChatResponse> {
const timeout = this.cloudConfig.timeout_ms || 60000;
try {
const response = await fetch(url, {
method: "POST",
headers: {
...this.getAuthHeaders(),
"Content-Type": "application/json",
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(timeout),
});
if (response.status === 429 && attempt < MAX_RETRIES) {
const retryAfter = response.headers.get("Retry-After");
const delay = retryAfter
? parseInt(retryAfter) * 1000
: BASE_BACKOFF_MS * Math.pow(2, attempt);
await this.sleep(delay);
return this.callWithRetry(url, body, attempt + 1);
}
if (response.status === 401 || response.status === 403) {
throw new Error(`Authentication failed. Check ${this.cloudConfig.api_key_env} environment variable.`);
}
if (response.status === 402) {
throw new Error("Quota exceeded. Check your Ollama Cloud billing status.");
}
if (!response.ok) {
const errorText = await response.text().catch(() => "unknown error");
throw new Error(`Ollama Cloud API error (${response.status}): ${errorText}`);
}
return (await response.json()) as OllamaChatResponse;
} catch (err) {
if (err instanceof TypeError && err.message.includes("fetch")) {
if (attempt < MAX_RETRIES) {
await this.sleep(BASE_BACKOFF_MS * Math.pow(2, attempt));
return this.callWithRetry(url, body, attempt + 1);
}
}
throw err;
}
}
private getAuthHeaders(): Record<string, string> {
const headers: Record<string, string> = {};
if (this.apiKey) {
headers["Authorization"] = `Bearer ${this.apiKey}`;
}
return headers;
}
private resolveApiKey(): string | null {
return process.env[this.cloudConfig.api_key_env] || null;
}
private sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
}
+72
View File
@@ -0,0 +1,72 @@
import { OllamaBaseBackend, OllamaMessage, OllamaChatResponse } from "./ollama-base.js";
import { OllamaLocalConfig } from "./types.js";
import { ToolRegistry } from "./tool-registry.js";
export class OllamaLocalBackend extends OllamaBaseBackend {
readonly name = "ollama-local";
private localConfig: OllamaLocalConfig;
constructor(config?: OllamaLocalConfig) {
super(config);
this.localConfig = config || { base_url: "http://localhost:11434", model_profile: "balanced" };
}
async isAvailable(): Promise<boolean> {
try {
const response = await fetch(`${this.localConfig.base_url}/api/tags`, {
signal: AbortSignal.timeout(5000),
});
return response.ok;
} catch {
return false;
}
}
protected resolveModel(): string {
if (this.localConfig.model) return this.localConfig.model;
return this.modelProfileToModel(this.localConfig.model_profile, []);
}
protected async callModel(
messages: OllamaMessage[],
model: string,
toolRegistry: ToolRegistry
): Promise<OllamaChatResponse> {
let resolvedModel = model;
if (!this.localConfig.model) {
const models = await this.fetchAvailableModels();
resolvedModel = this.modelProfileToModel(this.localConfig.model_profile, models);
}
const url = `${this.localConfig.base_url}/v1/chat/completions`;
const body: Record<string, unknown> = {
model: resolvedModel,
messages: messages.map((m) => {
const msg: Record<string, unknown> = { role: m.role, content: m.content };
if (m.name) msg.name = m.name;
if (m.tool_calls) msg.tool_calls = m.tool_calls;
return msg;
}),
tools: toolRegistry.getOpenAIToolSchema(),
stream: false,
};
const timeout = this.localConfig.timeout_ms || 10000;
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
signal: AbortSignal.timeout(timeout),
});
if (!response.ok) {
const errorText = await response.text().catch(() => "unknown error");
throw new Error(`Ollama local API error (${response.status}): ${errorText}`);
}
return (await response.json()) as OllamaChatResponse;
}
}
+182
View File
@@ -0,0 +1,182 @@
import { execSync, spawn } from "node:child_process";
import * as fs from "node:fs";
import * as path from "node:path";
import * as os from "node:os";
import {
IntelligenceBackend,
BackendRequest,
BackendResult,
BackendType,
OpencodeBackendConfig,
emptyTokenUsage,
emptyBackendResult,
} from "./types.js";
export class OpencodeBackend implements IntelligenceBackend {
readonly name = "opencode";
readonly type: BackendType = "agent";
private config: OpencodeBackendConfig;
constructor(config?: OpencodeBackendConfig) {
this.config = config || { enabled: true };
}
async isAvailable(): Promise<boolean> {
const executable = this.config.executable || "opencode";
try {
const result = execSync(`${executable} --version`, {
encoding: "utf-8",
timeout: 5000,
stdio: "pipe",
});
return !!result;
} catch {
return false;
}
}
async execute(request: BackendRequest): Promise<BackendResult> {
const executable = this.config.executable || "opencode";
const startTime = Date.now();
try {
const serializedRequest = this.serializeRequest(request);
const tempFile = path.join(
os.tmpdir(),
`ci-request-${request.persona}-${Date.now()}.json`
);
fs.writeFileSync(tempFile, serializedRequest, "utf-8");
const command = `${executable} --non-interactive "/ci-${request.workflow} ${request.task}"`;
const contextEnv = {
...process.env,
CI_BACKEND_REQUEST: tempFile,
CI_PROJECT_PATH: request.context.project_path,
CI_PHASE: String(request.context.phase),
CI_STAGE: request.context.stage,
CI_AUTONOMY: request.autonomy,
};
const result = execSync(command, {
cwd: request.context.project_path,
encoding: "utf-8",
timeout: 600000,
env: contextEnv,
stdio: ["pipe", "pipe", "pipe"],
maxBuffer: 10 * 1024 * 1024,
});
try {
fs.unlinkSync(tempFile);
} catch {}
return this.parseResult(result, Date.now() - startTime);
} catch (err) {
const execErr = err as { stderr?: string; status?: number };
try {
const tempFile = path.join(
os.tmpdir(),
`ci-request-${request.persona}-${startTime}.json`
);
if (fs.existsSync(tempFile)) fs.unlinkSync(tempFile);
} catch {}
if (execErr.stderr) {
return emptyBackendResult(
`opencode execution failed (exit ${execErr.status || "unknown"}): ${execErr.stderr}`
);
}
return emptyBackendResult(
`opencode backend error: ${err instanceof Error ? err.message : String(err)}`
);
}
}
private serializeRequest(request: BackendRequest): string {
return JSON.stringify({
persona: request.persona,
workflow: request.workflow,
task: request.task,
context: {
project_path: request.context.project_path,
phase: request.context.phase,
stage: request.context.stage,
specification: request.context.specification,
config_path: request.context.config_path,
},
autonomy: request.autonomy,
}, null, 2);
}
private parseResult(output: string, durationMs: number): BackendResult {
const jsonMatch = output.match(/\{[\s\S]*"success"[\s\S]*\}/);
if (jsonMatch) {
try {
const parsed = JSON.parse(jsonMatch[0]);
return {
success: parsed.success ?? true,
output: parsed.output || output,
artifacts: Array.isArray(parsed.artifacts)
? parsed.artifacts.filter((a: unknown) => !!a).map((a: Record<string, unknown>) => ({
path: String(a.path || ""),
content: String(a.content || ""),
operation: (a.operation as "create" | "update" | "delete") || "create",
}))
: [],
decisions: Array.isArray(parsed.decisions)
? parsed.decisions.filter((d: unknown) => !!d).map((d: Record<string, unknown>) => ({
id: String(d.id || "D-000"),
decision: String(d.decision || ""),
rationale: String(d.rationale || ""),
confidence: Number(d.confidence || 0.5),
category: (d.category as "implementation_approach" | "technology_choice" | "architecture" | "scope" | "verification" | "security" | "deployment" | "general") || "general",
alternatives_considered: Array.isArray(d.alternatives_considered)
? d.alternatives_considered.map((a: unknown) =>
typeof a === "string"
? { option: a, rejected_reason: "" }
: (a as { option: string; rejected_reason: string })
)
: [],
human_override: d.human_override ? String(d.human_override) : null,
timestamp: String(d.timestamp || new Date().toISOString()),
}))
: [],
escalations: Array.isArray(parsed.escalations)
? parsed.escalations.filter((e: unknown) => !!e).map((e: Record<string, unknown>) => ({
id: String(e.id || "E-000"),
timestamp: String(e.timestamp || new Date().toISOString()),
type: (e.type as "irreversible_action" | "verification_failure" | "low_confidence_decision" | "security_escalation" | "specification_ambiguity") || "specification_ambiguity",
phase: String(e.phase || ""),
description: String(e.description || ""),
context: String(e.context || ""),
options: Array.isArray(e.options) ? e.options : [],
default_option_id: String(e.default_option_id || ""),
resolution: (e.resolution as "approved" | "rejected" | "modified" | "pending" | "timeout_auto_proceed") || "pending",
audit_file: String(e.audit_file || ""),
}))
: [],
usage: parsed.usage || {
...emptyTokenUsage(),
total_tokens: Math.ceil(output.length / 4),
},
};
} catch {}
}
return {
success: true,
output,
artifacts: [],
decisions: [],
escalations: [],
usage: {
...emptyTokenUsage(),
total_tokens: Math.ceil(output.length / 4),
},
};
}
}
+135
View File
@@ -0,0 +1,135 @@
import * as fs from "node:fs";
import * as path from "node:path";
import * as os from "node:os";
import { ToolRegistry, TOOL_DEFINITIONS } from "../backends/tool-registry.js";
describe("ToolRegistry Extended", () => {
let tempDir: string;
let registry: ToolRegistry;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "ciagent-tool-registry-ext-"));
registry = new ToolRegistry(tempDir);
});
afterEach(() => {
fs.rmSync(tempDir, { recursive: true, force: true });
});
describe("readFile edge cases", () => {
it("reads empty file", () => {
const filePath = path.join(tempDir, "empty.txt");
fs.writeFileSync(filePath, "");
const result = registry.execute({ name: "readFile", arguments: { path: filePath } });
expect(result.content).toBe("");
expect(result.isError).toBeFalsy();
});
it("reads file with unicode content", () => {
const filePath = path.join(tempDir, "unicode.txt");
fs.writeFileSync(filePath, "héllo wörld 🌍");
const result = registry.execute({ name: "readFile", arguments: { path: filePath } });
expect(result.content).toBe("héllo wörld 🌍");
});
it("handles unreadable file gracefully", () => {
if (process.getuid?.() === 0) return;
const filePath = path.join(tempDir, "unreadable.txt");
fs.writeFileSync(filePath, "data");
fs.chmodSync(filePath, 0o000);
const result = registry.execute({ name: "readFile", arguments: { path: filePath } });
expect(result.isError).toBe(true);
fs.chmodSync(filePath, 0o644);
});
});
describe("writeFile edge cases", () => {
it("overwrites existing file", () => {
const filePath = path.join(tempDir, "overwrite.txt");
fs.writeFileSync(filePath, "old");
const result = registry.execute({ name: "writeFile", arguments: { path: filePath, content: "new" } });
expect(result.isError).toBeFalsy();
expect(fs.readFileSync(filePath, "utf-8")).toBe("new");
});
it("creates nested directories", () => {
const filePath = path.join(tempDir, "a", "b", "c", "deep.txt");
const result = registry.execute({ name: "writeFile", arguments: { path: filePath, content: "deep" } });
expect(result.isError).toBeFalsy();
expect(fs.readFileSync(filePath, "utf-8")).toBe("deep");
});
});
describe("editFile edge cases", () => {
it("replaces only first occurrence", () => {
const filePath = path.join(tempDir, "multi.txt");
fs.writeFileSync(filePath, "aaa bbb aaa");
const result = registry.execute({ name: "editFile", arguments: { path: filePath, old: "aaa", new: "zzz" } });
expect(result.isError).toBeFalsy();
expect(fs.readFileSync(filePath, "utf-8")).toBe("zzz bbb aaa");
});
it("handles empty old string", () => {
const filePath = path.join(tempDir, "empty-old.txt");
fs.writeFileSync(filePath, "hello");
const result = registry.execute({ name: "editFile", arguments: { path: filePath, old: "", new: "X" } });
expect(fs.readFileSync(filePath, "utf-8")).toContain("X");
});
});
describe("runBash edge cases", () => {
it("respects cwd argument", () => {
const subDir = path.join(tempDir, "subdir");
fs.mkdirSync(subDir);
const result = registry.execute({ name: "runBash", arguments: { command: "pwd", cwd: subDir } });
expect(result.content).toContain("subdir");
expect(result.isError).toBeFalsy();
});
it("respects timeout argument", () => {
const result = registry.execute({ name: "runBash", arguments: { command: "sleep 100", timeout: 500 } });
expect(result.isError).toBe(true);
});
it("captures stderr in error output", () => {
const result = registry.execute({ name: "runBash", arguments: { command: "echo error >&2 && exit 1" } });
expect(result.isError).toBe(true);
expect(result.content).toContain("error");
});
});
describe("glob edge cases", () => {
it("finds files in subdirectories", () => {
const subDir = path.join(tempDir, "src");
fs.mkdirSync(subDir);
fs.writeFileSync(path.join(subDir, "app.ts"), "");
fs.writeFileSync(path.join(subDir, "util.ts"), "");
const result = registry.execute({ name: "glob", arguments: { pattern: "**/*.ts" } });
const matches = JSON.parse(result.content);
expect(matches.length).toBeGreaterThanOrEqual(2);
});
it("returns empty array for no matches", () => {
const result = registry.execute({ name: "glob", arguments: { pattern: "*.xyz" } });
const matches = JSON.parse(result.content);
expect(matches).toEqual([]);
});
});
describe("grep edge cases", () => {
it("supports include pattern filter", () => {
fs.writeFileSync(path.join(tempDir, "app.ts"), "const x = 1;\n");
fs.writeFileSync(path.join(tempDir, "app.js"), "const x = 1;\n");
const result = registry.execute({ name: "grep", arguments: { pattern: "const", include: "*.ts" } });
const matches = JSON.parse(result.content);
expect(matches.every((m: { file: string }) => m.file.endsWith(".ts"))).toBe(true);
});
it("returns empty for no matches", () => {
fs.writeFileSync(path.join(tempDir, "app.ts"), "nothing interesting\n");
const result = registry.execute({ name: "grep", arguments: { pattern: "NONEXISTENT_PATTERN_XYZ", include: "*.ts" } });
const matches = JSON.parse(result.content);
expect(matches).toEqual([]);
});
});
});
+139
View File
@@ -0,0 +1,139 @@
import * as fs from "node:fs";
import * as path from "node:path";
import * as os from "node:os";
import { ToolRegistry, TOOL_DEFINITIONS } from "../backends/tool-registry.js";
describe("ToolRegistry", () => {
let tempDir: string;
let registry: ToolRegistry;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "ciagent-tool-registry-test-"));
registry = new ToolRegistry(tempDir);
});
afterEach(() => {
fs.rmSync(tempDir, { recursive: true, force: true });
});
describe("definitions", () => {
it("provides 6 tool definitions", () => {
expect(TOOL_DEFINITIONS).toHaveLength(6);
const names = TOOL_DEFINITIONS.map((d) => d.name);
expect(names).toContain("readFile");
expect(names).toContain("writeFile");
expect(names).toContain("editFile");
expect(names).toContain("runBash");
expect(names).toContain("glob");
expect(names).toContain("grep");
});
it("getOpenAIToolSchema returns function-type schema", () => {
const schema = registry.getOpenAIToolSchema();
expect(schema.length).toBe(6);
expect(schema[0].type).toBe("function");
expect((schema[0].function as Record<string, unknown>).name).toBeDefined();
expect((schema[0].function as Record<string, unknown>).parameters).toBeDefined();
});
});
describe("readFile", () => {
it("reads an existing file", () => {
const filePath = path.join(tempDir, "test.txt");
fs.writeFileSync(filePath, "hello world");
const result = registry.execute({ name: "readFile", arguments: { path: filePath } });
expect(result.name).toBe("readFile");
expect(result.content).toBe("hello world");
expect(result.isError).toBeFalsy();
});
it("returns error for missing file", () => {
const result = registry.execute({ name: "readFile", arguments: { path: "/nonexistent/file.txt" } });
expect(result.isError).toBe(true);
expect(result.content).toContain("not found");
});
it("returns error for files exceeding max size", () => {
const bigRegistry = new ToolRegistry(tempDir, 10);
const filePath = path.join(tempDir, "big.txt");
fs.writeFileSync(filePath, "x".repeat(100));
const result = bigRegistry.execute({ name: "readFile", arguments: { path: filePath } });
expect(result.isError).toBe(true);
expect(result.content).toContain("too large");
});
});
describe("writeFile", () => {
it("writes a file creating parent directories", () => {
const filePath = path.join(tempDir, "sub", "dir", "test.txt");
const result = registry.execute({ name: "writeFile", arguments: { path: filePath, content: "written" } });
expect(result.isError).toBeFalsy();
expect(fs.readFileSync(filePath, "utf-8")).toBe("written");
});
});
describe("editFile", () => {
it("replaces an exact string in a file", () => {
const filePath = path.join(tempDir, "edit.txt");
fs.writeFileSync(filePath, "hello world");
const result = registry.execute({ name: "editFile", arguments: { path: filePath, old: "hello", new: "goodbye" } });
expect(result.isError).toBeFalsy();
expect(fs.readFileSync(filePath, "utf-8")).toBe("goodbye world");
});
it("returns error when old string not found", () => {
const filePath = path.join(tempDir, "edit.txt");
fs.writeFileSync(filePath, "hello world");
const result = registry.execute({ name: "editFile", arguments: { path: filePath, old: "missing", new: "replacement" } });
expect(result.isError).toBe(true);
});
it("returns error for missing file", () => {
const result = registry.execute({ name: "editFile", arguments: { path: "/nonexistent", old: "a", new: "b" } });
expect(result.isError).toBe(true);
});
});
describe("runBash", () => {
it("executes a command and returns stdout", () => {
const result = registry.execute({ name: "runBash", arguments: { command: "echo hello" } });
expect(result.content).toContain("hello");
expect(result.isError).toBeFalsy();
});
it("returns error with stderr for failing commands", () => {
const result = registry.execute({ name: "runBash", arguments: { command: "false" } });
expect(result.isError).toBe(true);
expect(result.content).toContain("Exit code");
});
});
describe("glob", () => {
it("finds files matching a pattern", () => {
fs.writeFileSync(path.join(tempDir, "app.ts"), "");
fs.writeFileSync(path.join(tempDir, "app.test.ts"), "");
fs.writeFileSync(path.join(tempDir, "README.md"), "");
const result = registry.execute({ name: "glob", arguments: { pattern: "*.ts" } });
const matches = JSON.parse(result.content);
expect(matches.length).toBeGreaterThanOrEqual(2);
});
});
describe("grep", () => {
it("finds matching lines", () => {
fs.writeFileSync(path.join(tempDir, "app.ts"), "export function main() {}\nconst x = 1;\n");
const result = registry.execute({ name: "grep", arguments: { pattern: "export", include: "*.ts" } });
const matches = JSON.parse(result.content);
expect(matches.length).toBe(1);
expect(matches[0].content).toContain("export");
});
});
describe("unknown tool", () => {
it("returns error for unknown tool name", () => {
const result = registry.execute({ name: "unknownTool", arguments: {} });
expect(result.isError).toBe(true);
expect(result.content).toContain("Unknown tool");
});
});
});
+299
View File
@@ -0,0 +1,299 @@
import * as fs from "node:fs";
import * as path from "node:path";
import { execSync } from "node:child_process";
export interface ToolDefinition {
name: string;
description: string;
parameters: {
type: "object";
properties: Record<string, { type: string; description: string }>;
required: string[];
};
}
export interface ToolCall {
name: string;
arguments: Record<string, unknown>;
}
export interface ToolResult {
name: string;
content: string;
isError?: boolean;
}
export const TOOL_DEFINITIONS: ToolDefinition[] = [
{
name: "readFile",
description: "Read the contents of a file at the given path",
parameters: {
type: "object",
properties: {
path: { type: "string", description: "Absolute file path to read" },
},
required: ["path"],
},
},
{
name: "writeFile",
description: "Write content to a file, creating it if it doesn't exist",
parameters: {
type: "object",
properties: {
path: { type: "string", description: "Absolute file path to write" },
content: { type: "string", description: "Content to write to the file" },
},
required: ["path", "content"],
},
},
{
name: "editFile",
description: "Replace an exact string in a file with a new string",
parameters: {
type: "object",
properties: {
path: { type: "string", description: "Absolute file path to edit" },
old: { type: "string", description: "Exact string to find in the file" },
new: { type: "string", description: "String to replace it with" },
},
required: ["path", "old", "new"],
},
},
{
name: "runBash",
description: "Execute a bash command and return stdout/stderr",
parameters: {
type: "object",
properties: {
command: { type: "string", description: "Bash command to execute" },
cwd: { type: "string", description: "Working directory for the command" },
timeout: { type: "number", description: "Timeout in milliseconds (default 30000)" },
},
required: ["command"],
},
},
{
name: "glob",
description: "Find files matching a glob pattern recursively",
parameters: {
type: "object",
properties: {
pattern: { type: "string", description: "Glob pattern (e.g. **/*.ts)" },
cwd: { type: "string", description: "Directory to search in" },
},
required: ["pattern"],
},
},
{
name: "grep",
description: "Search file contents using a regular expression",
parameters: {
type: "object",
properties: {
pattern: { type: "string", description: "Regex pattern to search for" },
include: { type: "string", description: "File pattern to include (e.g. *.ts)" },
cwd: { type: "string", description: "Directory to search in" },
},
required: ["pattern"],
},
},
];
export class ToolRegistry {
private projectPath: string;
private maxFileSize: number;
constructor(projectPath: string, maxFileSize: number = 1024 * 1024) {
this.projectPath = projectPath;
this.maxFileSize = maxFileSize;
}
execute(call: ToolCall): ToolResult {
try {
switch (call.name) {
case "readFile":
return this.readFile(call.arguments);
case "writeFile":
return this.writeFile(call.arguments);
case "editFile":
return this.editFile(call.arguments);
case "runBash":
return this.runBash(call.arguments);
case "glob":
return this.glob(call.arguments);
case "grep":
return this.grep(call.arguments);
default:
return { name: call.name, content: `Unknown tool: ${call.name}`, isError: true };
}
} catch (err) {
return {
name: call.name,
content: `Tool error: ${err instanceof Error ? err.message : String(err)}`,
isError: true,
};
}
}
getDefinitions(): ToolDefinition[] {
return TOOL_DEFINITIONS;
}
getOpenAIToolSchema(): Array<Record<string, unknown>> {
return TOOL_DEFINITIONS.map((def) => ({
type: "function",
function: {
name: def.name,
description: def.description,
parameters: def.parameters,
},
}));
}
private readFile(args: Record<string, unknown>): ToolResult {
const filePath = String(args.path);
if (!fs.existsSync(filePath)) {
return { name: "readFile", content: `File not found: ${filePath}`, isError: true };
}
try {
const stat = fs.statSync(filePath);
if (stat.size > this.maxFileSize) {
return { name: "readFile", content: `File too large: ${filePath} (${stat.size} bytes)`, isError: true };
}
const content = fs.readFileSync(filePath, "utf-8");
return { name: "readFile", content };
} catch (err) {
return { name: "readFile", content: `Read error: ${err instanceof Error ? err.message : String(err)}`, isError: true };
}
}
private writeFile(args: Record<string, unknown>): ToolResult {
const filePath = String(args.path);
const content = String(args.content);
try {
const dir = path.dirname(filePath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(filePath, content, "utf-8");
return { name: "writeFile", content: `Written: ${filePath}` };
} catch (err) {
return { name: "writeFile", content: `Write error: ${err instanceof Error ? err.message : String(err)}`, isError: true };
}
}
private editFile(args: Record<string, unknown>): ToolResult {
const filePath = String(args.path);
const oldStr = String(args.old);
const newStr = String(args.new);
if (!fs.existsSync(filePath)) {
return { name: "editFile", content: `File not found: ${filePath}`, isError: true };
}
try {
const content = fs.readFileSync(filePath, "utf-8");
if (!content.includes(oldStr)) {
return { name: "editFile", content: `String not found in ${filePath}`, isError: true };
}
const updated = content.replace(oldStr, newStr);
fs.writeFileSync(filePath, updated, "utf-8");
return { name: "editFile", content: `Edited: ${filePath}` };
} catch (err) {
return { name: "editFile", content: `Edit error: ${err instanceof Error ? err.message : String(err)}`, isError: true };
}
}
private runBash(args: Record<string, unknown>): ToolResult {
const command = String(args.command);
const cwd = args.cwd ? String(args.cwd) : this.projectPath;
const timeout = args.timeout ? Number(args.timeout) : 30000;
try {
const stdout = execSync(command, {
cwd,
timeout,
encoding: "utf-8",
stdio: ["pipe", "pipe", "pipe"],
maxBuffer: 1024 * 1024,
});
return { name: "runBash", content: stdout || "(no output)" };
} catch (err: unknown) {
const execErr = err as { stderr?: string; stdout?: string; status?: number };
const output = [`Exit code: ${execErr.status || 1}`, `stdout: ${execErr.stdout || ""}`, `stderr: ${execErr.stderr || ""}`].join("\n");
return { name: "runBash", content: output, isError: true };
}
}
private glob(args: Record<string, unknown>): ToolResult {
const pattern = String(args.pattern);
const cwd = args.cwd ? String(args.cwd) : this.projectPath;
const matches = this.globRecursive(cwd, pattern);
return { name: "glob", content: JSON.stringify(matches.slice(0, 200)) };
}
private grep(args: Record<string, unknown>): ToolResult {
const pattern = String(args.pattern);
const cwd = args.cwd ? String(args.cwd) : this.projectPath;
const include = args.include ? String(args.include) : undefined;
const matches = this.grepRecursive(cwd, pattern, include);
return { name: "grep", content: JSON.stringify(matches.slice(0, 100)) };
}
private globRecursive(dir: string, pattern: string): string[] {
const results: string[] = [];
const regex = this.globToRegex(pattern);
try {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === ".git") continue;
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
results.push(...this.globRecursive(fullPath, pattern));
} else if (regex.test(entry.name) || regex.test(path.relative(this.projectPath, fullPath))) {
results.push(path.relative(this.projectPath, fullPath));
}
}
} catch {}
return results.sort();
}
private globToRegex(pattern: string): RegExp {
const escaped = pattern
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
.replace(/\*\*/g, "{{GLOBSTAR}}")
.replace(/\*/g, "[^/]*")
.replace(/{{GLOBSTAR}}/g, ".*")
.replace(/\?/g, "[^/]");
return new RegExp(`^${escaped}$`);
}
private grepRecursive(dir: string, patternStr: string, include?: string): Array<{ file: string; line: number; content: string }> {
const results: Array<{ file: string; line: number; content: string }> = [];
const regex = new RegExp(patternStr);
const includeRegex = include ? this.globToRegex(include) : null;
try {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === ".git") continue;
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
results.push(...this.grepRecursive(fullPath, patternStr, include));
} else if (includeRegex ? includeRegex.test(entry.name) : true) {
try {
const content = fs.readFileSync(fullPath, "utf-8");
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
if (regex.test(lines[i])) {
results.push({
file: path.relative(this.projectPath, fullPath),
line: i + 1,
content: lines[i].trim(),
});
}
}
} catch {}
}
}
} catch {}
return results;
}
}
+137
View File
@@ -0,0 +1,137 @@
import { AgentName, AutonomyLevel, ModelProfile } from "../types/config.js";
import { AgentContext } from "../agents/base.js";
import { Decision } from "../types/decisions.js";
import { Escalation } from "../types/escalation.js";
export type BackendType = "llm" | "agent";
export interface BackendRequest {
persona: AgentName;
workflow: string;
task: string;
context: AgentContext;
autonomy: AutonomyLevel;
}
export interface Artifact {
path: string;
content: string;
operation: "create" | "update" | "delete";
}
export interface TokenUsage {
input_tokens: number;
output_tokens: number;
total_tokens: number;
estimated_cost_usd: number;
}
export interface BackendResult {
success: boolean;
output: string;
artifacts: Artifact[];
decisions: Decision[];
escalations: Escalation[];
usage: TokenUsage;
error?: string;
}
export interface IntelligenceBackend {
readonly name: string;
readonly type: BackendType;
isAvailable(): Promise<boolean>;
execute(request: BackendRequest): Promise<BackendResult>;
}
export interface LLMBackendConfig {
base_url: string;
model_profile: ModelProfile;
model?: string;
timeout_ms?: number;
}
export interface OllamaLocalConfig extends LLMBackendConfig {
base_url: string;
model_profile: ModelProfile;
model?: string;
timeout_ms?: number;
}
export interface OllamaCloudConfig extends LLMBackendConfig {
base_url: string;
api_key_env: string;
model_profile: ModelProfile;
model?: string;
timeout_ms?: number;
}
export interface OpencodeBackendConfig {
enabled: boolean;
executable?: string;
}
export interface BackendConfigSection {
provider: "auto" | "opencode" | "ollama-local" | "ollama-cloud";
fallback?: "opencode" | "ollama-local" | "ollama-cloud";
agent_backends: {
opencode?: OpencodeBackendConfig;
};
llm_backends: {
"ollama-local"?: OllamaLocalConfig;
"ollama-cloud"?: OllamaCloudConfig;
};
}
export const DEFAULT_BACKEND_CONFIG: BackendConfigSection = {
provider: "auto",
agent_backends: {
opencode: { enabled: true },
},
llm_backends: {
"ollama-local": {
base_url: "http://localhost:11434",
model_profile: "balanced",
},
"ollama-cloud": {
base_url: "",
api_key_env: "OLLAMA_CLOUD_API_KEY",
model_profile: "quality",
timeout_ms: 60000,
},
},
};
export class BackendUnavailableError extends Error {
readonly backendName: string;
readonly agentName?: string;
constructor(backendName: string, agentName?: string) {
const agentMsg = agentName ? ` (agent: ${agentName})` : "";
super(
`Intelligence backend "${backendName}" is not available${agentMsg}. ` +
`Configure one of:\n` +
` 1. Install opencode: npm i -g opencode\n` +
` 2. Run Ollama locally: ollama serve\n` +
` 3. Set OLLAMA_CLOUD_API_KEY for remote inference`
);
this.name = "BackendUnavailableError";
this.backendName = backendName;
this.agentName = agentName;
}
}
export function emptyTokenUsage(): TokenUsage {
return { input_tokens: 0, output_tokens: 0, total_tokens: 0, estimated_cost_usd: 0 };
}
export function emptyBackendResult(error?: string): BackendResult {
return {
success: false,
output: "",
artifacts: [],
decisions: [],
escalations: [],
usage: emptyTokenUsage(),
error,
};
}
+387 -62
View File
@@ -1,6 +1,6 @@
import { Command } from "commander";
import { CIConfig, AutonomyLevel } from "../types/config.js";
import { initCI, loadConfig, isCIInitialized, saveConfig } from "../core/config.js";
import { CIAgentConfig, AutonomyLevel } from "../types/config.js";
import { initCIAgent, loadConfig, isCIAgentInitialized, saveConfig } from "../core/config.js";
import { Specification, parseSpecification } from "../types/specification.js";
import { saveSpecification } from "../core/clarify.js";
import { OrchestratorAgent } from "../agents/orchestrator.js";
@@ -12,12 +12,16 @@ import { loadSpecification as loadSpec } from "../core/clarify.js";
import { AgentContext } from "../agents/base.js";
import { ErrorRecovery } from "../core/error-recovery.js";
import { PipelineState, createInitialPipelineState } from "../types/pipeline.js";
import { resolveBackend } from "../backends/index.js";
import { BackendUnavailableError } from "../backends/types.js";
import { getAgent } from "../agents/index.js";
import * as fs from "node:fs";
import * as path from "node:path";
import { execSync } from "node:child_process";
export function createInitCommand(): Command {
return new Command("init")
.description("Initialize a new CI project from a specification")
.description("Initialize a new CIAgent project from a specification")
.argument("[specification]", "Inline specification text")
.option("-s, --spec <file>", "Specification file path")
.option("-c, --clarify", "Start interactive clarify phase", false)
@@ -28,12 +32,13 @@ export function createInitCommand(): Command {
)
.option("--model-profile <profile>", "Model profile: quality, speed, balanced", "quality")
.option("--no-parallel", "Disable parallel agent execution")
.option("--backend <provider>", "Intelligence backend: auto, opencode, ollama-local, ollama-cloud", "auto")
.action(async (specification, options) => {
const projectPath = process.cwd();
if (isCIInitialized(projectPath)) {
console.log("CI project already initialized in this directory.");
console.log("Use 'ci run' to execute the pipeline or 'ci status' to check progress.");
if (isCIAgentInitialized(projectPath)) {
console.log("CIAgent project already initialized in this directory.");
console.log("Use 'ciagent run' to execute the pipeline or 'ciagent status' to check progress.");
return;
}
@@ -55,7 +60,7 @@ export function createInitCommand(): Command {
}
const autonomyLevel = options.autonomy as AutonomyLevel;
const config: Partial<CIConfig> = {
const config: Partial<CIAgentConfig> = {
autonomy: {
level: autonomyLevel,
escalation_hooks: ["deploy", "delete_data", "merge_to_main"],
@@ -71,10 +76,19 @@ export function createInitCommand(): Command {
max_concurrent_agents: 5,
min_plans_for_parallel: 2,
},
backend: {
provider: options.backend || "auto",
agent_backends: { opencode: { enabled: true } },
llm_backends: {
"ollama-local": { base_url: "http://localhost:11434", model_profile: "balanced" },
"ollama-cloud": { base_url: "", api_key_env: "OLLAMA_CLOUD_API_KEY", model_profile: "quality", timeout_ms: 60000 },
},
},
};
const fullConfig = initCI(projectPath, config);
console.log(`✓ CI project initialized (autonomy: ${autonomyLevel})`);
const fullConfig = initCIAgent(projectPath, config);
console.log(`✓ CIAgent project initialized (autonomy: ${autonomyLevel})`);
console.log(` Backend: ${options.backend || "auto"}`);
if (specText) {
const spec: Specification = parseSpecification(specText, options.spec ? "file" : "inline");
@@ -101,36 +115,80 @@ export function createInitCommand(): Command {
}
}
console.log("\nConfiguration saved to .ci/config.json");
console.log("\nConfiguration saved to .ciagent/config.json");
console.log("\nNext steps:");
console.log(" ci run --all # Run full pipeline");
console.log(" ci run research # Run specific phase");
console.log(" ciagent run --all # Run full pipeline");
console.log(" ciagent run research # Run specific phase");
console.log(" ci status # Check project status");
});
}
async function resolveBackendForCommand(config: CIAgentConfig, overrideBackend?: string): Promise<{ backend: import("../backends/types.js").IntelligenceBackend | undefined; error?: string }> {
const backendConfig = { ...config.backend };
if (overrideBackend) {
backendConfig.provider = overrideBackend as typeof backendConfig.provider;
}
if (backendConfig.provider === "auto") {
try {
const backend = await resolveBackend(backendConfig);
console.log(` Backend: ${backend.name} (${backend.type})`);
return { backend };
} catch (err) {
if (err instanceof BackendUnavailableError) {
return { backend: undefined, error: err.message };
}
throw err;
}
}
try {
const { createBackend } = await import("../backends/index.js");
const backend = createBackend(backendConfig.provider, backendConfig);
if (await backend.isAvailable()) {
console.log(` Backend: ${backend.name} (${backend.type})`);
return { backend };
}
return { backend: undefined, error: `Configured backend "${backendConfig.provider}" is not available.` };
} catch (err) {
if (err instanceof BackendUnavailableError) {
return { backend: undefined, error: err.message };
}
throw err;
}
}
export function createRunCommand(): Command {
return new Command("run")
.description("Execute a specific phase autonomously")
.argument("[phase]", "Phase to run: research, plan, execute, verify, or --all")
.option("--all", "Execute all remaining phases sequentially")
.option("--phase <number>", "Phase number", "1")
.option("--backend <provider>", "Override intelligence backend for this run")
.action(async (phase, options) => {
const projectPath = process.cwd();
if (!isCIInitialized(projectPath)) {
console.error("CI project not initialized. Run 'ci init' first.");
if (!isCIAgentInitialized(projectPath)) {
console.error("CIAgent project not initialized. Run 'ciagent init' first.");
process.exit(1);
}
const config = loadConfig(projectPath);
const { backend, error: backendError } = await resolveBackendForCommand(config, options.backend);
if (!backend && backendError) {
console.warn(` ⚠ No intelligence backend available: ${backendError}`);
console.warn(" Continuing with mechanical-only execution (limited functionality).");
}
const orchestrator = new OrchestratorAgent(config);
const context: AgentContext = {
project_path: projectPath,
phase: parseInt(options.phase) || 1,
stage: phase || "all",
specification: "",
config_path: path.join(projectPath, ".ci", "config.json"),
config_path: path.join(projectPath, ".ciagent", "config.json"),
backend,
};
const spec = loadSpec(projectPath);
@@ -138,7 +196,7 @@ export function createRunCommand(): Command {
context.specification = spec.raw_content;
}
console.log(`Running CI pipeline...`);
console.log(`Running CIAgent pipeline...`);
if (options.all) {
console.log(" Mode: Full pipeline (all phases)");
} else {
@@ -163,16 +221,25 @@ export function createQuickCommand(): Command {
return new Command("quick")
.description("Execute an ad-hoc task with full agentic guarantees")
.argument("<description>", "Task description")
.action(async (description) => {
.option("--backend <provider>", "Override intelligence backend")
.action(async (description, options) => {
const projectPath = process.cwd();
console.log(`Quick task: ${description}`);
if (!isCIInitialized(projectPath)) {
const config = initCI(projectPath);
console.log("Initialized temporary CI project");
if (!isCIAgentInitialized(projectPath)) {
const config = initCIAgent(projectPath);
console.log("Initialized temporary CIAgent project");
}
const config = loadConfig(projectPath);
const { backend, error: backendError } = await resolveBackendForCommand(config, options.backend);
if (!backend) {
console.error(`\n✗ "ciagent quick" requires an intelligence backend.`);
if (backendError) console.error(` ${backendError}`);
process.exit(1);
}
const spec = parseSpecification(description, "inline");
saveSpecification(projectPath, spec);
@@ -182,7 +249,8 @@ export function createQuickCommand(): Command {
phase: 0,
stage: "all",
specification: description,
config_path: path.join(projectPath, ".ci", "config.json"),
config_path: path.join(projectPath, ".ciagent", "config.json"),
backend,
};
const result = await orchestrator.execute(context);
@@ -202,11 +270,21 @@ export function createDebugCommand(): Command {
.description("Autonomous debugging: diagnose root cause, propose fix")
.argument("[description]", "Description of the issue to debug")
.option("--confidence <threshold>", "Minimum confidence to auto-fix", "0.6")
.option("--backend <provider>", "Override intelligence backend")
.action(async (description, options) => {
const projectPath = process.cwd();
if (!isCIInitialized(projectPath)) {
console.error("CI project not initialized. Run 'ci init' first.");
if (!isCIAgentInitialized(projectPath)) {
console.error("CIAgent project not initialized. Run 'ciagent init' first.");
process.exit(1);
}
const config = loadConfig(projectPath);
const { backend, error: backendError } = await resolveBackendForCommand(config, options.backend);
if (!backend) {
console.error(`\n✗ "ciagent debug" requires an intelligence backend.`);
if (backendError) console.error(` ${backendError}`);
process.exit(1);
}
@@ -214,14 +292,26 @@ export function createDebugCommand(): Command {
if (description) {
console.log(` Issue: ${description}`);
}
const config = loadConfig(projectPath);
const recovery = new ErrorRecovery(config, projectPath);
console.log(` Confidence threshold: ${options.confidence}`);
console.log(" Diagnosing root cause...");
console.log("\n✓ Debug complete — autonomous diagnosis finished");
const debuggerAgent = getAgent("debugger");
const context: AgentContext = {
project_path: projectPath,
phase: 0,
stage: "debug",
specification: description || "",
config_path: path.join(projectPath, ".ciagent", "config.json"),
backend,
};
const result = await debuggerAgent.execute(context);
if (result.success) {
console.log(`\n✓ ${result.output}`);
} else {
console.error(`\n✗ Debug failed: ${result.error}`);
process.exit(1);
}
});
}
@@ -230,11 +320,12 @@ export function createVerifyCommand(): Command {
.description("Automated verification of a phase")
.argument("[phase]", "Phase number to verify", "1")
.option("--layer <layer>", "Run specific layer: structural, behavioral, security, quality", "all")
.option("--backend <provider>", "Override intelligence backend for behavioral verification")
.action(async (phase, options) => {
const projectPath = process.cwd();
if (!isCIInitialized(projectPath)) {
console.error("CI project not initialized. Run 'ci init' first.");
if (!isCIAgentInitialized(projectPath)) {
console.error("CIAgent project not initialized. Run 'ciagent init' first.");
process.exit(1);
}
@@ -276,17 +367,45 @@ export function createReviewCommand(): Command {
return new Command("review")
.description("Multi-persona autonomous code review")
.argument("[phase]", "Phase number to review", "1")
.action(async (phase) => {
.option("--backend <provider>", "Override intelligence backend")
.action(async (phase, options) => {
const projectPath = process.cwd();
if (!isCIInitialized(projectPath)) {
console.error("CI project not initialized. Run 'ci init' first.");
if (!isCIAgentInitialized(projectPath)) {
console.error("CIAgent project not initialized. Run 'ciagent init' first.");
process.exit(1);
}
const config = loadConfig(projectPath);
const { backend, error: backendError } = await resolveBackendForCommand(config, options.backend);
if (!backend) {
console.error(`\n✗ "ciagent review" requires an intelligence backend.`);
if (backendError) console.error(` ${backendError}`);
process.exit(1);
}
const phaseNum = parseInt(phase) || 1;
console.log(`Running code review for phase ${phaseNum}...`);
console.log("Review complete — findings logged to audit trail");
const reviewer = getAgent("code-reviewer");
const context: AgentContext = {
project_path: projectPath,
phase: phaseNum,
stage: "review",
specification: "",
config_path: path.join(projectPath, ".ciagent", "config.json"),
backend,
};
const result = await reviewer.execute(context);
if (result.success) {
console.log(`\n✓ ${result.output}`);
} else {
console.error(`\n✗ Review failed: ${result.error}`);
process.exit(1);
}
});
}
@@ -296,18 +415,19 @@ export function createStatusCommand(): Command {
.action(() => {
const projectPath = process.cwd();
if (!isCIInitialized(projectPath)) {
console.log("CI project not initialized in this directory.");
console.log("Run 'ci init' to get started.");
if (!isCIAgentInitialized(projectPath)) {
console.log("CIAgent project not initialized in this directory.");
console.log("Run 'ciagent init' to get started.");
return;
}
const config = loadConfig(projectPath);
const artifacts = new ArtifactManager(projectPath);
console.log("─── CI Project Status ───");
console.log("─── CIAgent Project Status ───");
console.log(`\nAutonomy: ${config.autonomy.level}`);
console.log(`Model Profile: ${config.model_profile}`);
console.log(`Backend: ${config.backend?.provider || "auto"}`);
console.log(`Parallelization: ${config.parallelization.enabled ? "enabled" : "disabled"}`);
const state = artifacts.readState();
@@ -324,7 +444,7 @@ export function createStatusCommand(): Command {
console.log(` ${icon} ${stage}`);
}
} else {
console.log("\nNo pipeline state found. Run 'ci run --all' to start.");
console.log("\nNo pipeline state found. Run 'ciagent run --all' to start.");
}
const summary = getAuditSummary(projectPath);
@@ -344,15 +464,15 @@ export function createAuditCommand(): Command {
.action((options) => {
const projectPath = process.cwd();
if (!isCIInitialized(projectPath)) {
console.error("CI project not initialized. Run 'ci init' first.");
if (!isCIAgentInitialized(projectPath)) {
console.error("CIAgent project not initialized. Run 'ciagent init' first.");
process.exit(1);
}
const phase = options.phase ? parseInt(options.phase) : undefined;
const summary = getAuditSummary(projectPath);
console.log("─── CI Audit Report ───");
console.log("─── CIAgent Audit Report ───");
console.log(`\nTotal Decisions: ${summary.total_decisions}`);
console.log(`Total Escalations: ${summary.total_escalations}`);
console.log(`Phases Audited: ${summary.phases.join(", ") || "none"}`);
@@ -393,11 +513,12 @@ export function createAuditCommand(): Command {
export function createClarifyCommand(): Command {
return new Command("clarify")
.description("Re-run the Clarify phase if new ambiguities have emerged")
.action(() => {
.option("--backend <provider>", "Use intelligence backend for question generation")
.action(async (options) => {
const projectPath = process.cwd();
if (!isCIInitialized(projectPath)) {
console.error("CI project not initialized. Run 'ci init' first.");
if (!isCIAgentInitialized(projectPath)) {
console.error("CIAgent project not initialized. Run 'ciagent init' first.");
process.exit(1);
}
@@ -405,7 +526,7 @@ export function createClarifyCommand(): Command {
const spec = loadSpec(projectPath);
if (!spec) {
console.error("No specification found. Run 'ci init' first.");
console.error("No specification found. Run 'ciagent init' first.");
process.exit(1);
}
@@ -432,25 +553,91 @@ export function createRollbackCommand(): Command {
.description("Autonomous undo with automatic dependency resolution")
.argument("<target>", "Phase number or plan ID to rollback to")
.option("--force", "Force rollback even with downstream dependencies")
.option("--backend <provider>", "Use intelligence backend for dependency resolution")
.action(async (target, options) => {
const projectPath = process.cwd();
if (!isCIInitialized(projectPath)) {
console.error("CI project not initialized. Run 'ci init' first.");
if (!isCIAgentInitialized(projectPath)) {
console.error("CIAgent project not initialized. Run 'ciagent init' first.");
process.exit(1);
}
console.log(`Rolling back to: ${target}`);
const phaseNum = parseInt(target) || 0;
console.log(`Rolling back to phase ${phaseNum}...`);
const config = loadConfig(projectPath);
const recovery = new ErrorRecovery(config, projectPath);
const result = await recovery.rollback(parseInt(target) || 0, "User-requested rollback");
try {
const branchName = `phase/${String(phaseNum).padStart(2, "0")}-*`;
const branches = execSync("git branch --list", {
cwd: projectPath,
encoding: "utf-8",
}).split("\n").map((b) => b.trim()).filter(Boolean);
if (result.recovered) {
console.log(`✓ Rollback complete: ${result.message}`);
} else {
console.error(`✗ Rollback failed: ${result.message}`);
process.exit(1);
const phaseBranches = branches.filter((b) =>
b.includes(`phase/${String(phaseNum).padStart(2, "0")}`)
);
if (phaseBranches.length > 0 && !options.force) {
console.log(`Found phase ${phaseNum} branches:`);
for (const b of phaseBranches) {
console.log(` ${b}`);
}
console.log("\nChecking for downstream dependencies...");
const downstreamPhases = branches.filter((b) => {
const match = b.match(/phase\/(\d+)/);
if (!match) return false;
return parseInt(match[1]) > phaseNum;
});
if (downstreamPhases.length > 0) {
console.warn(`⚠ Downstream phases found:`);
for (const b of downstreamPhases) {
console.warn(` ${b}`);
}
console.warn("Use --force to rollback anyway.");
process.exit(1);
}
}
const targetCommit = execSync(
`git log --all --grep="phase: ${phaseNum}" --format="%H" -1`,
{ cwd: projectPath, encoding: "utf-8" }
).trim();
if (targetCommit) {
console.log(` Resetting to commit: ${targetCommit.slice(0, 8)}`);
execSync(`git reset --hard ${targetCommit}`, {
cwd: projectPath,
stdio: "pipe",
});
console.log(`✓ Rollback complete: reset to phase ${phaseNum}`);
} else {
console.warn(` Could not find phase ${phaseNum} commit. Performing branch cleanup only.`);
for (const b of phaseBranches) {
const cleanName = b.replace(/^\*?\s*/, "");
if (cleanName) {
try {
execSync(`git branch -D ${cleanName}`, {
cwd: projectPath,
stdio: "pipe",
});
console.log(` Deleted branch: ${cleanName}`);
} catch {}
}
}
console.log(`✓ Rollback complete: cleaned up phase ${phaseNum} branches`);
}
} catch (err) {
const recovery = new ErrorRecovery(loadConfig(projectPath), projectPath);
const result = await recovery.rollback(phaseNum, "User-requested rollback");
if (result.recovered) {
console.log(`✓ Rollback complete: ${result.message}`);
} else {
console.error(`✗ Rollback failed: ${result.message}`);
process.exit(1);
}
}
});
}
@@ -459,11 +646,12 @@ export function createShipCommand(): Command {
return new Command("ship")
.description("Auto-complete phase: verify, security, commit, tag")
.argument("[phase]", "Phase number to ship", "1")
.action(async (phase) => {
.option("--backend <provider>", "Override intelligence backend")
.action(async (phase, options) => {
const projectPath = process.cwd();
if (!isCIInitialized(projectPath)) {
console.error("CI project not initialized. Run 'ci init' first.");
if (!isCIAgentInitialized(projectPath)) {
console.error("CIAgent project not initialized. Run 'ciagent init' first.");
process.exit(1);
}
@@ -491,7 +679,144 @@ export function createShipCommand(): Command {
console.log("\n Resolve escalations before deploying.");
}
console.log(" Committing and tagging...");
const config = loadConfig(projectPath);
try {
const isGitRepo = execSync("git rev-parse --is-inside-work-tree", {
cwd: projectPath,
encoding: "utf-8",
}).trim() === "true";
if (isGitRepo) {
console.log(" Computing version...");
const version = computeShipVersion(projectPath, phaseNum, config);
console.log(` Version: ${version.tag} (${version.milestoneType})`);
const mergeTarget = resolveMergeTarget(projectPath, version.milestoneType);
console.log(` Merge target: ${mergeTarget}`);
console.log(" Committing and tagging...");
try {
if (!validateVersionOrder(projectPath, version.tag)) {
console.error(`✗ Version ${version.tag} is not greater than existing tags. Aborting.`);
process.exit(1);
}
execSync(`git add -A`, { cwd: projectPath, stdio: "pipe" });
execSync(`git commit -m "chore: ship phase ${phaseNum}" --allow-empty`, {
cwd: projectPath,
stdio: "pipe",
});
execSync(`git tag -a ${version.tag} -m "CIAgent: Phase ${phaseNum} shipped"`, {
cwd: projectPath,
stdio: "pipe",
});
console.log(` ✓ Tagged: ${version.tag}`);
if (config.git.auto_push) {
execSync(`git push origin ${version.tag}`, { cwd: projectPath, stdio: "pipe" });
console.log(` ✓ Pushed tag: ${version.tag}`);
}
} catch (err) {
console.warn(` ⚠ Git operations failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
} catch {}
console.log(`\n✓ Phase ${phaseNum} shipped successfully`);
});
}
function computeShipVersion(
projectPath: string,
phaseNum: number,
config: CIAgentConfig
): { tag: string; milestoneType: "nfr" | "feature" | "schema-breaking" } {
const tags = execSync("git tag -l", { cwd: projectPath, encoding: "utf-8" })
.split("\n")
.map((t) => t.trim())
.filter(Boolean);
let major = 0;
let minor = 0;
let patch = 0;
for (const tag of tags) {
const match = tag.match(/^v(\d+)\.(\d+)\.(\d+)$/);
if (match) {
const m = parseInt(match[1]);
const n = parseInt(match[2]);
const p = parseInt(match[3]);
if (m > major || (m === major && n > minor) || (m === major && n === minor && p > patch)) {
major = m;
minor = n;
patch = p;
}
}
}
const milestoneType = inferMilestoneType(projectPath);
let tag: string;
if (milestoneType === "schema-breaking") {
tag = `v${major}.${minor + phaseNum}.0`;
} else {
tag = `v${major}.${minor}.${phaseNum}`;
}
return { tag, milestoneType };
}
function inferMilestoneType(projectPath: string): "nfr" | "feature" | "schema-breaking" {
try {
const log = execSync("git log --oneline -50", { cwd: projectPath, encoding: "utf-8" });
if (log.match(/\brefactor\b|\brewrite\b|\bmigrate\b|\brestructure\b/i)) return "schema-breaking";
if (log.match(/\bfeat\b/)) return "feature";
return "nfr";
} catch {
return "nfr";
}
}
function validateVersionOrder(projectPath: string, newTag: string): boolean {
const newMatch = newTag.match(/^v(\d+)\.(\d+)\.(\d+)$/);
if (!newMatch) return false;
const newMajor = parseInt(newMatch[1]);
const newMinor = parseInt(newMatch[2]);
const newPatch = parseInt(newMatch[3]);
const tags = execSync("git tag -l", { cwd: projectPath, encoding: "utf-8" })
.split("\n")
.map((t) => t.trim())
.filter(Boolean);
for (const tag of tags) {
const match = tag.match(/^v(\d+)\.(\d+)\.(\d+)$/);
if (!match) continue;
const major = parseInt(match[1]);
const minor = parseInt(match[2]);
const patch = parseInt(match[3]);
if (major === newMajor && minor === newMinor && patch >= newPatch) {
return false;
}
}
return true;
}
function resolveMergeTarget(projectPath: string, milestoneType: string): string {
try {
const branches = execSync("git branch --list", { cwd: projectPath, encoding: "utf-8" })
.split("\n")
.map((b) => b.trim().replace(/^\*?\s+/, ""))
.filter(Boolean);
const milestoneBranches = branches.filter((b) => b.startsWith("milestone/"));
if (milestoneBranches.length > 0) {
return milestoneBranches[0];
}
} catch {}
return "main";
}
+2 -2
View File
@@ -19,8 +19,8 @@ import {
const program = new Command();
program
.name("ci")
.description("CI — Continuous Intelligence: autonomous AI-driven software engineering harness")
.name("ciagent")
.description("CIAgent — Continuous Intelligence: autonomous AI-driven software engineering harness")
.version(VERSION)
.addCommand(createInitCommand())
.addCommand(createRunCommand())
+7 -8
View File
@@ -8,7 +8,7 @@ describe("ArtifactManager", () => {
let manager: ArtifactManager;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "ci-artifact-test-"));
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "ciagent-artifact-test-"));
manager = new ArtifactManager(tempDir);
});
@@ -17,17 +17,16 @@ describe("ArtifactManager", () => {
});
describe("ensureStructure", () => {
it("creates .planning directory structure", () => {
it("creates .ciagent directory structure", () => {
manager.ensureStructure();
expect(fs.existsSync(path.join(tempDir, ".planning"))).toBe(true);
expect(fs.existsSync(path.join(tempDir, ".planning", "phases"))).toBe(true);
expect(fs.existsSync(path.join(tempDir, ".ci", "audit"))).toBe(true);
expect(fs.existsSync(path.join(tempDir, ".ciagent"))).toBe(true);
expect(fs.existsSync(path.join(tempDir, ".ciagent", "audit"))).toBe(true);
});
it("is idempotent", () => {
manager.ensureStructure();
manager.ensureStructure();
expect(fs.existsSync(path.join(tempDir, ".planning"))).toBe(true);
expect(fs.existsSync(path.join(tempDir, ".ciagent"))).toBe(true);
});
});
@@ -68,7 +67,7 @@ describe("ArtifactManager", () => {
manager.writeProject(manifest);
const projectPath = path.join(tempDir, ".planning", "PROJECT.md");
const projectPath = path.join(tempDir, ".ciagent", "PROJECT.md");
expect(fs.existsSync(projectPath)).toBe(true);
const content = fs.readFileSync(projectPath, "utf-8");
expect(content).toContain("Test Project");
@@ -132,7 +131,7 @@ describe("ArtifactManager", () => {
],
});
const decisionsPath = path.join(tempDir, ".planning", "DECISIONS.md");
const decisionsPath = path.join(tempDir, ".ciagent", "DECISIONS.md");
expect(fs.existsSync(decisionsPath)).toBe(true);
const content = fs.readFileSync(decisionsPath, "utf-8");
expect(content).toContain("D-001");
+14 -14
View File
@@ -2,7 +2,7 @@ import * as fs from "node:fs";
import * as path from "node:path";
import { writeFile, readFile, ensureDir } from "../utils/file.js";
const PLANNING_DIR = ".planning";
const CI_DIR = ".ciagent";
export interface ProjectManifest {
name: string;
@@ -48,18 +48,18 @@ export class ArtifactManager {
this.projectPath = projectPath;
}
private get planningDir(): string {
return path.join(this.projectPath, PLANNING_DIR);
private get ciDir(): string {
return path.join(this.projectPath, CI_DIR);
}
ensureStructure(): void {
ensureDir(this.planningDir);
ensureDir(path.join(this.planningDir, "phases"));
ensureDir(path.join(this.projectPath, ".ci", "audit"));
ensureDir(this.ciDir);
ensureDir(path.join(this.ciDir, "phases"));
ensureDir(path.join(this.ciDir, "audit"));
}
isInitialized(): boolean {
return fs.existsSync(path.join(this.planningDir, "PROJECT.md"));
return fs.existsSync(path.join(this.ciDir, "PROJECT.md"));
}
writeProject(manifest: ProjectManifest): void {
@@ -81,7 +81,7 @@ export class ArtifactManager {
}
lines.push("");
writeFile(path.join(this.planningDir, "PROJECT.md"), lines.join("\n"));
writeFile(path.join(this.ciDir, "PROJECT.md"), lines.join("\n"));
}
writeDecisions(decisions: DecisionsManifest): void {
@@ -99,11 +99,11 @@ export class ArtifactManager {
lines.push(`- **Timestamp**: ${d.timestamp}`);
lines.push("");
}
writeFile(path.join(this.planningDir, "DECISIONS.md"), lines.join("\n"));
writeFile(path.join(this.ciDir, "DECISIONS.md"), lines.join("\n"));
}
writeState(state: StateManifest): void {
writeJSON(path.join(this.planningDir, "STATE.md.json"), state);
writeJSON(path.join(this.ciDir, "STATE.md.json"), state);
const lines = [
"# Project State",
@@ -124,11 +124,11 @@ export class ArtifactManager {
}
lines.push("");
writeFile(path.join(this.planningDir, "STATE.md"), lines.join("\n"));
writeFile(path.join(this.ciDir, "STATE.md"), lines.join("\n"));
}
readState(): StateManifest | null {
const filePath = path.join(this.planningDir, "STATE.md.json");
const filePath = path.join(this.ciDir, "STATE.md.json");
if (!fs.existsSync(filePath)) return null;
return JSON.parse(fs.readFileSync(filePath, "utf-8"));
}
@@ -150,7 +150,7 @@ export class ArtifactManager {
artifactName: string,
content: string
): void {
const phaseDir = path.join(this.planningDir, "phases", `phase-${phase}`);
const phaseDir = path.join(this.ciDir, "phases", `phase-${phase}`);
ensureDir(phaseDir);
writeFile(path.join(phaseDir, artifactName), content);
}
@@ -160,7 +160,7 @@ export class ArtifactManager {
artifactName: string
): string | null {
const filePath = path.join(
this.planningDir,
this.ciDir,
"phases",
`phase-${phase}`,
artifactName
+3 -4
View File
@@ -9,8 +9,8 @@ describe("Audit", () => {
let tempDir: string;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "ci-audit-test-"));
fs.mkdirSync(path.join(tempDir, ".ci", "audit"), { recursive: true });
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "ciagent-audit-test-"));
fs.mkdirSync(path.join(tempDir, ".ciagent", "audit"), { recursive: true });
});
afterEach(() => {
@@ -25,7 +25,6 @@ describe("Audit", () => {
confidence: 0.92,
category: "technology_choice",
alternatives_considered: [{ option: "MongoDB", rejected_reason: "No ACID" }],
learnship_equivalent: "discuss-phase would ask: What database?",
human_override: null,
};
@@ -41,7 +40,7 @@ describe("Audit", () => {
],
default_option_id: "A",
resolution: "pending",
audit_file: ".ci/audit/test.json",
audit_file: ".ciagent/audit/test.json",
};
describe("logDecision", () => {
+1 -1
View File
@@ -12,7 +12,7 @@ export interface AuditEntry {
const AUDIT_DIR = "audit";
function getAuditDir(projectPath: string): string {
return path.join(projectPath, ".ci", AUDIT_DIR);
return path.join(projectPath, ".ciagent", AUDIT_DIR);
}
function getAuditFilePath(projectPath: string, phase: number): string {
+137 -79
View File
@@ -1,17 +1,17 @@
import * as os from "node:os";
import * as path from "node:path";
import * as fs from "node:fs";
import { CiFiles, ProjectMd, RoadmapMd, RequirementsMd, ArchitectureMd } from "../core/ci-files.js";
import { CIAgentFiles, ProjectMd, RoadmapMd, RequirementsMd, ArchitectureMd } from "../core/ciagent-files.js";
function createTempDir(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), "ci-files-test-"));
return fs.mkdtempSync(path.join(os.tmpdir(), "ciagent-files-test-"));
}
function cleanup(dir: string): void {
fs.rmSync(dir, { recursive: true, force: true });
}
describe("CiFiles", () => {
describe("CIAgentFiles", () => {
let dir: string;
beforeEach(() => {
@@ -22,41 +22,41 @@ describe("CiFiles", () => {
cleanup(dir);
});
describe("ensureCIDir", () => {
it("creates .ci directory", () => {
const ciFiles = new CiFiles(dir);
describe("ensureCIAgentDir", () => {
it("creates .ciagent directory", () => {
const ciFiles = new CIAgentFiles(dir);
ciFiles.ensureCIDir();
expect(fs.existsSync(path.join(dir, ".ci"))).toBe(true);
expect(fs.existsSync(path.join(dir, ".ciagent"))).toBe(true);
});
});
describe("isInitialized", () => {
it("returns false when no config.json exists", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
expect(ciFiles.isInitialized()).toBe(false);
});
it("returns true when config.json exists", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.ensureCIDir();
fs.writeFileSync(path.join(dir, ".ci", "config.json"), "{}");
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), "{}");
expect(ciFiles.isInitialized()).toBe(true);
});
});
describe("projectSlug", () => {
it("defaults to empty string", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
expect(ciFiles.getProjectSlug()).toBe("");
});
it("uses provided project slug", () => {
const ciFiles = new CiFiles(dir, "task-api");
const ciFiles = new CIAgentFiles(dir, "task-api");
expect(ciFiles.getProjectSlug()).toBe("task-api");
});
it("setProjectSlug updates slug", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.setProjectSlug("auth-svc");
expect(ciFiles.getProjectSlug()).toBe("auth-svc");
});
@@ -64,14 +64,14 @@ describe("CiFiles", () => {
describe("multi-project support", () => {
it("isMultiProject returns false when not initialized", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
expect(ciFiles.isMultiProject()).toBe(false);
});
it("isMultiProject returns false for single-project config", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.ensureCIDir();
fs.writeFileSync(path.join(dir, ".ci", "config.json"), JSON.stringify({
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({
projects: [{ slug: "default", name: "Default" }],
active_project: "default",
}));
@@ -79,59 +79,59 @@ describe("CiFiles", () => {
});
it("isMultiProject returns false for config without projects array", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.ensureCIDir();
fs.writeFileSync(path.join(dir, ".ci", "config.json"), JSON.stringify({}));
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({}));
expect(ciFiles.isMultiProject()).toBe(false);
});
it("addProject adds a project to config", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.ensureCIDir();
fs.writeFileSync(path.join(dir, ".ci", "config.json"), JSON.stringify({
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({
projects: [],
active_project: "",
}));
ciFiles.addProject("task-api", "Task API", true);
const config = JSON.parse(fs.readFileSync(path.join(dir, ".ci", "config.json"), "utf-8"));
const config = JSON.parse(fs.readFileSync(path.join(dir, ".ciagent", "config.json"), "utf-8"));
expect(config.projects).toHaveLength(1);
expect(config.projects[0].slug).toBe("task-api");
expect(config.active_project).toBe("task-api");
});
it("addProject does not duplicate existing project", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.ensureCIDir();
fs.writeFileSync(path.join(dir, ".ci", "config.json"), JSON.stringify({
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({
projects: [{ slug: "task-api", name: "Task API" }],
active_project: "task-api",
}));
ciFiles.addProject("task-api", "Task API V2");
const config = JSON.parse(fs.readFileSync(path.join(dir, ".ci", "config.json"), "utf-8"));
const config = JSON.parse(fs.readFileSync(path.join(dir, ".ciagent", "config.json"), "utf-8"));
expect(config.projects).toHaveLength(1);
});
it("addProject creates project subdirectory", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.ensureCIDir();
fs.writeFileSync(path.join(dir, ".ci", "config.json"), JSON.stringify({
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({
projects: [],
active_project: "",
}));
ciFiles.addProject("task-api", "Task API", true);
expect(fs.existsSync(path.join(dir, ".ci", "task-api"))).toBe(true);
expect(fs.existsSync(path.join(dir, ".ciagent", "task-api"))).toBe(true);
});
it("getActiveProject returns from config", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.ensureCIDir();
fs.writeFileSync(path.join(dir, ".ci", "config.json"), JSON.stringify({
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({
projects: [{ slug: "task-api", name: "Task API", default: true }],
active_project: "task-api",
}));
@@ -140,9 +140,9 @@ describe("CiFiles", () => {
});
it("setActiveProject updates config", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.ensureCIDir();
fs.writeFileSync(path.join(dir, ".ci", "config.json"), JSON.stringify({
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({
projects: [
{ slug: "task-api", name: "Task API" },
{ slug: "auth-svc", name: "Auth Service" },
@@ -152,14 +152,14 @@ describe("CiFiles", () => {
ciFiles.setActiveProject("auth-svc");
const config = JSON.parse(fs.readFileSync(path.join(dir, ".ci", "config.json"), "utf-8"));
const config = JSON.parse(fs.readFileSync(path.join(dir, ".ciagent", "config.json"), "utf-8"));
expect(config.active_project).toBe("auth-svc");
});
it("listProjects returns projects from config", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.ensureCIDir();
fs.writeFileSync(path.join(dir, ".ci", "config.json"), JSON.stringify({
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({
projects: [
{ slug: "task-api", name: "Task API", default: true },
{ slug: "auth-svc", name: "Auth Service" },
@@ -176,71 +176,71 @@ describe("CiFiles", () => {
describe("needsMigration", () => {
it("returns false when not initialized", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
expect(ciFiles.needsMigration()).toBe(false);
});
it("returns false when already multi-project", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.ensureCIDir();
fs.writeFileSync(path.join(dir, ".ci", "config.json"), JSON.stringify({
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({
projects: [{ slug: "default", name: "Default" }],
}));
fs.writeFileSync(path.join(dir, ".ci", "PROJECT.md"), "# Test");
fs.writeFileSync(path.join(dir, ".ciagent", "PROJECT.md"), "# Test");
expect(ciFiles.needsMigration()).toBe(false);
});
it("returns true when flat files exist without subdirs or multi-project config", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.ensureCIDir();
fs.writeFileSync(path.join(dir, ".ci", "config.json"), JSON.stringify({}));
fs.writeFileSync(path.join(dir, ".ci", "PROJECT.md"), "# Test");
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({}));
fs.writeFileSync(path.join(dir, ".ciagent", "PROJECT.md"), "# Test");
expect(ciFiles.needsMigration()).toBe(true);
});
it("returns false when flat files exist but subdirs also exist", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.ensureCIDir();
fs.writeFileSync(path.join(dir, ".ci", "config.json"), JSON.stringify({}));
fs.writeFileSync(path.join(dir, ".ci", "PROJECT.md"), "# Test");
fs.mkdirSync(path.join(dir, ".ci", "task-api"));
fs.writeFileSync(path.join(dir, ".ci", "task-api", "PROJECT.md"), "# Task API");
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({}));
fs.writeFileSync(path.join(dir, ".ciagent", "PROJECT.md"), "# Test");
fs.mkdirSync(path.join(dir, ".ciagent", "task-api"));
fs.writeFileSync(path.join(dir, ".ciagent", "task-api", "PROJECT.md"), "# Task API");
expect(ciFiles.needsMigration()).toBe(false);
});
});
describe("migrateFlatToProject", () => {
it("moves flat files to project subdirectory", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.ensureCIDir();
fs.writeFileSync(path.join(dir, ".ci", "config.json"), JSON.stringify({}));
fs.writeFileSync(path.join(dir, ".ci", "PROJECT.md"), "# Test Project");
fs.writeFileSync(path.join(dir, ".ci", "ARCHITECTURE.md"), "# Architecture");
fs.writeFileSync(path.join(dir, ".ci", "ROADMAP.md"), "# Roadmap");
fs.writeFileSync(path.join(dir, ".ci", "REQUIREMENTS.md"), "# Requirements");
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({}));
fs.writeFileSync(path.join(dir, ".ciagent", "PROJECT.md"), "# Test Project");
fs.writeFileSync(path.join(dir, ".ciagent", "ARCHITECTURE.md"), "# Architecture");
fs.writeFileSync(path.join(dir, ".ciagent", "ROADMAP.md"), "# Roadmap");
fs.writeFileSync(path.join(dir, ".ciagent", "REQUIREMENTS.md"), "# Requirements");
ciFiles.migrateFlatToProject("my-app");
expect(fs.existsSync(path.join(dir, ".ci", "my-app", "PROJECT.md"))).toBe(true);
expect(fs.existsSync(path.join(dir, ".ci", "my-app", "ARCHITECTURE.md"))).toBe(true);
expect(fs.existsSync(path.join(dir, ".ci", "my-app", "ROADMAP.md"))).toBe(true);
expect(fs.existsSync(path.join(dir, ".ci", "my-app", "REQUIREMENTS.md"))).toBe(true);
expect(fs.existsSync(path.join(dir, ".ciagent", "my-app", "PROJECT.md"))).toBe(true);
expect(fs.existsSync(path.join(dir, ".ciagent", "my-app", "ARCHITECTURE.md"))).toBe(true);
expect(fs.existsSync(path.join(dir, ".ciagent", "my-app", "ROADMAP.md"))).toBe(true);
expect(fs.existsSync(path.join(dir, ".ciagent", "my-app", "REQUIREMENTS.md"))).toBe(true);
const config = JSON.parse(fs.readFileSync(path.join(dir, ".ci", "config.json"), "utf-8"));
const config = JSON.parse(fs.readFileSync(path.join(dir, ".ciagent", "config.json"), "utf-8"));
expect(config.projects).toHaveLength(1);
expect(config.active_project).toBe("my-app");
});
it("does not migrate when not needed", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.ensureCIDir();
fs.writeFileSync(path.join(dir, ".ci", "config.json"), JSON.stringify({
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({
projects: [{ slug: "existing", name: "Existing" }],
}));
ciFiles.migrateFlatToProject("new-proj");
const config = JSON.parse(fs.readFileSync(path.join(dir, ".ci", "config.json"), "utf-8"));
const config = JSON.parse(fs.readFileSync(path.join(dir, ".ciagent", "config.json"), "utf-8"));
expect(config.projects).toHaveLength(1);
expect(config.projects[0].slug).toBe("existing");
});
@@ -248,14 +248,14 @@ describe("CiFiles", () => {
describe("isNfrMilestone", () => {
it("returns true when no roadmap exists", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
expect(ciFiles.isNfrMilestone()).toBe(true);
});
it("returns true when phases are all NFR types", () => {
const ciFiles = new CiFiles(dir, "nfr-proj");
const ciFiles = new CIAgentFiles(dir, "nfr-proj");
ciFiles.ensureProjectDir();
fs.writeFileSync(path.join(dir, ".ci", "config.json"), JSON.stringify({
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({
projects: [{ slug: "nfr-proj", name: "NFR Project", default: true }],
active_project: "nfr-proj",
}));
@@ -263,7 +263,7 @@ describe("CiFiles", () => {
overview: "NFR-only",
phases: [
{ number: 1, name: "test-coverage", description: "Add tests", status: "in_progress", dependsOn: [], requirements: [], successCriteria: [] },
{ number: 2, name: "refactor-api", description: "Refactor", status: "not_started", dependsOn: [], requirements: [], successCriteria: [] },
{ number: 2, name: "perf-tune", description: "Tune perf", status: "not_started", dependsOn: [], requirements: [], successCriteria: [] },
],
};
ciFiles.writeRoadmapMd(roadmap);
@@ -271,9 +271,9 @@ describe("CiFiles", () => {
});
it("returns false when phases include feature work", () => {
const ciFiles = new CiFiles(dir, "feat-proj");
const ciFiles = new CIAgentFiles(dir, "feat-proj");
ciFiles.ensureProjectDir();
fs.writeFileSync(path.join(dir, ".ci", "config.json"), JSON.stringify({
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({
projects: [{ slug: "feat-proj", name: "Feature Project", default: true }],
active_project: "feat-proj",
}));
@@ -289,11 +289,69 @@ describe("CiFiles", () => {
});
});
describe("getMilestoneType", () => {
it("returns nfr when no roadmap exists", () => {
const ciFiles = new CIAgentFiles(dir);
expect(ciFiles.getMilestoneType()).toBe("nfr");
});
it("returns nfr when phases are all NFR types", () => {
const ciFiles = new CIAgentFiles(dir, "nfr-proj2");
ciFiles.ensureProjectDir();
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({
projects: [{ slug: "nfr-proj2", name: "NFR Project 2", default: true }],
active_project: "nfr-proj2",
}));
const roadmap: RoadmapMd = {
overview: "NFR-only",
phases: [
{ number: 1, name: "fix-bug", description: "Fix bug", status: "in_progress", dependsOn: [], requirements: [], successCriteria: [] },
],
};
ciFiles.writeRoadmapMd(roadmap);
expect(ciFiles.getMilestoneType()).toBe("nfr");
});
it("returns feature when phases include feat work", () => {
const ciFiles = new CIAgentFiles(dir, "feat-proj2");
ciFiles.ensureProjectDir();
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({
projects: [{ slug: "feat-proj2", name: "Feature Project 2", default: true }],
active_project: "feat-proj2",
}));
const roadmap: RoadmapMd = {
overview: "feature",
phases: [
{ number: 1, name: "auth-flow", description: "Auth feature", status: "in_progress", dependsOn: [], requirements: [], successCriteria: [] },
],
};
ciFiles.writeRoadmapMd(roadmap);
expect(ciFiles.getMilestoneType()).toBe("feature");
});
it("returns schema-breaking when phases include refactor/rewrite/migrate", () => {
const ciFiles = new CIAgentFiles(dir, "schema-proj");
ciFiles.ensureProjectDir();
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({
projects: [{ slug: "schema-proj", name: "Schema Project", default: true }],
active_project: "schema-proj",
}));
const roadmap: RoadmapMd = {
overview: "schema-breaking",
phases: [
{ number: 1, name: "refactor-core", description: "Refactor core", status: "in_progress", dependsOn: [], requirements: [], successCriteria: [] },
],
};
ciFiles.writeRoadmapMd(roadmap);
expect(ciFiles.getMilestoneType()).toBe("schema-breaking");
});
});
describe("multi-project file paths", () => {
it("writes PROJECT.md to project subdirectory when slug is set", () => {
const ciFiles = new CiFiles(dir, "my-app");
const ciFiles = new CIAgentFiles(dir, "my-app");
ciFiles.ensureCIDir();
fs.writeFileSync(path.join(dir, ".ci", "config.json"), JSON.stringify({
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({
projects: [{ slug: "my-app", name: "My App", default: true }],
active_project: "my-app",
}));
@@ -309,13 +367,13 @@ describe("CiFiles", () => {
ciFiles.writeProjectMd(project, "initial");
expect(fs.existsSync(path.join(dir, ".ci", "my-app", "PROJECT.md"))).toBe(true);
expect(fs.existsSync(path.join(dir, ".ciagent", "my-app", "PROJECT.md"))).toBe(true);
});
it("writes PROJECT.md to .ci root when no slug is set", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.ensureCIDir();
fs.writeFileSync(path.join(dir, ".ci", "config.json"), JSON.stringify({}));
fs.writeFileSync(path.join(dir, ".ciagent", "config.json"), JSON.stringify({}));
const project: ProjectMd = {
name: "Default App",
@@ -328,7 +386,7 @@ describe("CiFiles", () => {
ciFiles.writeProjectMd(project, "initial");
expect(fs.existsSync(path.join(dir, ".ci", "PROJECT.md"))).toBe(true);
expect(fs.existsSync(path.join(dir, ".ciagent", "PROJECT.md"))).toBe(true);
});
});
@@ -349,7 +407,7 @@ describe("CiFiles", () => {
};
it("writes and reads PROJECT.md", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.writeProjectMd(project, "initial creation");
const read = ciFiles.readProjectMd();
@@ -360,7 +418,7 @@ describe("CiFiles", () => {
});
it("overwrites PROJECT.md on update", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.writeProjectMd(project, "initial");
const updated = { ...project, coreValue: "Updated description" };
@@ -397,7 +455,7 @@ describe("CiFiles", () => {
};
it("writes and reads ROADMAP.md", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.writeRoadmapMd(roadmap);
const read = ciFiles.readRoadmapMd();
@@ -431,7 +489,7 @@ describe("CiFiles", () => {
};
it("writes and reads REQUIREMENTS.md", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.writeRequirementsMd(requirements);
const read = ciFiles.readRequirementsMd();
@@ -439,7 +497,7 @@ describe("CiFiles", () => {
});
it("updates requirement status", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.writeRequirementsMd(requirements);
ciFiles.updateRequirementStatus("AUTH-01", "complete");
@@ -465,7 +523,7 @@ describe("CiFiles", () => {
};
it("writes and reads ARCHITECTURE.md", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
ciFiles.writeArchitectureMd(arch);
const read = ciFiles.readArchitectureMd();
@@ -476,7 +534,7 @@ describe("CiFiles", () => {
describe("updatePhaseStatus", () => {
it("updates phase status in roadmap", () => {
const ciFiles = new CiFiles(dir);
const ciFiles = new CIAgentFiles(dir);
const roadmap: RoadmapMd = {
overview: "test",
phases: [
@@ -2,8 +2,9 @@ import * as fs from "node:fs";
import * as path from "node:path";
import { writeFile, readFile, ensureDir, fileExists } from "../utils/file.js";
import { PipelineStage } from "../types/pipeline.js";
import { MilestoneType } from "../types/config.js";
const CI_DIR = ".ci";
const CI_DIR = ".ciagent";
export interface ProjectMd {
name: string;
@@ -70,7 +71,7 @@ export interface ProjectEntry {
default?: boolean;
}
export class CiFiles {
export class CIAgentFiles {
private projectPath: string;
private projectSlug: string;
@@ -467,19 +468,31 @@ export class CiFiles {
this.writeRoadmapMd(roadmap);
}
isNfrMilestone(): boolean {
getMilestoneType(): MilestoneType {
const roadmap = this.readRoadmapMd();
if (!roadmap) return true;
if (!roadmap) return "nfr";
const nfrTypes: string[] = ["fix", "chore", "docs", "perf", "refactor", "test"];
const schemaBreakKeywords: string[] = ["refactor", "rewrite", "rearchitecture", "migrate", "restructure"];
let hasFeature = false;
let hasSchemaBreak = false;
for (const phase of roadmap.phases) {
if (phase.status === "in_progress" || phase.status === "not_started") {
if (phase.status === "in_progress" || phase.status === "not_started" || phase.status === "complete") {
const phaseName = phase.name.toLowerCase();
const hasFeature = !nfrTypes.some((t) => phaseName.includes(t)) && !phaseName.includes("bug") && !phaseName.includes("tune") && !phaseName.includes("refresh");
if (hasFeature) return false;
const isNfr = nfrTypes.some((t) => phaseName.includes(t)) || phaseName.includes("bug") || phaseName.includes("tune") || phaseName.includes("refresh");
if (!isNfr) hasFeature = true;
if (schemaBreakKeywords.some((k) => phaseName.includes(k))) hasSchemaBreak = true;
}
}
return true;
if (hasSchemaBreak) return "schema-breaking";
if (hasFeature) return "feature";
return "nfr";
}
isNfrMilestone(): boolean {
return this.getMilestoneType() === "nfr";
}
private parseProjectMd(content: string): ProjectMd {
@@ -545,21 +558,172 @@ export class CiFiles {
}
private parseRequirementsMd(content: string): RequirementsMd {
return {
v1: [],
v2: [],
outOfScope: [],
traceability: [],
};
const v1: RequirementsMd["v1"] = [];
const v2: RequirementsMd["v2"] = [];
const v1Section = this.extractSection(content, "## v1 Requirements");
if (v1Section) {
const categoryBlocks = v1Section.split(/\n### /).filter(Boolean);
for (const block of categoryBlocks) {
const lines = block.split("\n");
const category = lines[0].trim();
const items: Array<{ id: string; description: string }> = [];
for (const line of lines.slice(1)) {
const tableMatch = line.match(/^\|\s*([A-Z]+-\d+)\s*\|\s*(.+?)\s*\|/);
if (tableMatch) {
items.push({ id: tableMatch[1], description: tableMatch[2] });
continue;
}
const listMatch = line.match(/^\s*-?\s*\*?\s*\[?\s*\*?\s*([A-Z]+-\d+)[\]:\s*]*(.+)/);
if (listMatch) {
items.push({ id: listMatch[1], description: listMatch[2].trim() });
}
}
if (items.length > 0) {
v1.push({ category, items });
}
}
}
const v2Section = this.extractSection(content, "## v2 Requirements");
if (v2Section) {
const categoryBlocks = v2Section.split(/\n### /).filter(Boolean);
for (const block of categoryBlocks) {
const lines = block.split("\n");
const category = lines[0].trim();
const items: Array<{ id: string; description: string }> = [];
for (const line of lines.slice(1)) {
const tableMatch = line.match(/^\|\s*([A-Z]+-\d+)\s*\|\s*(.+?)\s*\|/);
if (tableMatch) {
items.push({ id: tableMatch[1], description: tableMatch[2] });
continue;
}
const listMatch = line.match(/^\s*-?\s*\*?\s*\[?\s*\*?\s*([A-Z]+-\d+)[\]:\s*]*(.+)/);
if (listMatch) {
items.push({ id: listMatch[1], description: listMatch[2].trim() });
}
}
if (items.length > 0) {
v2.push({ category, items });
}
}
}
const outOfScope: RequirementsMd["outOfScope"] = [];
const outSection = this.extractSection(content, "## Out of Scope");
if (outSection) {
const tableRows = outSection.split("\n").filter((line) => /^\|/.test(line) && !line.includes("---") && !line.includes("Feature"));
for (const row of tableRows) {
const cols = row.split("|").map((c) => c.trim()).filter(Boolean);
if (cols.length >= 2) {
outOfScope.push({ feature: cols[0], reason: cols[1] });
}
}
if (outOfScope.length === 0) {
const listItems = this.extractListItems(content, "## Out of Scope");
for (const item of listItems) {
outOfScope.push({ feature: item, reason: "" });
}
}
}
const traceability: RequirementsMd["traceability"] = [];
const traceSection = this.extractSection(content, "## Traceability");
if (traceSection) {
const activeHeader = traceSection.includes("Active Milestone")
? "## v0.5 Requirements (Active Milestone)"
: content.includes("## v1 Requirements")
? "## v1 Requirements"
: undefined;
const tableRows = traceSection.split("\n").filter((line) => /^\|/.test(line) && !line.includes("---") && !line.includes("Requirement") && !line.includes("REQ-ID"));
for (const row of tableRows) {
const cols = row.split("|").map((c) => c.trim()).filter(Boolean);
if (cols.length >= 3) {
const req = cols[0];
const phaseStr = cols[1];
const phaseMatch = phaseStr.match(/(\d+)/);
const phase = phaseMatch ? parseInt(phaseMatch[1], 10) : 0;
const statusStr = cols[2].toLowerCase();
const status = ["pending", "in_progress", "complete", "blocked", "covered"].includes(statusStr)
? (statusStr === "covered" ? "complete" : statusStr as "pending" | "in_progress" | "complete" | "blocked")
: "pending";
traceability.push({ requirement: req, phase, status });
}
}
}
const allReqIds = new Set<string>();
for (const cat of [...v1, ...v2]) {
for (const item of cat.items) {
allReqIds.add(item.id);
}
}
for (const t of traceability) {
allReqIds.add(t.requirement);
}
const coveredInTrace = new Set(traceability.filter((t) => t.status === "complete").map((t) => t.requirement));
for (const reqId of allReqIds) {
if (!coveredInTrace.has(reqId)) {
traceability.push({ requirement: reqId, phase: 0, status: "pending" });
}
}
return { v1, v2, outOfScope, traceability };
}
private parseArchitectureMd(content: string): ArchitectureMd {
return {
overview: this.extractSection(content, "## Overview") || "",
components: [],
dataFlow: this.extractSection(content, "## Data Flow") || "",
buildOrder: [],
};
const overview = this.extractSection(content, "## Overview") || "";
const components: ArchitectureMd["components"] = [];
const section = content;
const componentRegex = /###\s+(.+)/g;
let compMatch;
const h3Positions: Array<{ name: string; start: number }> = [];
while ((compMatch = componentRegex.exec(section)) !== null) {
h3Positions.push({ name: compMatch[1].trim(), start: compMatch.index + compMatch[0].length });
}
for (let i = 0; i < h3Positions.length; i++) {
const name = h3Positions[i].name;
const start = h3Positions[i].start;
const end = i + 1 < h3Positions.length ? h3Positions[i + 1].start - (content.substring(h3Positions[i + 1].start - 4, h3Positions[i + 1].start) === "### " ? 4 : 0) : content.length;
const block = content.slice(start, end);
const descMatch = block.match(/[-*]\s*\*?\*?(?:Description|description)\*?\*?\s*[:]\s*(.+)/);
const boundaryMatch = block.match(/[-*]\s*\*?\*?(?:Boundaries|boundaries)\*?\*?\s*[:]\s*(.+)/);
const depsMatch = block.match(/[-*]\s*\*?\*?(?:Depends on|depends on|Dependencies)\*?\*?\s*[:]\s*(.+)/);
components.push({
name,
description: descMatch ? descMatch[1].trim() : "",
boundaries: boundaryMatch ? boundaryMatch[1].trim() : "",
dependsOn: depsMatch
? depsMatch[1].split(",").map((d: string) => d.trim().replace(/\*\*/g, "")).filter(Boolean)
: [],
});
}
const dataFlow = this.extractSection(content, "## Data Flow")
|| this.extractSection(content, "## Data flow")
|| "";
const buildOrder: string[] = [];
const buildSection = this.extractSection(content, "## Build Order");
if (buildSection) {
const listItems = buildSection
.split("\n")
.filter((line) => /^\d+\./.test(line.trim()))
.map((line) => line.trim().replace(/^\d+\.\s*/, ""));
buildOrder.push(...listItems);
}
return { overview, components, dataFlow, buildOrder };
}
private extractSection(content: string, header: string): string | null {
+18 -18
View File
@@ -2,15 +2,15 @@ import * as fs from "node:fs";
import * as path from "node:path";
import * as os from "node:os";
import { ClarifyPhase, saveSpecification, loadSpecification } from "../core/clarify.js";
import { DEFAULT_CI_CONFIG } from "../types/config.js";
import { DEFAULT_CIAGENT_CONFIG } from "../types/config.js";
import { Specification, parseSpecification } from "../types/specification.js";
describe("ClarifyPhase", () => {
let tempDir: string;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "ci-clarify-test-"));
fs.mkdirSync(path.join(tempDir, ".ci"), { recursive: true });
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "ciagent-clarify-test-"));
fs.mkdirSync(path.join(tempDir, ".ciagent"), { recursive: true });
});
afterEach(() => {
@@ -41,7 +41,7 @@ describe("ClarifyPhase", () => {
describe("generateQuestions", () => {
it("generates questions for missing requirements", () => {
const clarify = new ClarifyPhase(DEFAULT_CI_CONFIG, tempDir);
const clarify = new ClarifyPhase(DEFAULT_CIAGENT_CONFIG, tempDir);
const questions = clarify.generateQuestions(specWithoutRequirements);
expect(questions.length).toBeGreaterThan(0);
const reqQuestion = questions.find((q) => q.category === "requirements");
@@ -50,7 +50,7 @@ describe("ClarifyPhase", () => {
});
it("generates questions for missing constraints", () => {
const clarify = new ClarifyPhase(DEFAULT_CI_CONFIG, tempDir);
const clarify = new ClarifyPhase(DEFAULT_CIAGENT_CONFIG, tempDir);
const questions = clarify.generateQuestions(specWithoutRequirements);
const constraintQuestion = questions.find((q) => q.category === "constraints");
expect(constraintQuestion).toBeDefined();
@@ -58,7 +58,7 @@ describe("ClarifyPhase", () => {
});
it("generates deployment question when deploy is mentioned without deploy constraint", () => {
const clarify = new ClarifyPhase(DEFAULT_CI_CONFIG, tempDir);
const clarify = new ClarifyPhase(DEFAULT_CIAGENT_CONFIG, tempDir);
const questions = clarify.generateQuestions(specWithRequirements);
const deployQuestion = questions.find((q) => q.category === "deployment");
expect(deployQuestion).toBeDefined();
@@ -66,8 +66,8 @@ describe("ClarifyPhase", () => {
it("respects clarify_budget", () => {
const limitedConfig = {
...DEFAULT_CI_CONFIG,
autonomy: { ...DEFAULT_CI_CONFIG.autonomy, clarify_budget: 1 },
...DEFAULT_CIAGENT_CONFIG,
autonomy: { ...DEFAULT_CIAGENT_CONFIG.autonomy, clarify_budget: 1 },
};
const clarify = new ClarifyPhase(limitedConfig, tempDir);
const questions = clarify.generateQuestions(specWithoutRequirements);
@@ -75,7 +75,7 @@ describe("ClarifyPhase", () => {
});
it("assigns sequential question IDs", () => {
const clarify = new ClarifyPhase(DEFAULT_CI_CONFIG, tempDir);
const clarify = new ClarifyPhase(DEFAULT_CIAGENT_CONFIG, tempDir);
const questions = clarify.generateQuestions(specWithoutRequirements);
for (let i = 0; i < questions.length; i++) {
expect(questions[i].id).toBe(`Q-${String(i + 1).padStart(3, "0")}`);
@@ -83,7 +83,7 @@ describe("ClarifyPhase", () => {
});
it("sorts questions by impact priority", () => {
const clarify = new ClarifyPhase(DEFAULT_CI_CONFIG, tempDir);
const clarify = new ClarifyPhase(DEFAULT_CIAGENT_CONFIG, tempDir);
const questions = clarify.generateQuestions(specWithoutRequirements);
const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
for (let i = 1; i < questions.length; i++) {
@@ -96,7 +96,7 @@ describe("ClarifyPhase", () => {
describe("answerQuestion", () => {
it("records an answer to a question", () => {
const clarify = new ClarifyPhase(DEFAULT_CI_CONFIG, tempDir);
const clarify = new ClarifyPhase(DEFAULT_CIAGENT_CONFIG, tempDir);
const questions = clarify.generateQuestions(specWithoutRequirements);
expect(questions.length).toBeGreaterThan(0);
@@ -107,7 +107,7 @@ describe("ClarifyPhase", () => {
});
it("returns null for unknown question ID", () => {
const clarify = new ClarifyPhase(DEFAULT_CI_CONFIG, tempDir);
const clarify = new ClarifyPhase(DEFAULT_CIAGENT_CONFIG, tempDir);
const result = clarify.answerQuestion("Q-999", "answer");
expect(result).toBeNull();
});
@@ -115,7 +115,7 @@ describe("ClarifyPhase", () => {
describe("acceptDefaults", () => {
it("accepts defaults for all unanswered questions", () => {
const clarify = new ClarifyPhase(DEFAULT_CI_CONFIG, tempDir);
const clarify = new ClarifyPhase(DEFAULT_CIAGENT_CONFIG, tempDir);
clarify.generateQuestions(specWithoutRequirements);
const result = clarify.acceptDefaults();
@@ -125,7 +125,7 @@ describe("ClarifyPhase", () => {
});
it("preserves manually answered questions", () => {
const clarify = new ClarifyPhase(DEFAULT_CI_CONFIG, tempDir);
const clarify = new ClarifyPhase(DEFAULT_CIAGENT_CONFIG, tempDir);
const questions = clarify.generateQuestions(specWithoutRequirements);
if (questions.length > 0) {
clarify.answerQuestion(questions[0].id, "My answer");
@@ -138,11 +138,11 @@ describe("ClarifyPhase", () => {
});
it("saves clarify responses file", () => {
const clarify = new ClarifyPhase(DEFAULT_CI_CONFIG, tempDir);
const clarify = new ClarifyPhase(DEFAULT_CIAGENT_CONFIG, tempDir);
clarify.generateQuestions(specWithoutRequirements);
clarify.acceptDefaults();
const responsesPath = path.join(tempDir, ".ci", "clarify-responses.md");
const responsesPath = path.join(tempDir, ".ciagent", "clarify-responses.md");
expect(fs.existsSync(responsesPath)).toBe(true);
const content = fs.readFileSync(responsesPath, "utf-8");
expect(content).toContain("Clarify Phase Responses");
@@ -154,8 +154,8 @@ describe("saveSpecification / loadSpecification", () => {
let tempDir: string;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "ci-spec-test-"));
fs.mkdirSync(path.join(tempDir, ".ci"), { recursive: true });
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "ciagent-spec-test-"));
fs.mkdirSync(path.join(tempDir, ".ciagent"), { recursive: true });
});
afterEach(() => {

Some files were not shown because too many files have changed in this diff Show More