@autobe/agent
Version:
AI backend server code generator
163 lines (147 loc) • 15.4 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformAnalyzeSectionCrossFileReviewHistory = void 0;
const utils_1 = require("@autobe/utils");
const uuid_1 = require("uuid");
const yaml_1 = __importDefault(require("yaml"));
/**
* Transform histories for cross-file lightweight review of section metadata.
*
* This transformer provides ONLY section titles, keywords, and purposes from
* ALL files — NOT full content. This keeps the input well within context limits
* even with hundreds of sections.
*/
const transformAnalyzeSectionCrossFileReviewHistory = (_ctx, props) => {
var _a, _b, _c;
return {
histories: [
{
id: (0, uuid_1.v7)(),
created_at: new Date().toISOString(),
type: "systemMessage",
text: "<!--\nfilename: ANALYZE_SECTION_CROSS_FILE_REVIEW.md\n-->\n# Cross-File Semantic Consistency Reviewer\n\nYou are the **Cross-File Semantic Consistency Reviewer** for hierarchical requirements documentation.\nYour role is to validate **semantic consistency** ACROSS all files \u2014 meaning-level contradictions, terminology alignment, and logical coherence that cannot be detected by mechanical validation.\n\nMechanical checks (undefined references, naming inconsistencies, scope violations) are handled separately by programmatic validators. You focus ONLY on issues requiring human-like judgment.\n\nThis is the cross-file consistency check in the 3-step hierarchical generation process:\n1. **Module (#)** \u2192 Completed\n2. **Unit (##)** \u2192 Completed\n3. **Section (###)** \u2192 Per-file review done \u2192 **CROSS-FILE Consistency**: Validate uniformity across all files\n\n**Your decision is the final quality gate for cross-file semantic consistency.**\n\nThis agent achieves its goal through function calling. **Function calling is MANDATORY**.\n\n**EXECUTION STRATEGY**:\n1. **Analyze**: Review cross-file semantic consistency across all files\n2. **Write**: Call `process({ request: { type: \"write\", ... } })` with file results\n3. **Revise** (if needed): Submit another `write` to refine your review\n4. **Complete**: Call `process({ request: { type: \"complete\" } })` to finalize\n\nYou may submit `write` up to 3 times (initial + 2 revisions), but this is a safety cap \u2014 not a target. Review your output and call `complete` if satisfied. Revise only for critical flaws \u2014 structural errors, missing requirements, or broken logic that would cause downstream failure.\n\n**PROHIBITIONS**:\n- \u274C NEVER call `write` or `complete` in parallel with preliminary requests\n- \u274C NEVER call `complete` before submitting at least one `write`\n\n---\n\n## 1. Cross-File Semantic Consistency Focus\n\nYou receive section titles, keywords, and brief content summaries from ALL files.\n\n### 1.1. Logical Contradictions (CRITICAL)\n- File A says \"soft delete with retention period\" but File B says \"hard delete immediately\"\n- File A says \"email/password authentication\" but File B says \"anonymous session\"\n- **REJECT if two files make directly contradictory claims**\n\n### 1.2. Terminology Alignment (ADVISORY)\n- Same concepts should use identical terms across files\n- Flag differences in feedback, do NOT reject\n\n### 1.3. Value Consistency (REJECT for conflicts)\n- IF two files state different values for the same constraint, REJECT the non-canonical file\n- 02-domain-model is authoritative for business concept definitions\n- 01-actors-and-auth is authoritative for permissions\n- Non-canonical files (00, 03, 05) should reference constraints, not redefine them\n\n### 1.4. Actor Consistency (ADVISORY)\n- All files should use actor names defined in the scenario\n- Flag new or inconsistent actors in feedback, do NOT reject\n\n### 1.5. Completeness (ADVISORY)\n- Features described in one file should have corresponding coverage in related files\n- Error scenarios in 03-functional-requirements should have matching error conditions in 04-business-rules\n- Validation rules in 04-business-rules should reference concepts defined in 02-domain-model\n- Flag gaps in feedback, do NOT reject\n\n### 1.6. Concept Name Consistency (ADVISORY)\n- Same concept should use same PascalCase name across all files\n- Flag differences in feedback, do NOT reject\n\n### 1.7. Cross-File Hallucination Check (CRITICAL)\n- A hallucinated feature referenced consistently across multiple files is still a hallucination\n- If one file introduces a feature not in the scenario, reject it even if other files reference it\n- 05-non-functional: specific SLO numbers, infrastructure requirements not in user input \u2192 REJECT\n- **REJECT files containing requirements not traceable to user input**\n\n### 1.8. Cross-File Verbosity (REJECT for excessive cross-file duplication)\n- Same concept explained in detail in multiple files = cross-file duplication\n- Example: \"data isolation\" described in 01, 02, 04, 05 \u2192 define once in canonical file, reference elsewhere\n- **REJECT non-canonical files if the same concept is fully defined/explained in 3+ files** \u2014 only the canonical file should contain the full definition, other files should reference it briefly\n- Canonical sources: 01 for actors/permissions, 02 for domain concepts, 04 for business rules/errors, 05 for data policies\n- Brief one-sentence references to canonical definitions are acceptable and expected\n\n---\n\n## 2. Decision Guidelines\n\n**APPROVE** when: no logical contradictions between files, no invented features, no incompatible models.\n\n**APPROVE with feedback** when: terminology differences, value inconsistencies, minor gaps \u2014 provide constructive feedback but APPROVE.\n\n**REJECT** when ANY of these are true:\n- Non-English text detected\n- Two files make directly contradictory claims about the same concept/behavior\n- Two files use incompatible authentication or authorization models\n- A file references actors or features explicitly marked as out-of-scope\n- A file invents features or concepts not defined in the scenario\n- Two files state different values for the same constraint (REJECT the non-canonical file)\n- Excessive cross-file duplication: same concept fully defined in 3+ files (REJECT non-canonical files)\n\n---\n\n## 3. Output Format\n\n### 3.1. All Files Approved\n```typescript\n// Step 1: Submit review results\nprocess({\n thinking: \"All files use consistent models and concept names.\",\n request: {\n type: \"write\",\n fileResults: [\n { fileIndex: 0, approved: true, feedback: \"Consistent with all other files.\" },\n { fileIndex: 1, approved: true, feedback: \"Minor note: consider aligning terminology.\" }\n ]\n }\n});\n\n// Step 2: Finalize the loop\nprocess({\n thinking: \"Cross-file review complete. Approved all files \u2014 no contradictions or hallucinations found.\",\n request: { type: \"complete\" }\n});\n```\n\n### 3.2. Some Files Rejected (with granular identification)\n\n```typescript\n// Step 1: Submit review results\nprocess({\n thinking: \"File 1 describes hard delete, contradicting File 2's soft delete.\",\n request: {\n type: \"write\",\n fileResults: [\n { fileIndex: 0, approved: true, feedback: \"Consistent.\", rejectedModuleUnits: null },\n {\n fileIndex: 1,\n approved: false,\n feedback: \"Contradicts File 2: hard delete vs soft delete.\",\n rejectedModuleUnits: [\n { moduleIndex: 1, unitIndices: [0], feedback: \"Change to soft delete to match 02-domain-model.\" }\n ]\n }\n ]\n }\n});\n\n// Step 2: Finalize the loop\nprocess({\n thinking: \"Contradictions documented. Rejected file 1 for hard-delete vs soft-delete contradiction.\",\n request: { type: \"complete\" }\n});\n```\n\n---\n\n## 4. Final Checklist\n\n**Cross-File Consistency:**\n- [ ] ALL text is in English only\n- [ ] No logical contradictions between files\n- [ ] No incompatible authentication/authorization models\n- [ ] No value conflicts between files for the same constraint (REJECT non-canonical)\n- [ ] (Advisory) Core concept names are identical across files\n- [ ] (Advisory) No out-of-scope features mentioned\n- [ ] (Advisory) Terminology and naming conventions aligned\n\n**Prohibited Content (MUST REJECT if present in any file):**\n- [ ] Database schemas, ERD, indexes, cascade rules\n- [ ] API endpoints (`POST /users`, `GET /todos/{id}`)\n- [ ] HTTP methods or status codes\n- [ ] JSON request/response examples\n- [ ] Field types or length constraints\n- [ ] Technical error codes\n\n**Business Language Check:**\n- [ ] All files describe WHAT, not HOW\n- [ ] Consistent business terminology across files\n- [ ] No technical implementation details\n\n**Function Call:**\n- [ ] Submit review results via `write` (revise only for critical flaws)\n- [ ] Finalize via `complete` after last `write`" /* AutoBeSystemPromptConstant.ANALYZE_SECTION_CROSS_FILE_REVIEW */,
},
...((_b = (_a = props.preliminary) === null || _a === void 0 ? void 0 : _a.getHistories()) !== null && _b !== void 0 ? _b : []),
{
id: (0, uuid_1.v7)(),
created_at: new Date().toISOString(),
type: "assistantMessage",
text: utils_1.StringUtil.trim `
## Language
The language of the document is ${JSON.stringify((_c = props.scenario.language) !== null && _c !== void 0 ? _c : "en-US")}.
## All Files' Section Metadata for Cross-File Consistency Review
Below is lightweight metadata (titles, keywords, purposes) from ALL files.
Full content has already been validated in per-file review.
${props.allFileSummaries
.map(({ file, moduleEvent, unitEvents, sectionEvents, status }, fileIndex) => `
---
## File ${fileIndex + 1}: ${file.filename} [Status: ${status === "approved" ? "✅ Previously Approved" : status === "rewritten" ? "🔄 Rewritten" : "🆕 New"}]
**Title**: ${moduleEvent.title}
**Summary**: ${moduleEvent.summary}
${sectionEvents
.map((sectionsForModule, moduleIndex) => {
var _a;
const moduleSection = moduleEvent.moduleSections[moduleIndex];
const unitEvent = unitEvents[moduleIndex];
return `
### Module ${moduleIndex + 1}: ${(_a = moduleSection === null || moduleSection === void 0 ? void 0 : moduleSection.title) !== null && _a !== void 0 ? _a : "Unknown"}
${sectionsForModule
.map((sectionEvent, unitIndex) => {
var _a, _b, _c;
const unitSection = unitEvent === null || unitEvent === void 0 ? void 0 : unitEvent.unitSections[unitIndex];
return `
#### Unit ${moduleIndex + 1}.${unitIndex + 1}: ${(_a = unitSection === null || unitSection === void 0 ? void 0 : unitSection.title) !== null && _a !== void 0 ? _a : "Unknown"}
**Keywords**: ${(_c = (_b = unitSection === null || unitSection === void 0 ? void 0 : unitSection.keywords) === null || _b === void 0 ? void 0 : _b.join(", ")) !== null && _c !== void 0 ? _c : "None"}
Sections:
${sectionEvent.sectionSections
.map((section) => {
const attrKeys = extractYamlAttributeKeys(section.content);
return `- **${section.title}**${attrKeys ? ` [attrs: ${attrKeys}]` : ""}`;
})
.join("\n")}
`;
})
.join("\n")}
`;
})
.join("\n")}
`)
.join("\n")}
${props.mechanicalViolationSummary
? `
## Mechanical Validation Results (Already Addressed Separately)
The following mechanical issues have been detected and will be patched separately.
You do NOT need to flag these — focus only on semantic/logical consistency:
${props.mechanicalViolationSummary}
`
: ""}
${props.fileDecisions && props.fileDecisions.length > 0
? `
## Extracted Key Decisions Per File
Below are the key behavioral decisions extracted from each file.
Use these to verify cross-file consistency — same topic+decision should have the same value across files.
${props.fileDecisions
.filter((fd) => fd.decisions.length > 0)
.map((fd) => `**${fd.filename}**:\n${fd.decisions.map((d) => `- ${d.topic}.${d.decision} = "${d.value}" — ${d.evidence.slice(0, 100)}`).join("\n")}`)
.join("\n\n")}
`
: ""}
## Cross-File Semantic Consistency Criteria
Focus ONLY on issues requiring human-like judgment:
1. Are there logical contradictions between files?
2. Is terminology aligned (same concepts = same terms)?
3. Are authentication/authorization models compatible across files?
4. Are there features described in one file that conflict with another?
5. Do any files invent features not in the scenario?
`,
},
],
userMessage: "Review ALL files' section metadata for cross-file consistency and provide per-file approved/rejected verdicts.",
};
};
exports.transformAnalyzeSectionCrossFileReviewHistory = transformAnalyzeSectionCrossFileReviewHistory;
// ─── Internal helpers ───
const YAML_CODE_BLOCK_REGEX = /```yaml\n([\s\S]*?)```/g;
const BACKTICK_ENTITY_FIELD_REGEX = /`(\w+\.\w+)`/g;
/**
* Extract Entity.attribute keys from YAML spec blocks and backtick references.
*
* Returns a compact comma-separated string of attribute keys (e.g.,
* "User.status, User.email, Todo.title") for lightweight cross-file
* visibility.
*/
const extractYamlAttributeKeys = (content) => {
var _a;
const keys = new Set();
// Extract from YAML spec blocks
const yamlMatches = content.matchAll(YAML_CODE_BLOCK_REGEX);
for (const match of yamlMatches) {
const yamlContent = (_a = match[1]) !== null && _a !== void 0 ? _a : "";
try {
const parsed = yaml_1.default.parse(yamlContent);
if (parsed &&
typeof parsed === "object" &&
typeof parsed.entity === "string" &&
Array.isArray(parsed.attributes)) {
for (const attr of parsed.attributes) {
if (attr && typeof attr.name === "string") {
keys.add(`${parsed.entity}.${attr.name}`);
}
}
}
}
catch (_b) {
// skip parse errors
}
}
// Extract from backtick `Entity.field` references
const backtickMatches = content.matchAll(BACKTICK_ENTITY_FIELD_REGEX);
for (const match of backtickMatches) {
keys.add(match[1]);
}
return [...keys].join(", ");
};
//# sourceMappingURL=transformAnalyzeSectionCrossFileReviewHistory.js.map