261006_01_ENH: 에이전트 참조 문서 합성 및 검증 기능 추가
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -4,3 +4,4 @@
|
||||
/.local/
|
||||
*.tmp
|
||||
*.bak
|
||||
/.idea/
|
||||
|
||||
19
README.md
19
README.md
@@ -1,6 +1,6 @@
|
||||
# KRI Agent Harness
|
||||
|
||||
This repository composes deterministic, self-contained `AGENTS.md` and paired `CLAUDE.md` files for repositories under the KRI development workspace.
|
||||
This repository composes deterministic `AGENTS.md`, paired `CLAUDE.md`, managed workflow skills, and shared-contract reference copies for repositories under the KRI development workspace.
|
||||
|
||||
## Requirements
|
||||
|
||||
@@ -27,7 +27,7 @@ Run commands from this repository root:
|
||||
|
||||
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 `workspace.local.yml` by default; `register --shared` writes `workspace.yml`. No command performs Git, database, deployment, or network operations.
|
||||
`plan`, `verify`, and `list` are read-only. `compose` writes generated `AGENTS.md`, `CLAUDE.md`, managed skills under `.agents/skills` and `.claude/skills`, and shared references under `.agent-harness/references`. It refuses to overwrite an unmanaged file. `register` writes `workspace.local.yml` by default; `register --shared` writes `workspace.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.
|
||||
|
||||
@@ -43,11 +43,24 @@ Use `--contract <contract-id>` to select the registered provider first and then
|
||||
Each managed repository owns:
|
||||
|
||||
- `.agent/profile.yml`
|
||||
- `.agent/project.md`
|
||||
- `.agent/project.md` as the concise task-to-reference router
|
||||
- `.agent/references/*.md` for repository-specific detail
|
||||
- `.agent/consumer.md` when it provides a shared contract
|
||||
- `.agent/consumer-references/*.md` for detailed shared consumer contracts
|
||||
|
||||
Edit source inputs, run `plan`, obtain the required approval, then run `compose`. Use `verify` to detect stale generated output.
|
||||
|
||||
Every `project.md` must contain `## Required Project References`. Each Markdown file under `.agent/references` must be routed from that section using a repository-relative backticked path. Reference-only content changes do not require recomposition when routing is unchanged, but `verify` still validates existence, containment, strict UTF-8, and routing completeness.
|
||||
|
||||
## Managed Skills
|
||||
|
||||
The harness owns canonical skill sources under `skills/<skill-name>/SKILL.md` and composes identical managed copies for both supported agents:
|
||||
|
||||
- Codex: `.agents/skills/<skill-name>/SKILL.md`
|
||||
- Claude Code: `.claude/skills/<skill-name>/SKILL.md`
|
||||
|
||||
The managed set includes `project-reference-loader`, which reloads only the current references matching each substantive task.
|
||||
|
||||
## Development
|
||||
|
||||
On Windows PowerShell, use `npm.cmd` because the `npm.ps1` shim may be blocked by execution policy:
|
||||
|
||||
@@ -4,6 +4,7 @@ contracts:
|
||||
- id: kri-front-common
|
||||
provider_project_id: kri-front-common
|
||||
consumer_file: .agent/consumer.md
|
||||
consumer_references_dir: .agent/consumer-references
|
||||
order: 100
|
||||
required_layers:
|
||||
- frontend
|
||||
@@ -12,6 +13,7 @@ contracts:
|
||||
- id: kri-ui-registry
|
||||
provider_project_id: kri-ui-registry
|
||||
consumer_file: .agent/consumer.md
|
||||
consumer_references_dir: .agent/consumer-references
|
||||
order: 200
|
||||
required_layers:
|
||||
- frontend
|
||||
@@ -20,6 +22,7 @@ contracts:
|
||||
- id: kri-common
|
||||
provider_project_id: kri-common
|
||||
consumer_file: .agent/consumer.md
|
||||
consumer_references_dir: .agent/consumer-references
|
||||
order: 300
|
||||
required_layers:
|
||||
- backend
|
||||
|
||||
367
dist/cli.cjs
vendored
367
dist/cli.cjs
vendored
@@ -14513,6 +14513,16 @@ var CLAUDE_CONTENT = "@AGENTS.md\n";
|
||||
var WARNING_BYTES = 26624;
|
||||
var MAX_BYTES = 32e3;
|
||||
var SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
||||
var MANAGED_SKILL_NAMES = [
|
||||
"attention-aware-communication",
|
||||
"karpathy-guidelines",
|
||||
"project-reference-loader",
|
||||
"verification-before-completion"
|
||||
];
|
||||
var MANAGED_SKILL_ROOTS = [".agents/skills", ".claude/skills"];
|
||||
var MANAGED_REFERENCE_ROOT = ".agent-harness/references";
|
||||
var PROJECT_REFERENCE_ROOT = ".agent/references";
|
||||
var PROJECT_ROUTER_HEADING = "## Required Project References";
|
||||
var HarnessError = class extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
@@ -14576,6 +14586,86 @@ async function readRequiredFragment(filePath, kind, id) {
|
||||
content
|
||||
};
|
||||
}
|
||||
async function listMarkdownFiles(rootPath, label, required) {
|
||||
if (!await pathExists(rootPath)) {
|
||||
if (required) {
|
||||
return fail(`${label} does not exist: ${rootPath}`);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
if (!await isDirectory(rootPath)) {
|
||||
return fail(`${label} must be a directory: ${rootPath}`);
|
||||
}
|
||||
const files = [];
|
||||
const visit = async (directoryPath) => {
|
||||
const entries = await (0, import_promises.readdir)(directoryPath, { withFileTypes: true });
|
||||
for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
|
||||
const candidate = import_node_path.default.join(directoryPath, entry.name);
|
||||
assertContained(rootPath, candidate, label);
|
||||
if (entry.isSymbolicLink()) {
|
||||
return fail(`${label} must not contain symbolic links: ${candidate}`);
|
||||
}
|
||||
if (entry.isDirectory()) {
|
||||
await visit(candidate);
|
||||
} else if (entry.isFile() && entry.name.toLowerCase().endsWith(".md")) {
|
||||
files.push(candidate);
|
||||
}
|
||||
}
|
||||
};
|
||||
await visit(rootPath);
|
||||
return files.sort((left, right) => left.localeCompare(right));
|
||||
}
|
||||
function portableRelative(rootPath, filePath) {
|
||||
return import_node_path.default.relative(rootPath, filePath).replace(/\\/g, "/");
|
||||
}
|
||||
async function validateProjectReferences(repositoryPath, projectContent) {
|
||||
if (!normalizeNewlines(projectContent).includes(PROJECT_ROUTER_HEADING)) {
|
||||
return fail(`.agent/project.md must contain ${PROJECT_ROUTER_HEADING}: ${repositoryPath}`);
|
||||
}
|
||||
const referencesRoot = import_node_path.default.join(repositoryPath, ".agent", "references");
|
||||
const files = await listMarkdownFiles(referencesRoot, "Project references", false);
|
||||
const actual = new Map(
|
||||
files.map((filePath) => [
|
||||
`${PROJECT_REFERENCE_ROOT}/${portableRelative(referencesRoot, filePath)}`,
|
||||
filePath
|
||||
])
|
||||
);
|
||||
const declared = /* @__PURE__ */ new Set();
|
||||
const pattern = /`(\.agent\/references\/[^`\r\n]+\.md)`/g;
|
||||
for (const match of normalizeNewlines(projectContent).matchAll(pattern)) {
|
||||
const matchedPath = match[1];
|
||||
if (!matchedPath) {
|
||||
continue;
|
||||
}
|
||||
const relativePath = matchedPath.replace(/\\/g, "/");
|
||||
if (relativePath.includes("../") || relativePath.includes("/..")) {
|
||||
return fail(`Project reference path must not escape .agent/references: ${relativePath}`);
|
||||
}
|
||||
declared.add(relativePath);
|
||||
}
|
||||
for (const relativePath of declared) {
|
||||
if (!actual.has(relativePath)) {
|
||||
return fail(`Declared project reference does not exist: ${repositoryPath} -> ${relativePath}`);
|
||||
}
|
||||
}
|
||||
const unreferenced = [...actual.keys()].filter((relativePath) => !declared.has(relativePath));
|
||||
if (unreferenced.length > 0) {
|
||||
return fail(`Project reference is not routed from .agent/project.md: ${unreferenced.join(", ")}`);
|
||||
}
|
||||
const references = [];
|
||||
for (const [relativePath, filePath] of [...actual.entries()].sort(([left], [right]) => left.localeCompare(right))) {
|
||||
const content = await readStrictUtf8(filePath, relativePath);
|
||||
if (normalizeFragment(content).length === 0) {
|
||||
return fail(`Project reference is empty: ${filePath}`);
|
||||
}
|
||||
references.push({
|
||||
relativePath,
|
||||
path: filePath,
|
||||
bytes: Buffer.byteLength(content, "utf8")
|
||||
});
|
||||
}
|
||||
return references;
|
||||
}
|
||||
function parseYaml(text, label) {
|
||||
const document = (0, import_yaml.parseDocument)(text, {
|
||||
prettyErrors: true,
|
||||
@@ -14645,12 +14735,25 @@ function parseContractCatalog(value, label) {
|
||||
}
|
||||
assertExactKeys(
|
||||
item,
|
||||
["id", "provider_project_id", "consumer_file", "order", "required_layers"],
|
||||
[
|
||||
"id",
|
||||
"provider_project_id",
|
||||
"consumer_file",
|
||||
"consumer_references_dir",
|
||||
"order",
|
||||
"required_layers"
|
||||
],
|
||||
itemLabel
|
||||
);
|
||||
const { id, provider_project_id: providerProjectId, consumer_file: consumerFile, order } = item;
|
||||
const {
|
||||
id,
|
||||
provider_project_id: providerProjectId,
|
||||
consumer_file: consumerFile,
|
||||
consumer_references_dir: consumerReferencesDir,
|
||||
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 || import_node_path.default.isAbsolute(consumerFile) || typeof order !== "number" || !Number.isInteger(order) || !Array.isArray(requiredLayers) || requiredLayers.some(
|
||||
if (typeof id !== "string" || !SLUG_PATTERN.test(id) || typeof providerProjectId !== "string" || !SLUG_PATTERN.test(providerProjectId) || typeof consumerFile !== "string" || consumerFile.length === 0 || import_node_path.default.isAbsolute(consumerFile) || typeof consumerReferencesDir !== "string" || consumerReferencesDir.length === 0 || import_node_path.default.isAbsolute(consumerReferencesDir) || 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.`);
|
||||
@@ -14664,6 +14767,7 @@ function parseContractCatalog(value, label) {
|
||||
id,
|
||||
provider_project_id: providerProjectId,
|
||||
consumer_file: consumerFile,
|
||||
consumer_references_dir: consumerReferencesDir,
|
||||
order,
|
||||
required_layers: requiredLayers
|
||||
};
|
||||
@@ -14850,6 +14954,95 @@ async function resolveConsumerFragment(context, contract, kind) {
|
||||
assertContained(providerRoot, consumerPath, `Consumer file for ${contract.id}`);
|
||||
return readRequiredFragment(consumerPath, kind, contract.id);
|
||||
}
|
||||
async function contractReferenceSources(context, contract) {
|
||||
const providerRoot = await resolveRegisteredProject(context, contract.provider_project_id);
|
||||
const sourceRoot = import_node_path.default.resolve(providerRoot, contract.consumer_references_dir);
|
||||
assertContained(providerRoot, sourceRoot, `Consumer references for ${contract.id}`);
|
||||
const files = await listMarkdownFiles(
|
||||
sourceRoot,
|
||||
`Consumer references for ${contract.id}`,
|
||||
true
|
||||
);
|
||||
if (files.length === 0) {
|
||||
return fail(`Consumer references for ${contract.id} must contain at least one Markdown file.`);
|
||||
}
|
||||
return files.map((sourcePath) => {
|
||||
const relativeSourcePath = portableRelative(sourceRoot, sourcePath);
|
||||
return {
|
||||
sourcePath,
|
||||
relativeSourcePath,
|
||||
relativeTargetPath: `${MANAGED_REFERENCE_ROOT}/${contract.id}/${relativeSourcePath}`
|
||||
};
|
||||
});
|
||||
}
|
||||
async function validateConsumerReferenceRouting(context, contract, fragment) {
|
||||
const sources = await contractReferenceSources(context, contract);
|
||||
const expected = new Set(sources.map((source) => source.relativeTargetPath));
|
||||
const declared = /* @__PURE__ */ new Set();
|
||||
const contractPrefix = `${MANAGED_REFERENCE_ROOT}/${contract.id}/`;
|
||||
for (const match of fragment.content.matchAll(/`([^`\r\n]+\.md)`/g)) {
|
||||
const matchedPath = match[1];
|
||||
if (!matchedPath) {
|
||||
continue;
|
||||
}
|
||||
const relativePath = matchedPath.replace(/\\/g, "/");
|
||||
if (relativePath.startsWith(contractPrefix)) {
|
||||
declared.add(relativePath);
|
||||
}
|
||||
}
|
||||
const missing = [...expected].filter((relativePath) => !declared.has(relativePath));
|
||||
const unknown = [...declared].filter((relativePath) => !expected.has(relativePath));
|
||||
if (missing.length > 0 || unknown.length > 0) {
|
||||
return fail(
|
||||
`Consumer reference routing mismatch for ${contract.id}. Missing: ${missing.join(", ") || "none"}; unknown: ${unknown.join(", ") || "none"}.`
|
||||
);
|
||||
}
|
||||
return sources;
|
||||
}
|
||||
async function renderManagedReference(sourcePath, contract, relativeSourcePath) {
|
||||
const source = normalizeFragment(await readStrictUtf8(sourcePath));
|
||||
if (source.length === 0) {
|
||||
return fail(`Managed consumer reference is empty: ${sourcePath}`);
|
||||
}
|
||||
const marker = [
|
||||
"<!--",
|
||||
GENERATED_MARKER,
|
||||
`Contract: ${contract.id}`,
|
||||
`Source: ${contract.consumer_references_dir.replace(/\\/g, "/")}/${relativeSourcePath}`,
|
||||
"-->"
|
||||
].join("\n");
|
||||
return `${marker}
|
||||
|
||||
${source}
|
||||
`;
|
||||
}
|
||||
async function planManagedContractReferences(context, repositoryPath, contracts, fragmentsByContract) {
|
||||
const outputs = [];
|
||||
for (const contract of contracts) {
|
||||
const fragment = fragmentsByContract.get(contract.id);
|
||||
if (!fragment) {
|
||||
return fail(`Missing consumer fragment while planning references: ${contract.id}`);
|
||||
}
|
||||
const sources = await validateConsumerReferenceRouting(context, contract, fragment);
|
||||
for (const source of sources) {
|
||||
const targetPath = import_node_path.default.join(repositoryPath, ...source.relativeTargetPath.split("/"));
|
||||
const content = await renderManagedReference(
|
||||
source.sourcePath,
|
||||
contract,
|
||||
source.relativeSourcePath
|
||||
);
|
||||
outputs.push({
|
||||
contractId: contract.id,
|
||||
sourcePath: source.sourcePath,
|
||||
relativePath: source.relativeTargetPath,
|
||||
targetPath,
|
||||
content,
|
||||
state: await inspectManagedOutput(targetPath, content)
|
||||
});
|
||||
}
|
||||
}
|
||||
return outputs;
|
||||
}
|
||||
function generatedHeader(profile) {
|
||||
return [
|
||||
"<!--",
|
||||
@@ -14875,6 +15068,66 @@ async function inspectAgentsOutput(filePath, expected) {
|
||||
}
|
||||
return current.slice(0, 512).includes(GENERATED_MARKER) ? "stale" : "unmanaged";
|
||||
}
|
||||
async function inspectManagedOutput(filePath, expected) {
|
||||
if (!await pathExists(filePath)) {
|
||||
return "missing";
|
||||
}
|
||||
let current;
|
||||
try {
|
||||
current = await readStrictUtf8(filePath);
|
||||
} catch {
|
||||
return "unmanaged";
|
||||
}
|
||||
if (current === expected) {
|
||||
return "current";
|
||||
}
|
||||
return current.slice(0, 1024).includes(GENERATED_MARKER) ? "stale" : "unmanaged";
|
||||
}
|
||||
async function renderManagedSkill(sourcePath, name) {
|
||||
const source = normalizeNewlines(await readStrictUtf8(sourcePath));
|
||||
if (!source.startsWith("---\n")) {
|
||||
return fail(`Managed skill must start with YAML front matter: ${sourcePath}`);
|
||||
}
|
||||
const closingIndex = source.indexOf("\n---\n", 4);
|
||||
if (closingIndex < 0) {
|
||||
return fail(`Managed skill has no closing YAML front matter: ${sourcePath}`);
|
||||
}
|
||||
const frontMatter = parseYaml(source.slice(4, closingIndex), `${sourcePath} front matter`);
|
||||
if (!isPlainObject(frontMatter) || frontMatter.name !== name || typeof frontMatter.description !== "string" || frontMatter.description.trim().length === 0) {
|
||||
return fail(`Managed skill must declare matching name and non-empty description: ${sourcePath}`);
|
||||
}
|
||||
const frontMatterEnd = closingIndex + "\n---\n".length;
|
||||
const marker = [
|
||||
"<!--",
|
||||
GENERATED_MARKER,
|
||||
`Source: skills/${name}/SKILL.md`,
|
||||
"-->",
|
||||
""
|
||||
].join("\n");
|
||||
return `${source.slice(0, frontMatterEnd)}
|
||||
${marker}${source.slice(frontMatterEnd).trimStart().trimEnd()}
|
||||
`;
|
||||
}
|
||||
async function planManagedSkills(context, repositoryPath) {
|
||||
const outputs = [];
|
||||
for (const name of MANAGED_SKILL_NAMES) {
|
||||
const sourcePath = import_node_path.default.join(context.harnessRoot, "skills", name, "SKILL.md");
|
||||
const content = await renderManagedSkill(sourcePath, name);
|
||||
for (const root of MANAGED_SKILL_ROOTS) {
|
||||
const relativePath = `${root}/${name}/SKILL.md`;
|
||||
const targetPath = import_node_path.default.join(repositoryPath, ...relativePath.split("/"));
|
||||
outputs.push({
|
||||
name,
|
||||
sourcePath,
|
||||
relativePath,
|
||||
targetPath,
|
||||
content,
|
||||
state: await inspectManagedOutput(targetPath, content)
|
||||
});
|
||||
}
|
||||
}
|
||||
return outputs;
|
||||
}
|
||||
async function inspectClaudeOutput(filePath) {
|
||||
if (!await pathExists(filePath)) {
|
||||
return "missing";
|
||||
@@ -14940,11 +15193,14 @@ async function planProject(harnessRoot, projectId) {
|
||||
);
|
||||
}
|
||||
const consumes = (profile.shared_contracts?.consumes ?? []).map((id) => contractById(context, id)).sort((left, right) => left.order - right.order);
|
||||
const contractFragments = /* @__PURE__ */ new Map();
|
||||
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 fragment = await resolveConsumerFragment(context, contract, "shared-contract");
|
||||
contractFragments.set(contract.id, fragment);
|
||||
fragments.push(fragment);
|
||||
}
|
||||
const providedPaths = /* @__PURE__ */ new Set();
|
||||
const provides = (profile.shared_contracts?.provides ?? []).map((id) => contractById(context, id)).sort((left, right) => left.order - right.order);
|
||||
@@ -14956,28 +15212,54 @@ async function planProject(harnessRoot, projectId) {
|
||||
continue;
|
||||
}
|
||||
providedPaths.add(dedupeKey);
|
||||
fragments.push(await readRequiredFragment(consumerPath, "provided-contract", contract.id));
|
||||
const fragment = await readRequiredFragment(consumerPath, "provided-contract", contract.id);
|
||||
contractFragments.set(contract.id, fragment);
|
||||
fragments.push(fragment);
|
||||
}
|
||||
fragments.push(
|
||||
await readRequiredFragment(
|
||||
import_node_path.default.join(repositoryPath, ".agent", "project.md"),
|
||||
"project",
|
||||
projectId
|
||||
)
|
||||
const projectFragment = await readRequiredFragment(
|
||||
import_node_path.default.join(repositoryPath, ".agent", "project.md"),
|
||||
"project",
|
||||
projectId
|
||||
);
|
||||
const projectReferences = await validateProjectReferences(
|
||||
repositoryPath,
|
||||
projectFragment.content
|
||||
);
|
||||
fragments.push(projectFragment);
|
||||
const agentsContent = `${[generatedHeader(profile), ...fragments.map((fragment) => fragment.content)].join("\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 warnings = [];
|
||||
if (agentsBytes > WARNING_BYTES) {
|
||||
warnings.push(`Generated AGENTS.md is ${agentsBytes} bytes and exceeds the ${WARNING_BYTES}-byte warning threshold.`);
|
||||
}
|
||||
if (projectFragment.bytes > 4096) {
|
||||
warnings.push(`.agent/project.md is ${projectFragment.bytes} bytes; keep the routing file near 2,000-3,000 bytes and move conditional detail to .agent/references.`);
|
||||
}
|
||||
for (const reference of projectReferences) {
|
||||
if (reference.bytes > 16384) {
|
||||
warnings.push(`${reference.relativePath} is ${reference.bytes} bytes; consider splitting it by task scope.`);
|
||||
}
|
||||
}
|
||||
const agentsPath = import_node_path.default.join(repositoryPath, "AGENTS.md");
|
||||
const claudePath = import_node_path.default.join(repositoryPath, "CLAUDE.md");
|
||||
const output = {
|
||||
agents: await inspectAgentsOutput(agentsPath, agentsContent),
|
||||
claude: await inspectClaudeOutput(claudePath)
|
||||
};
|
||||
const skills = await planManagedSkills(context, repositoryPath);
|
||||
const activeContracts = [...new Map(
|
||||
[...consumes, ...provides].map((contract) => [contract.id, contract])
|
||||
).values()].sort((left, right) => left.order - right.order);
|
||||
const managedReferences = await planManagedContractReferences(
|
||||
context,
|
||||
repositoryPath,
|
||||
activeContracts,
|
||||
contractFragments
|
||||
);
|
||||
return {
|
||||
projectId,
|
||||
repositoryPath,
|
||||
@@ -14987,7 +15269,10 @@ async function planProject(harnessRoot, projectId) {
|
||||
claudeContent: CLAUDE_CONTENT,
|
||||
agentsBytes,
|
||||
warnings,
|
||||
output
|
||||
output,
|
||||
skills,
|
||||
managedReferences,
|
||||
projectReferences
|
||||
};
|
||||
}
|
||||
async function replaceFilesAtomically(files) {
|
||||
@@ -15047,6 +15332,20 @@ async function composeProject(harnessRoot, projectId) {
|
||||
if (plan.output.claude === "unmanaged") {
|
||||
fail(`Refusing to overwrite unmanaged CLAUDE.md in ${plan.repositoryPath}`);
|
||||
}
|
||||
const unmanagedSkill = plan.skills.find((skill) => skill.state === "unmanaged");
|
||||
if (unmanagedSkill) {
|
||||
fail(
|
||||
`Refusing to overwrite unmanaged skill ${unmanagedSkill.relativePath} in ${plan.repositoryPath}`
|
||||
);
|
||||
}
|
||||
const unmanagedReference = plan.managedReferences.find(
|
||||
(reference) => reference.state === "unmanaged"
|
||||
);
|
||||
if (unmanagedReference) {
|
||||
fail(
|
||||
`Refusing to overwrite unmanaged shared reference ${unmanagedReference.relativePath} in ${plan.repositoryPath}`
|
||||
);
|
||||
}
|
||||
const writes = [];
|
||||
const changed = [];
|
||||
if (plan.output.agents !== "current") {
|
||||
@@ -15057,11 +15356,23 @@ async function composeProject(harnessRoot, projectId) {
|
||||
writes.push({ target: import_node_path.default.join(plan.repositoryPath, "CLAUDE.md"), content: plan.claudeContent });
|
||||
changed.push("CLAUDE.md");
|
||||
}
|
||||
for (const skill of plan.skills) {
|
||||
if (skill.state !== "current") {
|
||||
writes.push({ target: skill.targetPath, content: skill.content });
|
||||
changed.push(skill.relativePath);
|
||||
}
|
||||
}
|
||||
for (const reference of plan.managedReferences) {
|
||||
if (reference.state !== "current") {
|
||||
writes.push({ target: reference.targetPath, content: reference.content });
|
||||
changed.push(reference.relativePath);
|
||||
}
|
||||
}
|
||||
if (writes.length > 0) {
|
||||
await replaceFilesAtomically(writes);
|
||||
}
|
||||
const refreshed = await planProject(harnessRoot, projectId);
|
||||
if (refreshed.output.agents !== "current" || refreshed.output.claude !== "current") {
|
||||
if (refreshed.output.agents !== "current" || refreshed.output.claude !== "current" || refreshed.skills.some((skill) => skill.state !== "current") || refreshed.managedReferences.some((reference) => reference.state !== "current")) {
|
||||
fail(`Generated output verification failed for ${projectId}.`);
|
||||
}
|
||||
return { ...refreshed, changed };
|
||||
@@ -15272,6 +15583,12 @@ function printPlan(plan, harnessRoot) {
|
||||
console.log(`repository: ${plan.repositoryPath}`);
|
||||
console.log(`AGENTS.md: ${plan.output.agents}`);
|
||||
console.log(`CLAUDE.md: ${plan.output.claude}`);
|
||||
for (const skill of plan.skills) {
|
||||
console.log(`${skill.relativePath}: ${skill.state}`);
|
||||
}
|
||||
for (const reference of plan.managedReferences) {
|
||||
console.log(`${reference.relativePath}: ${reference.state}`);
|
||||
}
|
||||
console.log(`size: ${plan.agentsBytes} bytes`);
|
||||
console.log("fragments:");
|
||||
for (const fragment of plan.fragments) {
|
||||
@@ -15279,6 +15596,12 @@ function printPlan(plan, harnessRoot) {
|
||||
` - ${fragment.kind}:${fragment.id} (${fragment.bytes} bytes) ${displayPath(fragment.path, [plan.repositoryPath, harnessRoot])}`
|
||||
);
|
||||
}
|
||||
if (plan.projectReferences.length > 0) {
|
||||
console.log("project references:");
|
||||
for (const reference of plan.projectReferences) {
|
||||
console.log(` - ${reference.relativePath} (${reference.bytes} bytes)`);
|
||||
}
|
||||
}
|
||||
for (const warning of plan.warnings) {
|
||||
console.log(`warning: ${warning}`);
|
||||
}
|
||||
@@ -15339,7 +15662,7 @@ async function run() {
|
||||
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") {
|
||||
if (plan.output.agents !== "current" || plan.output.claude !== "current" || plan.skills.some((skill) => skill.state !== "current") || plan.managedReferences.some((reference) => reference.state !== "current")) {
|
||||
failed = true;
|
||||
}
|
||||
}
|
||||
@@ -15362,6 +15685,20 @@ async function run() {
|
||||
if (preflight.output.claude === "unmanaged") {
|
||||
throw new HarnessError(`Refusing to overwrite unmanaged CLAUDE.md in ${preflight.repositoryPath}`);
|
||||
}
|
||||
const unmanagedSkill = preflight.skills.find((skill) => skill.state === "unmanaged");
|
||||
if (unmanagedSkill) {
|
||||
throw new HarnessError(
|
||||
`Refusing to overwrite unmanaged skill ${unmanagedSkill.relativePath} in ${preflight.repositoryPath}`
|
||||
);
|
||||
}
|
||||
const unmanagedReference = preflight.managedReferences.find(
|
||||
(reference) => reference.state === "unmanaged"
|
||||
);
|
||||
if (unmanagedReference) {
|
||||
throw new HarnessError(
|
||||
`Refusing to overwrite unmanaged shared reference ${unmanagedReference.relativePath} in ${preflight.repositoryPath}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const projectId of projectIds) {
|
||||
|
||||
339
dist/index.cjs
vendored
339
dist/index.cjs
vendored
@@ -14529,6 +14529,16 @@ var CLAUDE_CONTENT = "@AGENTS.md\n";
|
||||
var WARNING_BYTES = 26624;
|
||||
var MAX_BYTES = 32e3;
|
||||
var SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
||||
var MANAGED_SKILL_NAMES = [
|
||||
"attention-aware-communication",
|
||||
"karpathy-guidelines",
|
||||
"project-reference-loader",
|
||||
"verification-before-completion"
|
||||
];
|
||||
var MANAGED_SKILL_ROOTS = [".agents/skills", ".claude/skills"];
|
||||
var MANAGED_REFERENCE_ROOT = ".agent-harness/references";
|
||||
var PROJECT_REFERENCE_ROOT = ".agent/references";
|
||||
var PROJECT_ROUTER_HEADING = "## Required Project References";
|
||||
var HarnessError = class extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
@@ -14592,6 +14602,86 @@ async function readRequiredFragment(filePath, kind, id) {
|
||||
content
|
||||
};
|
||||
}
|
||||
async function listMarkdownFiles(rootPath, label, required) {
|
||||
if (!await pathExists(rootPath)) {
|
||||
if (required) {
|
||||
return fail(`${label} does not exist: ${rootPath}`);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
if (!await isDirectory(rootPath)) {
|
||||
return fail(`${label} must be a directory: ${rootPath}`);
|
||||
}
|
||||
const files = [];
|
||||
const visit = async (directoryPath) => {
|
||||
const entries = await (0, import_promises.readdir)(directoryPath, { withFileTypes: true });
|
||||
for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
|
||||
const candidate = import_node_path.default.join(directoryPath, entry.name);
|
||||
assertContained(rootPath, candidate, label);
|
||||
if (entry.isSymbolicLink()) {
|
||||
return fail(`${label} must not contain symbolic links: ${candidate}`);
|
||||
}
|
||||
if (entry.isDirectory()) {
|
||||
await visit(candidate);
|
||||
} else if (entry.isFile() && entry.name.toLowerCase().endsWith(".md")) {
|
||||
files.push(candidate);
|
||||
}
|
||||
}
|
||||
};
|
||||
await visit(rootPath);
|
||||
return files.sort((left, right) => left.localeCompare(right));
|
||||
}
|
||||
function portableRelative(rootPath, filePath) {
|
||||
return import_node_path.default.relative(rootPath, filePath).replace(/\\/g, "/");
|
||||
}
|
||||
async function validateProjectReferences(repositoryPath, projectContent) {
|
||||
if (!normalizeNewlines(projectContent).includes(PROJECT_ROUTER_HEADING)) {
|
||||
return fail(`.agent/project.md must contain ${PROJECT_ROUTER_HEADING}: ${repositoryPath}`);
|
||||
}
|
||||
const referencesRoot = import_node_path.default.join(repositoryPath, ".agent", "references");
|
||||
const files = await listMarkdownFiles(referencesRoot, "Project references", false);
|
||||
const actual = new Map(
|
||||
files.map((filePath) => [
|
||||
`${PROJECT_REFERENCE_ROOT}/${portableRelative(referencesRoot, filePath)}`,
|
||||
filePath
|
||||
])
|
||||
);
|
||||
const declared = /* @__PURE__ */ new Set();
|
||||
const pattern = /`(\.agent\/references\/[^`\r\n]+\.md)`/g;
|
||||
for (const match of normalizeNewlines(projectContent).matchAll(pattern)) {
|
||||
const matchedPath = match[1];
|
||||
if (!matchedPath) {
|
||||
continue;
|
||||
}
|
||||
const relativePath = matchedPath.replace(/\\/g, "/");
|
||||
if (relativePath.includes("../") || relativePath.includes("/..")) {
|
||||
return fail(`Project reference path must not escape .agent/references: ${relativePath}`);
|
||||
}
|
||||
declared.add(relativePath);
|
||||
}
|
||||
for (const relativePath of declared) {
|
||||
if (!actual.has(relativePath)) {
|
||||
return fail(`Declared project reference does not exist: ${repositoryPath} -> ${relativePath}`);
|
||||
}
|
||||
}
|
||||
const unreferenced = [...actual.keys()].filter((relativePath) => !declared.has(relativePath));
|
||||
if (unreferenced.length > 0) {
|
||||
return fail(`Project reference is not routed from .agent/project.md: ${unreferenced.join(", ")}`);
|
||||
}
|
||||
const references = [];
|
||||
for (const [relativePath, filePath] of [...actual.entries()].sort(([left], [right]) => left.localeCompare(right))) {
|
||||
const content = await readStrictUtf8(filePath, relativePath);
|
||||
if (normalizeFragment(content).length === 0) {
|
||||
return fail(`Project reference is empty: ${filePath}`);
|
||||
}
|
||||
references.push({
|
||||
relativePath,
|
||||
path: filePath,
|
||||
bytes: Buffer.byteLength(content, "utf8")
|
||||
});
|
||||
}
|
||||
return references;
|
||||
}
|
||||
function parseYaml(text, label) {
|
||||
const document = (0, import_yaml.parseDocument)(text, {
|
||||
prettyErrors: true,
|
||||
@@ -14661,12 +14751,25 @@ function parseContractCatalog(value, label) {
|
||||
}
|
||||
assertExactKeys(
|
||||
item,
|
||||
["id", "provider_project_id", "consumer_file", "order", "required_layers"],
|
||||
[
|
||||
"id",
|
||||
"provider_project_id",
|
||||
"consumer_file",
|
||||
"consumer_references_dir",
|
||||
"order",
|
||||
"required_layers"
|
||||
],
|
||||
itemLabel
|
||||
);
|
||||
const { id, provider_project_id: providerProjectId, consumer_file: consumerFile, order } = item;
|
||||
const {
|
||||
id,
|
||||
provider_project_id: providerProjectId,
|
||||
consumer_file: consumerFile,
|
||||
consumer_references_dir: consumerReferencesDir,
|
||||
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 || import_node_path.default.isAbsolute(consumerFile) || typeof order !== "number" || !Number.isInteger(order) || !Array.isArray(requiredLayers) || requiredLayers.some(
|
||||
if (typeof id !== "string" || !SLUG_PATTERN.test(id) || typeof providerProjectId !== "string" || !SLUG_PATTERN.test(providerProjectId) || typeof consumerFile !== "string" || consumerFile.length === 0 || import_node_path.default.isAbsolute(consumerFile) || typeof consumerReferencesDir !== "string" || consumerReferencesDir.length === 0 || import_node_path.default.isAbsolute(consumerReferencesDir) || 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.`);
|
||||
@@ -14680,6 +14783,7 @@ function parseContractCatalog(value, label) {
|
||||
id,
|
||||
provider_project_id: providerProjectId,
|
||||
consumer_file: consumerFile,
|
||||
consumer_references_dir: consumerReferencesDir,
|
||||
order,
|
||||
required_layers: requiredLayers
|
||||
};
|
||||
@@ -14866,6 +14970,95 @@ async function resolveConsumerFragment(context, contract, kind) {
|
||||
assertContained(providerRoot, consumerPath, `Consumer file for ${contract.id}`);
|
||||
return readRequiredFragment(consumerPath, kind, contract.id);
|
||||
}
|
||||
async function contractReferenceSources(context, contract) {
|
||||
const providerRoot = await resolveRegisteredProject(context, contract.provider_project_id);
|
||||
const sourceRoot = import_node_path.default.resolve(providerRoot, contract.consumer_references_dir);
|
||||
assertContained(providerRoot, sourceRoot, `Consumer references for ${contract.id}`);
|
||||
const files = await listMarkdownFiles(
|
||||
sourceRoot,
|
||||
`Consumer references for ${contract.id}`,
|
||||
true
|
||||
);
|
||||
if (files.length === 0) {
|
||||
return fail(`Consumer references for ${contract.id} must contain at least one Markdown file.`);
|
||||
}
|
||||
return files.map((sourcePath) => {
|
||||
const relativeSourcePath = portableRelative(sourceRoot, sourcePath);
|
||||
return {
|
||||
sourcePath,
|
||||
relativeSourcePath,
|
||||
relativeTargetPath: `${MANAGED_REFERENCE_ROOT}/${contract.id}/${relativeSourcePath}`
|
||||
};
|
||||
});
|
||||
}
|
||||
async function validateConsumerReferenceRouting(context, contract, fragment) {
|
||||
const sources = await contractReferenceSources(context, contract);
|
||||
const expected = new Set(sources.map((source) => source.relativeTargetPath));
|
||||
const declared = /* @__PURE__ */ new Set();
|
||||
const contractPrefix = `${MANAGED_REFERENCE_ROOT}/${contract.id}/`;
|
||||
for (const match of fragment.content.matchAll(/`([^`\r\n]+\.md)`/g)) {
|
||||
const matchedPath = match[1];
|
||||
if (!matchedPath) {
|
||||
continue;
|
||||
}
|
||||
const relativePath = matchedPath.replace(/\\/g, "/");
|
||||
if (relativePath.startsWith(contractPrefix)) {
|
||||
declared.add(relativePath);
|
||||
}
|
||||
}
|
||||
const missing = [...expected].filter((relativePath) => !declared.has(relativePath));
|
||||
const unknown = [...declared].filter((relativePath) => !expected.has(relativePath));
|
||||
if (missing.length > 0 || unknown.length > 0) {
|
||||
return fail(
|
||||
`Consumer reference routing mismatch for ${contract.id}. Missing: ${missing.join(", ") || "none"}; unknown: ${unknown.join(", ") || "none"}.`
|
||||
);
|
||||
}
|
||||
return sources;
|
||||
}
|
||||
async function renderManagedReference(sourcePath, contract, relativeSourcePath) {
|
||||
const source = normalizeFragment(await readStrictUtf8(sourcePath));
|
||||
if (source.length === 0) {
|
||||
return fail(`Managed consumer reference is empty: ${sourcePath}`);
|
||||
}
|
||||
const marker = [
|
||||
"<!--",
|
||||
GENERATED_MARKER,
|
||||
`Contract: ${contract.id}`,
|
||||
`Source: ${contract.consumer_references_dir.replace(/\\/g, "/")}/${relativeSourcePath}`,
|
||||
"-->"
|
||||
].join("\n");
|
||||
return `${marker}
|
||||
|
||||
${source}
|
||||
`;
|
||||
}
|
||||
async function planManagedContractReferences(context, repositoryPath, contracts, fragmentsByContract) {
|
||||
const outputs = [];
|
||||
for (const contract of contracts) {
|
||||
const fragment = fragmentsByContract.get(contract.id);
|
||||
if (!fragment) {
|
||||
return fail(`Missing consumer fragment while planning references: ${contract.id}`);
|
||||
}
|
||||
const sources = await validateConsumerReferenceRouting(context, contract, fragment);
|
||||
for (const source of sources) {
|
||||
const targetPath = import_node_path.default.join(repositoryPath, ...source.relativeTargetPath.split("/"));
|
||||
const content = await renderManagedReference(
|
||||
source.sourcePath,
|
||||
contract,
|
||||
source.relativeSourcePath
|
||||
);
|
||||
outputs.push({
|
||||
contractId: contract.id,
|
||||
sourcePath: source.sourcePath,
|
||||
relativePath: source.relativeTargetPath,
|
||||
targetPath,
|
||||
content,
|
||||
state: await inspectManagedOutput(targetPath, content)
|
||||
});
|
||||
}
|
||||
}
|
||||
return outputs;
|
||||
}
|
||||
function generatedHeader(profile) {
|
||||
return [
|
||||
"<!--",
|
||||
@@ -14891,6 +15084,66 @@ async function inspectAgentsOutput(filePath, expected) {
|
||||
}
|
||||
return current.slice(0, 512).includes(GENERATED_MARKER) ? "stale" : "unmanaged";
|
||||
}
|
||||
async function inspectManagedOutput(filePath, expected) {
|
||||
if (!await pathExists(filePath)) {
|
||||
return "missing";
|
||||
}
|
||||
let current;
|
||||
try {
|
||||
current = await readStrictUtf8(filePath);
|
||||
} catch {
|
||||
return "unmanaged";
|
||||
}
|
||||
if (current === expected) {
|
||||
return "current";
|
||||
}
|
||||
return current.slice(0, 1024).includes(GENERATED_MARKER) ? "stale" : "unmanaged";
|
||||
}
|
||||
async function renderManagedSkill(sourcePath, name) {
|
||||
const source = normalizeNewlines(await readStrictUtf8(sourcePath));
|
||||
if (!source.startsWith("---\n")) {
|
||||
return fail(`Managed skill must start with YAML front matter: ${sourcePath}`);
|
||||
}
|
||||
const closingIndex = source.indexOf("\n---\n", 4);
|
||||
if (closingIndex < 0) {
|
||||
return fail(`Managed skill has no closing YAML front matter: ${sourcePath}`);
|
||||
}
|
||||
const frontMatter = parseYaml(source.slice(4, closingIndex), `${sourcePath} front matter`);
|
||||
if (!isPlainObject(frontMatter) || frontMatter.name !== name || typeof frontMatter.description !== "string" || frontMatter.description.trim().length === 0) {
|
||||
return fail(`Managed skill must declare matching name and non-empty description: ${sourcePath}`);
|
||||
}
|
||||
const frontMatterEnd = closingIndex + "\n---\n".length;
|
||||
const marker = [
|
||||
"<!--",
|
||||
GENERATED_MARKER,
|
||||
`Source: skills/${name}/SKILL.md`,
|
||||
"-->",
|
||||
""
|
||||
].join("\n");
|
||||
return `${source.slice(0, frontMatterEnd)}
|
||||
${marker}${source.slice(frontMatterEnd).trimStart().trimEnd()}
|
||||
`;
|
||||
}
|
||||
async function planManagedSkills(context, repositoryPath) {
|
||||
const outputs = [];
|
||||
for (const name of MANAGED_SKILL_NAMES) {
|
||||
const sourcePath = import_node_path.default.join(context.harnessRoot, "skills", name, "SKILL.md");
|
||||
const content = await renderManagedSkill(sourcePath, name);
|
||||
for (const root of MANAGED_SKILL_ROOTS) {
|
||||
const relativePath = `${root}/${name}/SKILL.md`;
|
||||
const targetPath = import_node_path.default.join(repositoryPath, ...relativePath.split("/"));
|
||||
outputs.push({
|
||||
name,
|
||||
sourcePath,
|
||||
relativePath,
|
||||
targetPath,
|
||||
content,
|
||||
state: await inspectManagedOutput(targetPath, content)
|
||||
});
|
||||
}
|
||||
}
|
||||
return outputs;
|
||||
}
|
||||
async function inspectClaudeOutput(filePath) {
|
||||
if (!await pathExists(filePath)) {
|
||||
return "missing";
|
||||
@@ -14956,11 +15209,14 @@ async function planProject(harnessRoot, projectId) {
|
||||
);
|
||||
}
|
||||
const consumes = (profile.shared_contracts?.consumes ?? []).map((id) => contractById(context, id)).sort((left, right) => left.order - right.order);
|
||||
const contractFragments = /* @__PURE__ */ new Map();
|
||||
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 fragment = await resolveConsumerFragment(context, contract, "shared-contract");
|
||||
contractFragments.set(contract.id, fragment);
|
||||
fragments.push(fragment);
|
||||
}
|
||||
const providedPaths = /* @__PURE__ */ new Set();
|
||||
const provides = (profile.shared_contracts?.provides ?? []).map((id) => contractById(context, id)).sort((left, right) => left.order - right.order);
|
||||
@@ -14972,28 +15228,54 @@ async function planProject(harnessRoot, projectId) {
|
||||
continue;
|
||||
}
|
||||
providedPaths.add(dedupeKey);
|
||||
fragments.push(await readRequiredFragment(consumerPath, "provided-contract", contract.id));
|
||||
const fragment = await readRequiredFragment(consumerPath, "provided-contract", contract.id);
|
||||
contractFragments.set(contract.id, fragment);
|
||||
fragments.push(fragment);
|
||||
}
|
||||
fragments.push(
|
||||
await readRequiredFragment(
|
||||
import_node_path.default.join(repositoryPath, ".agent", "project.md"),
|
||||
"project",
|
||||
projectId
|
||||
)
|
||||
const projectFragment = await readRequiredFragment(
|
||||
import_node_path.default.join(repositoryPath, ".agent", "project.md"),
|
||||
"project",
|
||||
projectId
|
||||
);
|
||||
const projectReferences = await validateProjectReferences(
|
||||
repositoryPath,
|
||||
projectFragment.content
|
||||
);
|
||||
fragments.push(projectFragment);
|
||||
const agentsContent = `${[generatedHeader(profile), ...fragments.map((fragment) => fragment.content)].join("\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 warnings = [];
|
||||
if (agentsBytes > WARNING_BYTES) {
|
||||
warnings.push(`Generated AGENTS.md is ${agentsBytes} bytes and exceeds the ${WARNING_BYTES}-byte warning threshold.`);
|
||||
}
|
||||
if (projectFragment.bytes > 4096) {
|
||||
warnings.push(`.agent/project.md is ${projectFragment.bytes} bytes; keep the routing file near 2,000-3,000 bytes and move conditional detail to .agent/references.`);
|
||||
}
|
||||
for (const reference of projectReferences) {
|
||||
if (reference.bytes > 16384) {
|
||||
warnings.push(`${reference.relativePath} is ${reference.bytes} bytes; consider splitting it by task scope.`);
|
||||
}
|
||||
}
|
||||
const agentsPath = import_node_path.default.join(repositoryPath, "AGENTS.md");
|
||||
const claudePath = import_node_path.default.join(repositoryPath, "CLAUDE.md");
|
||||
const output = {
|
||||
agents: await inspectAgentsOutput(agentsPath, agentsContent),
|
||||
claude: await inspectClaudeOutput(claudePath)
|
||||
};
|
||||
const skills = await planManagedSkills(context, repositoryPath);
|
||||
const activeContracts = [...new Map(
|
||||
[...consumes, ...provides].map((contract) => [contract.id, contract])
|
||||
).values()].sort((left, right) => left.order - right.order);
|
||||
const managedReferences = await planManagedContractReferences(
|
||||
context,
|
||||
repositoryPath,
|
||||
activeContracts,
|
||||
contractFragments
|
||||
);
|
||||
return {
|
||||
projectId,
|
||||
repositoryPath,
|
||||
@@ -15003,7 +15285,10 @@ async function planProject(harnessRoot, projectId) {
|
||||
claudeContent: CLAUDE_CONTENT,
|
||||
agentsBytes,
|
||||
warnings,
|
||||
output
|
||||
output,
|
||||
skills,
|
||||
managedReferences,
|
||||
projectReferences
|
||||
};
|
||||
}
|
||||
async function replaceFilesAtomically(files) {
|
||||
@@ -15063,6 +15348,20 @@ async function composeProject(harnessRoot, projectId) {
|
||||
if (plan.output.claude === "unmanaged") {
|
||||
fail(`Refusing to overwrite unmanaged CLAUDE.md in ${plan.repositoryPath}`);
|
||||
}
|
||||
const unmanagedSkill = plan.skills.find((skill) => skill.state === "unmanaged");
|
||||
if (unmanagedSkill) {
|
||||
fail(
|
||||
`Refusing to overwrite unmanaged skill ${unmanagedSkill.relativePath} in ${plan.repositoryPath}`
|
||||
);
|
||||
}
|
||||
const unmanagedReference = plan.managedReferences.find(
|
||||
(reference) => reference.state === "unmanaged"
|
||||
);
|
||||
if (unmanagedReference) {
|
||||
fail(
|
||||
`Refusing to overwrite unmanaged shared reference ${unmanagedReference.relativePath} in ${plan.repositoryPath}`
|
||||
);
|
||||
}
|
||||
const writes = [];
|
||||
const changed = [];
|
||||
if (plan.output.agents !== "current") {
|
||||
@@ -15073,11 +15372,23 @@ async function composeProject(harnessRoot, projectId) {
|
||||
writes.push({ target: import_node_path.default.join(plan.repositoryPath, "CLAUDE.md"), content: plan.claudeContent });
|
||||
changed.push("CLAUDE.md");
|
||||
}
|
||||
for (const skill of plan.skills) {
|
||||
if (skill.state !== "current") {
|
||||
writes.push({ target: skill.targetPath, content: skill.content });
|
||||
changed.push(skill.relativePath);
|
||||
}
|
||||
}
|
||||
for (const reference of plan.managedReferences) {
|
||||
if (reference.state !== "current") {
|
||||
writes.push({ target: reference.targetPath, content: reference.content });
|
||||
changed.push(reference.relativePath);
|
||||
}
|
||||
}
|
||||
if (writes.length > 0) {
|
||||
await replaceFilesAtomically(writes);
|
||||
}
|
||||
const refreshed = await planProject(harnessRoot, projectId);
|
||||
if (refreshed.output.agents !== "current" || refreshed.output.claude !== "current") {
|
||||
if (refreshed.output.agents !== "current" || refreshed.output.claude !== "current" || refreshed.skills.some((skill) => skill.state !== "current") || refreshed.managedReferences.some((reference) => reference.state !== "current")) {
|
||||
fail(`Generated output verification failed for ${projectId}.`);
|
||||
}
|
||||
return { ...refreshed, changed };
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## 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.
|
||||
The composer builds deterministic repository instructions, workflow skills, and shared-contract reference copies 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. Codex and Claude Code discover their managed skills from their repository-scoped skill directories.
|
||||
|
||||
## Runtime
|
||||
|
||||
@@ -33,6 +33,9 @@ The composer reads these inputs as strict UTF-8 text:
|
||||
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
|
||||
9. Each canonical `skills/<skill-name>/SKILL.md`
|
||||
10. Repository-authored `.agent/references/**/*.md` routed from `.agent/project.md`
|
||||
11. Provider-authored `.agent/consumer-references/**/*.md` routed from `.agent/consumer.md`
|
||||
|
||||
The target repository profile is `.agent/profile.yml` and must conform to `schemas/profile.schema.json`. Machine paths never belong in the profile.
|
||||
|
||||
@@ -71,6 +74,8 @@ Render the header as an HTML comment so it does not become an instruction headin
|
||||
- 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.
|
||||
- Read `consumer_references_dir`, require at least one strict UTF-8 Markdown reference, and require `consumer_file` to route every source reference to `.agent-harness/references/<contract-id>/...`.
|
||||
- Copy those references into each provider and consumer repository as managed, repository-local files. Refuse to overwrite a target without the harness marker.
|
||||
- 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`.
|
||||
@@ -90,7 +95,10 @@ Fail composition when any of these conditions is true:
|
||||
- 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.
|
||||
- `.agent/project.md` does not contain `## Required Project References`.
|
||||
- A routed `.agent/references` path is missing, escapes the reference root, is invalid UTF-8, or an authored Markdown reference is not routed by `.agent/project.md`.
|
||||
- A providing repository's `.agent/consumer.md` is missing or empty.
|
||||
- A shared consumer reference directory is missing or empty, or `consumer.md` does not route every shared reference.
|
||||
- A migration target containing `nextjs` does not also contain `react`.
|
||||
- Any Markdown, JSON, or YAML input is not strict UTF-8 without BOM.
|
||||
|
||||
@@ -116,24 +124,47 @@ Write exactly:
|
||||
|
||||
Use UTF-8 without BOM, LF line endings, and exactly one trailing newline. Refuse to overwrite other existing content.
|
||||
|
||||
### Managed Skills
|
||||
|
||||
For each canonical skill, write identical generated copies to:
|
||||
|
||||
- `.agents/skills/<skill-name>/SKILL.md` for Codex
|
||||
- `.claude/skills/<skill-name>/SKILL.md` for Claude Code
|
||||
|
||||
The generated marker follows the YAML front matter so skill discovery remains valid. Managed skills use UTF-8 without BOM, LF line endings, and exactly one trailing newline. Missing and stale managed files may be written; an existing file without the generated marker is unmanaged and must not be overwritten.
|
||||
|
||||
The default managed skills are `attention-aware-communication` for response presentation, `karpathy-guidelines` for implementation discipline, `project-reference-loader` for task-scoped context loading, and `verification-before-completion` for evidence-gated completion claims.
|
||||
|
||||
### Managed Shared References
|
||||
|
||||
For every provided or consumed contract, copy each provider source from its cataloged `consumer_references_dir` to:
|
||||
|
||||
```text
|
||||
.agent-harness/references/<contract-id>/<relative-source-path>
|
||||
```
|
||||
|
||||
Generated references use UTF-8 without BOM, LF line endings, a harness marker, and one trailing newline. They are shared by Codex and Claude Code. Edit the provider source and recompose; never edit a generated consumer copy directly.
|
||||
|
||||
## 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 32,000 bytes, leaving 768 bytes below Codex's default 32 KiB combined limit.
|
||||
- Warn when `.agent/project.md` exceeds 4,096 bytes; keep it near 2-3 KiB and route conditional detail to `.agent/references`.
|
||||
- Warn when one project reference exceeds 16,384 bytes so it can be split by task scope.
|
||||
- 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.
|
||||
- `verify`: compare expected and stored instructions, skills, and shared references byte for byte while validating authored project references; return a failure exit code for drift.
|
||||
- `compose`: atomically replace only managed or missing instructions, skills, and shared references, then verify them again.
|
||||
- `register`: validate a relative project path and matching profile, then atomically update `workspace.local.yml` by default or `workspace.yml` when `--shared` is explicit.
|
||||
|
||||
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.
|
||||
Tests use isolated temporary workspaces. They cover deterministic order, byte-for-byte verification, project-reference routing, shared-reference distribution, semantic validation, contract-target selection and isolation, unmanaged-file refusal, safe registration paths, and hard size-limit enforcement.
|
||||
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@kri/ai-agent-harness",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@kri/ai-agent-harness",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"dependencies": {
|
||||
"ajv": "8.20.0",
|
||||
"yaml": "2.9.0"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@kri/ai-agent-harness",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
37
skills/attention-aware-communication/SKILL.md
Normal file
37
skills/attention-aware-communication/SKILL.md
Normal file
@@ -0,0 +1,37 @@
|
||||
---
|
||||
name: attention-aware-communication
|
||||
description: Shape substantive answers, progress updates, and completion reports for fast, accurate reading without reducing the underlying work.
|
||||
---
|
||||
|
||||
# Attention-Aware Communication
|
||||
|
||||
This skill changes presentation only. Investigate, implement, and verify as deeply as the task requires.
|
||||
|
||||
## Default: Attention-kind
|
||||
|
||||
- Put the bottom line in the first sentence and use plain Korean.
|
||||
- Say the least that fully answers, then stop. Remove preambles, padding, repetition, and closing restatements.
|
||||
- Never omit a number, scope condition, risk, prerequisite, uncertainty, or other fact that could cause the user to act incorrectly.
|
||||
- For genuine breadth, explain the one or two most important points first, name the remaining areas, and let the user choose whether to expand them. Do not use this to defer required caveats or a complete focused answer.
|
||||
- When the user asks for a detailed explanation, walkthrough, rationale, or full picture, suspend brevity and provide the necessary detail in scannable sections.
|
||||
- When asked for a deliverable such as a command, message, snippet, or commit text, return the deliverable without unnecessary framing unless safety or correctness requires context.
|
||||
- Ask one blocking question at a time and put it last. Keep working when a non-blocking assumption is safe.
|
||||
|
||||
## Progress and Completion: Rundown
|
||||
|
||||
Use Rundown formatting when a task has multiple steps or mixed states:
|
||||
|
||||
- Start with a one-line outcome that includes any blocker.
|
||||
- Distinguish verified completion, work in progress, work not started, and unknown state. Omit empty categories.
|
||||
- Put each blocker or material risk on its own line.
|
||||
- Report only observed states. Mark an unknown as unknown and state what check would resolve it.
|
||||
- End with the next action or a small numbered choice only when the user must decide.
|
||||
|
||||
## Explicit-Only: Spartan
|
||||
|
||||
Use Spartan style only when the user explicitly asks for it:
|
||||
|
||||
- Lead with the complete answer in one sentence.
|
||||
- Be terse, blunt, and direct; remove warmth, hedging, transitions, narration, and summaries.
|
||||
- Keep all load-bearing facts, warnings, and conditions even when they make the answer longer.
|
||||
- If the user also asks for depth, provide the full detail in short, separated blocks.
|
||||
33
skills/karpathy-guidelines/SKILL.md
Normal file
33
skills/karpathy-guidelines/SKILL.md
Normal file
@@ -0,0 +1,33 @@
|
||||
---
|
||||
name: karpathy-guidelines
|
||||
description: Keep implementation, refactoring, and code review assumption-aware, simple, surgical, and tied to verifiable success criteria.
|
||||
---
|
||||
|
||||
# Karpathy Guidelines
|
||||
|
||||
Use these guidelines while implementing, refactoring, or reviewing code. They refine execution quality but do not expand the approved task scope.
|
||||
|
||||
## Think Before Coding
|
||||
|
||||
- Inspect the relevant code and repository conventions before choosing a solution.
|
||||
- Surface an assumption when different choices would materially change behavior, compatibility, data, or scope.
|
||||
- Ask only when the decision cannot be discovered safely and a reasonable assumption would be risky. Otherwise proceed with the smallest reasonable assumption and report it.
|
||||
|
||||
## Simplicity First
|
||||
|
||||
- Implement the smallest complete solution that satisfies the observable requirement.
|
||||
- Do not add speculative abstractions, extension points, configuration, fallback paths, or dependencies for hypothetical future use.
|
||||
- Prefer an existing repository pattern or standard-library capability over a new local framework.
|
||||
|
||||
## Surgical Changes
|
||||
|
||||
- Every changed line must trace to the approved objective, required validation, or a necessary compatibility adjustment.
|
||||
- Preserve existing naming, structure, public behavior, and formatting outside that boundary.
|
||||
- Do not mix the task with unrelated cleanup. Remove dead code, duplication, or ceremony introduced by the current change before finishing.
|
||||
|
||||
## Goal-Driven Execution
|
||||
|
||||
- Translate the request into observable success criteria before implementation.
|
||||
- Choose the narrowest check that can fail for the behavior being changed, then run broader repository checks when appropriate.
|
||||
- Iterate only within the approved scope until the criteria pass or a concrete blocker is established.
|
||||
- Before reporting completion, inspect the final diff for unnecessary code and use `verification-before-completion` for fresh evidence.
|
||||
25
skills/project-reference-loader/SKILL.md
Normal file
25
skills/project-reference-loader/SKILL.md
Normal file
@@ -0,0 +1,25 @@
|
||||
---
|
||||
name: project-reference-loader
|
||||
description: Load the current project-specific and shared reference documents routed by AGENTS.md before substantive repository analysis, implementation, debugging, review, or planning.
|
||||
---
|
||||
|
||||
# Project Reference Loader
|
||||
|
||||
Use the repository's generated `AGENTS.md` as the routing entrypoint.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Find the `Required Project References` and shared-contract reference routes that match the current task.
|
||||
2. Read the current contents of every matching file before relying on remembered project behavior, even when the file was read earlier in the session.
|
||||
3. If the task crosses multiple scopes, read every matching reference. Do not load unrelated references merely because they exist.
|
||||
4. Treat routed references as binding project instructions within their stated scope. Resolve conflicts using the precedence rules in `AGENTS.md`.
|
||||
5. If a required reference is missing, unreadable, outside the repository, or internally inconsistent, stop the affected work and report the exact problem instead of guessing.
|
||||
|
||||
## Change Handling
|
||||
|
||||
- Edit authored project detail under `.agent/references/` when the durable rule belongs only to that repository.
|
||||
- Edit the provider's `.agent/consumer-references/` when the rule is part of a shared consumer contract.
|
||||
- Never edit generated `.agent-harness/references/` copies directly.
|
||||
- Changing `.agent/references/` does not require recomposing `AGENTS.md` when its route is unchanged; changing routing, `project.md`, `consumer.md`, or shared reference sources does.
|
||||
|
||||
Before completion, confirm that the references used still exist and that the result does not contradict them. This skill does not expand authorization to edit, commit, push, deploy, connect to external systems, or perform destructive operations.
|
||||
34
skills/verification-before-completion/SKILL.md
Normal file
34
skills/verification-before-completion/SKILL.md
Normal file
@@ -0,0 +1,34 @@
|
||||
---
|
||||
name: verification-before-completion
|
||||
description: Require fresh, claim-specific evidence before reporting work complete, fixed, passing, ready, or safe to commit or publish.
|
||||
---
|
||||
|
||||
# Verification Before Completion
|
||||
|
||||
No completion claim without fresh evidence. This workflow verifies status; it does not authorize a commit, push, deployment, database operation, or other protected action.
|
||||
|
||||
## Verification Gate
|
||||
|
||||
Before making a success claim:
|
||||
|
||||
1. State the exact claim internally and identify which observable check can prove or disprove it.
|
||||
2. Run the relevant command or inspection fresh after the final change. Use repository-defined commands; do not invent a substitute that proves a different property.
|
||||
3. Read the complete result needed for the claim, including the exit code, failure count, skipped checks, and generated changes.
|
||||
4. Compare the evidence with the claim and the approved acceptance criteria.
|
||||
5. Report only the status supported by that evidence.
|
||||
|
||||
## Evidence Rules
|
||||
|
||||
- A passing lint does not prove compilation, a passing build does not prove runtime behavior, and a passing narrow test does not prove unrelated requirements.
|
||||
- For a regression test, establish that it is capable of detecting the defect when practical; do not treat an always-passing test as proof.
|
||||
- Recheck the worktree or final diff after generators, formatters, tests, or builds that may create or alter files.
|
||||
- Separate verified results, failures, checks not run, and pre-existing failures. Never quietly merge them into a success statement.
|
||||
- For delegated work, inspect the returned changes and run the relevant verification yourself before accepting the completion claim.
|
||||
- For absence or universal claims such as “no occurrences” or “all projects,” use a check whose scope actually covers the claim.
|
||||
|
||||
## Reporting
|
||||
|
||||
- Cite the commands or inspections actually run and summarize their observed results.
|
||||
- If a required check cannot run, state the actual incomplete or blocked status and the exact reason.
|
||||
- Do not use “should work,” “probably passes,” “seems correct,” or similar language as a substitute for verification.
|
||||
- Do not claim completion while a required check is failing or while known correctness, encoding, security, or generated-output drift remains unresolved.
|
||||
@@ -28,6 +28,13 @@ Later and more specific instructions may override earlier general instructions o
|
||||
- Lead with the result or decision, then provide only the detail needed to verify it.
|
||||
- Do not create or retain a full session transcript.
|
||||
|
||||
### Attention-Aware Response Style
|
||||
|
||||
- Use `attention-aware-communication` for substantive answers, progress updates, and completion reports.
|
||||
- Default to concise, bottom-line-first Korean without omitting a condition, risk, number, or uncertainty needed for a correct decision.
|
||||
- Give full detail when the user requests depth. Use Spartan style only when explicitly requested.
|
||||
- Presentation rules never reduce investigation, implementation, validation, or reporting obligations.
|
||||
|
||||
## Work Authorization
|
||||
|
||||
- The default workflow is discussion first and explicit execution approval second.
|
||||
@@ -145,6 +152,13 @@ Preferred human-facing tools:
|
||||
- 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.
|
||||
|
||||
## Workflow Skills
|
||||
|
||||
- Use `project-reference-loader` before substantive repository analysis, planning, implementation, debugging, or review. Read only the current project and shared references routed for that task, and reread them for each related task even if they were loaded earlier in the session.
|
||||
- Use `karpathy-guidelines` when implementing, refactoring, or reviewing code. It keeps assumptions visible, changes surgical, and success criteria verifiable.
|
||||
- Use `verification-before-completion` before claiming that work is complete, fixed, passing, ready, or safe to commit or publish.
|
||||
- A skill does not expand task scope or authorize Git publication, database execution, deployment, destructive actions, or external communication.
|
||||
|
||||
## Validation
|
||||
|
||||
- Discover supported build, test, lint, type-check, and formatting commands from repository files and project instructions. Do not invent commands.
|
||||
|
||||
33
src/cli.ts
33
src/cli.ts
@@ -112,6 +112,12 @@ function printPlan(plan: ProjectPlan, harnessRoot: string): void {
|
||||
console.log(`repository: ${plan.repositoryPath}`);
|
||||
console.log(`AGENTS.md: ${plan.output.agents}`);
|
||||
console.log(`CLAUDE.md: ${plan.output.claude}`);
|
||||
for (const skill of plan.skills) {
|
||||
console.log(`${skill.relativePath}: ${skill.state}`);
|
||||
}
|
||||
for (const reference of plan.managedReferences) {
|
||||
console.log(`${reference.relativePath}: ${reference.state}`);
|
||||
}
|
||||
console.log(`size: ${plan.agentsBytes} bytes`);
|
||||
console.log("fragments:");
|
||||
for (const fragment of plan.fragments) {
|
||||
@@ -119,6 +125,12 @@ function printPlan(plan: ProjectPlan, harnessRoot: string): void {
|
||||
` - ${fragment.kind}:${fragment.id} (${fragment.bytes} bytes) ${displayPath(fragment.path, [plan.repositoryPath, harnessRoot])}`,
|
||||
);
|
||||
}
|
||||
if (plan.projectReferences.length > 0) {
|
||||
console.log("project references:");
|
||||
for (const reference of plan.projectReferences) {
|
||||
console.log(` - ${reference.relativePath} (${reference.bytes} bytes)`);
|
||||
}
|
||||
}
|
||||
for (const warning of plan.warnings) {
|
||||
console.log(`warning: ${warning}`);
|
||||
}
|
||||
@@ -193,7 +205,12 @@ async function run(): Promise<void> {
|
||||
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") {
|
||||
if (
|
||||
plan.output.agents !== "current"
|
||||
|| plan.output.claude !== "current"
|
||||
|| plan.skills.some((skill) => skill.state !== "current")
|
||||
|| plan.managedReferences.some((reference) => reference.state !== "current")
|
||||
) {
|
||||
failed = true;
|
||||
}
|
||||
}
|
||||
@@ -217,6 +234,20 @@ async function run(): Promise<void> {
|
||||
if (preflight.output.claude === "unmanaged") {
|
||||
throw new HarnessError(`Refusing to overwrite unmanaged CLAUDE.md in ${preflight.repositoryPath}`);
|
||||
}
|
||||
const unmanagedSkill = preflight.skills.find((skill) => skill.state === "unmanaged");
|
||||
if (unmanagedSkill) {
|
||||
throw new HarnessError(
|
||||
`Refusing to overwrite unmanaged skill ${unmanagedSkill.relativePath} in ${preflight.repositoryPath}`,
|
||||
);
|
||||
}
|
||||
const unmanagedReference = preflight.managedReferences.find(
|
||||
(reference) => reference.state === "unmanaged",
|
||||
);
|
||||
if (unmanagedReference) {
|
||||
throw new HarnessError(
|
||||
`Refusing to overwrite unmanaged shared reference ${unmanagedReference.relativePath} in ${preflight.repositoryPath}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const projectId of projectIds) {
|
||||
|
||||
414
src/harness.ts
414
src/harness.ts
@@ -7,6 +7,7 @@ import {
|
||||
import {
|
||||
access,
|
||||
mkdir,
|
||||
readdir,
|
||||
readFile,
|
||||
realpath,
|
||||
rename,
|
||||
@@ -25,6 +26,16 @@ const CLAUDE_CONTENT = "@AGENTS.md\n";
|
||||
const WARNING_BYTES = 26_624;
|
||||
const MAX_BYTES = 32_000;
|
||||
const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
||||
const MANAGED_SKILL_NAMES = [
|
||||
"attention-aware-communication",
|
||||
"karpathy-guidelines",
|
||||
"project-reference-loader",
|
||||
"verification-before-completion",
|
||||
] as const;
|
||||
const MANAGED_SKILL_ROOTS = [".agents/skills", ".claude/skills"] as const;
|
||||
const MANAGED_REFERENCE_ROOT = ".agent-harness/references";
|
||||
const PROJECT_REFERENCE_ROOT = ".agent/references";
|
||||
const PROJECT_ROUTER_HEADING = "## Required Project References";
|
||||
|
||||
export class HarnessError extends Error {
|
||||
constructor(message: string) {
|
||||
@@ -87,6 +98,7 @@ interface ContractDefinition {
|
||||
id: string;
|
||||
provider_project_id: string;
|
||||
consumer_file: string;
|
||||
consumer_references_dir: string;
|
||||
order: number;
|
||||
required_layers: ProjectLayer[];
|
||||
}
|
||||
@@ -124,6 +136,30 @@ export interface OutputInspection {
|
||||
claude: OutputState;
|
||||
}
|
||||
|
||||
export interface SkillOutput {
|
||||
name: string;
|
||||
sourcePath: string;
|
||||
relativePath: string;
|
||||
targetPath: string;
|
||||
content: string;
|
||||
state: OutputState;
|
||||
}
|
||||
|
||||
export interface ManagedReferenceOutput {
|
||||
contractId: string;
|
||||
sourcePath: string;
|
||||
relativePath: string;
|
||||
targetPath: string;
|
||||
content: string;
|
||||
state: OutputState;
|
||||
}
|
||||
|
||||
export interface ProjectReference {
|
||||
relativePath: string;
|
||||
path: string;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
export interface ProjectPlan {
|
||||
projectId: string;
|
||||
repositoryPath: string;
|
||||
@@ -134,6 +170,9 @@ export interface ProjectPlan {
|
||||
agentsBytes: number;
|
||||
warnings: string[];
|
||||
output: OutputInspection;
|
||||
skills: SkillOutput[];
|
||||
managedReferences: ManagedReferenceOutput[];
|
||||
projectReferences: ProjectReference[];
|
||||
}
|
||||
|
||||
export interface ComposeResult extends ProjectPlan {
|
||||
@@ -212,6 +251,100 @@ async function readRequiredFragment(
|
||||
};
|
||||
}
|
||||
|
||||
async function listMarkdownFiles(
|
||||
rootPath: string,
|
||||
label: string,
|
||||
required: boolean,
|
||||
): Promise<string[]> {
|
||||
if (!(await pathExists(rootPath))) {
|
||||
if (required) {
|
||||
return fail(`${label} does not exist: ${rootPath}`);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
if (!(await isDirectory(rootPath))) {
|
||||
return fail(`${label} must be a directory: ${rootPath}`);
|
||||
}
|
||||
|
||||
const files: string[] = [];
|
||||
const visit = async (directoryPath: string): Promise<void> => {
|
||||
const entries = await readdir(directoryPath, { withFileTypes: true });
|
||||
for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
|
||||
const candidate = path.join(directoryPath, entry.name);
|
||||
assertContained(rootPath, candidate, label);
|
||||
if (entry.isSymbolicLink()) {
|
||||
return fail(`${label} must not contain symbolic links: ${candidate}`);
|
||||
}
|
||||
if (entry.isDirectory()) {
|
||||
await visit(candidate);
|
||||
} else if (entry.isFile() && entry.name.toLowerCase().endsWith(".md")) {
|
||||
files.push(candidate);
|
||||
}
|
||||
}
|
||||
};
|
||||
await visit(rootPath);
|
||||
return files.sort((left, right) => left.localeCompare(right));
|
||||
}
|
||||
|
||||
function portableRelative(rootPath: string, filePath: string): string {
|
||||
return path.relative(rootPath, filePath).replace(/\\/g, "/");
|
||||
}
|
||||
|
||||
async function validateProjectReferences(
|
||||
repositoryPath: string,
|
||||
projectContent: string,
|
||||
): Promise<ProjectReference[]> {
|
||||
if (!normalizeNewlines(projectContent).includes(PROJECT_ROUTER_HEADING)) {
|
||||
return fail(`.agent/project.md must contain ${PROJECT_ROUTER_HEADING}: ${repositoryPath}`);
|
||||
}
|
||||
|
||||
const referencesRoot = path.join(repositoryPath, ".agent", "references");
|
||||
const files = await listMarkdownFiles(referencesRoot, "Project references", false);
|
||||
const actual = new Map(
|
||||
files.map((filePath) => [
|
||||
`${PROJECT_REFERENCE_ROOT}/${portableRelative(referencesRoot, filePath)}`,
|
||||
filePath,
|
||||
]),
|
||||
);
|
||||
const declared = new Set<string>();
|
||||
const pattern = /`(\.agent\/references\/[^`\r\n]+\.md)`/g;
|
||||
for (const match of normalizeNewlines(projectContent).matchAll(pattern)) {
|
||||
const matchedPath = match[1];
|
||||
if (!matchedPath) {
|
||||
continue;
|
||||
}
|
||||
const relativePath = matchedPath.replace(/\\/g, "/");
|
||||
if (relativePath.includes("../") || relativePath.includes("/..")) {
|
||||
return fail(`Project reference path must not escape .agent/references: ${relativePath}`);
|
||||
}
|
||||
declared.add(relativePath);
|
||||
}
|
||||
|
||||
for (const relativePath of declared) {
|
||||
if (!actual.has(relativePath)) {
|
||||
return fail(`Declared project reference does not exist: ${repositoryPath} -> ${relativePath}`);
|
||||
}
|
||||
}
|
||||
const unreferenced = [...actual.keys()].filter((relativePath) => !declared.has(relativePath));
|
||||
if (unreferenced.length > 0) {
|
||||
return fail(`Project reference is not routed from .agent/project.md: ${unreferenced.join(", ")}`);
|
||||
}
|
||||
|
||||
const references: ProjectReference[] = [];
|
||||
for (const [relativePath, filePath] of [...actual.entries()].sort(([left], [right]) => left.localeCompare(right))) {
|
||||
const content = await readStrictUtf8(filePath, relativePath);
|
||||
if (normalizeFragment(content).length === 0) {
|
||||
return fail(`Project reference is empty: ${filePath}`);
|
||||
}
|
||||
references.push({
|
||||
relativePath,
|
||||
path: filePath,
|
||||
bytes: Buffer.byteLength(content, "utf8"),
|
||||
});
|
||||
}
|
||||
return references;
|
||||
}
|
||||
|
||||
function parseYaml(text: string, label: string): unknown {
|
||||
const document = parseDocument(text, {
|
||||
prettyErrors: true,
|
||||
@@ -303,11 +436,24 @@ function parseContractCatalog(value: unknown, label: string): ContractCatalog {
|
||||
}
|
||||
assertExactKeys(
|
||||
item,
|
||||
["id", "provider_project_id", "consumer_file", "order", "required_layers"],
|
||||
[
|
||||
"id",
|
||||
"provider_project_id",
|
||||
"consumer_file",
|
||||
"consumer_references_dir",
|
||||
"order",
|
||||
"required_layers",
|
||||
],
|
||||
itemLabel,
|
||||
);
|
||||
|
||||
const { id, provider_project_id: providerProjectId, consumer_file: consumerFile, order } = item;
|
||||
const {
|
||||
id,
|
||||
provider_project_id: providerProjectId,
|
||||
consumer_file: consumerFile,
|
||||
consumer_references_dir: consumerReferencesDir,
|
||||
order,
|
||||
} = item;
|
||||
const requiredLayers = item.required_layers;
|
||||
if (
|
||||
typeof id !== "string"
|
||||
@@ -317,6 +463,9 @@ function parseContractCatalog(value: unknown, label: string): ContractCatalog {
|
||||
|| typeof consumerFile !== "string"
|
||||
|| consumerFile.length === 0
|
||||
|| path.isAbsolute(consumerFile)
|
||||
|| typeof consumerReferencesDir !== "string"
|
||||
|| consumerReferencesDir.length === 0
|
||||
|| path.isAbsolute(consumerReferencesDir)
|
||||
|| typeof order !== "number"
|
||||
|| !Number.isInteger(order)
|
||||
|| !Array.isArray(requiredLayers)
|
||||
@@ -336,6 +485,7 @@ function parseContractCatalog(value: unknown, label: string): ContractCatalog {
|
||||
id,
|
||||
provider_project_id: providerProjectId,
|
||||
consumer_file: consumerFile,
|
||||
consumer_references_dir: consumerReferencesDir,
|
||||
order,
|
||||
required_layers: requiredLayers as ProjectLayer[],
|
||||
};
|
||||
@@ -580,6 +730,112 @@ async function resolveConsumerFragment(
|
||||
return readRequiredFragment(consumerPath, kind, contract.id);
|
||||
}
|
||||
|
||||
async function contractReferenceSources(
|
||||
context: HarnessContext,
|
||||
contract: ContractDefinition,
|
||||
): Promise<Array<{ sourcePath: string; relativeSourcePath: string; relativeTargetPath: string }>> {
|
||||
const providerRoot = await resolveRegisteredProject(context, contract.provider_project_id);
|
||||
const sourceRoot = path.resolve(providerRoot, contract.consumer_references_dir);
|
||||
assertContained(providerRoot, sourceRoot, `Consumer references for ${contract.id}`);
|
||||
const files = await listMarkdownFiles(
|
||||
sourceRoot,
|
||||
`Consumer references for ${contract.id}`,
|
||||
true,
|
||||
);
|
||||
if (files.length === 0) {
|
||||
return fail(`Consumer references for ${contract.id} must contain at least one Markdown file.`);
|
||||
}
|
||||
return files.map((sourcePath) => {
|
||||
const relativeSourcePath = portableRelative(sourceRoot, sourcePath);
|
||||
return {
|
||||
sourcePath,
|
||||
relativeSourcePath,
|
||||
relativeTargetPath: `${MANAGED_REFERENCE_ROOT}/${contract.id}/${relativeSourcePath}`,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function validateConsumerReferenceRouting(
|
||||
context: HarnessContext,
|
||||
contract: ContractDefinition,
|
||||
fragment: CompositionFragment,
|
||||
): Promise<Array<{ sourcePath: string; relativeSourcePath: string; relativeTargetPath: string }>> {
|
||||
const sources = await contractReferenceSources(context, contract);
|
||||
const expected = new Set(sources.map((source) => source.relativeTargetPath));
|
||||
const declared = new Set<string>();
|
||||
const contractPrefix = `${MANAGED_REFERENCE_ROOT}/${contract.id}/`;
|
||||
for (const match of fragment.content.matchAll(/`([^`\r\n]+\.md)`/g)) {
|
||||
const matchedPath = match[1];
|
||||
if (!matchedPath) {
|
||||
continue;
|
||||
}
|
||||
const relativePath = matchedPath.replace(/\\/g, "/");
|
||||
if (relativePath.startsWith(contractPrefix)) {
|
||||
declared.add(relativePath);
|
||||
}
|
||||
}
|
||||
const missing = [...expected].filter((relativePath) => !declared.has(relativePath));
|
||||
const unknown = [...declared].filter((relativePath) => !expected.has(relativePath));
|
||||
if (missing.length > 0 || unknown.length > 0) {
|
||||
return fail(
|
||||
`Consumer reference routing mismatch for ${contract.id}. Missing: ${missing.join(", ") || "none"}; unknown: ${unknown.join(", ") || "none"}.`,
|
||||
);
|
||||
}
|
||||
return sources;
|
||||
}
|
||||
|
||||
async function renderManagedReference(
|
||||
sourcePath: string,
|
||||
contract: ContractDefinition,
|
||||
relativeSourcePath: string,
|
||||
): Promise<string> {
|
||||
const source = normalizeFragment(await readStrictUtf8(sourcePath));
|
||||
if (source.length === 0) {
|
||||
return fail(`Managed consumer reference is empty: ${sourcePath}`);
|
||||
}
|
||||
const marker = [
|
||||
"<!--",
|
||||
GENERATED_MARKER,
|
||||
`Contract: ${contract.id}`,
|
||||
`Source: ${contract.consumer_references_dir.replace(/\\/g, "/")}/${relativeSourcePath}`,
|
||||
"-->",
|
||||
].join("\n");
|
||||
return `${marker}\n\n${source}\n`;
|
||||
}
|
||||
|
||||
async function planManagedContractReferences(
|
||||
context: HarnessContext,
|
||||
repositoryPath: string,
|
||||
contracts: ContractDefinition[],
|
||||
fragmentsByContract: Map<string, CompositionFragment>,
|
||||
): Promise<ManagedReferenceOutput[]> {
|
||||
const outputs: ManagedReferenceOutput[] = [];
|
||||
for (const contract of contracts) {
|
||||
const fragment = fragmentsByContract.get(contract.id);
|
||||
if (!fragment) {
|
||||
return fail(`Missing consumer fragment while planning references: ${contract.id}`);
|
||||
}
|
||||
const sources = await validateConsumerReferenceRouting(context, contract, fragment);
|
||||
for (const source of sources) {
|
||||
const targetPath = path.join(repositoryPath, ...source.relativeTargetPath.split("/"));
|
||||
const content = await renderManagedReference(
|
||||
source.sourcePath,
|
||||
contract,
|
||||
source.relativeSourcePath,
|
||||
);
|
||||
outputs.push({
|
||||
contractId: contract.id,
|
||||
sourcePath: source.sourcePath,
|
||||
relativePath: source.relativeTargetPath,
|
||||
targetPath,
|
||||
content,
|
||||
state: await inspectManagedOutput(targetPath, content),
|
||||
});
|
||||
}
|
||||
}
|
||||
return outputs;
|
||||
}
|
||||
|
||||
function generatedHeader(profile: ProjectProfile): string {
|
||||
return [
|
||||
"<!--",
|
||||
@@ -607,6 +863,75 @@ async function inspectAgentsOutput(filePath: string, expected: string): Promise<
|
||||
return current.slice(0, 512).includes(GENERATED_MARKER) ? "stale" : "unmanaged";
|
||||
}
|
||||
|
||||
async function inspectManagedOutput(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, 1_024).includes(GENERATED_MARKER) ? "stale" : "unmanaged";
|
||||
}
|
||||
|
||||
async function renderManagedSkill(sourcePath: string, name: string): Promise<string> {
|
||||
const source = normalizeNewlines(await readStrictUtf8(sourcePath));
|
||||
if (!source.startsWith("---\n")) {
|
||||
return fail(`Managed skill must start with YAML front matter: ${sourcePath}`);
|
||||
}
|
||||
const closingIndex = source.indexOf("\n---\n", 4);
|
||||
if (closingIndex < 0) {
|
||||
return fail(`Managed skill has no closing YAML front matter: ${sourcePath}`);
|
||||
}
|
||||
const frontMatter = parseYaml(source.slice(4, closingIndex), `${sourcePath} front matter`);
|
||||
if (
|
||||
!isPlainObject(frontMatter)
|
||||
|| frontMatter.name !== name
|
||||
|| typeof frontMatter.description !== "string"
|
||||
|| frontMatter.description.trim().length === 0
|
||||
) {
|
||||
return fail(`Managed skill must declare matching name and non-empty description: ${sourcePath}`);
|
||||
}
|
||||
const frontMatterEnd = closingIndex + "\n---\n".length;
|
||||
const marker = [
|
||||
"<!--",
|
||||
GENERATED_MARKER,
|
||||
`Source: skills/${name}/SKILL.md`,
|
||||
"-->",
|
||||
"",
|
||||
].join("\n");
|
||||
return `${source.slice(0, frontMatterEnd)}\n${marker}${source.slice(frontMatterEnd).trimStart().trimEnd()}\n`;
|
||||
}
|
||||
|
||||
async function planManagedSkills(
|
||||
context: HarnessContext,
|
||||
repositoryPath: string,
|
||||
): Promise<SkillOutput[]> {
|
||||
const outputs: SkillOutput[] = [];
|
||||
for (const name of MANAGED_SKILL_NAMES) {
|
||||
const sourcePath = path.join(context.harnessRoot, "skills", name, "SKILL.md");
|
||||
const content = await renderManagedSkill(sourcePath, name);
|
||||
for (const root of MANAGED_SKILL_ROOTS) {
|
||||
const relativePath = `${root}/${name}/SKILL.md`;
|
||||
const targetPath = path.join(repositoryPath, ...relativePath.split("/"));
|
||||
outputs.push({
|
||||
name,
|
||||
sourcePath,
|
||||
relativePath,
|
||||
targetPath,
|
||||
content,
|
||||
state: await inspectManagedOutput(targetPath, content),
|
||||
});
|
||||
}
|
||||
}
|
||||
return outputs;
|
||||
}
|
||||
|
||||
async function inspectClaudeOutput(filePath: string): Promise<OutputState> {
|
||||
if (!(await pathExists(filePath))) {
|
||||
return "missing";
|
||||
@@ -682,11 +1007,14 @@ export async function planProject(
|
||||
const consumes = (profile.shared_contracts?.consumes ?? [])
|
||||
.map((id) => contractById(context, id))
|
||||
.sort((left, right) => left.order - right.order);
|
||||
const contractFragments = new Map<string, CompositionFragment>();
|
||||
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 fragment = await resolveConsumerFragment(context, contract, "shared-contract");
|
||||
contractFragments.set(contract.id, fragment);
|
||||
fragments.push(fragment);
|
||||
}
|
||||
|
||||
const providedPaths = new Set<string>();
|
||||
@@ -701,25 +1029,39 @@ export async function planProject(
|
||||
continue;
|
||||
}
|
||||
providedPaths.add(dedupeKey);
|
||||
fragments.push(await readRequiredFragment(consumerPath, "provided-contract", contract.id));
|
||||
const fragment = await readRequiredFragment(consumerPath, "provided-contract", contract.id);
|
||||
contractFragments.set(contract.id, fragment);
|
||||
fragments.push(fragment);
|
||||
}
|
||||
|
||||
fragments.push(
|
||||
await readRequiredFragment(
|
||||
path.join(repositoryPath, ".agent", "project.md"),
|
||||
"project",
|
||||
projectId,
|
||||
),
|
||||
const projectFragment = await readRequiredFragment(
|
||||
path.join(repositoryPath, ".agent", "project.md"),
|
||||
"project",
|
||||
projectId,
|
||||
);
|
||||
const projectReferences = await validateProjectReferences(
|
||||
repositoryPath,
|
||||
projectFragment.content,
|
||||
);
|
||||
fragments.push(projectFragment);
|
||||
|
||||
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 warnings: string[] = [];
|
||||
if (agentsBytes > WARNING_BYTES) {
|
||||
warnings.push(`Generated AGENTS.md is ${agentsBytes} bytes and exceeds the ${WARNING_BYTES}-byte warning threshold.`);
|
||||
}
|
||||
if (projectFragment.bytes > 4_096) {
|
||||
warnings.push(`.agent/project.md is ${projectFragment.bytes} bytes; keep the routing file near 2,000-3,000 bytes and move conditional detail to .agent/references.`);
|
||||
}
|
||||
for (const reference of projectReferences) {
|
||||
if (reference.bytes > 16_384) {
|
||||
warnings.push(`${reference.relativePath} is ${reference.bytes} bytes; consider splitting it by task scope.`);
|
||||
}
|
||||
}
|
||||
|
||||
const agentsPath = path.join(repositoryPath, "AGENTS.md");
|
||||
const claudePath = path.join(repositoryPath, "CLAUDE.md");
|
||||
@@ -727,6 +1069,16 @@ export async function planProject(
|
||||
agents: await inspectAgentsOutput(agentsPath, agentsContent),
|
||||
claude: await inspectClaudeOutput(claudePath),
|
||||
};
|
||||
const skills = await planManagedSkills(context, repositoryPath);
|
||||
const activeContracts = [...new Map(
|
||||
[...consumes, ...provides].map((contract) => [contract.id, contract]),
|
||||
).values()].sort((left, right) => left.order - right.order);
|
||||
const managedReferences = await planManagedContractReferences(
|
||||
context,
|
||||
repositoryPath,
|
||||
activeContracts,
|
||||
contractFragments,
|
||||
);
|
||||
|
||||
return {
|
||||
projectId,
|
||||
@@ -738,6 +1090,9 @@ export async function planProject(
|
||||
agentsBytes,
|
||||
warnings,
|
||||
output,
|
||||
skills,
|
||||
managedReferences,
|
||||
projectReferences,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -807,6 +1162,20 @@ export async function composeProject(
|
||||
if (plan.output.claude === "unmanaged") {
|
||||
fail(`Refusing to overwrite unmanaged CLAUDE.md in ${plan.repositoryPath}`);
|
||||
}
|
||||
const unmanagedSkill = plan.skills.find((skill) => skill.state === "unmanaged");
|
||||
if (unmanagedSkill) {
|
||||
fail(
|
||||
`Refusing to overwrite unmanaged skill ${unmanagedSkill.relativePath} in ${plan.repositoryPath}`,
|
||||
);
|
||||
}
|
||||
const unmanagedReference = plan.managedReferences.find(
|
||||
(reference) => reference.state === "unmanaged",
|
||||
);
|
||||
if (unmanagedReference) {
|
||||
fail(
|
||||
`Refusing to overwrite unmanaged shared reference ${unmanagedReference.relativePath} in ${plan.repositoryPath}`,
|
||||
);
|
||||
}
|
||||
|
||||
const writes: Array<{ target: string; content: string }> = [];
|
||||
const changed: string[] = [];
|
||||
@@ -818,12 +1187,29 @@ export async function composeProject(
|
||||
writes.push({ target: path.join(plan.repositoryPath, "CLAUDE.md"), content: plan.claudeContent });
|
||||
changed.push("CLAUDE.md");
|
||||
}
|
||||
for (const skill of plan.skills) {
|
||||
if (skill.state !== "current") {
|
||||
writes.push({ target: skill.targetPath, content: skill.content });
|
||||
changed.push(skill.relativePath);
|
||||
}
|
||||
}
|
||||
for (const reference of plan.managedReferences) {
|
||||
if (reference.state !== "current") {
|
||||
writes.push({ target: reference.targetPath, content: reference.content });
|
||||
changed.push(reference.relativePath);
|
||||
}
|
||||
}
|
||||
if (writes.length > 0) {
|
||||
await replaceFilesAtomically(writes);
|
||||
}
|
||||
|
||||
const refreshed = await planProject(harnessRoot, projectId);
|
||||
if (refreshed.output.agents !== "current" || refreshed.output.claude !== "current") {
|
||||
if (
|
||||
refreshed.output.agents !== "current"
|
||||
|| refreshed.output.claude !== "current"
|
||||
|| refreshed.skills.some((skill) => skill.state !== "current")
|
||||
|| refreshed.managedReferences.some((reference) => reference.state !== "current")
|
||||
) {
|
||||
fail(`Generated output verification failed for ${projectId}.`);
|
||||
}
|
||||
return { ...refreshed, changed };
|
||||
|
||||
@@ -47,6 +47,7 @@ async function createFixture(t) {
|
||||
path.join(packageRoot, "schemas", "workspace.schema.json"),
|
||||
path.join(harnessRoot, "schemas", "workspace.schema.json"),
|
||||
);
|
||||
await cp(path.join(packageRoot, "skills"), path.join(harnessRoot, "skills"), { recursive: true });
|
||||
|
||||
await writeText(
|
||||
path.join(harnessRoot, "workspace.yml"),
|
||||
@@ -70,6 +71,7 @@ contracts:
|
||||
- id: kri-ui-registry
|
||||
provider_project_id: kri-ui-registry
|
||||
consumer_file: .agent/consumer.md
|
||||
consumer_references_dir: .agent/consumer-references
|
||||
order: 100
|
||||
required_layers:
|
||||
- frontend
|
||||
@@ -94,7 +96,11 @@ contracts:
|
||||
|
||||
await writeText(
|
||||
path.join(providerRoot, ".agent", "consumer.md"),
|
||||
"## KRI UI Consumer Rule\n",
|
||||
"## KRI UI Consumer Rule\n\n- Read `.agent-harness/references/kri-ui-registry/components.md` before component work.\n",
|
||||
);
|
||||
await writeText(
|
||||
path.join(providerRoot, ".agent", "consumer-references", "components.md"),
|
||||
"# Shared component contract\n",
|
||||
);
|
||||
await writeText(
|
||||
path.join(providerRoot, ".agent", "profile.yml"),
|
||||
@@ -113,7 +119,7 @@ shared_contracts:
|
||||
- kri-ui-registry
|
||||
`,
|
||||
);
|
||||
await writeText(path.join(providerRoot, ".agent", "project.md"), "## Registry Project Rule\n");
|
||||
await writeText(path.join(providerRoot, ".agent", "project.md"), "## Registry Project Rule\n\n## Required Project References\n\n- No additional project references are required.\n");
|
||||
await writeText(
|
||||
path.join(appRoot, ".agent", "profile.yml"),
|
||||
`schema_version: 1
|
||||
@@ -144,7 +150,7 @@ migration:
|
||||
strategy: staged
|
||||
`,
|
||||
);
|
||||
await writeText(path.join(appRoot, ".agent", "project.md"), "## Project Rule\n");
|
||||
await writeText(path.join(appRoot, ".agent", "project.md"), "## Project Rule\n\n## Required Project References\n\n- No additional project references are required.\n");
|
||||
|
||||
await writeText(
|
||||
path.join(anotherAppRoot, ".agent", "profile.yml"),
|
||||
@@ -164,7 +170,7 @@ shared_contracts:
|
||||
- kri-ui-registry
|
||||
`,
|
||||
);
|
||||
await writeText(path.join(anotherAppRoot, ".agent", "project.md"), "## Another Project Rule\n");
|
||||
await writeText(path.join(anotherAppRoot, ".agent", "project.md"), "## Another Project Rule\n\n## Required Project References\n\n- No additional project references are required.\n");
|
||||
|
||||
await writeText(
|
||||
path.join(unrelatedRoot, ".agent", "profile.yml"),
|
||||
@@ -179,7 +185,7 @@ stack:
|
||||
- typescript
|
||||
`,
|
||||
);
|
||||
await writeText(path.join(unrelatedRoot, ".agent", "project.md"), "## Unrelated Rule\n");
|
||||
await writeText(path.join(unrelatedRoot, ".agent", "project.md"), "## Unrelated Rule\n\n## Required Project References\n\n- No additional project references are required.\n");
|
||||
|
||||
return { temporaryRoot, harnessRoot, appRoot, anotherAppRoot, providerRoot, unrelatedRoot };
|
||||
}
|
||||
@@ -204,17 +210,95 @@ test("composes fragments in deterministic order and verifies byte-for-byte outpu
|
||||
);
|
||||
assert.equal(plan.output.agents, "missing");
|
||||
assert.equal(plan.output.claude, "missing");
|
||||
assert.deepEqual(
|
||||
plan.skills.map((skill) => skill.state),
|
||||
["missing", "missing", "missing", "missing", "missing", "missing", "missing", "missing"],
|
||||
);
|
||||
assert.deepEqual(plan.managedReferences.map((reference) => reference.state), ["missing"]);
|
||||
|
||||
const result = await composeProject(harnessRoot, "sample-front");
|
||||
assert.deepEqual(result.changed, ["AGENTS.md", "CLAUDE.md"]);
|
||||
assert.deepEqual(result.changed, [
|
||||
"AGENTS.md",
|
||||
"CLAUDE.md",
|
||||
".agents/skills/attention-aware-communication/SKILL.md",
|
||||
".claude/skills/attention-aware-communication/SKILL.md",
|
||||
".agents/skills/karpathy-guidelines/SKILL.md",
|
||||
".claude/skills/karpathy-guidelines/SKILL.md",
|
||||
".agents/skills/project-reference-loader/SKILL.md",
|
||||
".claude/skills/project-reference-loader/SKILL.md",
|
||||
".agents/skills/verification-before-completion/SKILL.md",
|
||||
".claude/skills/verification-before-completion/SKILL.md",
|
||||
".agent-harness/references/kri-ui-registry/components.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");
|
||||
for (const skill of result.skills) {
|
||||
assert.equal(await readFile(skill.targetPath, "utf8"), skill.content);
|
||||
assert.match(skill.content, /GENERATED BY KRI AGENT HARNESS/);
|
||||
}
|
||||
for (const reference of result.managedReferences) {
|
||||
assert.equal(await readFile(reference.targetPath, "utf8"), reference.content);
|
||||
assert.match(reference.content, /GENERATED BY KRI AGENT HARNESS/);
|
||||
}
|
||||
|
||||
const verified = await verifyProject(harnessRoot, "sample-front");
|
||||
assert.deepEqual(verified.output, { agents: "current", claude: "current" });
|
||||
assert.deepEqual(
|
||||
verified.skills.map((skill) => skill.state),
|
||||
["current", "current", "current", "current", "current", "current", "current", "current"],
|
||||
);
|
||||
assert.deepEqual(verified.managedReferences.map((reference) => reference.state), ["current"]);
|
||||
assert.deepEqual((await composeProject(harnessRoot, "sample-front")).changed, []);
|
||||
});
|
||||
|
||||
test("refuses to overwrite an unmanaged skill", async (t) => {
|
||||
const { harnessRoot, appRoot } = await createFixture(t);
|
||||
await writeText(
|
||||
path.join(appRoot, ".agents", "skills", "karpathy-guidelines", "SKILL.md"),
|
||||
"# Hand-written skill\n",
|
||||
);
|
||||
|
||||
await assert.rejects(
|
||||
() => composeProject(harnessRoot, "sample-front"),
|
||||
/Refusing to overwrite unmanaged skill \.agents\/skills\/karpathy-guidelines\/SKILL\.md/,
|
||||
);
|
||||
});
|
||||
|
||||
test("validates routed project references and rejects unreferenced files", async (t) => {
|
||||
const { harnessRoot, appRoot } = await createFixture(t);
|
||||
await writeText(
|
||||
path.join(appRoot, ".agent", "references", "api-contract.md"),
|
||||
"# API contract\n",
|
||||
);
|
||||
await assert.rejects(
|
||||
() => planProject(harnessRoot, "sample-front"),
|
||||
/Project reference is not routed from \.agent\/project\.md/,
|
||||
);
|
||||
|
||||
await writeText(
|
||||
path.join(appRoot, ".agent", "project.md"),
|
||||
"## Project Rule\n\n## Required Project References\n\n- Before API work, read `.agent/references/api-contract.md`.\n",
|
||||
);
|
||||
const plan = await planProject(harnessRoot, "sample-front");
|
||||
assert.deepEqual(
|
||||
plan.projectReferences.map((reference) => reference.relativePath),
|
||||
[".agent/references/api-contract.md"],
|
||||
);
|
||||
});
|
||||
|
||||
test("refuses to overwrite an unmanaged shared reference", async (t) => {
|
||||
const { harnessRoot, appRoot } = await createFixture(t);
|
||||
await writeText(
|
||||
path.join(appRoot, ".agent-harness", "references", "kri-ui-registry", "components.md"),
|
||||
"# Hand-written shared reference\n",
|
||||
);
|
||||
|
||||
await assert.rejects(
|
||||
() => composeProject(harnessRoot, "sample-front"),
|
||||
/Refusing to overwrite unmanaged shared reference/,
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects nextjs without react", async (t) => {
|
||||
const { harnessRoot, appRoot } = await createFixture(t);
|
||||
const profilePath = path.join(appRoot, ".agent", "profile.yml");
|
||||
@@ -333,7 +417,7 @@ stack:
|
||||
);
|
||||
await writeText(
|
||||
path.join(projectRoot, ".agent", "project.md"),
|
||||
"## Legacy Korean Path Rule\n",
|
||||
"## Legacy Korean Path Rule\n\n## Required Project References\n\n- No additional project references are required.\n",
|
||||
);
|
||||
|
||||
const registration = await registerProject(
|
||||
@@ -345,19 +429,23 @@ stack:
|
||||
|
||||
const plan = await planProject(harnessRoot, "legacy-korean-path");
|
||||
assert.equal(path.normalize(plan.repositoryPath), path.normalize(projectRoot));
|
||||
assert.deepEqual((await composeProject(harnessRoot, "legacy-korean-path")).changed, [
|
||||
"AGENTS.md",
|
||||
"CLAUDE.md",
|
||||
]);
|
||||
const composed = await composeProject(harnessRoot, "legacy-korean-path");
|
||||
assert.deepEqual(composed.changed.slice(0, 2), ["AGENTS.md", "CLAUDE.md"]);
|
||||
assert.equal(composed.changed.length, 10);
|
||||
assert.deepEqual((await verifyProject(harnessRoot, "legacy-korean-path")).output, {
|
||||
agents: "current",
|
||||
claude: "current",
|
||||
});
|
||||
assert.ok(
|
||||
(await verifyProject(harnessRoot, "legacy-korean-path")).skills.every(
|
||||
(skill) => skill.state === "current",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
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(33_000)}\n`);
|
||||
await writeText(path.join(appRoot, ".agent", "project.md"), `## Project Rule\n\n${"x".repeat(33_000)}\n\n## Required Project References\n\n- No additional project references are required.\n`);
|
||||
|
||||
await assert.rejects(
|
||||
() => planProject(harnessRoot, "sample-front"),
|
||||
@@ -399,6 +487,19 @@ test("selects a contract provider first, sorts consumers, and composes only affe
|
||||
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.match(
|
||||
await readFile(
|
||||
path.join(
|
||||
affectedRoot,
|
||||
".agents",
|
||||
"skills",
|
||||
"verification-before-completion",
|
||||
"SKILL.md",
|
||||
),
|
||||
"utf8",
|
||||
),
|
||||
/GENERATED BY KRI AGENT HARNESS/,
|
||||
);
|
||||
}
|
||||
assert.equal(
|
||||
await readFile(path.join(unrelatedRoot, "AGENTS.md"), "utf8").catch(() => null),
|
||||
|
||||
@@ -52,3 +52,15 @@ projects:
|
||||
path: ____Project/260529_강원문화재단 모니터링/gwcf-review-back
|
||||
gwcf-review-front:
|
||||
path: ____Project/260529_강원문화재단 모니터링/gwcf-review-front
|
||||
epolicy-dash-back:
|
||||
path: ____Project/260812_한국에너지정보문화재단/epolicy-dash-back
|
||||
epolicy-dash-front:
|
||||
path: ____Project/260812_한국에너지정보문화재단/epolicy-dash-front
|
||||
ksif-manage-front:
|
||||
path: ____Project/260818_세종학당/ksif-manage-front
|
||||
ksif-manage-back:
|
||||
path: ____Project/260818_세종학당/ksif-manage-back
|
||||
k-musical-manage-front:
|
||||
path: ____Project/260903_K-뮤지컬/k-musical-manage-front
|
||||
k-musical-manage-back:
|
||||
path: ____Project/260903_K-뮤지컬/k-musical-manage-back
|
||||
|
||||
Reference in New Issue
Block a user