feat: initialize AI agent harness

This commit is contained in:
2026-08-06 12:27:34 +09:00
commit 358d83df57
38 changed files with 34045 additions and 0 deletions

1
.gitattributes vendored Normal file
View File

@@ -0,0 +1 @@
* text=auto eol=lf

5
.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
/node_modules/
/.build/
/workspace.local.yml
*.tmp
*.bak

57
README.md Normal file
View File

@@ -0,0 +1,57 @@
# KRI Agent Harness
This repository composes deterministic, self-contained `AGENTS.md` and paired `CLAUDE.md` files for repositories under the KRI development workspace.
## Requirements
- Windows PowerShell 5.1 or newer
- Node.js 20 or newer
The committed `dist` bundle contains runtime dependencies. `npm install` is needed only when changing or rebuilding the harness source.
## Commands
Run commands from this repository root:
```powershell
.\scripts\agent-harness.cmd list
.\scripts\agent-harness.cmd plan --project kri-contact-front
.\scripts\agent-harness.cmd plan --contract kri-common
.\scripts\agent-harness.cmd verify --project kri-contact-front
.\scripts\agent-harness.cmd verify --contract kri-common
.\scripts\agent-harness.cmd compose --project kri-contact-front
.\scripts\agent-harness.cmd compose --contract kri-common
.\scripts\agent-harness.cmd register --project kri-contact-front --path _KriContact/contact-front
```
The `.cmd` launcher invokes the PowerShell wrapper with a process-scoped execution-policy bypass. It does not change the user or machine execution policy. When local scripts are already allowed, `scripts\agent-harness.ps1` may be called directly.
`plan`, `verify`, and `list` are read-only. `compose` writes only generated `AGENTS.md` and `CLAUDE.md`. `register` writes only `workspace.local.yml`. No command performs Git, database, deployment, or network operations.
Use `--contract <contract-id>` to select the registered provider first and then only registered consumers of that contract, ordered by project ID. Use `--all` only when every registered project is intentionally in scope. `--project`, `--contract`, and `--all` are mutually exclusive.
## Workspace Files
- `workspace.yml` contains shared relative project registrations and is committed.
- `workspace.local.yml` contains machine-local registrations and is ignored by Git.
- `workspace.local.example.yml` documents the local format.
- Project paths are relative to `workspace_root` and may not escape it.
## Repository Inputs
Each managed repository owns:
- `.agent/profile.yml`
- `.agent/project.md`
- `.agent/consumer.md` when it provides a shared contract
Edit source inputs, run `plan`, obtain the required approval, then run `compose`. Use `verify` to detect stale generated output.
## Development
On Windows PowerShell, use `npm.cmd` because the `npm.ps1` shim may be blocked by execution policy:
```powershell
npm.cmd install
npm.cmd run verify
```

26
catalog/contracts.yml Normal file
View File

@@ -0,0 +1,26 @@
schema_version: 1
contracts:
- id: kri-front-common
provider_project_id: kri-front-common
consumer_file: .agent/consumer.md
order: 100
required_layers:
- frontend
- fullstack
- id: kri-ui-registry
provider_project_id: kri-ui-registry
consumer_file: .agent/consumer.md
order: 200
required_layers:
- frontend
- fullstack
- id: kri-common
provider_project_id: kri-common
consumer_file: .agent/consumer.md
order: 300
required_layers:
- backend
- fullstack

15375
dist/cli.cjs vendored Normal file

File diff suppressed because it is too large Load Diff

15197
dist/index.cjs vendored Normal file

File diff suppressed because it is too large Load Diff

139
docs/composition.md Normal file
View File

@@ -0,0 +1,139 @@
# KRI Agent Harness Composition Specification
## Purpose
The composer builds deterministic, self-contained repository instructions from centrally maintained rules and repository-owned metadata. Repository agents read the generated `AGENTS.md`; Claude Code reads the paired `CLAUDE.md`, which imports that generated file.
## Runtime
- `scripts/agent-harness.ps1` is the Windows PowerShell 5.1-compatible wrapper.
- `scripts/agent-harness.cmd` launches that wrapper with a process-scoped execution-policy bypass for machines that block unsigned local PowerShell scripts; it does not change user or machine policy.
- The wrapper requires Node.js 20 or newer and invokes the bundled `dist/cli.cjs` engine.
- Runtime dependencies are bundled into `dist`; composing and verifying do not require `npm install` or network access.
- Source builds use TypeScript, YAML parsing, JSON Schema validation, and esbuild.
## Workspace Resolution
- `workspace.yml` is the committed shared registry and must declare `workspace_root` as the harness's direct parent directory.
- `workspace.local.yml` is an optional, Git-ignored registry for machine-local projects and must not override `workspace_root`.
- Duplicate project IDs across the shared and local registries are errors.
- Every project path is relative to `workspace_root`. Absolute paths, the workspace root itself, and paths that escape the resolved workspace root are rejected.
- A registry key must match the repository profile's `project.id`.
- Shared contract provider IDs are resolved through the merged registry.
## Inputs
The composer reads these inputs as strict UTF-8 text:
1. `sources/base.md`
2. `sources/project-types/<project.type>.md`
3. `sources/stacks/<stack-id>.md` for each `profile.yml` `stack` entry, in declared order
4. `sources/stacks/<database.engine>.md` once for each unique database engine, in first-declaration order
5. `sources/policies/planned-migration.md` when a `migration` block exists
6. Shared contract consumer files resolved through `catalog/contracts.yml` and the merged workspace registry
7. The target repository's `.agent/project.md`
8. The target repository's `.agent/consumer.md` when the profile provides at least one shared contract
The target repository profile is `.agent/profile.yml` and must conform to `schemas/profile.schema.json`. Machine paths never belong in the profile.
## Composition Order
Write sections in this order:
1. Deterministic generated-file header
2. Base rules
3. Project-type rules
4. Declared technology-stack rules
5. Derived database-engine rules
6. Active migration policy
7. Consumed shared contracts, ordered by the catalog `order` value
8. The provider repository's own consumer contract, when applicable
9. Project-specific rules
Separate non-empty fragments with exactly one blank line. Do not add timestamps, machine paths, Git branches, or other volatile values. Do not silently truncate or summarize a fragment.
## Generated Header
Use this logical content, substituting deterministic profile values:
```text
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Project: <project.id>
Schema version: <schema_version>
Edit the source fragments or repository .agent files, then recompose.
```
Render the header as an HTML comment so it does not become an instruction heading.
## Shared Contract Resolution
- A profile declares shared contract IDs under `shared_contracts.consumes` and `shared_contracts.provides`.
- Resolve each contract ID in `catalog/contracts.yml`.
- Resolve its `provider_project_id` to a repository path through the merged workspace registry.
- Read the catalog's `consumer_file` from that provider repository at composition time.
- A new composition therefore picks up the latest local consumer contract immediately; committed generated files remain stable until recomposed and committed again.
- `--contract <contract-id>` selects the registered provider first, followed by only profiles that explicitly consume that contract, ordered by project ID. It does not select unrelated registered projects.
- Contract selection fails for an unknown contract, an unregistered provider, or a provider profile that does not declare the catalog contract under `shared_contracts.provides`.
- Do not allow the same contract in both `provides` and `consumes`.
- A provider repository is exempt from automatic layer requirements. Its `consumes` list is explicit so self-imports and circular assumptions are not introduced.
- For a non-legacy, non-provider repository, every catalog contract whose `required_layers` contains the project layer must be declared in `consumes`.
- A legacy repository may opt into any compatible shared contract, but the composer must not add one implicitly.
## Semantic Validation
Fail composition when any of these conditions is true:
- The profile has an unknown field, invalid enum value, duplicate ID, or unresolved fragment.
- A `nextjs` stack does not also declare `react`.
- A database ID is duplicated or its engine fragment does not exist.
- `shared_contracts` contains a duplicate, an unknown contract, or a provides/consumes overlap.
- A required non-legacy shared contract is missing.
- A provider project is not registered or its consumer file is missing or empty.
- `.agent/project.md` is missing or empty.
- A providing repository's `.agent/consumer.md` is missing or empty.
- A migration target containing `nextjs` does not also contain `react`.
- Any Markdown, JSON, or YAML input is not strict UTF-8 without BOM.
The `access` field for a database is optional. Its absence grants no database execution permission. Any declared access level remains subordinate to the Base rule requiring separate explicit approval for database execution.
## Outputs
### `AGENTS.md`
- Self-contained; it must not depend on imports or files outside the repository.
- UTF-8 without BOM and LF line endings.
- Ends with exactly one newline.
- Contains no generated timestamp or absolute machine path.
- An existing file without the harness generated marker is unmanaged and must not be overwritten.
### `CLAUDE.md`
Write exactly:
```md
@AGENTS.md
```
Use UTF-8 without BOM, LF line endings, and exactly one trailing newline. Refuse to overwrite other existing content.
## Size Budget
Codex uses a 32 KiB default combined project-instruction limit. To leave room for possible nested guidance:
- Warn when generated `AGENTS.md` exceeds 26 KiB (26,624 bytes).
- Fail when it exceeds 30 KiB (30,720 bytes).
- Never solve an overflow by truncating content. Shorten or split the source rules deliberately.
## Commands
- `list`: list shared and local registrations without modifying files.
- `plan`: resolve, validate, compose in memory, and report fragments, size, warnings, and output state.
- `verify`: compare expected and stored output byte for byte without modifying files; return a failure exit code for drift.
- `compose`: atomically replace only managed or missing `AGENTS.md` and `CLAUDE.md` files, then verify them again.
- `register`: validate a relative project path and matching profile, then atomically update only `workspace.local.yml`.
For `plan`, `verify`, and `compose`, select exactly one scope with `--project <id>`, `--contract <contract-id>`, or `--all`. Contract scope processes the provider first and consumers in project-ID order. No command performs Git, database, deployment, paid API, or network operations. `--all` must be explicit; a single project is the normal scope.
## Verification
Tests use isolated temporary workspaces. They cover deterministic order, byte-for-byte verification, semantic validation, contract-target selection and isolation, unmanaged-file refusal, safe registration paths, and hard size-limit enforcement.

971
package-lock.json generated Normal file
View File

@@ -0,0 +1,971 @@
{
"name": "@kri/ai-agent-harness",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@kri/ai-agent-harness",
"version": "0.1.0",
"dependencies": {
"ajv": "8.20.0",
"yaml": "2.9.0"
},
"bin": {
"kri-agent-harness": "dist/cli.cjs"
},
"devDependencies": {
"@types/node": "20.19.43",
"esbuild": "0.28.1",
"typescript": "7.0.2"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
"integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",
"integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",
"integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",
"integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",
"integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",
"integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",
"integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",
"integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",
"integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",
"integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",
"integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",
"integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",
"integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",
"integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",
"integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",
"integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",
"integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",
"integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",
"integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",
"integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",
"integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",
"integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",
"integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",
"integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",
"integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",
"integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@types/node": {
"version": "20.19.43",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz",
"integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/@typescript/typescript-aix-ppc64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
"integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-darwin-arm64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",
"integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-darwin-x64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",
"integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-freebsd-arm64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",
"integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-freebsd-x64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",
"integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-linux-arm": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",
"integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-linux-arm64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",
"integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-linux-loong64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",
"integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",
"cpu": [
"loong64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-linux-mips64el": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",
"integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-linux-ppc64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",
"integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-linux-riscv64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",
"integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-linux-s390x": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",
"integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",
"cpu": [
"s390x"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-linux-x64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",
"integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-netbsd-arm64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",
"integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-netbsd-x64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",
"integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-openbsd-arm64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",
"integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-openbsd-x64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",
"integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-sunos-x64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",
"integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-win32-arm64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",
"integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/@typescript/typescript-win32-x64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",
"integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/ajv": {
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
"integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
"license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.3",
"fast-uri": "^3.0.1",
"json-schema-traverse": "^1.0.0",
"require-from-string": "^2.0.2"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/epoberezkin"
}
},
"node_modules/esbuild": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
"integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.28.1",
"@esbuild/android-arm": "0.28.1",
"@esbuild/android-arm64": "0.28.1",
"@esbuild/android-x64": "0.28.1",
"@esbuild/darwin-arm64": "0.28.1",
"@esbuild/darwin-x64": "0.28.1",
"@esbuild/freebsd-arm64": "0.28.1",
"@esbuild/freebsd-x64": "0.28.1",
"@esbuild/linux-arm": "0.28.1",
"@esbuild/linux-arm64": "0.28.1",
"@esbuild/linux-ia32": "0.28.1",
"@esbuild/linux-loong64": "0.28.1",
"@esbuild/linux-mips64el": "0.28.1",
"@esbuild/linux-ppc64": "0.28.1",
"@esbuild/linux-riscv64": "0.28.1",
"@esbuild/linux-s390x": "0.28.1",
"@esbuild/linux-x64": "0.28.1",
"@esbuild/netbsd-arm64": "0.28.1",
"@esbuild/netbsd-x64": "0.28.1",
"@esbuild/openbsd-arm64": "0.28.1",
"@esbuild/openbsd-x64": "0.28.1",
"@esbuild/openharmony-arm64": "0.28.1",
"@esbuild/sunos-x64": "0.28.1",
"@esbuild/win32-arm64": "0.28.1",
"@esbuild/win32-ia32": "0.28.1",
"@esbuild/win32-x64": "0.28.1"
}
},
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"license": "MIT"
},
"node_modules/fast-uri": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz",
"integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fastify"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fastify"
}
],
"license": "BSD-3-Clause"
},
"node_modules/json-schema-traverse": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
"license": "MIT"
},
"node_modules/require-from-string": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
"integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/typescript": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",
"integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc"
},
"engines": {
"node": ">=16.20.0"
},
"optionalDependencies": {
"@typescript/typescript-aix-ppc64": "7.0.2",
"@typescript/typescript-darwin-arm64": "7.0.2",
"@typescript/typescript-darwin-x64": "7.0.2",
"@typescript/typescript-freebsd-arm64": "7.0.2",
"@typescript/typescript-freebsd-x64": "7.0.2",
"@typescript/typescript-linux-arm": "7.0.2",
"@typescript/typescript-linux-arm64": "7.0.2",
"@typescript/typescript-linux-loong64": "7.0.2",
"@typescript/typescript-linux-mips64el": "7.0.2",
"@typescript/typescript-linux-ppc64": "7.0.2",
"@typescript/typescript-linux-riscv64": "7.0.2",
"@typescript/typescript-linux-s390x": "7.0.2",
"@typescript/typescript-linux-x64": "7.0.2",
"@typescript/typescript-netbsd-arm64": "7.0.2",
"@typescript/typescript-netbsd-x64": "7.0.2",
"@typescript/typescript-openbsd-arm64": "7.0.2",
"@typescript/typescript-openbsd-x64": "7.0.2",
"@typescript/typescript-sunos-x64": "7.0.2",
"@typescript/typescript-win32-arm64": "7.0.2",
"@typescript/typescript-win32-x64": "7.0.2"
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
},
"node_modules/yaml": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
"integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
"license": "ISC",
"bin": {
"yaml": "bin.mjs"
},
"engines": {
"node": ">= 14.6"
},
"funding": {
"url": "https://github.com/sponsors/eemeli"
}
}
}
}

30
package.json Normal file
View File

@@ -0,0 +1,30 @@
{
"name": "@kri/ai-agent-harness",
"version": "0.1.0",
"private": true,
"type": "module",
"bin": {
"kri-agent-harness": "./dist/cli.cjs"
},
"exports": {
".": "./dist/index.cjs"
},
"scripts": {
"build": "node scripts/build.mjs",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "node --test",
"verify": "npm run typecheck && npm run build && npm test"
},
"engines": {
"node": ">=20"
},
"dependencies": {
"ajv": "8.20.0",
"yaml": "2.9.0"
},
"devDependencies": {
"@types/node": "20.19.43",
"esbuild": "0.28.1",
"typescript": "7.0.2"
}
}

173
schemas/profile.schema.json Normal file
View File

@@ -0,0 +1,173 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://kri.local/agent-harness/profile.schema.json",
"title": "KRI Agent Harness Project Profile",
"type": "object",
"additionalProperties": false,
"required": [
"schema_version",
"project",
"stack"
],
"properties": {
"schema_version": {
"const": 1
},
"project": {
"type": "object",
"additionalProperties": false,
"required": [
"id",
"name",
"type",
"layer",
"legacy"
],
"properties": {
"id": {
"$ref": "#/$defs/slug"
},
"name": {
"type": "string",
"minLength": 1
},
"type": {
"enum": [
"library",
"scaffold-cli",
"shared-service",
"internal-service",
"requested-project"
]
},
"layer": {
"enum": [
"frontend",
"backend",
"fullstack",
"standalone"
]
},
"legacy": {
"type": "boolean"
}
}
},
"stack": {
"type": "array",
"minItems": 1,
"uniqueItems": true,
"items": {
"$ref": "#/$defs/stack_id"
}
},
"shared_contracts": {
"type": "object",
"additionalProperties": false,
"minProperties": 1,
"properties": {
"provides": {
"$ref": "#/$defs/contract_list"
},
"consumes": {
"$ref": "#/$defs/contract_list"
}
}
},
"databases": {
"type": "array",
"uniqueItems": true,
"items": {
"type": "object",
"additionalProperties": false,
"required": [
"id",
"engine",
"role"
],
"properties": {
"id": {
"$ref": "#/$defs/slug"
},
"engine": {
"enum": [
"mysql",
"mssql"
]
},
"role": {
"$ref": "#/$defs/slug"
},
"access": {
"enum": [
"read-only",
"read-write"
]
}
}
}
},
"migration": {
"type": "object",
"additionalProperties": false,
"required": [
"status",
"target_stack",
"strategy"
],
"properties": {
"status": {
"enum": [
"planned",
"active",
"paused"
]
},
"target_stack": {
"type": "array",
"minItems": 1,
"uniqueItems": true,
"items": {
"$ref": "#/$defs/stack_id"
}
},
"strategy": {
"const": "staged"
}
}
}
},
"$defs": {
"slug": {
"type": "string",
"pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$"
},
"stack_id": {
"enum": [
"typescript",
"react",
"nextjs",
"java-springboot",
"classic-asp",
"dotnet-csharp",
"python",
"ai-llm"
]
},
"contract_id": {
"enum": [
"kri-front-common",
"kri-ui-registry",
"kri-common"
]
},
"contract_list": {
"type": "array",
"minItems": 1,
"uniqueItems": true,
"items": {
"$ref": "#/$defs/contract_id"
}
}
}
}

View File

@@ -0,0 +1,39 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://kri.local/agent-harness/workspace.schema.json",
"title": "KRI Agent Harness Workspace",
"type": "object",
"additionalProperties": false,
"required": [
"schema_version",
"projects"
],
"properties": {
"schema_version": {
"const": 1
},
"workspace_root": {
"type": "string",
"minLength": 1
},
"projects": {
"type": "object",
"propertyNames": {
"$ref": "profile.schema.json#/$defs/slug"
},
"additionalProperties": {
"type": "object",
"additionalProperties": false,
"required": [
"path"
],
"properties": {
"path": {
"type": "string",
"minLength": 1
}
}
}
}
}
}

View File

@@ -0,0 +1,5 @@
@echo off
setlocal
set "SCRIPT_DIR=%~dp0"
powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File "%SCRIPT_DIR%agent-harness.ps1" %*
exit /b %ERRORLEVEL%

33
scripts/agent-harness.ps1 Normal file
View File

@@ -0,0 +1,33 @@
[CmdletBinding()]
param(
[Parameter(ValueFromRemainingArguments = $true)]
[string[]] $HarnessArguments
)
$ErrorActionPreference = 'Stop'
$scriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$harnessRoot = Split-Path -Parent $scriptRoot
$entryPoint = Join-Path $harnessRoot 'dist\cli.cjs'
if (-not (Test-Path -LiteralPath $entryPoint -PathType Leaf)) {
throw "Harness entry point not found: $entryPoint"
}
$nodeCommand = Get-Command node -ErrorAction SilentlyContinue
if ($null -eq $nodeCommand) {
throw 'Node.js 20 or newer is required.'
}
$nodeVersionText = (& $nodeCommand.Source --version).TrimStart('v')
if ($LASTEXITCODE -ne 0) {
exit $LASTEXITCODE
}
$nodeVersion = [Version] $nodeVersionText
if ($nodeVersion.Major -lt 20) {
throw "Node.js 20 or newer is required. Found: $nodeVersionText"
}
& $nodeCommand.Source $entryPoint @HarnessArguments
exit $LASTEXITCODE

33
scripts/build.mjs Normal file
View File

@@ -0,0 +1,33 @@
import { chmod, rm } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { build } from "esbuild";
const harnessRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
await rm(path.join(harnessRoot, "dist"), { recursive: true, force: true });
const common = {
absWorkingDir: harnessRoot,
bundle: true,
platform: "node",
target: "node20",
format: "cjs",
legalComments: "eof",
sourcemap: false,
};
await Promise.all([
build({
...common,
entryPoints: [path.join(harnessRoot, "src", "cli.ts")],
outfile: path.join(harnessRoot, "dist", "cli.cjs"),
banner: { js: "#!/usr/bin/env node" },
}),
build({
...common,
entryPoints: [path.join(harnessRoot, "src", "index.ts")],
outfile: path.join(harnessRoot, "dist", "index.cjs"),
}),
]);
await chmod(path.join(harnessRoot, "dist", "cli.cjs"), 0o755);

180
sources/base.md Normal file
View File

@@ -0,0 +1,180 @@
# KRI Development Base Instructions
This document defines the shared working rules for KRI development repositories.
Keep project-specific facts and commands in the project profile and project rules.
## Instruction Resolution
Apply repository instructions in this order:
1. Base rules
2. Project-type rules
3. Technology-stack rules
4. Shared consumer contracts
5. Project-specific rules
6. The explicitly approved task scope
Later and more specific instructions may override earlier general instructions only within their stated scope.
- Apply a shared consumer contract only when `.agent/profile.yml` declares it.
- Do not silently resolve a material instruction conflict. Report the conflicting rules and request a decision before changing files.
- Rules involving destructive actions, credentials, external systems, production, deployment, databases, or Git publication require explicit authorization even when a later rule is less restrictive.
## Communication
- Respond to the user in Korean unless the user requests another language.
- Keep code identifiers, commands, paths, protocol names, and external API terms in their original form.
- Follow the repository's existing language conventions for code comments and user-facing messages.
- Lead with the result or decision, then provide only the detail needed to verify it.
- Do not create or retain a full session transcript.
## Work Authorization
- The default workflow is discussion first and explicit execution approval second.
- During discussion, perform only read-only investigation needed to understand the task and propose a concrete plan, unless the user prohibits inspection.
- Read-only investigation may include file inspection, code search, encoding checks, `git status`, `git diff`, `git log`, and sanitized official-documentation lookup.
- Before execution approval, do not edit files, install dependencies, run builds or tests, start services, connect to databases, or change local or external state.
- Before requesting approval, describe the intended scope, affected areas, validation plan, and material risks.
- Treat approval as limited to the presented scope. Pause and discuss again if the work materially expands.
- If the user explicitly requests immediate execution without prior discussion, the discussion gate may be skipped for the stated scope.
- Fast-track authorization does not implicitly authorize protected operations such as destructive commands, production changes, deployments, database mutations, Git publication, or external messages.
## Local Development Environment
- Primary OS: Windows 11.
- Primary shell: PowerShell.
- Use Git Bash only when the repository already depends on Bash or POSIX shell behavior.
- Prefer repository-provided wrappers and scripts over globally installed commands.
- Do not assume that GNU utilities, WSL, Docker, or a Unix-compatible shell are available unless the project profile confirms them.
- Detect Java, Node.js, .NET, Python, package-manager, and database-tool versions from repository configuration.
- Do not install or modify global toolchains as part of a project task.
Preferred human-facing tools:
- Classic ASP: Visual Studio Code
- Java and Spring Boot: IntelliJ IDEA
- C# and .NET: JetBrains Rider
- JavaScript, TypeScript, and Next.js: JetBrains WebStorm
- Python: JetBrains PyCharm
- Microsoft SQL Server: SQL Server Management Studio
- Other databases: JetBrains DataGrip
- These preferences do not authorize launching or controlling a GUI application.
- Prefer IDE-independent commands that can also run in CI.
- Do not modify global IDE settings.
- Do not create or modify `.idea`, `.vscode`, workspace, or run-configuration files unless the approved task requires it.
- Preserve existing shared IDE configuration when it is already tracked.
## PowerShell and Path Safety
- Quote paths containing spaces, brackets, parentheses, Korean characters, or PowerShell metacharacters.
- Prefer `-LiteralPath` when operating on an exact filesystem path.
- Use project-relative paths in committed configuration and documentation. Do not commit machine-specific paths such as `D:\_____Dev\...`.
- Do not pass filesystem targets between PowerShell, `cmd.exe`, and Bash for destructive or recursive operations.
- Keep a filesystem operation within one shell from target resolution through execution.
- Before a recursive delete or move, resolve and verify every absolute target.
- Never use a drive root, workspace root, user profile, unresolved variable, wildcard, or broad glob as a recursive delete target.
- Prefer recoverable operations when practical.
## Change Discipline
- Preserve all existing user changes, including uncommitted and untracked work.
- Keep changes minimal but complete for the approved objective.
- Avoid unrelated cleanup, formatting, renaming, dependency upgrades, and architectural refactoring.
- Do not overwrite or revert unrelated changes.
- Stop and report when the requested change overlaps existing work in a way that cannot be handled safely.
- Prefer changing an authoritative source over editing generated output.
- Treat files marked as generated as read-only unless regeneration is part of the approved plan.
- Do not edit vendored dependencies, build outputs, caches, or generated clients unless explicitly required.
- Do not regenerate a broad set of files for a narrow change without first explaining the expected output scope.
## Text Encoding and Korean Content Safety
- Treat the existing file encoding, BOM state, and line-ending style as part of the file's contract.
- Preserve Korean comments, user-facing messages, error messages, identifiers, and documentation exactly unless the task explicitly requires changing them.
- Do not assume that garbled terminal output means the file itself is corrupted. Verify bytes and encoding before modifying suspicious text.
- Before editing an existing text file, determine its current encoding and BOM state when repository configuration does not already guarantee them.
- Do not convert encoding, add or remove a BOM, or normalize line endings as a side effect of an unrelated change.
- Avoid whole-file rewrites for small changes.
- Do not rewrite source files through `Get-Content | Set-Content`, `Out-File`, shell redirection, or another method whose encoding behavior is implicit.
- Do not use a patching or formatting tool on a non-UTF-8 file unless it is known to preserve that file's encoding.
- Treat a console display problem and an on-disk encoding problem as separate issues.
- After editing Korean text, inspect the diff for replacement characters (`<60>`), mojibake, unexpected escapes, BOM changes, and unrelated line-ending changes.
- Run `.agent/tools/check-encoding.ps1` when it is available and the change touches Korean text or a non-default encoding.
- If encoding cannot be identified confidently, stop before writing and report the affected file and evidence.
- For a new text file, follow repository configuration. If no rule exists, use UTF-8 without BOM.
## Git Safety
- Use `git status`, `git diff`, and `git log` for read-only investigation.
- Do not run `commit`, `push`, `pull`, `fetch`, `merge`, `rebase`, `reset`, `checkout`, `switch`, `stash`, `clean`, `tag`, or force operations unless that specific operation is explicitly approved.
- Source-edit approval does not include commit or push approval.
- Never amend an existing commit unless explicitly requested.
- Before an approved commit, show the intended files, validation results, and proposed commit message.
- Never push directly to a protected branch unless the user names the target branch and explicitly authorizes the push.
## Dependencies and External Actions
- Use the package manager, lockfile, and toolchain already selected by the repository.
- Do not install global packages.
- Do not add, remove, or upgrade a dependency unless it was included in the approved plan.
- Pause for approval if an unplanned dependency becomes necessary.
- Keep lockfiles synchronized with approved dependency changes.
- Do not deploy, publish packages, create releases, send messages or email, call business APIs, or modify external services unless explicitly requested.
- Never upload proprietary source code, internal documents, credentials, customer data, or database contents to an external service.
- Remove secrets and unnecessary internal identifiers from external search queries.
## Database Safety
- Treat writing or reviewing SQL as source code separately from executing SQL against a database.
- SQL files, migrations, schema proposals, and query drafts may be created within an approved source-change scope.
- Do not connect to a shared, staging, or production database without explicit authorization for that environment.
- Read-only queries against a non-local database also require authorization because results may contain sensitive data.
- Do not execute DDL, DML, stored procedures, migrations, administrative commands, or data-correction scripts against a non-disposable database without separate authorization for the exact target and operation.
- Source-change approval does not authorize migration execution.
- Use a disposable local or test database for approved validation only after verifying its identity and disposable nature.
- Never place credentials, connection strings, or sensitive query results in source files, logs, generated documents, or chat output.
## Secrets and Sensitive Data
- Never add credentials, tokens, passwords, private keys, connection strings, session identifiers, or production data to source control.
- Read sensitive files only when the approved task requires it and no safer source exists.
- Prefer inspecting configuration keys and schemas without displaying secret values.
- Never echo secrets into terminal output, chat responses, logs, diffs, generated documents, test fixtures, or screenshots.
- Redact sensitive values when reporting errors or command output.
- If a possible secret is discovered, do not repeat it. Report only its location, type, and recommended containment action.
- Do not rotate, revoke, copy, or otherwise modify credentials unless that exact action is explicitly authorized.
## Validation
- Discover supported build, test, lint, type-check, and formatting commands from repository files and project instructions. Do not invent commands.
- Include intended validation in the discussion-phase plan.
- After approved changes, run the narrowest relevant validation first, then broader checks when appropriate.
- Limit formatting to files within the approved scope.
- Do not run tests that require a shared database, production service, paid external API, or sensitive data unless separately authorized.
- Do not claim that a check passed unless it was executed successfully.
- If a check cannot be run, state the exact reason.
- Distinguish a current-change failure from a pre-existing failure or an undetermined failure.
- Do not fix unrelated failures without expanding the approved scope.
- Inspect the worktree after validation for unexpected generated files, formatting churn, encoding changes, or lockfile changes.
## Artifacts and Session Records
- Do not create full-session transcripts, automatic HTML copies, analysis reports, or extra documentation unless explicitly requested.
- Store durable information in the repository's existing documentation structure.
- Do not place generated reports or temporary analysis files in the repository root.
- Remove task-specific temporary files created by the current task after validation when removal is safe.
## Completion Report
When implementation is complete, report in Korean:
- what changed and why;
- the main affected files or components;
- validation commands actually executed and their results;
- checks not executed and the reason;
- remaining risks, assumptions, or follow-up work;
- database, deployment, dependency, encoding, and compatibility impact when applicable.
- Do not report completion while required validation is failing or known encoding corruption is unresolved.
- Keep the report concise and do not include a full session transcript.

View File

@@ -0,0 +1,11 @@
## Planned Migration
- Treat the current stack and production behavior as authoritative until an explicit migration task and slice are approved.
- Do not begin a partial migration while handling an unrelated feature, fix, review, or refactor.
- Before migration work, document the relevant baseline: routes, APIs, authentication, authorization, state, data contracts, environment variables, build, deployment, operations, and user-visible behavior.
- Define small staged slices with acceptance criteria, compatibility requirements, validation, rollout, and rollback for each slice.
- Keep migrated and non-migrated areas interoperable for as long as both remain active.
- Apply target-stack conventions only inside the approved slice and shared boundaries that must change with it.
- Establish behavior equivalence with representative checks before removing the previous implementation.
- Separate intentional product or behavior changes from framework-only migration changes so each can be reviewed independently.
- For standalone React applications, the default planned target is Next.js with TypeScript unless the project profile explicitly declares another approved target.

View File

@@ -0,0 +1,13 @@
## Internal Service Project Rules
- Internal-only usage does not reduce security, privacy, compatibility, or validation requirements.
- Preserve authentication, authorization, role boundaries, auditability, and personal-data protections.
- Identify affected user workflows before changing visible behavior.
- Treat Frontend and Backend repositories as separate deployable systems with an explicit API contract between them.
- Coordinate request, response, authentication, error, and versioning changes across both sides when the approved scope includes both repositories.
- Do not silently require a simultaneous Frontend and Backend deployment.
- Prefer backward-compatible transitions when deployments may occur independently.
- Include migration and rollback considerations for database, API, and configuration changes.
- Do not modernize legacy code as an unrelated side effect.
- Apply Classic ASP text-safety rules only when the project profile declares the `classic-asp` stack.
- Do not access or modify production data merely because the service is internal.

View File

@@ -0,0 +1,13 @@
## Library Project Rules
- Treat exported code, configuration keys, registry schemas, generated artifacts, package coordinates, and documented behavior as consumer-facing contracts.
- Before changing a public surface, classify the change as internal, backward-compatible, deprecating, or breaking.
- Do not remove, rename, relocate, or materially change a public API without an approved compatibility and migration plan.
- Preserve consumer override points and optional integrations.
- Do not make an optional peer, compile-only, or runtime dependency mandatory without reviewing consumer impact.
- Prefer additive evolution and deprecation over immediate removal.
- When a public contract changes, update tests, human documentation, and the library's consumer contract in the same approved change.
- Validate both the source and the distributable artifact when supported.
- Inspect known consumers when available, but do not modify consumer repositories unless they are included in the approved scope.
- Version changes, publication, registry deployment, and package replacement require separate authorization.
- Keep repository-maintainer rules in `.agent/project.md` and downstream usage rules in `.agent/consumer.md`.

View File

@@ -0,0 +1,14 @@
## Requested Project Rules
- Treat the approved requirements, acceptance criteria, and recorded decisions as the primary scope boundary.
- Do not infer a requirement solely from a file name, folder date, or apparently newer document.
- When requirements conflict, report the exact sources and request a decision.
- Preserve original customer, partner, and planning documents as read-only evidence unless document editing is explicitly approved.
- Summarize durable implementation requirements inside the repository rather than relying only on files outside the repository.
- Do not expand the deliverable with speculative features, infrastructure, or architectural changes.
- Record material assumptions and unresolved decisions in the project-specific rules or existing project documentation.
- Define observable acceptance criteria before implementation.
- Treat separately managed Frontend and Backend repositories as independent deliverables with a coordinated contract.
- Protect customer, partner, survey, and field data as sensitive information.
- Keep handoff, operation, configuration, and validation instructions usable by the requesting team.
- Report deviations from the requested scope and obtain approval before proceeding.

View File

@@ -0,0 +1,14 @@
## Scaffold CLI Project Rules
- Treat both the CLI interface and the generated project structure as public contracts.
- Preserve existing command names, flags, defaults, prompts, exit behavior, and generated paths unless a breaking change is explicitly approved.
- Keep generation deterministic for the same input and template version.
- Do not embed credentials, user-specific absolute paths, local machine state, or uncommitted source files in templates.
- Never overwrite a non-empty target directory unless the user explicitly selected and authorized the supported force behavior.
- Validate template changes by generating a project in a newly created, disposable directory.
- Validate the generated project with its own type-check, build, or compile commands when practical.
- Inspect generated output for unresolved placeholders, accidental secrets, invalid encodings, machine-specific paths, and unexpected files.
- Keep README usage, CLI help, templates, and implementation synchronized.
- Preserve operation when the central Agent Harness is not installed.
- Generate the committed Agent Harness file set by default for every new project.
- Updating embedded harness templates does not authorize publishing the CLI package.

View File

@@ -0,0 +1,13 @@
## Shared Service Project Rules
- Treat APIs, message formats, callback behavior, identifiers, error responses, and operational defaults as contracts used by multiple consumers.
- Prefer backward-compatible API and schema evolution.
- Identify all externally visible side effects before changing a request flow.
- Design retryable operations to be idempotent where duplicate execution could send multiple notifications, create duplicate records, or generate inconsistent results.
- Define explicit timeout, retry, and failure behavior for external dependencies.
- Do not send real email, SMS, notifications, callbacks, or business requests during development or validation.
- Use mocks, fakes, test recipients, or disposable local integrations only when their safety is verified.
- Do not expose credentials, message contents, personal data, shortened target URLs, or authentication material in logs.
- Preserve authentication, authorization, rate limits, validation, and abuse controls when modifying endpoints.
- Review database and rollout compatibility before changing persisted data or shared service behavior.
- Include consumer impact and rollback considerations in the completion report.

12
sources/stacks/ai-llm.md Normal file
View File

@@ -0,0 +1,12 @@
## AI and LLM Workloads
- Treat prompts, schemas, model routing, retrieval, pre-processing, post-processing, thresholds, and evaluations as source-controlled behavior.
- Explain the behavioral impact before changing a provider, model, embedding, prompt, threshold, chunking, or ranking strategy.
- Do not call paid model, embedding, transcription, vision, or other metered APIs without separate explicit approval.
- Do not send proprietary, personal, customer, survey, receipt, transcript, or other sensitive data to an external model or service without exact authorization for that data and destination.
- Prefer mocks and sanitized deterministic fixtures for development and tests.
- Validate structured model output before business use and handle refusals, malformed output, timeouts, rate limits, and provider failures explicitly.
- Keep API keys and provider credentials in the repository's approved secret mechanism, never in source, prompts, fixtures, logs, or committed configuration.
- Redact sensitive prompt, response, token, trace, and provider-error content from logs and reports.
- Separate deterministic business rules from probabilistic model behavior so critical rules remain testable.
- Compare representative evaluation results before and after behavioral changes, and report material quality, cost, latency, privacy, and reproducibility tradeoffs.

View File

@@ -0,0 +1,17 @@
## Classic ASP
- Prioritize behavior preservation. Do not modernize syntax, includes, data access, error handling, or page structure outside the approved scope.
- Trace the full include chain and relevant application/session/configuration dependencies before changing shared ASP behavior.
- Preserve `Response.CodePage`, `Response.CharSet`, page directives, response headers, and the existing browser/server encoding contract.
- Parameterize ADO commands and preserve the expected command type, parameter order, data types, sizes, directions, result sets, and transaction behavior.
- Close and release recordsets, commands, connections, streams, and other COM resources on every applicable path.
- Preserve the established `On Error Resume Next` and error propagation pattern; do not suppress newly introduced failures.
### Legacy Text File Safety
- Treat each existing Classic ASP text file's byte encoding, BOM state, and line endings as part of its contract.
- Detect those properties before editing and preserve them exactly unless an encoding conversion is explicitly approved.
- Do not assume UTF-8. Existing files may use UTF-8 with or without BOM, EUC-KR/CP949, or another legacy encoding.
- Keep Korean comments, literals, SQL, HTML, JavaScript, and error messages byte-safe. Stop if the source encoding cannot be identified confidently.
- Avoid formatters or bulk rewrites that normalize encoding or line endings across the file.
- After editing, run the harness encoding check and inspect the diff for replacement characters, mojibake, unexpected BOM changes, or whole-file churn.

View File

@@ -0,0 +1,10 @@
## .NET and C#
- Treat the configured target framework, SDK, language version, nullable mode, application model, package versions, and solution layout as authoritative.
- Do not use APIs unavailable to the target framework or perform framework, project-format, or package migrations outside the approved scope.
- Preserve the repository's dependency-injection, configuration, logging, exception, serialization, and data-access conventions.
- Use async APIs for asynchronous I/O and avoid sync-over-async blocking such as `.Result` and `.Wait()`.
- Dispose `IDisposable` and `IAsyncDisposable` resources deterministically.
- For WinForms, preserve designer ownership, UI-thread access, event lifecycle, and the existing separation between generated designer code and hand-written code.
- Keep secrets and environment-specific endpoints out of source and committed configuration.
- Run the narrowest relevant restore, build, test, and analyzer commands supported by the repository and target framework.

View File

@@ -0,0 +1,12 @@
## Java and Spring Boot
- Treat the configured JDK, Spring Boot, Gradle, plugin, dependency, and package versions as authoritative.
- Use the repository's Gradle Wrapper. Do not substitute a machine-global Gradle installation.
- Preserve the established package layout and controller, application/service, domain, and persistence boundaries.
- Keep controllers thin, place business rules in the established service/domain layer, and prefer constructor injection.
- Apply request and configuration validation at boundaries and preserve the project's exception and response conventions.
- Make transaction boundaries explicit and narrow; do not add broad transactions to hide lifecycle or query problems.
- Preserve authentication, authorization, auditing, logging, and secret-management conventions.
- Do not edit generated QueryDSL or other generated sources. Change their source definitions and regenerate only when the repository workflow requires it.
- Use the approved KriCommon contract when the project profile includes it; do not duplicate shared backend behavior locally.
- Run the narrowest relevant Gradle compile, test, static-analysis, and build tasks.

10
sources/stacks/mssql.md Normal file
View File

@@ -0,0 +1,10 @@
## Microsoft SQL Server
- Use T-SQL syntax and behavior only for data sources whose declared engine is `mssql`.
- Preserve the configured SQL Server version, database and schema names, collation, naming, migration, and access conventions.
- Parameterize values. Do not build SQL by concatenating untrusted input.
- Preserve Unicode behavior and use the repository's established `nvarchar`/`nchar` and parameter conventions where Korean or other Unicode text is possible.
- Treat stored-procedure parameters, result sets, return values, transaction behavior, and error behavior as public contracts.
- Consider indexes and actual execution characteristics for changed filters, joins, ordering, grouping, and pagination.
- Do not introduce MySQL or other dialect syntax into MSSQL paths.
- Keep read-only legacy integrations read-only. A source-code change approval authorizes SQL analysis and script drafting only; execution requires separate explicit approval and the declared data-source access level.

9
sources/stacks/mysql.md Normal file
View File

@@ -0,0 +1,9 @@
## MySQL
- Use MySQL syntax and behavior only for data sources whose declared engine is `mysql`.
- Preserve the configured version, schema, character set, collation, time zone, naming, migration, and access conventions.
- Parameterize values. Do not build SQL by concatenating untrusted input.
- Consider indexes and execution plans for changed filters, joins, ordering, grouping, and pagination without guessing from small data sets.
- Preserve transaction, locking, null, date/time, decimal, and generated-key semantics.
- Do not introduce MSSQL or other dialect syntax into MySQL paths.
- A source-code change approval authorizes SQL analysis and migration drafting only. Execute DDL, DML, procedures, or migrations only with separate explicit approval and the declared data-source access level.

11
sources/stacks/nextjs.md Normal file
View File

@@ -0,0 +1,11 @@
## Next.js
- Treat the repository's current Next.js and React versions, routing model, rendering model, and package manager as authoritative.
- Preserve server and client component boundaries. Add `use client` only when browser APIs, state, effects, or client-only libraries require it.
- Keep secrets, privileged data access, and server-only modules out of client bundles.
- Preserve established route, layout, middleware, authentication, authorization, caching, revalidation, and error-handling conventions.
- Validate request parameters, payloads, headers, cookies, and external responses at runtime.
- Do not create new frontend TypeScript type or interface names ending in `Dto` or `DTO`. Use domain- or purpose-specific names such as `User`, `UserInput`, `UserRequest`, or `UserResponse`; do not rename existing types solely to enforce this rule outside the approved scope.
- Use the approved KRI frontend and UI contracts when the project profile includes them; do not copy shared implementations into an application.
- Avoid incidental routing-model or rendering-strategy migrations.
- Run the repository's focused lint, type-check, test, and production build commands as applicable.

12
sources/stacks/python.md Normal file
View File

@@ -0,0 +1,12 @@
## Python
- Detect and preserve the repository's interpreter version, virtual environment, dependency mechanism, formatter, linter, type checker, and test runner.
- Use the project-local environment. Do not install packages globally or alter unrelated environments.
- Preserve the existing dependency-file strategy; do not broadly regenerate or reorder requirement files for a narrow change.
- Preserve file encoding and line endings, especially in Korean source, prompts, fixtures, and documents.
- Follow the repository's import, typing, Pydantic/model, exception, logging, and entry-point conventions.
- Use explicit paths and encodings for file I/O, and clean up temporary resources deterministically.
- Avoid broad exception handling unless it is an intentional application boundary with actionable diagnostics.
- Keep credentials, tokens, model keys, and environment-specific endpoints out of source and committed configuration.
- Use sanitized, minimal fixtures instead of production survey, receipt, transcript, customer, or internal documents.
- Run the narrowest relevant pytest, lint, type-check, and application smoke checks available in the repository.

9
sources/stacks/react.md Normal file
View File

@@ -0,0 +1,9 @@
## React
- Treat the current React version, component style, state management, routing, styling, and test approach as authoritative.
- Do not perform unrelated class-to-hook, JavaScript-to-TypeScript, state-library, styling-system, or React-to-Next.js migrations.
- Keep components focused and follow the repository's established split between presentation, state, data access, and side effects.
- Keep effects dependency-correct and clean up subscriptions, timers, listeners, and in-flight work where applicable.
- Use stable semantic keys and preserve accessibility, loading, empty, error, disabled, and success states.
- Preserve public component props and shared UI contracts unless a coordinated breaking change is explicitly approved.
- Treat any planned Next.js migration as a separate policy and task; the current React application remains authoritative until that migration slice is approved.

View File

@@ -0,0 +1,9 @@
## TypeScript
- Treat the repository's current TypeScript version, `tsconfig` files, module system, path aliases, and package manager as authoritative.
- Preserve or strengthen existing strictness. Do not weaken compiler options or hide errors with broad `any`, `@ts-ignore`, or unsafe assertions.
- Prefer narrow domain types, discriminated unions, and explicit boundary types over duplicated or overly generic shapes.
- Validate untrusted runtime input even when a compile-time type exists.
- Keep imports, exports, aliases, and generated-code boundaries consistent with the repository.
- Do not introduce a JavaScript-to-TypeScript conversion outside the approved scope.
- Run the repository's focused type-check, lint, test, and build commands as applicable.

255
src/cli.ts Normal file
View File

@@ -0,0 +1,255 @@
import path from "node:path";
import {
composeProject,
HarnessError,
listProjects,
planProject,
registerProject,
selectProjectIdsByContract,
verifyProject,
type ProjectPlan,
} from "./harness.js";
interface CliOptions {
command?: string;
project?: string;
contract?: string;
projectPath?: string;
all: boolean;
help: boolean;
}
function usage(): string {
return `KRI Agent Harness
Usage:
agent-harness list
agent-harness plan --project <id>
agent-harness plan --contract <contract-id>
agent-harness plan --all
agent-harness verify --project <id>
agent-harness verify --contract <contract-id>
agent-harness verify --all
agent-harness compose --project <id>
agent-harness compose --contract <contract-id>
agent-harness compose --all
agent-harness register --project <id> --path <workspace-relative-path>
Commands:
list List registered projects without modifying files.
plan Resolve and validate inputs, then report proposed output state.
verify Compare generated output byte for byte without modifying files.
compose Write managed AGENTS.md and CLAUDE.md files.
register Add a project to workspace.local.yml.
`;
}
function requireValue(args: string[], index: number, option: string): string {
const value = args[index + 1];
if (!value || value.startsWith("--")) {
throw new HarnessError(`Missing value for ${option}.`);
}
return value;
}
function parseArgs(args: string[]): CliOptions {
if (args[0] === "--help" || args[0] === "-h") {
return { command: undefined, all: false, help: true };
}
const options: CliOptions = {
command: args[0],
all: false,
help: false,
};
for (let index = 1; index < args.length; index += 1) {
const argument = args[index];
switch (argument) {
case "--project":
options.project = requireValue(args, index, argument);
index += 1;
break;
case "--contract":
options.contract = requireValue(args, index, argument);
index += 1;
break;
case "--path":
options.projectPath = requireValue(args, index, argument);
index += 1;
break;
case "--all":
options.all = true;
break;
case "--help":
case "-h":
options.help = true;
break;
default:
throw new HarnessError(`Unknown argument: ${argument}`);
}
}
return options;
}
function displayPath(filePath: string, roots: string[]): string {
for (const root of roots) {
const relativePath = path.relative(root, filePath);
if (relativePath && !relativePath.startsWith("..") && !path.isAbsolute(relativePath)) {
return relativePath.replace(/\\/g, "/");
}
}
return filePath;
}
function printPlan(plan: ProjectPlan, harnessRoot: string): void {
console.log(`[${plan.projectId}]`);
console.log(`repository: ${plan.repositoryPath}`);
console.log(`AGENTS.md: ${plan.output.agents}`);
console.log(`CLAUDE.md: ${plan.output.claude}`);
console.log(`size: ${plan.agentsBytes} bytes`);
console.log("fragments:");
for (const fragment of plan.fragments) {
console.log(
` - ${fragment.kind}:${fragment.id} (${fragment.bytes} bytes) ${displayPath(fragment.path, [plan.repositoryPath, harnessRoot])}`,
);
}
for (const warning of plan.warnings) {
console.log(`warning: ${warning}`);
}
}
async function targetProjectIds(
harnessRoot: string,
options: CliOptions,
): Promise<string[]> {
const selectorCount = [Boolean(options.project), Boolean(options.contract), options.all]
.filter(Boolean)
.length;
if (selectorCount > 1) {
throw new HarnessError("Use exactly one of --project, --contract, or --all.");
}
if (options.project) {
return [options.project];
}
if (options.contract) {
return selectProjectIdsByContract(harnessRoot, options.contract);
}
if (options.all) {
return (await listProjects(harnessRoot)).map((project) => project.id);
}
throw new HarnessError("Specify --project <id>, --contract <contract-id>, or --all.");
}
async function run(): Promise<void> {
const options = parseArgs(process.argv.slice(2));
if (options.help || !options.command) {
console.log(usage());
return;
}
const harnessRoot = process.env.KRI_AGENT_HARNESS_ROOT
? path.resolve(process.env.KRI_AGENT_HARNESS_ROOT)
: path.resolve(__dirname, "..");
switch (options.command) {
case "list": {
if (options.project || options.contract || options.all || options.projectPath) {
throw new HarnessError("list does not accept --project, --contract, --all, or --path.");
}
const projects = await listProjects(harnessRoot);
for (const project of projects) {
console.log(
`${project.id}\t${project.source}\t${project.exists ? "present" : "missing"}\t${project.path}`,
);
}
return;
}
case "plan": {
if (options.projectPath) {
throw new HarnessError("plan does not accept --path.");
}
for (const projectId of await targetProjectIds(harnessRoot, options)) {
printPlan(await planProject(harnessRoot, projectId), harnessRoot);
}
return;
}
case "verify": {
if (options.projectPath) {
throw new HarnessError("verify does not accept --path.");
}
let failed = false;
for (const projectId of await targetProjectIds(harnessRoot, options)) {
const plan = await verifyProject(harnessRoot, projectId);
printPlan(plan, harnessRoot);
if (plan.output.agents !== "current" || plan.output.claude !== "current") {
failed = true;
}
}
if (failed) {
process.exitCode = 1;
}
return;
}
case "compose": {
if (options.projectPath) {
throw new HarnessError("compose does not accept --path.");
}
const projectIds = await targetProjectIds(harnessRoot, options);
if (projectIds.length > 1) {
for (const projectId of projectIds) {
const preflight = await planProject(harnessRoot, projectId);
if (preflight.output.agents === "unmanaged") {
throw new HarnessError(`Refusing to overwrite unmanaged AGENTS.md in ${preflight.repositoryPath}`);
}
if (preflight.output.claude === "unmanaged") {
throw new HarnessError(`Refusing to overwrite unmanaged CLAUDE.md in ${preflight.repositoryPath}`);
}
}
}
for (const projectId of projectIds) {
const result = await composeProject(harnessRoot, projectId);
printPlan(result, harnessRoot);
console.log(
result.changed.length > 0
? `updated: ${result.changed.join(", ")}`
: "updated: none",
);
}
return;
}
case "register": {
if (options.contract || options.all) {
throw new HarnessError("register does not accept --contract or --all.");
}
if (!options.project || !options.projectPath) {
throw new HarnessError("register requires --project <id> and --path <relative-path>.");
}
const result = await registerProject(harnessRoot, options.project, options.projectPath);
console.log(
result.changed
? `registered: ${options.project} -> ${result.path}`
: `registered: unchanged (${options.project} -> ${result.path})`,
);
return;
}
default:
throw new HarnessError(`Unknown command: ${options.command}`);
}
}
run().catch((error: unknown) => {
if (error instanceof HarnessError) {
console.error(`ERROR: ${error.message}`);
} else if (error instanceof Error) {
console.error(`ERROR: ${error.stack ?? error.message}`);
} else {
console.error(`ERROR: ${String(error)}`);
}
process.exitCode = 1;
});

945
src/harness.ts Normal file
View File

@@ -0,0 +1,945 @@
import {
Ajv2020,
type AnySchema,
type ErrorObject,
type ValidateFunction,
} from "ajv/dist/2020.js";
import {
access,
mkdir,
readFile,
realpath,
rename,
rm,
stat,
writeFile,
} from "node:fs/promises";
import { constants as fsConstants } from "node:fs";
import { randomUUID } from "node:crypto";
import path from "node:path";
import { TextDecoder } from "node:util";
import { parseDocument, stringify as stringifyYaml } from "yaml";
const GENERATED_MARKER = "GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.";
const CLAUDE_CONTENT = "@AGENTS.md\n";
const WARNING_BYTES = 26_624;
const MAX_BYTES = 30_720;
const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
export class HarnessError extends Error {
constructor(message: string) {
super(message);
this.name = "HarnessError";
}
}
export type ProjectType =
| "library"
| "scaffold-cli"
| "shared-service"
| "internal-service"
| "requested-project";
export type ProjectLayer = "frontend" | "backend" | "fullstack" | "standalone";
export interface ProjectProfile {
schema_version: 1;
project: {
id: string;
name: string;
type: ProjectType;
layer: ProjectLayer;
legacy: boolean;
};
stack: string[];
shared_contracts?: {
provides?: string[];
consumes?: string[];
};
databases?: Array<{
id: string;
engine: string;
role: string;
access?: "read-only" | "read-write";
}>;
migration?: {
status: "planned" | "active" | "paused";
target_stack: string[];
strategy: "staged";
};
}
interface WorkspaceDocument {
schema_version: 1;
workspace_root?: string;
projects: Record<string, { path: string }>;
}
export interface WorkspaceProject {
id: string;
path: string;
source: "shared" | "local";
}
interface ContractDefinition {
id: string;
provider_project_id: string;
consumer_file: string;
order: number;
required_layers: ProjectLayer[];
}
interface ContractCatalog {
schema_version: 1;
contracts: ContractDefinition[];
}
interface Validators {
profile: ValidateFunction;
workspace: ValidateFunction;
}
export interface HarnessContext {
harnessRoot: string;
workspaceRoot: string;
projects: Map<string, WorkspaceProject>;
contracts: ContractDefinition[];
validators: Validators;
}
export interface CompositionFragment {
kind: string;
id: string;
path: string;
bytes: number;
content: string;
}
export type OutputState = "missing" | "current" | "stale" | "unmanaged";
export interface OutputInspection {
agents: OutputState;
claude: OutputState;
}
export interface ProjectPlan {
projectId: string;
repositoryPath: string;
profile: ProjectProfile;
fragments: CompositionFragment[];
agentsContent: string;
claudeContent: string;
agentsBytes: number;
warnings: string[];
output: OutputInspection;
}
export interface ComposeResult extends ProjectPlan {
changed: string[];
}
function fail(message: string): never {
throw new HarnessError(message);
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
async function pathExists(filePath: string): Promise<boolean> {
try {
await access(filePath, fsConstants.F_OK);
return true;
} catch {
return false;
}
}
async function isDirectory(directoryPath: string): Promise<boolean> {
try {
return (await stat(directoryPath)).isDirectory();
} catch {
return false;
}
}
function normalizeNewlines(value: string): string {
return value.replace(/\r\n?/g, "\n");
}
function normalizeFragment(value: string): string {
return normalizeNewlines(value).trim();
}
async function readStrictUtf8(filePath: string, label = filePath): Promise<string> {
let bytes: Buffer;
try {
bytes = await readFile(filePath);
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
return fail(`Cannot read ${label}: ${detail}`);
}
if (bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) {
return fail(`${label} must be UTF-8 without BOM.`);
}
try {
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
} catch {
return fail(`${label} is not valid UTF-8.`);
}
}
async function readRequiredFragment(
filePath: string,
kind: string,
id: string,
): Promise<CompositionFragment> {
const content = normalizeFragment(await readStrictUtf8(filePath));
if (content.length === 0) {
return fail(`Required instruction fragment is empty: ${filePath}`);
}
return {
kind,
id,
path: filePath,
bytes: Buffer.byteLength(content, "utf8"),
content,
};
}
function parseYaml(text: string, label: string): unknown {
const document = parseDocument(text, {
prettyErrors: true,
uniqueKeys: true,
});
if (document.errors.length > 0) {
return fail(`${label} is invalid YAML:\n${document.errors.map((error) => `- ${error.message}`).join("\n")}`);
}
return document.toJS();
}
async function readYaml(filePath: string): Promise<unknown> {
return parseYaml(await readStrictUtf8(filePath), filePath);
}
async function readJson(filePath: string): Promise<unknown> {
const text = await readStrictUtf8(filePath);
try {
return JSON.parse(text) as unknown;
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
return fail(`${filePath} is invalid JSON: ${detail}`);
}
}
function formatValidationErrors(errors: ErrorObject[] | null | undefined): string {
if (!errors || errors.length === 0) {
return "unknown schema violation";
}
return errors
.map((error) => `${error.instancePath || "/"} ${error.message ?? "is invalid"}`)
.join("; ");
}
async function loadValidators(harnessRoot: string): Promise<Validators> {
const profileSchemaPath = path.join(harnessRoot, "schemas", "profile.schema.json");
const workspaceSchemaPath = path.join(harnessRoot, "schemas", "workspace.schema.json");
const profileSchema = await readJson(profileSchemaPath) as AnySchema;
const workspaceSchema = await readJson(workspaceSchemaPath) as AnySchema;
const ajv = new Ajv2020({ allErrors: true, strict: true });
ajv.addSchema(profileSchema);
return {
profile: ajv.getSchema("https://kri.local/agent-harness/profile.schema.json")
?? ajv.compile(profileSchema),
workspace: ajv.compile(workspaceSchema),
};
}
function validateDocument(
validator: ValidateFunction,
value: unknown,
label: string,
): void {
if (!validator(value)) {
fail(`${label} failed schema validation: ${formatValidationErrors(validator.errors)}`);
}
}
function assertExactKeys(
value: Record<string, unknown>,
allowed: readonly string[],
label: string,
): void {
const unknown = Object.keys(value).filter((key) => !allowed.includes(key));
if (unknown.length > 0) {
fail(`${label} has unknown fields: ${unknown.join(", ")}`);
}
}
function parseContractCatalog(value: unknown, label: string): ContractCatalog {
if (!isPlainObject(value)) {
return fail(`${label} must be a mapping.`);
}
assertExactKeys(value, ["schema_version", "contracts"], label);
if (value.schema_version !== 1 || !Array.isArray(value.contracts)) {
return fail(`${label} must declare schema_version: 1 and a contracts list.`);
}
const ids = new Set<string>();
const orders = new Set<number>();
const contracts = value.contracts.map((item, index): ContractDefinition => {
const itemLabel = `${label} contracts[${index}]`;
if (!isPlainObject(item)) {
return fail(`${itemLabel} must be a mapping.`);
}
assertExactKeys(
item,
["id", "provider_project_id", "consumer_file", "order", "required_layers"],
itemLabel,
);
const { id, provider_project_id: providerProjectId, consumer_file: consumerFile, order } = item;
const requiredLayers = item.required_layers;
if (
typeof id !== "string"
|| !SLUG_PATTERN.test(id)
|| typeof providerProjectId !== "string"
|| !SLUG_PATTERN.test(providerProjectId)
|| typeof consumerFile !== "string"
|| consumerFile.length === 0
|| path.isAbsolute(consumerFile)
|| typeof order !== "number"
|| !Number.isInteger(order)
|| !Array.isArray(requiredLayers)
|| requiredLayers.some(
(layer) => !["frontend", "backend", "fullstack", "standalone"].includes(String(layer)),
)
) {
return fail(`${itemLabel} has an invalid field value.`);
}
if (ids.has(id) || orders.has(order)) {
return fail(`${itemLabel} duplicates a contract id or order.`);
}
ids.add(id);
orders.add(order);
return {
id,
provider_project_id: providerProjectId,
consumer_file: consumerFile,
order,
required_layers: requiredLayers as ProjectLayer[],
};
});
return { schema_version: 1, contracts: contracts.sort((left, right) => left.order - right.order) };
}
function assertContained(rootPath: string, candidatePath: string, label: string): void {
const relativePath = path.relative(rootPath, candidatePath);
if (
relativePath === ".."
|| relativePath.startsWith(`..${path.sep}`)
|| path.isAbsolute(relativePath)
) {
fail(`${label} escapes the allowed root: ${candidatePath}`);
}
}
function comparablePath(value: string): string {
const normalized = path.normalize(path.resolve(value));
return process.platform === "win32" ? normalized.toLowerCase() : normalized;
}
async function loadWorkspaceDocument(
filePath: string,
validators: Validators,
): Promise<WorkspaceDocument> {
const value = await readYaml(filePath);
validateDocument(validators.workspace, value, filePath);
return value as WorkspaceDocument;
}
export async function loadHarnessContext(harnessRootInput: string): Promise<HarnessContext> {
const harnessRoot = path.resolve(harnessRootInput);
const validators = await loadValidators(harnessRoot);
const sharedPath = path.join(harnessRoot, "workspace.yml");
const localPath = path.join(harnessRoot, "workspace.local.yml");
const shared = await loadWorkspaceDocument(sharedPath, validators);
if (!shared.workspace_root) {
return fail(`${sharedPath} must declare workspace_root.`);
}
if (path.isAbsolute(shared.workspace_root)) {
return fail(`${sharedPath} workspace_root must be relative to the harness directory.`);
}
const workspaceRootCandidate = path.resolve(harnessRoot, shared.workspace_root);
if (!(await isDirectory(workspaceRootCandidate))) {
return fail(`Workspace root does not exist: ${workspaceRootCandidate}`);
}
const workspaceRoot = await realpath(workspaceRootCandidate);
const resolvedHarnessRoot = await realpath(harnessRoot);
if (comparablePath(path.dirname(resolvedHarnessRoot)) !== comparablePath(workspaceRoot)) {
return fail(`${sharedPath} workspace_root must resolve to the harness parent directory.`);
}
const projects = new Map<string, WorkspaceProject>();
for (const [id, entry] of Object.entries(shared.projects)) {
projects.set(id, { id, path: entry.path, source: "shared" });
}
if (await pathExists(localPath)) {
const local = await loadWorkspaceDocument(localPath, validators);
if (local.workspace_root !== undefined) {
return fail(`${localPath} must not override workspace_root.`);
}
for (const [id, entry] of Object.entries(local.projects)) {
if (projects.has(id)) {
return fail(`Project id is registered in both workspace files: ${id}`);
}
projects.set(id, { id, path: entry.path, source: "local" });
}
}
for (const project of projects.values()) {
if (path.isAbsolute(project.path)) {
return fail(`Project path must be relative: ${project.id} -> ${project.path}`);
}
const projectCandidate = path.resolve(workspaceRoot, project.path);
if (comparablePath(projectCandidate) === comparablePath(workspaceRoot)) {
return fail(`Project path cannot be the workspace root: ${project.id}`);
}
assertContained(workspaceRoot, projectCandidate, `Project ${project.id}`);
}
const catalogPath = path.join(harnessRoot, "catalog", "contracts.yml");
const contracts = parseContractCatalog(await readYaml(catalogPath), catalogPath).contracts;
return {
harnessRoot,
workspaceRoot,
projects,
contracts,
validators,
};
}
async function resolveRegisteredProject(
context: HarnessContext,
projectId: string,
): Promise<string> {
const project = context.projects.get(projectId);
if (!project) {
return fail(`Project is not registered: ${projectId}`);
}
const candidate = path.resolve(context.workspaceRoot, project.path);
assertContained(context.workspaceRoot, candidate, `Project ${projectId}`);
if (!(await isDirectory(candidate))) {
return fail(`Registered project directory does not exist: ${candidate}`);
}
const resolved = await realpath(candidate);
assertContained(context.workspaceRoot, resolved, `Project ${projectId}`);
return resolved;
}
async function loadProfile(
context: HarnessContext,
repositoryPath: string,
expectedProjectId: string,
): Promise<ProjectProfile> {
const profilePath = path.join(repositoryPath, ".agent", "profile.yml");
const value = await readYaml(profilePath);
validateDocument(context.validators.profile, value, profilePath);
const profile = value as ProjectProfile;
if (profile.project.id !== expectedProjectId) {
return fail(
`Profile project id does not match workspace registration: ${profile.project.id} != ${expectedProjectId}`,
);
}
validateProfileSemantics(context, profile);
return profile;
}
function validateProfileSemantics(context: HarnessContext, profile: ProjectProfile): void {
if (profile.stack.includes("nextjs") && !profile.stack.includes("react")) {
fail("A nextjs stack must also declare react.");
}
if (
profile.migration?.target_stack.includes("nextjs")
&& !profile.migration.target_stack.includes("react")
) {
fail("A migration target containing nextjs must also contain react.");
}
const databaseIds = new Set<string>();
for (const database of profile.databases ?? []) {
if (databaseIds.has(database.id)) {
fail(`Duplicate database id: ${database.id}`);
}
databaseIds.add(database.id);
}
const provides = profile.shared_contracts?.provides ?? [];
const consumes = profile.shared_contracts?.consumes ?? [];
const overlap = provides.filter((id) => consumes.includes(id));
if (overlap.length > 0) {
fail(`Shared contracts cannot be both provided and consumed: ${overlap.join(", ")}`);
}
const catalogById = new Map(context.contracts.map((contract) => [contract.id, contract]));
for (const id of [...provides, ...consumes]) {
if (!catalogById.has(id)) {
fail(`Unknown shared contract: ${id}`);
}
}
for (const id of provides) {
const contract = catalogById.get(id)!;
if (contract.provider_project_id !== profile.project.id) {
fail(`Project ${profile.project.id} is not the catalog provider for contract ${id}.`);
}
}
if (!profile.project.legacy && provides.length === 0) {
const missing = context.contracts
.filter((contract) => contract.required_layers.includes(profile.project.layer))
.filter((contract) => !consumes.includes(contract.id))
.map((contract) => contract.id);
if (missing.length > 0) {
fail(`Missing required shared contracts for ${profile.project.layer}: ${missing.join(", ")}`);
}
}
}
function contractById(context: HarnessContext, id: string): ContractDefinition {
const contract = context.contracts.find((candidate) => candidate.id === id);
if (!contract) {
return fail(`Unknown shared contract: ${id}`);
}
return contract;
}
function compareProjectIds(left: string, right: string): number {
return left < right ? -1 : left > right ? 1 : 0;
}
export async function selectProjectIdsByContract(
harnessRoot: string,
contractId: string,
): Promise<string[]> {
const context = await loadHarnessContext(harnessRoot);
const contract = contractById(context, contractId);
if (!context.projects.has(contract.provider_project_id)) {
return fail(
`Contract provider project is not registered: ${contract.id} -> ${contract.provider_project_id}`,
);
}
const providerRoot = await resolveRegisteredProject(context, contract.provider_project_id);
const providerProfile = await loadProfile(context, providerRoot, contract.provider_project_id);
if (!(providerProfile.shared_contracts?.provides ?? []).includes(contract.id)) {
return fail(
`Contract provider ${contract.provider_project_id} does not declare shared_contracts.provides: ${contract.id}`,
);
}
const consumerIds: string[] = [];
const candidateIds = [...context.projects.keys()]
.filter((projectId) => projectId !== contract.provider_project_id)
.sort(compareProjectIds);
for (const projectId of candidateIds) {
const repositoryPath = await resolveRegisteredProject(context, projectId);
const profile = await loadProfile(context, repositoryPath, projectId);
if ((profile.shared_contracts?.consumes ?? []).includes(contract.id)) {
consumerIds.push(projectId);
}
}
return [contract.provider_project_id, ...consumerIds];
}
async function resolveConsumerFragment(
context: HarnessContext,
contract: ContractDefinition,
kind: string,
): Promise<CompositionFragment> {
const providerRoot = await resolveRegisteredProject(context, contract.provider_project_id);
const consumerPath = path.resolve(providerRoot, contract.consumer_file);
assertContained(providerRoot, consumerPath, `Consumer file for ${contract.id}`);
return readRequiredFragment(consumerPath, kind, contract.id);
}
function generatedHeader(profile: ProjectProfile): string {
return [
"<!--",
GENERATED_MARKER,
`Project: ${profile.project.id}`,
`Schema version: ${profile.schema_version}`,
"Edit the source fragments or repository .agent files, then recompose.",
"-->",
].join("\n");
}
async function inspectAgentsOutput(filePath: string, expected: string): Promise<OutputState> {
if (!(await pathExists(filePath))) {
return "missing";
}
let current: string;
try {
current = await readStrictUtf8(filePath);
} catch {
return "unmanaged";
}
if (current === expected) {
return "current";
}
return current.slice(0, 512).includes(GENERATED_MARKER) ? "stale" : "unmanaged";
}
async function inspectClaudeOutput(filePath: string): Promise<OutputState> {
if (!(await pathExists(filePath))) {
return "missing";
}
let current: string;
try {
current = await readStrictUtf8(filePath);
} catch {
return "unmanaged";
}
if (current === CLAUDE_CONTENT) {
return "current";
}
const normalized = `${normalizeNewlines(current).trimEnd()}\n`;
return normalized === CLAUDE_CONTENT ? "stale" : "unmanaged";
}
export async function planProject(
harnessRoot: string,
projectId: string,
): Promise<ProjectPlan> {
const context = await loadHarnessContext(harnessRoot);
const repositoryPath = await resolveRegisteredProject(context, projectId);
const profile = await loadProfile(context, repositoryPath, projectId);
const fragments: CompositionFragment[] = [];
fragments.push(
await readRequiredFragment(path.join(context.harnessRoot, "sources", "base.md"), "base", "base"),
);
fragments.push(
await readRequiredFragment(
path.join(context.harnessRoot, "sources", "project-types", `${profile.project.type}.md`),
"project-type",
profile.project.type,
),
);
for (const stackId of profile.stack) {
fragments.push(
await readRequiredFragment(
path.join(context.harnessRoot, "sources", "stacks", `${stackId}.md`),
"stack",
stackId,
),
);
}
const seenEngines = new Set<string>();
for (const database of profile.databases ?? []) {
if (seenEngines.has(database.engine)) {
continue;
}
seenEngines.add(database.engine);
fragments.push(
await readRequiredFragment(
path.join(context.harnessRoot, "sources", "stacks", `${database.engine}.md`),
"database",
database.engine,
),
);
}
if (profile.migration) {
fragments.push(
await readRequiredFragment(
path.join(context.harnessRoot, "sources", "policies", "planned-migration.md"),
"policy",
"planned-migration",
),
);
}
const consumes = (profile.shared_contracts?.consumes ?? [])
.map((id) => contractById(context, id))
.sort((left, right) => left.order - right.order);
for (const contract of consumes) {
if (contract.provider_project_id === projectId) {
fail(`Project cannot consume its own shared contract: ${contract.id}`);
}
fragments.push(await resolveConsumerFragment(context, contract, "shared-contract"));
}
const providedPaths = new Set<string>();
const provides = (profile.shared_contracts?.provides ?? [])
.map((id) => contractById(context, id))
.sort((left, right) => left.order - right.order);
for (const contract of provides) {
const consumerPath = path.resolve(repositoryPath, contract.consumer_file);
assertContained(repositoryPath, consumerPath, `Consumer file for ${contract.id}`);
const dedupeKey = process.platform === "win32" ? consumerPath.toLowerCase() : consumerPath;
if (providedPaths.has(dedupeKey)) {
continue;
}
providedPaths.add(dedupeKey);
fragments.push(await readRequiredFragment(consumerPath, "provided-contract", contract.id));
}
fragments.push(
await readRequiredFragment(
path.join(repositoryPath, ".agent", "project.md"),
"project",
projectId,
),
);
const agentsContent = `${[generatedHeader(profile), ...fragments.map((fragment) => fragment.content)].join("\n\n")}\n`;
const agentsBytes = Buffer.byteLength(agentsContent, "utf8");
if (agentsBytes > MAX_BYTES) {
fail(`Generated AGENTS.md is ${agentsBytes} bytes and exceeds the ${MAX_BYTES}-byte limit.`);
}
const warnings = agentsBytes > WARNING_BYTES
? [`Generated AGENTS.md is ${agentsBytes} bytes and exceeds the ${WARNING_BYTES}-byte warning threshold.`]
: [];
const agentsPath = path.join(repositoryPath, "AGENTS.md");
const claudePath = path.join(repositoryPath, "CLAUDE.md");
const output = {
agents: await inspectAgentsOutput(agentsPath, agentsContent),
claude: await inspectClaudeOutput(claudePath),
};
return {
projectId,
repositoryPath,
profile,
fragments,
agentsContent,
claudeContent: CLAUDE_CONTENT,
agentsBytes,
warnings,
output,
};
}
async function replaceFilesAtomically(files: Array<{ target: string; content: string }>): Promise<void> {
const token = `${process.pid}-${randomUUID()}`;
const operations = files.map((file) => ({
...file,
temp: `${file.target}.agent-harness-${token}.tmp`,
backup: `${file.target}.agent-harness-${token}.bak`,
hadOriginal: false,
installed: false,
}));
try {
for (const operation of operations) {
await mkdir(path.dirname(operation.target), { recursive: true });
await writeFile(operation.temp, operation.content, { encoding: "utf8", flag: "wx" });
}
for (const operation of operations) {
operation.hadOriginal = await pathExists(operation.target);
if (operation.hadOriginal) {
await rename(operation.target, operation.backup);
}
await rename(operation.temp, operation.target);
operation.installed = true;
}
} catch (error) {
for (const operation of [...operations].reverse()) {
try {
if (operation.installed && await pathExists(operation.target)) {
await rm(operation.target, { force: true });
}
if (await pathExists(operation.backup)) {
await rename(operation.backup, operation.target);
}
await rm(operation.temp, { force: true });
} catch {
// Preserve the original failure. Remaining temp or backup paths identify incomplete cleanup.
}
}
const detail = error instanceof Error ? error.message : String(error);
fail(`Failed to replace generated files atomically: ${detail}`);
}
for (const operation of operations) {
if (operation.hadOriginal) {
try {
await rm(operation.backup, { force: true });
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
fail(`Generated files were installed, but backup cleanup failed: ${operation.backup}: ${detail}`);
}
}
}
}
export async function composeProject(
harnessRoot: string,
projectId: string,
): Promise<ComposeResult> {
const plan = await planProject(harnessRoot, projectId);
if (plan.output.agents === "unmanaged") {
fail(`Refusing to overwrite unmanaged AGENTS.md in ${plan.repositoryPath}`);
}
if (plan.output.claude === "unmanaged") {
fail(`Refusing to overwrite unmanaged CLAUDE.md in ${plan.repositoryPath}`);
}
const writes: Array<{ target: string; content: string }> = [];
const changed: string[] = [];
if (plan.output.agents !== "current") {
writes.push({ target: path.join(plan.repositoryPath, "AGENTS.md"), content: plan.agentsContent });
changed.push("AGENTS.md");
}
if (plan.output.claude !== "current") {
writes.push({ target: path.join(plan.repositoryPath, "CLAUDE.md"), content: plan.claudeContent });
changed.push("CLAUDE.md");
}
if (writes.length > 0) {
await replaceFilesAtomically(writes);
}
const refreshed = await planProject(harnessRoot, projectId);
if (refreshed.output.agents !== "current" || refreshed.output.claude !== "current") {
fail(`Generated output verification failed for ${projectId}.`);
}
return { ...refreshed, changed };
}
export async function verifyProject(
harnessRoot: string,
projectId: string,
): Promise<ProjectPlan> {
return planProject(harnessRoot, projectId);
}
function normalizedRelativeProjectPath(value: string): string {
if (path.isAbsolute(value)) {
fail(`Registration path must be relative: ${value}`);
}
const normalized = value.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/$/, "");
if (!normalized || normalized === ".") {
fail("Registration path must identify a project directory.");
}
return normalized;
}
async function writeSingleFileAtomically(target: string, content: string): Promise<void> {
const token = `${process.pid}-${randomUUID()}`;
const temp = `${target}.agent-harness-${token}.tmp`;
const backup = `${target}.agent-harness-${token}.bak`;
const hadOriginal = await pathExists(target);
try {
await writeFile(temp, content, { encoding: "utf8", flag: "wx" });
if (hadOriginal) {
await rename(target, backup);
}
await rename(temp, target);
if (hadOriginal) {
await rm(backup, { force: true });
}
} catch (error) {
try {
await rm(temp, { force: true });
if (await pathExists(backup)) {
if (await pathExists(target)) {
await rm(target, { force: true });
}
await rename(backup, target);
}
} catch {
// Preserve the original failure.
}
const detail = error instanceof Error ? error.message : String(error);
fail(`Failed to update ${target}: ${detail}`);
}
}
export async function registerProject(
harnessRoot: string,
projectId: string,
projectPathInput: string,
): Promise<{ changed: boolean; path: string }> {
if (!SLUG_PATTERN.test(projectId)) {
fail(`Invalid project id: ${projectId}`);
}
const projectPath = normalizedRelativeProjectPath(projectPathInput);
const context = await loadHarnessContext(harnessRoot);
const candidate = path.resolve(context.workspaceRoot, projectPath);
assertContained(context.workspaceRoot, candidate, `Project ${projectId}`);
if (!(await isDirectory(candidate))) {
fail(`Project directory does not exist: ${candidate}`);
}
const resolvedCandidate = await realpath(candidate);
assertContained(context.workspaceRoot, resolvedCandidate, `Project ${projectId}`);
const existing = context.projects.get(projectId);
if (existing) {
const existingPath = path.resolve(context.workspaceRoot, existing.path);
if (comparablePath(existingPath) === comparablePath(candidate)) {
return { changed: false, path: projectPath };
}
fail(`Project id is already registered with another path: ${projectId}`);
}
const profilePath = path.join(resolvedCandidate, ".agent", "profile.yml");
const profileValue = await readYaml(profilePath);
validateDocument(context.validators.profile, profileValue, profilePath);
const profile = profileValue as ProjectProfile;
if (profile.project.id !== projectId) {
fail(`Profile project id does not match registration: ${profile.project.id} != ${projectId}`);
}
const localPath = path.join(context.harnessRoot, "workspace.local.yml");
let local: WorkspaceDocument = { schema_version: 1, projects: {} };
if (await pathExists(localPath)) {
local = await loadWorkspaceDocument(localPath, context.validators);
if (local.workspace_root !== undefined) {
fail(`${localPath} must not override workspace_root.`);
}
}
if (local.projects[projectId]) {
fail(`Project id already exists in ${localPath}: ${projectId}`);
}
local.projects[projectId] = { path: projectPath };
const sortedProjects = Object.fromEntries(
Object.entries(local.projects).sort(([left], [right]) => left.localeCompare(right)),
);
const serialized = normalizeNewlines(stringifyYaml({ schema_version: 1, projects: sortedProjects }));
await writeSingleFileAtomically(localPath, serialized.endsWith("\n") ? serialized : `${serialized}\n`);
return { changed: true, path: projectPath };
}
export async function listProjects(harnessRoot: string): Promise<Array<WorkspaceProject & { exists: boolean }>> {
const context = await loadHarnessContext(harnessRoot);
const projects = [...context.projects.values()].sort((left, right) => left.id.localeCompare(right.id));
return Promise.all(projects.map(async (project) => ({
...project,
exists: await isDirectory(path.resolve(context.workspaceRoot, project.path)),
})));
}
export function generatedMarker(): string {
return GENERATED_MARKER;
}

1
src/index.ts Normal file
View File

@@ -0,0 +1 @@
export * from "./harness.js";

354
tests/harness.test.mjs Normal file
View File

@@ -0,0 +1,354 @@
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import test from "node:test";
import { promisify } from "node:util";
const require = createRequire(import.meta.url);
const {
composeProject,
planProject,
registerProject,
selectProjectIdsByContract,
verifyProject,
} = require("../dist/index.cjs");
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const execFileAsync = promisify(execFile);
async function writeText(filePath, content) {
await mkdir(path.dirname(filePath), { recursive: true });
await writeFile(filePath, content, "utf8");
}
async function createFixture(t) {
const temporaryRoot = await mkdtemp(path.join(os.tmpdir(), "kri-agent-harness-"));
t.after(async () => {
await rm(temporaryRoot, { recursive: true, force: true });
});
const harnessRoot = path.join(temporaryRoot, "_________AgentHarnessBase");
const appRoot = path.join(temporaryRoot, "apps", "sample-front");
const anotherAppRoot = path.join(temporaryRoot, "apps", "another-front");
const unrelatedRoot = path.join(temporaryRoot, "tools", "unrelated-tool");
const providerRoot = path.join(temporaryRoot, "providers", "kri-ui-registry");
await mkdir(path.join(harnessRoot, "schemas"), { recursive: true });
await cp(
path.join(packageRoot, "schemas", "profile.schema.json"),
path.join(harnessRoot, "schemas", "profile.schema.json"),
);
await cp(
path.join(packageRoot, "schemas", "workspace.schema.json"),
path.join(harnessRoot, "schemas", "workspace.schema.json"),
);
await writeText(
path.join(harnessRoot, "workspace.yml"),
`schema_version: 1
workspace_root: ..
projects:
sample-front:
path: apps/sample-front
unrelated-tool:
path: tools/unrelated-tool
kri-ui-registry:
path: providers/kri-ui-registry
another-front:
path: apps/another-front
`,
);
await writeText(
path.join(harnessRoot, "catalog", "contracts.yml"),
`schema_version: 1
contracts:
- id: kri-ui-registry
provider_project_id: kri-ui-registry
consumer_file: .agent/consumer.md
order: 100
required_layers:
- frontend
- fullstack
`,
);
const fragments = {
"sources/base.md": "# Base Rule",
"sources/project-types/internal-service.md": "## Internal Service Rule",
"sources/project-types/library.md": "## Library Rule",
"sources/project-types/scaffold-cli.md": "## Scaffold CLI Rule",
"sources/stacks/typescript.md": "## TypeScript Rule",
"sources/stacks/react.md": "## React Rule",
"sources/stacks/nextjs.md": "## Next.js Rule",
"sources/stacks/mysql.md": "## MySQL Rule",
"sources/policies/planned-migration.md": "## Migration Rule",
};
for (const [relativePath, content] of Object.entries(fragments)) {
await writeText(path.join(harnessRoot, relativePath), `${content}\n`);
}
await writeText(
path.join(providerRoot, ".agent", "consumer.md"),
"## KRI UI Consumer Rule\n",
);
await writeText(
path.join(providerRoot, ".agent", "profile.yml"),
`schema_version: 1
project:
id: kri-ui-registry
name: KRI UI Registry
type: library
layer: frontend
legacy: false
stack:
- typescript
- react
shared_contracts:
provides:
- kri-ui-registry
`,
);
await writeText(path.join(providerRoot, ".agent", "project.md"), "## Registry Project Rule\n");
await writeText(
path.join(appRoot, ".agent", "profile.yml"),
`schema_version: 1
project:
id: sample-front
name: Sample Front
type: internal-service
layer: frontend
legacy: false
stack:
- typescript
- react
- nextjs
shared_contracts:
consumes:
- kri-ui-registry
databases:
- id: application
engine: mysql
role: primary
access: read-write
migration:
status: planned
target_stack:
- typescript
- react
- nextjs
strategy: staged
`,
);
await writeText(path.join(appRoot, ".agent", "project.md"), "## Project Rule\n");
await writeText(
path.join(anotherAppRoot, ".agent", "profile.yml"),
`schema_version: 1
project:
id: another-front
name: Another Front
type: internal-service
layer: frontend
legacy: false
stack:
- typescript
- react
- nextjs
shared_contracts:
consumes:
- kri-ui-registry
`,
);
await writeText(path.join(anotherAppRoot, ".agent", "project.md"), "## Another Project Rule\n");
await writeText(
path.join(unrelatedRoot, ".agent", "profile.yml"),
`schema_version: 1
project:
id: unrelated-tool
name: Unrelated Tool
type: scaffold-cli
layer: standalone
legacy: false
stack:
- typescript
`,
);
await writeText(path.join(unrelatedRoot, ".agent", "project.md"), "## Unrelated Rule\n");
return { temporaryRoot, harnessRoot, appRoot, anotherAppRoot, providerRoot, unrelatedRoot };
}
test("composes fragments in deterministic order and verifies byte-for-byte output", async (t) => {
const { harnessRoot, appRoot } = await createFixture(t);
const plan = await planProject(harnessRoot, "sample-front");
assert.deepEqual(
plan.fragments.map((fragment) => `${fragment.kind}:${fragment.id}`),
[
"base:base",
"project-type:internal-service",
"stack:typescript",
"stack:react",
"stack:nextjs",
"database:mysql",
"policy:planned-migration",
"shared-contract:kri-ui-registry",
"project:sample-front",
],
);
assert.equal(plan.output.agents, "missing");
assert.equal(plan.output.claude, "missing");
const result = await composeProject(harnessRoot, "sample-front");
assert.deepEqual(result.changed, ["AGENTS.md", "CLAUDE.md"]);
assert.equal(await readFile(path.join(appRoot, "AGENTS.md"), "utf8"), result.agentsContent);
assert.equal(await readFile(path.join(appRoot, "CLAUDE.md"), "utf8"), "@AGENTS.md\n");
const verified = await verifyProject(harnessRoot, "sample-front");
assert.deepEqual(verified.output, { agents: "current", claude: "current" });
assert.deepEqual((await composeProject(harnessRoot, "sample-front")).changed, []);
});
test("rejects nextjs without react", async (t) => {
const { harnessRoot, appRoot } = await createFixture(t);
const profilePath = path.join(appRoot, ".agent", "profile.yml");
const profile = await readFile(profilePath, "utf8");
await writeFile(profilePath, profile.replace(" - react\n", ""), "utf8");
await assert.rejects(
() => planProject(harnessRoot, "sample-front"),
/nextjs stack must also declare react/,
);
});
test("refuses to overwrite unmanaged AGENTS.md", async (t) => {
const { harnessRoot, appRoot } = await createFixture(t);
await writeText(path.join(appRoot, "AGENTS.md"), "# Hand-written instructions\n");
await assert.rejects(
() => composeProject(harnessRoot, "sample-front"),
/Refusing to overwrite unmanaged AGENTS\.md/,
);
assert.equal(
await readFile(path.join(appRoot, "AGENTS.md"), "utf8"),
"# Hand-written instructions\n",
);
assert.equal(await readFile(path.join(appRoot, "CLAUDE.md"), "utf8").catch(() => null), null);
});
test("registers a safe relative project path and rejects path escape", async (t) => {
const { temporaryRoot, harnessRoot } = await createFixture(t);
const newProjectRoot = path.join(temporaryRoot, "apps", "new-tool");
await writeText(
path.join(newProjectRoot, ".agent", "profile.yml"),
`schema_version: 1
project:
id: new-tool
name: New Tool
type: scaffold-cli
layer: standalone
legacy: false
stack:
- typescript
`,
);
const result = await registerProject(harnessRoot, "new-tool", "apps/new-tool");
assert.equal(result.changed, true);
const localWorkspace = await readFile(path.join(harnessRoot, "workspace.local.yml"), "utf8");
assert.match(localWorkspace, /new-tool:/);
assert.match(localWorkspace, /path: apps\/new-tool/);
await assert.rejects(
() => registerProject(harnessRoot, "outside", "../outside"),
/escapes the allowed root/,
);
});
test("fails instead of truncating output above the hard size limit", async (t) => {
const { harnessRoot, appRoot } = await createFixture(t);
await writeText(path.join(appRoot, ".agent", "project.md"), `## Project Rule\n\n${"x".repeat(31_000)}\n`);
await assert.rejects(
() => planProject(harnessRoot, "sample-front"),
/exceeds the 30720-byte limit/,
);
});
test("selects a contract provider first, sorts consumers, and composes only affected projects", async (t) => {
const {
harnessRoot,
appRoot,
anotherAppRoot,
providerRoot,
unrelatedRoot,
} = await createFixture(t);
assert.deepEqual(
await selectProjectIdsByContract(harnessRoot, "kri-ui-registry"),
["kri-ui-registry", "another-front", "sample-front"],
);
await assert.rejects(
() => selectProjectIdsByContract(harnessRoot, "unknown-contract"),
/Unknown shared contract: unknown-contract/,
);
const environment = {
...process.env,
KRI_AGENT_HARNESS_ROOT: harnessRoot,
};
const composed = await execFileAsync(
process.execPath,
[path.join(packageRoot, "dist", "cli.cjs"), "compose", "--contract", "kri-ui-registry"],
{ env: environment },
);
assert.equal(composed.stderr, "");
assert.ok(composed.stdout.indexOf("[kri-ui-registry]") < composed.stdout.indexOf("[another-front]"));
assert.ok(composed.stdout.indexOf("[another-front]") < composed.stdout.indexOf("[sample-front]"));
for (const affectedRoot of [providerRoot, anotherAppRoot, appRoot]) {
assert.match(await readFile(path.join(affectedRoot, "AGENTS.md"), "utf8"), /GENERATED BY KRI AGENT HARNESS/);
assert.equal(await readFile(path.join(affectedRoot, "CLAUDE.md"), "utf8"), "@AGENTS.md\n");
}
assert.equal(
await readFile(path.join(unrelatedRoot, "AGENTS.md"), "utf8").catch(() => null),
null,
);
const verified = await execFileAsync(
process.execPath,
[path.join(packageRoot, "dist", "cli.cjs"), "verify", "--contract", "kri-ui-registry"],
{ env: environment },
);
assert.equal(verified.stderr, "");
});
test("runs the bundled CLI against an isolated harness root", async (t) => {
const { harnessRoot } = await createFixture(t);
const { stdout, stderr } = await execFileAsync(
process.execPath,
[path.join(packageRoot, "dist", "cli.cjs"), "list"],
{
env: {
...process.env,
KRI_AGENT_HARNESS_ROOT: harnessRoot,
},
},
);
assert.equal(stderr, "");
assert.match(stdout, /sample-front\tshared\tpresent\tapps\/sample-front/);
assert.match(stdout, /kri-ui-registry\tshared\tpresent\tproviders\/kri-ui-registry/);
const help = await execFileAsync(
process.execPath,
[path.join(packageRoot, "dist", "cli.cjs"), "--help"],
);
assert.equal(help.stderr, "");
assert.match(help.stdout, /KRI Agent Harness/);
});

22
tsconfig.json Normal file
View File

@@ -0,0 +1,22 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": [
"ES2022"
],
"module": "NodeNext",
"moduleResolution": "NodeNext",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"noUncheckedIndexedAccess": true,
"types": [
"node"
]
},
"include": [
"src/**/*.ts"
]
}

View File

@@ -0,0 +1,5 @@
schema_version: 1
projects:
example-project:
path: ____Project/example-project

10
workspace.yml Normal file
View File

@@ -0,0 +1,10 @@
schema_version: 1
workspace_root: ..
projects:
kri-front-common:
path: __KRI-Common/KriFrontCommon
kri-ui-registry:
path: __KRI-Common/KriUiRegistry
kri-common:
path: __KRI-Common/KriCommon