Промты агентов перенесены в docs модуля (p-*.md внутри feature); прежняя версия читает approved, новая - proposed; тест промтов
All checks were successful
ci / test (push) Successful in 24s
ci / deploy (push) Successful in 1m34s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-16 21:34:18 +03:00
parent b4a2a2ca99
commit 63e7dd790b
34 changed files with 765 additions and 52 deletions

View File

@@ -1,12 +1,124 @@
import { readFileSync } from "node:fs";
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
/** Папка promts микросервиса (работает из src и из dist). */
export const promptsDir = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "promts");
/**
* Промты лежат в docs модуля, внутри feature, файлами `p-<имя>.md`:
* docs/<approved|proposed>/modules/khbuild_assistant_prep/<module>/<feature>/p-<имя>.md
* approved - промты прежней версии агента (все реальные менеджеры), proposed - новой версии (тестовый менеджер).
*
* Формат файла:
* - крупный промт (одним файлом): `# Название`, затем текст промта (в нём могут быть свои заголовки), затем необязательный `## Описание`;
* - мелкие фрагменты (несколько в файле): каждый - `# Название`, текст, необязательный `## Описание`. Текст фрагмента не содержит строк, начинающихся с `# `.
* Подстановки `{{имя}}` заменяются значениями из vars.
*/
export type PromptSide = "approved" | "proposed";
export function loadPrompt(name: string, vars: Record<string, string> = {}, dir: string = promptsDir): string {
let text = readFileSync(join(dir, name), "utf8").replace(/\r/g, "");
for (const [k, v] of Object.entries(vars)) text = text.split(`{{${k}}}`).join(v);
return text.trim();
const here = dirname(fileURLToPath(import.meta.url));
/** Корень docs репозитория (работает из src и из dist: .../packages/khbuild_assistant_prep/<src|dist>/agents -> корень). */
export const defaultDocsRoot = join(here, "..", "..", "..", "..", "docs");
export const PACKAGE_DOCS = "khbuild_assistant_prep";
export interface PromptPart {
title: string;
body: string;
description?: string;
}
const norm = (s: string) => s.replace(/\r/g, "");
/** Отделяет необязательный раздел `## Описание` (последняя строка ровно `## Описание`). */
function splitDescription(text: string): { body: string; description?: string } {
const lines = text.split("\n");
const i = lines.lastIndexOf("## Описание");
if (i < 0) return { body: text.trim() };
return { body: lines.slice(0, i).join("\n").trim(), description: lines.slice(i + 1).join("\n").trim() };
}
/** Крупный промт: первая строка `# Название`, остальное - промт (до `## Описание`). */
export function parsePromptFile(text: string): PromptPart {
const t = norm(text).trim();
const m = t.match(/^# (.+)\n/);
if (!m) throw new Error("в файле промта нет заголовка `# Название` первой строкой");
return { title: m[1]!.trim(), ...splitDescription(t.slice(m[0].length)) };
}
/** Мелкие фрагменты: каждый начинается строкой `# Название`. */
export function parseFragments(text: string): PromptPart[] {
const parts: PromptPart[] = [];
let title: string | null = null;
let buf: string[] = [];
const flush = () => {
if (title !== null) parts.push({ title, ...splitDescription(buf.join("\n")) });
};
for (const line of norm(text).split("\n")) {
const m = line.match(/^# (.+?)\s*$/);
if (m) {
flush();
title = m[1]!;
buf = [];
} else buf.push(line);
}
flush();
return parts;
}
export function fillVars(text: string, vars: Record<string, string>): string {
let out = text;
for (const [k, v] of Object.entries(vars)) out = out.split(`{{${k}}}`).join(v);
return out;
}
const found = new Map<string, string>();
/** Ищет файл `p-*.md` по имени в папке модулей пакета (любая глубина). */
export function findPromptFile(name: string, side: PromptSide, docsRoot: string = defaultDocsRoot): string {
const key = `${docsRoot}|${side}|${name}`;
const cached = found.get(key);
if (cached) return cached;
const root = join(docsRoot, side, "modules", PACKAGE_DOCS);
const walk = (dir: string): string | null => {
if (!existsSync(dir)) return null;
for (const n of readdirSync(dir)) {
const p = join(dir, n);
if (statSync(p).isDirectory()) {
const r = walk(p);
if (r) return r;
} else if (n === name) return p;
}
return null;
};
const p = walk(root);
if (!p) throw new Error(`промт ${name} не найден в ${root}`);
found.set(key, p);
return p;
}
/** Все файлы промтов `p-*.md` стороны (для проверок). */
export function listPromptFiles(side: PromptSide, docsRoot: string = defaultDocsRoot): string[] {
const root = join(docsRoot, side, "modules", PACKAGE_DOCS);
const out: string[] = [];
const walk = (dir: string) => {
if (!existsSync(dir)) return;
for (const n of readdirSync(dir)) {
const p = join(dir, n);
if (statSync(p).isDirectory()) walk(p);
else if (/^p-.+\.md$/.test(n)) out.push(p);
}
};
walk(root);
return out.sort();
}
/** Крупный промт целиком (с подстановками). */
export function loadPrompt(name: string, vars: Record<string, string> = {}, side: PromptSide = "approved", docsRoot?: string): string {
return fillVars(parsePromptFile(readFileSync(findPromptFile(name, side, docsRoot), "utf8")).body, vars);
}
/** Фрагмент из файла с несколькими промтами, по заголовку. */
export function loadFragment(file: string, title: string, vars: Record<string, string> = {}, side: PromptSide = "approved", docsRoot?: string): string {
const parts = parseFragments(readFileSync(findPromptFile(file, side, docsRoot), "utf8"));
const p = parts.find((x) => x.title === title);
if (!p) throw new Error(`в ${file} (${side}) нет фрагмента «${title}»`);
return fillVars(p.body, vars);
}

View File

@@ -4,6 +4,7 @@ import type { Logger, Pool } from "khb_common";
import { ClaudeError, type ClaudeResult, type ClaudeRunner, type ToolSet, type TurnTiming } from "./cli-runner.js";
import type { LiveRunner } from "./live-runner.js";
import { KeyedMutex, Semaphore } from "./pool.js";
import { loadFragment, type PromptSide } from "./prompts.js";
import { missingSections, parseSections } from "./sections.js";
import type { AgentSettings } from "../settings.js";
@@ -43,6 +44,9 @@ export interface AgentOutcome {
export const useLive = (ctx: Pick<AgentContext, "liveRunner" | "settings">, managerId: string): boolean =>
!!ctx.liveRunner && (ctx.settings.live?.managerIds ?? []).includes(managerId);
/** Откуда агент менеджера берёт промты: новая версия - proposed, прежняя - approved. */
export const promptSideFor = (ctx: Pick<AgentContext, "liveRunner" | "settings">, managerId: string): PromptSide => (useLive(ctx, managerId) ? "proposed" : "approved");
export const managerWorkDir = (s: AgentSettings, managerId: string) => join(s.workRoot, managerId);
/** Текущая память менеджера (создаёт пустую запись при первом обращении). */
@@ -162,7 +166,7 @@ export function runManagerAgent(
lastErr = `в ответе нет разделов: ${missing.map((m) => `## ${m}`).join(", ")}`;
await finishRun(ctx, runId, false, { durationMs: res.durationMs, costUsd: res.costUsd, error: lastErr, changes });
resume = true;
prompt = `Твой предыдущий ответ не принят: ${lastErr}. Исправь и выведи ответ ЦЕЛИКОМ в требуемом формате (разделы \`## Название\`), без пояснений вне разделов. Ничего повторно не выполняй в системах (JobTread и др.), только поправь формат.`;
prompt = loadFragment("p-result-validator.md", "Исправь формат ответа", { error: lastErr }, promptSideFor(ctx, opts.managerId));
}
throw fail(lastErr);
}),

View File

@@ -71,7 +71,7 @@ export async function buildStep2Prompt(ctx: AgentContext, managerId: string, pac
);
const mem = await loadMemory(ctx.pool, managerId);
return [
loadPrompt("step2_prepare.md"),
loadPrompt("p-step2-prepare.md"),
"",
"Не используй инструменты, только текст.",
"",