261006_01_ENH: 에이전트 참조 문서 합성 및 검증 기능 추가

This commit is contained in:
2026-10-06 10:19:14 +09:00
parent 74d8ec48d2
commit 4ec2ef8bb7
17 changed files with 1435 additions and 66 deletions

367
dist/cli.cjs vendored
View File

@@ -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) {