Agent Harness
Публичная копия обвязки агентной разработки: гейты, journeys, скиллы и шаблоны. Без ключей и личных данных.
Публичная копия обвязки агентной разработки: гейты, journeys, скиллы и шаблоны. Без ключей и личных данных.
Принят владельцем вручную — без оценки ИИ. Очки за вклад не начислены. Оценка восстановлена по объёму правки.
| +добавлено | import AxeBuilder from '@axe-core/playwright' |
| +добавлено | import { expect, test } from '@playwright/test' |
| +добавлено | import { openRoute } from './helpers' |
| +добавлено | import { routes } from './routes' |
| +добавлено | |
| +добавлено | const WCAG_TAGS = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa'] |
| +добавлено | const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select, textarea, [tabindex]:not([tabindex="-1"])' |
| +добавлено | // Framework dev overlays (Next.js, Vite) are not part of the product UI. |
| +добавлено | const DEV_OVERLAY = 'nextjs-portal, [data-nextjs-toast], [data-nextjs-dialog-overlay], vite-error-overlay' |
| +добавлено | |
| +добавлено | for (const route of routes) { |
| +добавлено | for (const colorScheme of ['light', 'dark'] as const) { |
| +добавлено | test(`${route.name} has no axe violations (${colorScheme}) @a11y`, async ({ page }, testInfo) => { |
| +добавлено | await page.emulateMedia({ colorScheme }) |
| +добавлено | await openRoute(page, route) |
| +добавлено | const results = await new AxeBuilder({ page }).withTags(WCAG_TAGS).exclude('[data-a11y-ignore]').exclude('nextjs-portal').analyze() |
| +добавлено | |
| +добавлено | await testInfo.attach('axe-results', { body: JSON.stringify(results.violations, null, 2), contentType: 'application/json' }) |
| +добавлено | const summary = results.violations.map((v) => `${v.impact} ${v.id}: ${v.help} (${v.nodes.length}) ${v.nodes[0]?.target.join(' ')}`) |
| +добавлено | expect(summary, 'axe WCAG 2.2 AA violations').toEqual([]) |
| +добавлено | }) |
| +добавлено | } |
| +добавлено | |
| +добавлено | test(`${route.name} keyboard focus is visible @a11y`, async ({ page }) => { |
| +добавлено | await openRoute(page, route) |
| +добавлено | const focusables = await page |
| +добавлено | .locator(`:is(${FOCUSABLE}):not(${DEV_OVERLAY}):not(${DEV_OVERLAY} *)`) |
| +добавлено | .count() |
| +добавлено | test.skip(focusables === 0, 'no focusable elements on this route') |
| +добавлено | |
| +добавлено | const steps = Math.min(focusables, 15) |
| +добавлено | const invisible: string[] = [] |
| +добавлено | for (let i = 0; i < steps; i += 1) { |
| +добавлено | await page.keyboard.press('Tab') |
| +добавлено | const info = await page.evaluate((overlay) => { |
| +добавлено | const el = document.activeElement as HTMLElement | null |
| +добавлено | if (!el || el === document.body || el.closest(overlay)) return null |
| +добавлено | const s = getComputedStyle(el) |
| +добавлено | const visible = (s.outlineStyle !== 'none' && parseFloat(s.outlineWidth) > 0) || s.boxShadow !== 'none' |
| +добавлено | return { visible, label: `${el.tagName.toLowerCase()}${el.id ? `#${el.id}` : ''} "${(el.getAttribute('aria-label') ?? el.textContent ?? '').trim().slice(0, 40)}"` } |
| +добавлено | }, DEV_OVERLAY) |
| +добавлено | if (info && !info.visible) invisible.push(info.label) |
| +добавлено | } |
| +добавлено | expect(invisible, 'focused elements without a visible focus indicator').toEqual([]) |
| +добавлено | }) |
| +добавлено | |
| +добавлено | test(`${route.name} respects prefers-reduced-motion @a11y`, async ({ page }) => { |
| +добавлено | await page.emulateMedia({ reducedMotion: 'reduce' }) |
| +добавлено | await openRoute(page, route) |
| +добавлено | const longAnimations = await page.evaluate(() => |
| +добавлено | document.getAnimations().filter((a) => { |
| +добавлено | const t = a.effect?.getComputedTiming() |
| +добавлено | return t && (t.iterations === Infinity || Number(t.duration) > 500) |
| +добавлено | }).length, |
| +добавлено | ) |
| +добавлено | expect(longAnimations, 'long or infinite animations while reduced motion is requested').toBe(0) |
| +добавлено | }) |
| +добавлено | } |
| +добавлено | import type { Page } from '@playwright/test' |
| +добавлено | import type { RouteCheck } from './routes' |
| +добавлено | |
| +добавлено | export async function openRoute(page: Page, route: RouteCheck) { |
| +добавлено | const response = await page.goto(route.path, { waitUntil: 'networkidle' }) |
| +добавлено | if (route.waitFor) await page.locator(route.waitFor).first().waitFor() |
| +добавлено | await page.evaluate(() => document.fonts.ready) |
| +добавлено | return response |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function collectConsoleErrors(page: Page) { |
| +добавлено | const errors: string[] = [] |
| +добавлено | page.on('console', (msg) => { |
| +добавлено | if (msg.type() === 'error') errors.push(msg.text()) |
| +добавлено | }) |
| +добавлено | page.on('pageerror', (err) => errors.push(err.message)) |
| +добавлено | return errors |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function horizontalOverflow(page: Page) { |
| +добавлено | return page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth) |
| +добавлено | } |
| +добавлено | // Every user-facing route the agents must keep healthy. Add a route here in the same |
| +добавлено | // change that creates the page; e2e, a11y and visual specs all iterate this list. |
| +добавлено | export type RouteCheck = { |
| +добавлено | path: string |
| +добавлено | name: string |
| +добавлено | waitFor?: string |
| +добавлено | skipVisual?: boolean |
| +добавлено | } |
| +добавлено | |
| +добавлено | export const routes: RouteCheck[] = [{ path: '/', name: 'home' }] |
| +добавлено | import { expect, test } from '@playwright/test' |
| +добавлено | import { collectConsoleErrors, horizontalOverflow, openRoute } from './helpers' |
| +добавлено | import { routes } from './routes' |
| +добавлено | |
| +добавлено | for (const route of routes) { |
| +добавлено | test(`${route.name} renders without errors @e2e`, async ({ page }) => { |
| +добавлено | const errors = collectConsoleErrors(page) |
| +добавлено | const response = await openRoute(page, route) |
| +добавлено | |
| +добавлено | expect(response?.status() ?? 0, 'HTTP status').toBeLessThan(400) |
| +добавлено | await expect(page.locator('main'), 'page has a <main> landmark').toHaveCount(1) |
| +добавлено | await expect(page.locator('h1'), 'page has exactly one <h1>').toHaveCount(1) |
| +добавлено | expect(await horizontalOverflow(page), 'no horizontal scroll').toBeLessThanOrEqual(0) |
| +добавлено | expect(errors, 'console errors').toEqual([]) |
| +добавлено | }) |
| +добавлено | |
| +добавлено | test(`${route.name} images load and have alt @e2e`, async ({ page }) => { |
| +добавлено | await openRoute(page, route) |
| +добавлено | const broken = await page.locator('img').evaluateAll((imgs) => |
| +добавлено | (imgs as HTMLImageElement[]).filter((img) => img.complete && img.naturalWidth === 0).map((img) => img.currentSrc || img.src), |
| +добавлено | ) |
| +добавлено | expect(broken, 'broken images').toEqual([]) |
| +добавлено | const missingAlt = await page.locator('img:not([alt])').count() |
| +добавлено | expect(missingAlt, 'images without alt attribute').toBe(0) |
| +добавлено | }) |
| +добавлено | } |
| +добавлено | import { expect, test } from '@playwright/test' |
| +добавлено | import { openRoute } from './helpers' |
| +добавлено | import { routes } from './routes' |
| +добавлено | |
| +добавлено | // Baselines are OS/browser specific. Create and update them only on the same platform |
| +добавлено | // as CI (or in the Playwright Docker image), and only with human approval. |
| +добавлено | for (const route of routes.filter((r) => !r.skipVisual)) { |
| +добавлено | for (const colorScheme of ['light', 'dark'] as const) { |
| +добавлено | test(`${route.name} matches baseline (${colorScheme}) @visual`, async ({ page }) => { |
| +добавлено | await page.emulateMedia({ colorScheme, reducedMotion: 'reduce' }) |
| +добавлено | await openRoute(page, route) |
| +добавлено | await expect(page).toHaveScreenshot(`${route.name}-${colorScheme}.png`, { |
| +добавлено | fullPage: true, |
| +добавлено | mask: [page.locator('[data-visual-mask]')], |
| +добавлено | }) |
| +добавлено | }) |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import '@testing-library/jest-dom/vitest' |
| +добавлено | import { cleanup } from '@testing-library/react' |
| +добавлено | import { afterEach } from 'vitest' |
| +добавлено | |
| +добавлено | afterEach(() => cleanup()) |
| +добавлено | #!/usr/bin/env node |
| +добавлено | // Architecture gate: module graph, layer boundaries, cycles, complexity budgets. |
| +добавлено | // Config: architecture.json | .agent-arch.json | ~/.agent-harness/architecture.json |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { parseArgs, list, readJson, readJsonc, writeJsonAtomic, wildcardToRegExp, stateDir, appendEvent, fail, homeDir } from './lib.mjs'; |
| +добавлено | |
| +добавлено | const SOURCE_EXT = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs']; |
| +добавлено | const DEFAULT_EXCLUDE = ['**/node_modules/**', '**/dist/**', '**/build/**', '**/.next/**', '**/.git/**', '**/.agent-state/**', '**/coverage/**']; |
| +добавлено | const DEFAULT_FAIL_ON = ['layer-violation', 'forbidden-import', 'cycle']; |
| +добавлено | |
| +добавлено | function toPosix(p) { |
| +добавлено | return p.split(path.sep).join('/'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function walk(dir, skip) { |
| +добавлено | const out = []; |
| +добавлено | if (!fs.existsSync(dir)) return out; |
| +добавлено | const stack = [dir]; |
| +добавлено | while (stack.length) { |
| +добавлено | const current = stack.pop(); |
| +добавлено | for (const entry of fs.readdirSync(current, { withFileTypes: true })) { |
| +добавлено | if (skip.has(entry.name)) continue; |
| +добавлено | const full = path.join(current, entry.name); |
| +добавлено | if (entry.isDirectory()) stack.push(full); |
| +добавлено | else if (entry.isFile()) out.push(full); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return out; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function loadConfig(cwd, explicit) { |
| +добавлено | if (explicit && explicit !== true) { |
| +добавлено | if (!fs.existsSync(explicit)) fail(`Config not found: ${explicit}`); |
| +добавлено | return { path: path.resolve(explicit), config: readJsonc(explicit) }; |
| +добавлено | } |
| +добавлено | const candidates = [ |
| +добавлено | path.join(cwd, 'architecture.json'), |
| +добавлено | path.join(cwd, '.agent-arch.json'), |
| +добавлено | path.join(cwd, 'architecture.jsonc'), |
| +добавлено | path.join(homeDir(), '.agent-harness', 'architecture.json'), |
| +добавлено | ]; |
| +добавлено | const found = candidates.find((p) => fs.existsSync(p)); |
| +добавлено | return found ? { path: found, config: readJsonc(found) } : null; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // Replace comments and string contents with spaces, preserving offsets and newlines, |
| +добавлено | // so brace matching and function detection are not confused by literals. |
| +добавлено | function sanitize(src) { |
| +добавлено | const out = src.split(''); |
| +добавлено | let i = 0; |
| +добавлено | const n = src.length; |
| +добавлено | let state = 'code'; |
| +добавлено | while (i < n) { |
| +добавлено | const ch = src[i]; |
| +добавлено | const next = src[i + 1]; |
| +добавлено | if (state === 'code') { |
| +добавлено | if (ch === '/' && next === '/') { |
| +добавлено | while (i < n && src[i] !== '\n') { out[i] = ' '; i += 1; } |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | if (ch === '/' && next === '*') { |
| +добавлено | out[i] = ' '; out[i + 1] = ' '; i += 2; |
| +добавлено | while (i < n && !(src[i] === '*' && src[i + 1] === '/')) { if (src[i] !== '\n') out[i] = ' '; i += 1; } |
| +добавлено | if (i < n) { out[i] = ' '; out[i + 1] = ' '; i += 2; } |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | if (ch === "'" || ch === '"' || ch === '`') { state = ch; out[i] = ' '; i += 1; continue; } |
| +добавлено | i += 1; |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | // inside a string |
| +добавлено | if (ch === '\\') { out[i] = ' '; if (i + 1 < n) out[i + 1] = ' '; i += 2; continue; } |
| +добавлено | if (ch === state) { out[i] = ' '; state = 'code'; i += 1; continue; } |
| +добавлено | if (ch !== '\n') out[i] = ' '; |
| +добавлено | i += 1; |
| +добавлено | } |
| +добавлено | return out.join(''); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const IMPORT_PATTERNS = [ |
| +добавлено | /\bimport\s+(?:[\s\S]*?\s+from\s+)?['"]([^'"]+)['"]/g, |
| +добавлено | /\bexport\s+(?:[\s\S]*?\s+from\s+)['"]([^'"]+)['"]/g, |
| +добавлено | /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g, |
| +добавлено | /\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g, |
| +добавлено | ]; |
| +добавлено | |
| +добавлено | function extractSpecifiers(src) { |
| +добавлено | const clean = sanitize(src); |
| +добавлено | // sanitize blanks string contents, so re-scan the original with literal positions |
| +добавлено | const specs = []; |
| +добавлено | for (const pattern of IMPORT_PATTERNS) { |
| +добавлено | pattern.lastIndex = 0; |
| +добавлено | let match; |
| +добавлено | while ((match = pattern.exec(src)) !== null) { |
| +добавлено | // a real statement keeps its keyword in the sanitized text; commented or stringified ones are blanked |
| +добавлено | if (clean[match.index] === ' ') continue; |
| +добавлено | specs.push(match[1]); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return [...new Set(specs)]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function packageName(spec) { |
| +добавлено | if (spec.startsWith('@')) return spec.split('/').slice(0, 2).join('/'); |
| +добавлено | return spec.split('/')[0]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function compileMatcher(pattern) { |
| +добавлено | const norm = toPosix(pattern).replace(/\/+$/, ''); |
| +добавлено | const re = wildcardToRegExp(norm); |
| +добавлено | const reDeep = wildcardToRegExp(`${norm}/**`); |
| +добавлено | return (rel) => re.test(rel) || reDeep.test(rel) || rel === norm; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function createResolver(cwd, aliases) { |
| +добавлено | const extCandidates = ['', ...SOURCE_EXT, ...SOURCE_EXT.map((e) => `/index${e}`)]; |
| +добавлено | return (fromRel, spec) => { |
| +добавлено | let base = null; |
| +добавлено | if (spec.startsWith('.')) { |
| +добавлено | base = path.resolve(path.dirname(path.join(cwd, fromRel)), spec); |
| +добавлено | } else { |
| +добавлено | for (const alias of aliases) { |
| +добавлено | const prefix = alias.prefix ?? ''; |
| +добавлено | if (prefix && spec.startsWith(prefix)) { |
| +добавлено | base = path.resolve(cwd, alias.target ?? '', spec.slice(prefix.length)); |
| +добавлено | break; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | if (!base) return { kind: 'external', name: packageName(spec) }; |
| +добавлено | for (const ext of extCandidates) { |
| +добавлено | const candidate = `${base}${ext}`; |
| +добавлено | if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) { |
| +добавлено | return { kind: 'internal', file: toPosix(path.relative(cwd, candidate)) }; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | const looksLikeAsset = /\.(css|scss|sass|less|json|svg|png|jpe?g|webp|gif|md|vue|svelte|astro|html)$/i.test(spec); |
| +добавлено | if (looksLikeAsset) return { kind: 'external', name: packageName(spec) }; |
| +добавлено | // The target may not exist yet (being written in this change): keep the intended path |
| +добавлено | // so layer and forbidden-import rules still apply to it. |
| +добавлено | return { kind: 'unresolved', spec, guess: toPosix(path.relative(cwd, base)).replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/, '') }; |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function findCycles(graph) { |
| +добавлено | let counter = 0; |
| +добавлено | const index = new Map(); |
| +добавлено | const low = new Map(); |
| +добавлено | const onStack = new Set(); |
| +добавлено | const stack = []; |
| +добавлено | const sccs = []; |
| +добавлено | const visit = (v) => { |
| +добавлено | index.set(v, counter); |
| +добавлено | low.set(v, counter); |
| +добавлено | counter += 1; |
| +добавлено | stack.push(v); |
| +добавлено | onStack.add(v); |
| +добавлено | for (const w of graph.get(v) ?? []) { |
| +добавлено | if (!index.has(w)) { |
| +добавлено | visit(w); |
| +добавлено | low.set(v, Math.min(low.get(v), low.get(w))); |
| +добавлено | } else if (onStack.has(w)) { |
| +добавлено | low.set(v, Math.min(low.get(v), index.get(w))); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | if (low.get(v) === index.get(v)) { |
| +добавлено | const scc = []; |
| +добавлено | let w; |
| +добавлено | do { |
| +добавлено | w = stack.pop(); |
| +добавлено | onStack.delete(w); |
| +добавлено | scc.push(w); |
| +добавлено | } while (w !== v); |
| +добавлено | const selfLoop = scc.length === 1 && (graph.get(scc[0]) ?? new Set()).has(scc[0]); |
| +добавлено | if (scc.length > 1 || selfLoop) sccs.push(scc.reverse()); |
| +добавлено | } |
| +добавлено | }; |
| +добавлено | for (const node of graph.keys()) if (!index.has(node)) visit(node); |
| +добавлено | return sccs; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function lineStartsOf(src) { |
| +добавлено | const starts = [0]; |
| +добавлено | for (let i = 0; i < src.length; i += 1) if (src[i] === '\n') starts.push(i + 1); |
| +добавлено | return starts; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function lineAt(starts, offset) { |
| +добавлено | let lo = 0; |
| +добавлено | let hi = starts.length - 1; |
| +добавлено | while (lo < hi) { |
| +добавлено | const mid = (lo + hi + 1) >> 1; |
| +добавлено | if (starts[mid] <= offset) lo = mid; |
| +добавлено | else hi = mid - 1; |
| +добавлено | } |
| +добавлено | return lo + 1; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function countTopLevelCommas(params) { |
| +добавлено | let depth = 0; |
| +добавлено | let count = 0; |
| +добавлено | let hasContent = false; |
| +добавлено | for (const ch of params) { |
| +добавлено | if ('([{<'.includes(ch)) depth += 1; |
| +добавлено | else if (')]}>'.includes(ch)) depth -= 1; |
| +добавлено | else if (ch === ',' && depth === 0) count += 1; |
| +добавлено | if (!/\s/.test(ch)) hasContent = true; |
| +добавлено | } |
| +добавлено | return hasContent ? count + 1 : 0; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const FN_PATTERNS = [ |
| +добавлено | /(?:^|[^.\w$])(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)\s*(?:<[^>()]*>)?\s*\(([^()]*)\)/g, |
| +добавлено | /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+?)?=\s*(?:async\s*)?(?:\(([^()]*)\)|([A-Za-z_$][\w$]*))\s*(?::[^={]+?)?=>\s*\{/g, |
| +добавлено | ]; |
| +добавлено | |
| +добавлено | function scanFunctions(rel, src, budgets) { |
| +добавлено | const clean = sanitize(src); |
| +добавлено | const starts = lineStartsOf(src); |
| +добавлено | const issues = []; |
| +добавлено | const seen = new Set(); |
| +добавлено | for (const pattern of FN_PATTERNS) { |
| +добавлено | pattern.lastIndex = 0; |
| +добавлено | let match; |
| +добавлено | while ((match = pattern.exec(clean)) !== null) { |
| +добавлено | const name = match[1] ?? '<anonymous>'; |
| +добавлено | const open = clean.indexOf('{', match.index + match[0].length - 1); |
| +добавлено | if (open === -1) continue; |
| +добавлено | let depth = 0; |
| +добавлено | let end = -1; |
| +добавлено | let maxDepth = 0; |
| +добавлено | for (let i = open; i < clean.length; i += 1) { |
| +добавлено | if (clean[i] === '{') { depth += 1; maxDepth = Math.max(maxDepth, depth); } |
| +добавлено | else if (clean[i] === '}') { depth -= 1; if (depth === 0) { end = i; break; } } |
| +добавлено | } |
| +добавлено | if (end === -1) continue; |
| +добавлено | const startLine = lineAt(starts, match.index); |
| +добавлено | const endLine = lineAt(starts, end); |
| +добавлено | const key = `${startLine}:${name}`; |
| +добавлено | if (seen.has(key)) continue; |
| +добавлено | seen.add(key); |
| +добавлено | const length = endLine - startLine + 1; |
| +добавлено | const paramsRaw = match[2] ?? (match[3] ? match[3] : ''); |
| +добавлено | const paramCount = match[3] ? 1 : countTopLevelCommas(paramsRaw); |
| +добавлено | const where = `${rel}:${startLine}`; |
| +добавлено | if (budgets.maxFunctionLines && length > budgets.maxFunctionLines) { |
| +добавлено | issues.push({ rule: 'function-too-long', file: rel, line: startLine, message: `${where} ${name} is ${length} lines (budget ${budgets.maxFunctionLines})` }); |
| +добавлено | } |
| +добавлено | if (budgets.maxParams && paramCount > budgets.maxParams) { |
| +добавлено | issues.push({ rule: 'too-many-params', file: rel, line: startLine, message: `${where} ${name} takes ${paramCount} parameters (budget ${budgets.maxParams})` }); |
| +добавлено | } |
| +добавлено | if (budgets.maxNesting && maxDepth - 1 > budgets.maxNesting) { |
| +добавлено | issues.push({ rule: 'deep-nesting', file: rel, line: startLine, message: `${where} ${name} nests ${maxDepth - 1} levels (budget ${budgets.maxNesting})` }); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return issues; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function analyze(cwd, config) { |
| +добавлено | const extensions = config.extensions ?? SOURCE_EXT; |
| +добавлено | const excludeMatchers = (config.exclude ?? DEFAULT_EXCLUDE).map(compileMatcher); |
| +добавлено | const skipDirs = new Set(['node_modules', '.git', '.agent-state', 'dist', 'build', '.next', 'coverage']); |
| +добавлено | const files = walk(cwd, skipDirs) |
| +добавлено | .map((f) => toPosix(path.relative(cwd, f))) |
| +добавлено | .filter((rel) => extensions.includes(path.extname(rel)) && !excludeMatchers.some((m) => m(rel))); |
| +добавлено | |
| +добавлено | const layers = (config.layers ?? []).map((layer) => ({ ...layer, match: compileMatcher(layer.path) })); |
| +добавлено | const layerOf = (rel) => { |
| +добавлено | let best = null; |
| +добавлено | for (const layer of layers) { |
| +добавлено | if (layer.match(rel) && (!best || layer.path.length > best.path.length)) best = layer; |
| +добавлено | } |
| +добавлено | return best; |
| +добавлено | }; |
| +добавлено | const forbidden = (config.forbidden ?? []).map((rule) => ({ |
| +добавлено | ...rule, |
| +добавлено | fromMatch: compileMatcher(rule.from), |
| +добавлено | toMatch: compileMatcher(rule.to), |
| +добавлено | })); |
| +добавлено | const forbiddenPackages = config.forbiddenPackages ?? []; |
| +добавлено | const resolver = createResolver(cwd, config.aliases ?? []); |
| +добавлено | const graph = new Map(); |
| +добавлено | const externalDeps = new Map(); |
| +добавлено | const issues = []; |
| +добавлено | const budgets = config.budgets ?? {}; |
| +добавлено | const stats = { files: files.length, edges: 0, external: 0 }; |
| +добавлено | |
| +добавлено | const boundaryIssues = (rel, targetRel) => { |
| +добавлено | const hitForbidden = forbidden.find((r) => r.fromMatch(rel) && r.toMatch(targetRel)); |
| +добавлено | if (hitForbidden) { |
| +добавлено | return [{ rule: 'forbidden-import', severity: 'error', file: rel, line: 0, message: `${rel} -> ${targetRel}${hitForbidden.reason ? ` — ${hitForbidden.reason}` : ''}` }]; |
| +добавлено | } |
| +добавлено | const fromLayer = layerOf(rel); |
| +добавлено | const toLayer = layerOf(targetRel); |
| +добавлено | if (fromLayer && toLayer && fromLayer.name !== toLayer.name) { |
| +добавлено | const allowed = fromLayer.mayImport ?? []; |
| +добавлено | if (!allowed.includes(toLayer.name)) { |
| +добавлено | return [{ rule: 'layer-violation', severity: 'error', file: rel, line: 0, message: `${fromLayer.name} (${rel}) -> ${toLayer.name} (${targetRel}); allowed: ${allowed.length ? allowed.join(', ') : 'none'}` }]; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return []; |
| +добавлено | }; |
| +добавлено | |
| +добавлено | for (const rel of files) { |
| +добавлено | const src = fs.readFileSync(path.join(cwd, rel), 'utf8'); |
| +добавлено | if (budgets.maxFileLines) { |
| +добавлено | const lines = src.split('\n').length; |
| +добавлено | if (lines > budgets.maxFileLines) { |
| +добавлено | issues.push({ rule: 'file-too-long', severity: 'warning', file: rel, line: 1, message: `${rel} is ${lines} lines (budget ${budgets.maxFileLines})` }); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | issues.push(...scanFunctions(rel, src, budgets).map((i) => ({ ...i, severity: 'warning' }))); |
| +добавлено | |
| +добавлено | const targets = new Set(); |
| +добавлено | for (const spec of extractSpecifiers(src)) { |
| +добавлено | for (const rule of forbiddenPackages) { |
| +добавлено | if (wildcardToRegExp(rule.pattern ?? rule).test(spec) || wildcardToRegExp(rule.pattern ?? rule).test(packageName(spec))) { |
| +добавлено | issues.push({ rule: 'forbidden-package', severity: 'error', file: rel, line: 0, message: `${rel} imports "${spec}"${rule.reason ? ` — ${rule.reason}` : ''}` }); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | const resolved = resolver(rel, spec); |
| +добавлено | if (resolved.kind === 'internal') { |
| +добавлено | targets.add(resolved.file); |
| +добавлено | stats.edges += 1; |
| +добавлено | issues.push(...boundaryIssues(rel, resolved.file)); |
| +добавлено | } else if (resolved.kind === 'external') { |
| +добавлено | const normalized = resolved.name.replace(/^node:/, ''); |
| +добавлено | const bucket = externalDeps.get(normalized) ?? new Set(); |
| +добавлено | bucket.add(rel); |
| +добавлено | externalDeps.set(normalized, bucket); |
| +добавлено | } else if (resolved.kind === 'unresolved') { |
| +добавлено | issues.push({ rule: 'unresolved-import', severity: 'warning', file: rel, line: 0, message: `${rel} imports "${resolved.spec}" which does not resolve to a project file` }); |
| +добавлено | issues.push(...boundaryIssues(rel, resolved.guess)); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | graph.set(rel, targets); |
| +добавлено | } |
| +добавлено | |
| +добавлено | stats.external = externalDeps.size; |
| +добавлено | if (config.cycles !== false) { |
| +добавлено | for (const scc of findCycles(graph)) { |
| +добавлено | if (config.cycles?.maxLength && scc.length <= config.cycles.maxLength) continue; |
| +добавлено | issues.push({ rule: 'cycle', severity: 'error', file: scc[0], line: 0, message: `import cycle (${scc.length}): ${scc.join(' -> ')} -> ${scc[0]}` }); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return { files, graph, issues, externalDeps, stats, layers: layers.map((l) => ({ name: l.name, path: l.path, mayImport: l.mayImport ?? [] })) }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function summarize(result, config) { |
| +добавлено | const failOn = config.failOn ?? DEFAULT_FAIL_ON; |
| +добавлено | const errors = result.issues.filter((i) => i.severity === 'error' || failOn.includes(i.rule)); |
| +добавлено | const warnings = result.issues.filter((i) => !errors.includes(i)); |
| +добавлено | const byRule = {}; |
| +добавлено | for (const issue of errors) byRule[issue.rule] = (byRule[issue.rule] ?? 0) + 1; |
| +добавлено | return { errors, warnings, byRule }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function printIssues(issues, label) { |
| +добавлено | if (!issues.length) return; |
| +добавлено | console.log(`\n${label}:`); |
| +добавлено | for (const issue of issues) { |
| +добавлено | console.log(` [${issue.rule}] ${issue.message}`); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | function printMap(result, cwd) { |
| +добавлено | console.log(`Modules: ${result.stats.files} imports: ${result.stats.edges} external packages: ${result.stats.external}`); |
| +добавлено | for (const layer of result.layers) { |
| +добавлено | const count = result.files.filter((f) => compileMatcher(layer.path)(f)).length; |
| +добавлено | console.log(` ${layer.name.padEnd(16)} ${layer.path.padEnd(28)} files=${count} mayImport=[${layer.mayImport.join(', ')}]`); |
| +добавлено | } |
| +добавлено | if (result.externalDeps.size) { |
| +добавлено | console.log('\nExternal dependencies:'); |
| +добавлено | for (const [name, users] of [...result.externalDeps.entries()].sort((a, b) => b[1].size - a[1].size)) { |
| +добавлено | console.log(` ${name.padEnd(28)} used by ${users.size}`); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | function main() { |
| +добавлено | const { positional, flags } = parseArgs(process.argv.slice(2)); |
| +добавлено | const command = positional[0] ?? 'check'; |
| +добавлено | const cwd = path.resolve(flags.cwd && flags.cwd !== true ? flags.cwd : process.cwd()); |
| +добавлено | const loaded = loadConfig(cwd, flags.config); |
| +добавлено | |
| +добавлено | if (command === 'init') { |
| +добавлено | const target = path.resolve(cwd, (flags.out && flags.out !== true ? flags.out : 'architecture.json')); |
| +добавлено | if (fs.existsSync(target) && !flags.force) fail(`${target} exists; pass --force to overwrite`); |
| +добавлено | const srcDir = ['src', 'app', 'lib'].find((d) => fs.existsSync(path.join(cwd, d))) ?? 'src'; |
| +добавлено | const template = { |
| +добавлено | layers: [ |
| +добавлено | { name: 'domain', path: `${srcDir}/domain`, mayImport: ['domain'] }, |
| +добавлено | { name: 'application', path: `${srcDir}/application`, mayImport: ['domain', 'application'] }, |
| +добавлено | { name: 'infrastructure', path: `${srcDir}/infrastructure`, mayImport: ['domain', 'application', 'infrastructure'] }, |
| +добавлено | { name: 'ui', path: `${srcDir}/ui`, mayImport: ['application', 'domain', 'ui'] }, |
| +добавлено | ], |
| +добавлено | forbidden: [ |
| +добавлено | { from: `${srcDir}/ui/**`, to: `${srcDir}/infrastructure/**`, reason: 'UI must not reach persistence directly' }, |
| +добавлено | { from: `${srcDir}/domain/**`, to: `${srcDir}/ui/**`, reason: 'domain must not know about UI' }, |
| +добавлено | ], |
| +добавлено | budgets: { maxFileLines: 400, maxFunctionLines: 60, maxParams: 5, maxNesting: 4 }, |
| +добавлено | cycles: true, |
| +добавлено | failOn: DEFAULT_FAIL_ON, |
| +добавлено | }; |
| +добавлено | if (fs.existsSync(path.join(cwd, 'tsconfig.json'))) template.aliases = [{ prefix: '@/', target: `${srcDir}/` }]; |
| +добавлено | writeJsonAtomic(target, template); |
| +добавлено | console.log(`Wrote ${path.relative(cwd, target)} — adjust layer paths, then run: node ~/.agent-harness/tools/arch.mjs check`); |
| +добавлено | return 0; |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (!loaded) { |
| +добавлено | console.error('error: no architecture config (architecture.json / .agent-arch.json)'); |
| +добавлено | console.error('Run: node ~/.agent-harness/tools/arch.mjs init'); |
| +добавлено | return 2; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const result = analyze(cwd, loaded.config); |
| +добавлено | const { errors, warnings, byRule } = summarize(result, loaded.config); |
| +добавлено | |
| +добавлено | if (!result.files.length) { |
| +добавлено | printMap(result, cwd); |
| +добавлено | console.error(`error: no source files matched ${loaded.config.extensions?.join(', ') ?? SOURCE_EXT.join(', ')} under ${cwd}`); |
| +добавлено | console.error('Architecture is unverified (empty map proves nothing), not passed.'); |
| +добавлено | return 2; |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (command === 'map') { |
| +добавлено | printMap(result, cwd); |
| +добавлено | printIssues(warnings, 'Warnings'); |
| +добавлено | printIssues(errors, 'Errors'); |
| +добавлено | return errors.length ? 1 : 0; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const runId = new Date().toISOString().replace(/[:.]/g, '-'); |
| +добавлено | const artifactDir = path.join(stateDir(cwd), 'artifacts'); |
| +добавлено | const summary = { |
| +добавлено | runId, |
| +добавлено | cwd, |
| +добавлено | config: loaded.path, |
| +добавлено | verdict: errors.length ? 'failed' : 'passed', |
| +добавлено | stats: result.stats, |
| +добавлено | byRule, |
| +добавлено | errors, |
| +добавлено | warnings, |
| +добавлено | finishedAt: new Date().toISOString(), |
| +добавлено | }; |
| +добавлено | writeJsonAtomic(path.join(artifactDir, `arch-${runId}.json`), summary); |
| +добавлено | writeJsonAtomic(path.join(artifactDir, 'arch-latest.json'), summary); |
| +добавлено | appendEvent(cwd, { type: 'arch.checked', runId, verdict: summary.verdict, errors: errors.length }); |
| +добавлено | |
| +добавлено | if (flags.json) { |
| +добавлено | console.log(JSON.stringify(summary, null, 2)); |
| +добавлено | } else { |
| +добавлено | printMap(result, cwd); |
| +добавлено | printIssues(errors, 'Errors'); |
| +добавлено | printIssues(warnings, 'Warnings (non-blocking)'); |
| +добавлено | console.log(`\nVerdict: ${summary.verdict.toUpperCase()} artifacts: ${toPosix(path.relative(cwd, path.join(artifactDir, 'arch-latest.json')))}`); |
| +добавлено | } |
| +добавлено | return errors.length ? 1 : 0; |
| +добавлено | } |
| +добавлено | |
| +добавлено | process.exitCode = main(); |
| +добавлено | #!/usr/bin/env node |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { spawnSync } from 'node:child_process'; |
| +добавлено | import { HARNESS_ROOT, parseArgs, list, readJson, writeJsonAtomic, stateDir, fail } from './lib.mjs'; |
| +добавлено | |
| +добавлено | function harnessCommit() { |
| +добавлено | const rev = spawnSync('git', ['rev-parse', '--short', 'HEAD'], { cwd: HARNESS_ROOT, encoding: 'utf8' }); |
| +добавлено | if (rev.status !== 0) return null; |
| +добавлено | const dirty = spawnSync('git', ['status', '--porcelain'], { cwd: HARNESS_ROOT, encoding: 'utf8' }).stdout.trim(); |
| +добавлено | return `${rev.stdout.trim()}${dirty ? '-dirty' : ''}`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const tasksFile = fs.existsSync(path.join(HARNESS_ROOT, 'bench', 'tasks.json')) ? path.join(HARNESS_ROOT, 'bench', 'tasks.json') : fail('bench/tasks.json not found'); |
| +добавлено | const { tasks } = readJson(tasksFile); |
| +добавлено | const runsDir = path.join(stateDir(), 'bench'); |
| +добавлено | const { positional, flags } = parseArgs(process.argv.slice(2)); |
| +добавлено | const [command, id] = positional; |
| +добавлено | |
| +добавлено | function task(taskId) { |
| +добавлено | return tasks.find((t) => t.id === taskId) ?? fail(`Unknown bench task ${taskId}`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (command === 'list' || !command) { |
| +добавлено | for (const t of tasks) console.log(`${t.id.padEnd(20)} ${t.title} (${t.checks.length} checks)`); |
| +добавлено | } else if (command === 'start') { |
| +добавлено | const t = task(id); |
| +добавлено | if (!flags.agent || !flags.model) fail('--agent pi|opencode and --model <id> are required for comparable runs'); |
| +добавлено | const run = { task: t.id, agent: flags.agent, model: flags.model, harness: readJson(path.join(HARNESS_ROOT, 'harness.json')).version, harnessCommit: harnessCommit(), node: process.versions.node, platform: process.platform, startedAt: new Date().toISOString(), checks: Object.fromEntries(t.checks.map((c) => [c, null])) }; |
| +добавлено | const file = path.join(runsDir, `${t.id}-${Date.now()}.json`); |
| +добавлено | writeJsonAtomic(file, run); |
| +добавлено | console.log(`Run file: ${file}\n${t.setup ? `\nSetup: ${t.setup}\n` : ''}\nPrompt:\n${t.prompt}\n\nChecks:\n${t.checks.map((c, i) => ` ${i + 1}. ${c}`).join('\n')}`); |
| +добавлено | } else if (command === 'score') { |
| +добавлено | const file = flags.run; |
| +добавлено | if (!file || file === true) fail('--run <run-file> is required'); |
| +добавлено | const run = readJson(file); |
| +добавлено | const keys = Object.keys(run.checks); |
| +добавлено | const pick = (v) => list(v).map((n) => keys[Number(n) - 1] ?? fail(`No check #${n}`)); |
| +добавлено | for (const k of pick(flags.pass)) run.checks[k] = true; |
| +добавлено | for (const k of pick(flags.fail)) run.checks[k] = false; |
| +добавлено | run.note = flags.note ?? run.note ?? null; |
| +добавлено | run.scoredAt = new Date().toISOString(); |
| +добавлено | writeJsonAtomic(file, run); |
| +добавлено | const passed = Object.values(run.checks).filter((v) => v === true).length; |
| +добавлено | console.log(`${run.task}: ${passed}/${keys.length}${Object.values(run.checks).includes(null) ? ' (some checks unscored)' : ''}`); |
| +добавлено | } else if (command === 'report') { |
| +добавлено | if (!fs.existsSync(runsDir)) fail('No runs yet'); |
| +добавлено | for (const f of fs.readdirSync(runsDir).filter((n) => n.endsWith('.json')).sort()) { |
| +добавлено | const r = readJson(path.join(runsDir, f)); |
| +добавлено | const vals = Object.values(r.checks); |
| +добавлено | console.log(`${r.task.padEnd(20)} ${r.agent.padEnd(9)} ${r.model.padEnd(24)} v${r.harness}${r.harnessCommit ? `@${r.harnessCommit}` : ''} ${vals.filter((v) => v === true).length}/${vals.length}${vals.includes(null) ? '*' : ''}`); |
| +добавлено | } |
| +добавлено | } else { |
| +добавлено | console.log('Usage: node bench.mjs list | start <id> --agent pi|opencode --model <id> | score --run <file> --pass 1,2 --fail 3 [--note ""] | report'); |
| +добавлено | process.exit(1); |
| +добавлено | } |
| +добавлено | #!/usr/bin/env node |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { parseArgs, readJson, writeJsonAtomic, walkFiles, stateDir, appendEvent } from './lib.mjs'; |
| +добавлено | |
| +добавлено | const { flags } = parseArgs(process.argv.slice(2)); |
| +добавлено | const cwd = path.resolve(flags.cwd && flags.cwd !== true ? flags.cwd : process.cwd()); |
| +добавлено | const rel = (f) => path.relative(cwd, f).split(path.sep).join('/'); |
| +добавлено | |
| +добавлено | const pkg = readJson(path.join(cwd, 'package.json'), {}); |
| +добавлено | const deps = { ...pkg.dependencies, ...pkg.devDependencies }; |
| +добавлено | const has = (name) => (name in deps ? deps[name] : null); |
| +добавлено | const pick = (names) => names.filter((n) => has(n)).map((n) => `${n}@${deps[n]}`); |
| +добавлено | |
| +добавлено | const stack = { |
| +добавлено | framework: pick(['next', 'nuxt', '@sveltejs/kit', 'astro', '@remix-run/react', 'react-router', 'vite']), |
| +добавлено | ui: pick(['react', 'vue', 'svelte', 'solid-js', 'preact']), |
| +добавлено | styling: pick(['tailwindcss', '@tailwindcss/postcss', 'styled-components', '@emotion/react', 'sass', '@vanilla-extract/css']), |
| +добавлено | primitives: pick(['@radix-ui/react-dialog', 'radix-ui', '@headlessui/react', '@ark-ui/react', 'react-aria-components', '@base-ui-components/react']), |
| +добавлено | icons: pick(['lucide-react', '@heroicons/react', 'react-icons', '@tabler/icons-react', '@phosphor-icons/react', '@radix-ui/react-icons']), |
| +добавлено | data: pick(['swr', '@tanstack/react-query', 'zustand', 'jotai', '@reduxjs/toolkit']), |
| +добавлено | forms: pick(['react-hook-form', 'zod', 'valibot', '@conform-to/react']), |
| +добавлено | motion: pick(['framer-motion', 'motion', 'gsap']), |
| +добавлено | i18n: pick(['next-intl', 'i18next', 'react-i18next', '@lingui/core']), |
| +добавлено | tests: pick(['vitest', 'jest', '@testing-library/react', '@playwright/test', '@axe-core/playwright', '@lhci/cli', '@storybook/react']), |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const files = walkFiles(cwd).filter((f) => !rel(f).startsWith('.agent-')); |
| +добавлено | const shadcn = readJson(path.join(cwd, 'components.json'), null); |
| +добавлено | |
| +добавлено | const uiDirs = ['components/ui', 'src/components/ui', 'app/components/ui'].map((d) => path.join(cwd, d)).filter((d) => fs.existsSync(d)); |
| +добавлено | const uiComponents = uiDirs.flatMap((d) => fs.readdirSync(d).filter((f) => /\.(tsx|jsx|vue|svelte)$/.test(f)).map((f) => f.replace(/\.\w+$/, ''))); |
| +добавлено | const componentFiles = files.filter((f) => /\/components\//.test(rel(f)) && !/\/components\/ui\//.test(rel(f)) && /\.(tsx|jsx|vue|svelte)$/.test(f)); |
| +добавлено | |
| +добавлено | const cssFiles = files.filter((f) => f.endsWith('.css')); |
| +добавлено | const tokens = { root: {}, dark: {}, theme: {} }; |
| +добавлено | let tailwindMode = fs.readdirSync(cwd).some((f) => /^tailwind\.config\./.test(f)) ? 'v3 (tailwind.config)' : null; |
| +добавлено | for (const file of cssFiles) { |
| +добавлено | const css = fs.readFileSync(file, 'utf8'); |
| +добавлено | if (/@import\s+["']tailwindcss["']/.test(css)) tailwindMode = 'v4 (@import "tailwindcss" + @theme)'; |
| +добавлено | for (const [scope, re] of [ |
| +добавлено | ['root', /:root\s*\{([^}]*)\}/g], |
| +добавлено | ['dark', /\.dark\s*\{([^}]*)\}/g], |
| +добавлено | ['theme', /@theme(?:\s+inline)?\s*\{([^}]*)\}/g], |
| +добавлено | ]) { |
| +добавлено | for (const block of css.matchAll(re)) { |
| +добавлено | for (const decl of block[1].matchAll(/(--[\w-]+)\s*:\s*([^;]+);/g)) tokens[scope][decl[1]] = decl[2].trim(); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | const fonts = new Set(); |
| +добавлено | for (const f of files.filter((x) => /\.(tsx|jsx|ts|js)$/.test(x) && /layout|_app|root/.test(path.basename(x)))) { |
| +добавлено | const src = fs.readFileSync(f, 'utf8'); |
| +добавлено | for (const m of src.matchAll(/import\s*\{([^}]+)\}\s*from\s*["']next\/font\/(google|local)["']/g)) for (const n of m[1].split(',')) fonts.add(`${n.trim()} (${m[2]})`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const DRIFT_RULES = [ |
| +добавлено | { id: 'hex-color', re: /#[0-9a-fA-F]{3,8}\b/g, why: 'raw hex instead of a token' }, |
| +добавлено | { id: 'palette-class', re: /\b(?:bg|text|border|ring|fill|stroke|from|to|via)-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d{2,3}\b/g, why: 'palette color instead of semantic token' }, |
| +добавлено | { id: 'arbitrary-value', re: /\b[a-z-]+-\[[^\]\s]+\]/g, why: 'arbitrary Tailwind value' }, |
| +добавлено | { id: 'inline-style', re: /style=\{\{/g, why: 'inline style object' }, |
| +добавлено | { id: 'white-black', re: /\b(?:bg|text|border)-(?:white|black)\b/g, why: 'white/black instead of background/foreground' }, |
| +добавлено | ]; |
| +добавлено | const drift = Object.fromEntries(DRIFT_RULES.map((r) => [r.id, { count: 0, why: r.why, files: {} }])); |
| +добавлено | for (const f of files.filter((x) => /\.(tsx|jsx|vue|svelte)$/.test(x))) { |
| +добавлено | const src = fs.readFileSync(f, 'utf8'); |
| +добавлено | for (const r of DRIFT_RULES) { |
| +добавлено | const n = (src.match(r.re) ?? []).length; |
| +добавлено | if (!n) continue; |
| +добавлено | drift[r.id].count += n; |
| +добавлено | drift[r.id].files[rel(f)] = n; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | const topFiles = (files) => Object.entries(files).sort((a, b) => b[1] - a[1]).slice(0, 5).map(([f, n]) => `${f} (${n})`).join(', '); |
| +добавлено | |
| +добавлено | const map = { |
| +добавлено | generatedAt: new Date().toISOString(), |
| +добавлено | cwd, |
| +добавлено | stack, |
| +добавлено | tailwind: tailwindMode, |
| +добавлено | shadcn: shadcn ? { style: shadcn.style ?? null, baseColor: shadcn.tailwind?.baseColor ?? null, aliases: shadcn.aliases ?? null } : null, |
| +добавлено | uiComponents, |
| +добавлено | featureComponents: componentFiles.map(rel), |
| +добавлено | tokens, |
| +добавлено | fonts: [...fonts], |
| +добавлено | drift: Object.fromEntries(Object.entries(drift).map(([k, v]) => [k, { count: v.count, why: v.why, top: topFiles(v.files) }])), |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const line = (label, values) => `- **${label}:** ${values.length ? values.join(', ') : '—'}`; |
| +добавлено | const tokenList = (obj) => Object.keys(obj).length ? Object.keys(obj).join(' ') : '—'; |
| +добавлено | const md = `# Design map |
| +добавлено | |
| +добавлено | Generated ${map.generatedAt} by design-map.mjs. Read before writing UI. Reuse what is here; add a token or primitive only when nothing fits, and say so in the handoff. |
| +добавлено | |
| +добавлено | ## Stack |
| +добавлено | ${Object.entries(stack).map(([k, v]) => line(k, v)).join('\n')} |
| +добавлено | - **tailwind:** ${tailwindMode ?? '—'} |
| +добавлено | - **shadcn:** ${shadcn ? `style=${map.shadcn.style}, baseColor=${map.shadcn.baseColor}` : '—'} |
| +добавлено | - **fonts:** ${map.fonts.join(', ') || '—'} |
| +добавлено | |
| +добавлено | ## Primitives (reuse, do not duplicate) |
| +добавлено | ${uiComponents.length ? uiComponents.map((c) => `\`${c}\``).join(' ') : '— (no components/ui)'} |
| +добавлено | |
| +добавлено | ## Feature components |
| +добавлено | ${map.featureComponents.length ? map.featureComponents.slice(0, 60).map((c) => `- ${c}`).join('\n') : '—'}${map.featureComponents.length > 60 ? `\n- … ${map.featureComponents.length - 60} more` : ''} |
| +добавлено | |
| +добавлено | ## Tokens |
| +добавлено | - **:root** ${tokenList(tokens.root)} |
| +добавлено | - **.dark** ${tokenList(tokens.dark)} |
| +добавлено | - **@theme** ${tokenList(tokens.theme)} |
| +добавлено | |
| +добавлено | ## Drift (lower is better; a diff must not raise these) |
| +добавлено | | rule | count | why | top files | |
| +добавлено | |---|---|---|---| |
| +добавлено | ${Object.entries(map.drift).map(([k, v]) => `| ${k} | ${v.count} | ${v.why} | ${v.top || '—'} |`).join('\n')} |
| +добавлено | `; |
| +добавлено | |
| +добавлено | const outDir = stateDir(cwd); |
| +добавлено | fs.mkdirSync(outDir, { recursive: true }); |
| +добавлено | fs.writeFileSync(path.join(outDir, 'design-map.md'), md); |
| +добавлено | writeJsonAtomic(path.join(outDir, 'design-map.json'), map); |
| +добавлено | appendEvent(cwd, { type: 'design-map.generated', primitives: uiComponents.length, drift: Object.fromEntries(Object.entries(map.drift).map(([k, v]) => [k, v.count])) }); |
| +добавлено | |
| +добавлено | if (flags.compare && flags.compare !== true) { |
| +добавлено | const before = readJson(path.resolve(flags.compare), null); |
| +добавлено | if (!before) { |
| +добавлено | console.error(`Cannot read ${flags.compare}`); |
| +добавлено | process.exit(1); |
| +добавлено | } |
| +добавлено | const worse = Object.entries(map.drift).filter(([k, v]) => v.count > (before.drift?.[k]?.count ?? 0)); |
| +добавлено | for (const [k, v] of Object.entries(map.drift)) console.log(`${k.padEnd(16)} ${String(before.drift?.[k]?.count ?? 0).padStart(5)} -> ${String(v.count).padStart(5)}`); |
| +добавлено | console.log(worse.length ? `\nDrift increased: ${worse.map(([k]) => k).join(', ')}` : '\nNo drift increase.'); |
| +добавлено | process.exit(worse.length ? 1 : 0); |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (flags.json) console.log(JSON.stringify(map, null, 2)); |
| +добавлено | else console.log(`${md}\nSaved: ${rel(path.join(outDir, 'design-map.md'))}`); |
| +добавлено | #!/usr/bin/env node |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { spawnSync } from 'node:child_process'; |
| +добавлено | import { HARNESS_ROOT, homeDir, parseArgs, readJsonc, readJson, sha256 } from './lib.mjs'; |
| +добавлено | import { loadManifest, validateSkillsDir, parity } from './skills.mjs'; |
| +добавлено | import { scanFiles } from './policy.mjs'; |
| +добавлено | |
| +добавлено | const { flags } = parseArgs(process.argv.slice(2)); |
| +добавлено | const FRONTEND_MCP = ['playwright', 'chrome-devtools', 'context7']; |
| +добавлено | const home = homeDir(); |
| +добавлено | const results = []; |
| +добавлено | const add = (level, area, message) => results.push({ level, area, message }); |
| +добавлено | |
| +добавлено | function bin(name, args = ['--version']) { |
| +добавлено | const res = spawnSync(name, args, { encoding: 'utf8', shell: process.platform === 'win32', timeout: 15000 }); |
| +добавлено | if (res.error || res.status !== 0) return null; |
| +добавлено | return (res.stdout || res.stderr).trim().split('\n')[0]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const nodeMajor = Number(process.versions.node.split('.')[0]); |
| +добавлено | add(nodeMajor >= 20 ? 'ok' : 'error', 'node', `v${process.versions.node}${nodeMajor >= 20 ? '' : ' (need >= 20)'}`); |
| +добавлено | |
| +добавлено | for (const [name, level, why] of [ |
| +добавлено | ['git', 'error', 'worktrees, review diff, release gate'], |
| +добавлено | ['ssh', 'warn', 'VPS tasks'], |
| +добавлено | ['npx', 'warn', 'MCP servers (searxng, playwright)'], |
| +добавлено | ['uvx', 'warn', 'mcp-server-fetch'], |
| +добавлено | ['pi', 'warn', 'Pi agent'], |
| +добавлено | ['opencode', 'warn', 'OpenCode agent'], |
| +добавлено | ]) { |
| +добавлено | const version = bin(name, name === 'ssh' ? ['-V'] : ['--version']); |
| +добавлено | add(version ? 'ok' : level, name, version ?? `not found (${why})`); |
| +добавлено | } |
| +добавлено | const pms = ['pnpm', 'npm', 'yarn', 'bun'].filter((pm) => bin(pm)); |
| +добавлено | add(pms.length ? 'ok' : 'error', 'package-managers', pms.join(', ') || 'none found'); |
| +добавлено | |
| +добавлено | const manifest = loadManifest(); |
| +добавлено | const skillIssues = [ |
| +добавлено | ...validateSkillsDir(path.join(HARNESS_ROOT, manifest.paths.piSkills)), |
| +добавлено | ...validateSkillsDir(path.join(HARNESS_ROOT, manifest.paths.opencodeSkills)), |
| +добавлено | ...parity(manifest), |
| +добавлено | ]; |
| +добавлено | for (const i of skillIssues) add(i.level, 'skills', `${i.where}: ${i.message}`); |
| +добавлено | if (!skillIssues.some((i) => i.level === 'error')) add('ok', 'skills', 'frontmatter + Pi/OpenCode parity'); |
| +добавлено | |
| +добавлено | const installed = readJson(path.join(home, '.agent-harness', 'installed.json'), null); |
| +добавлено | if (!installed) add('warn', 'install', 'harness not installed in home (node tools/install.mjs)'); |
| +добавлено | else { |
| +добавлено | const drift = installed.files.filter((f) => !fs.existsSync(f.path) || sha256(f.path) !== f.sha256); |
| +добавлено | add(drift.length ? 'warn' : 'ok', 'install', drift.length ? `${drift.length} installed file(s) changed since install: ${drift.slice(0, 3).map((d) => d.path).join(', ')}` : `v${installed.version}, ${installed.files.length} files intact`); |
| +добавлено | if (installed.version !== manifest.version) add('warn', 'install', `installed ${installed.version}, harness is ${manifest.version}: reinstall`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | add(fs.existsSync(path.join(home, 'AGENTS.md')) ? 'ok' : 'warn', 'memory', fs.existsSync(path.join(home, 'AGENTS.md')) ? '~/AGENTS.md present' : '~/AGENTS.md missing'); |
| +добавлено | if (fs.existsSync(path.join(home, 'AGENTS.md.harness-new'))) add('warn', 'memory', '~/AGENTS.md.harness-new waits for a manual merge'); |
| +добавлено | |
| +добавлено | const ocConfig = ['opencode.jsonc', 'opencode.json'].map((f) => path.join(home, '.config', 'opencode', f)).find((f) => fs.existsSync(f)); |
| +добавлено | if (!ocConfig) add('warn', 'opencode-config', 'no ~/.config/opencode/opencode.json(c)'); |
| +добавлено | else { |
| +добавлено | try { |
| +добавлено | const cfg = readJsonc(ocConfig); |
| +добавлено | const mcp = cfg.mcp ?? {}; |
| +добавлено | if (mcp.servers) add('warn', 'opencode-config', 'uses "mcp.servers": the official schema expects mcp.<name> directly. Confirm with `opencode mcp list` on your build.'); |
| +добавлено | const entries = Object.entries(mcp.servers ?? mcp); |
| +добавлено | for (const [name, server] of entries) { |
| +добавлено | if (server.disabled !== undefined) add('warn', 'opencode-config', `mcp ${name}: "disabled" is not in the official schema, use "enabled": false`); |
| +добавлено | const cmd = Array.isArray(server.command) ? server.command : []; |
| +добавлено | const viaShell = /^(bash|sh|zsh|cmd|powershell|pwsh)(\.exe)?$/i.test(String(cmd[0] ?? '')) && cmd.some((a) => /^-\w*c$/.test(String(a))); |
| +добавлено | const substFields = [server.environment ?? {}, ...(viaShell ? [] : cmd.slice(1))]; |
| +добавлено | if (JSON.stringify(substFields).includes('${')) add('warn', 'opencode-config', `mcp ${name}: "\${VAR}" is not expanded by OpenCode, use "{env:VAR}"`); |
| +добавлено | } |
| +добавлено | add('ok', 'opencode-config', `${path.basename(ocConfig)} parsed, ${entries.length} MCP server(s)`); |
| +добавлено | const names = entries.map(([n]) => n); |
| +добавлено | const lacking = FRONTEND_MCP.filter((n) => !names.includes(n)); |
| +добавлено | if (lacking.length) add('warn', 'opencode-config', `frontend MCP missing: ${lacking.join(', ')} (see opencode/opencode.jsonc.example)`); |
| +добавлено | if (!cfg.permission) add('warn', 'opencode-config', 'no "permission" block: dangerous commands run without approval (node tools/policy.mjs opencode-permission)'); |
| +добавлено | } catch (error) { |
| +добавлено | add('error', 'opencode-config', `${ocConfig}: ${error.message}`); |
| +добавлено | } |
| +добавлено | const leaks = scanFiles([ocConfig]); |
| +добавлено | if (leaks.length) add('error', 'secrets', `${ocConfig} contains ${leaks.length} plaintext secret(s); move them to env and reference {env:VAR}`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const piSettings = path.join(home, '.pi', 'agent', 'settings.json'); |
| +добавлено | if (fs.existsSync(piSettings)) { |
| +добавлено | try { |
| +добавлено | const s = readJson(piSettings); |
| +добавлено | const missing = ['npm:pi-subagents', 'npm:pi-mcp-adapter', 'npm:pi-web-access'].filter((p) => !(s.packages ?? []).includes(p)); |
| +добавлено | add(missing.length ? 'warn' : 'ok', 'pi-config', missing.length ? `missing packages: ${missing.join(', ')}` : 'required packages listed'); |
| +добавлено | const piMcp = path.join(home, '.config', 'mcp', 'mcp.json'); |
| +добавлено | const piServers = Object.keys(readJson(piMcp, {}).mcpServers ?? {}); |
| +добавлено | const piMissing = FRONTEND_MCP.filter((n) => !piServers.includes(n)); |
| +добавлено | add(piMissing.length ? 'warn' : 'ok', 'pi-mcp', fs.existsSync(piMcp) ? (piMissing.length ? `~/.config/mcp/mcp.json lacks: ${piMissing.join(', ')}` : `${piServers.length} server(s) incl. frontend set`) : 'no ~/.config/mcp/mcp.json (pi-mcp-adapter has no servers)'); |
| +добавлено | } catch (error) { |
| +добавлено | add('error', 'pi-config', error.message); |
| +добавлено | } |
| +добавлено | } else add('warn', 'pi-config', 'no ~/.pi/agent/settings.json'); |
| +добавлено | |
| +добавлено | for (const [name, why] of [['TAVILY_API_KEY', 'tavily MCP stays off'], ['CONTEXT7_API_KEY', 'context7 works with lower rate limits']]) add(process.env[name] ? 'ok' : 'warn', 'env', `${name} ${process.env[name] ? 'set' : `not set (${why})`}`); |
| +добавлено | |
| +добавлено | const templatesDir = path.join(HARNESS_ROOT, 'templates', 'frontend'); |
| +добавлено | add(fs.existsSync(path.join(templatesDir, 'playwright.config.ts')) ? 'ok' : 'error', 'templates', fs.existsSync(templatesDir) ? 'frontend templates present' : `missing ${templatesDir}`); |
| +добавлено | const chrome = ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser'].map((b) => bin(b)).find(Boolean); |
| +добавлено | add(chrome ? 'ok' : 'warn', 'chrome', chrome ?? 'no Chrome/Chromium in PATH (chrome-devtools MCP, lhci need one; playwright installs its own)'); |
| +добавлено | |
| +добавлено | const sshConfig = path.join(home, '.ssh', 'config'); |
| +добавлено | if (fs.existsSync(sshConfig)) { |
| +добавлено | const hosts = fs.readFileSync(sshConfig, 'utf8').split('\n').filter((l) => /^\s*Host\s+(?!\*)/.test(l)).length; |
| +добавлено | add(hosts ? 'ok' : 'warn', 'ssh', `${hosts} host alias(es) in ~/.ssh/config`); |
| +добавлено | } else add('warn', 'ssh', 'no ~/.ssh/config (VPS work needs host aliases + keys)'); |
| +добавлено | |
| +добавлено | async function probe(url) { |
| +добавлено | try { |
| +добавлено | const res = await fetch(url, { signal: AbortSignal.timeout(2500) }); |
| +добавлено | return res.status; |
| +добавлено | } catch { |
| +добавлено | return null; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | const searx = flags.searxng && flags.searxng !== true ? flags.searxng : 'http://127.0.0.1:8080'; |
| +добавлено | const status = await probe(`${searx}/search?q=ping&format=json`); |
| +добавлено | add(status === 200 ? 'ok' : 'warn', 'searxng', status === 200 ? `${searx} answers JSON` : `${searx} ${status ? `HTTP ${status} (enable json format in settings.yml?)` : 'unreachable'}`); |
| +добавлено | |
| +добавлено | if (flags.mcp) { |
| +добавлено | const out = spawnSync('opencode', ['mcp', 'list'], { encoding: 'utf8', timeout: 60000, shell: process.platform === 'win32' }); |
| +добавлено | if (out.error || out.status !== 0) add('warn', 'mcp-live', `opencode mcp list failed: ${(out.stderr || out.error?.message || '').trim().split('\n')[0]}`); |
| +добавлено | else for (const line of out.stdout.split('\n').filter((l) => l.trim())) add(/✗|fail|error/i.test(line) ? 'error' : 'ok', 'mcp-live', line.trim()); |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (flags.json) console.log(JSON.stringify(results, null, 2)); |
| +добавлено | else { |
| +добавлено | const icon = { ok: 'OK ', warn: 'WARN', error: 'FAIL' }; |
| +добавлено | for (const r of results) console.log(`${icon[r.level]} ${r.area.padEnd(16)} ${r.message}`); |
| +добавлено | const errors = results.filter((r) => r.level === 'error').length; |
| +добавлено | const warns = results.filter((r) => r.level === 'warn').length; |
| +добавлено | console.log(`\n${errors} error(s), ${warns} warning(s).${flags.mcp ? '' : ' Add --mcp for a live MCP check.'}`); |
| +добавлено | } |
| +добавлено | process.exit(results.some((r) => r.level === 'error') ? 1 : 0); |
| +добавлено | { |
| +добавлено | "runId": "2026-11-05T05-22-39-926Z", |
| +добавлено | "cwd": "<HOME>\\.agent-harness\\tools\\fixtures\\arch\\clean", |
| +добавлено | "config": "<HOME>\\.agent-harness\\tools\\fixtures\\arch\\clean\\architecture.json", |
| +добавлено | "verdict": "passed", |
| +добавлено | "stats": { |
| +добавлено | "files": 5, |
| +добавлено | "edges": 7, |
| +добавлено | "external": 0 |
| +добавлено | }, |
| +добавлено | "byRule": {}, |
| +добавлено | "errors": [], |
| +добавлено | "warnings": [], |
| +добавлено | "finishedAt": "2026-11-05T05:22:39.932Z" |
| +добавлено | } |
| +добавлено | { |
| +добавлено | "runId": "2026-11-05T05-23-06-663Z", |
| +добавлено | "cwd": "<HOME>\\.agent-harness\\tools\\fixtures\\arch\\clean", |
| +добавлено | "config": "<HOME>\\.agent-harness\\tools\\fixtures\\arch\\clean\\architecture.json", |
| +добавлено | "verdict": "passed", |
| +добавлено | "stats": { |
| +добавлено | "files": 5, |
| +добавлено | "edges": 7, |
| +добавлено | "external": 0 |
| +добавлено | }, |
| +добавлено | "byRule": {}, |
| +добавлено | "errors": [], |
| +добавлено | "warnings": [], |
| +добавлено | "finishedAt": "2026-11-05T05:23:06.664Z" |
| +добавлено | } |
| +добавлено | { |
| +добавлено | "runId": "2026-11-05T05-23-12-588Z", |
| +добавлено | "cwd": "<HOME>\\.agent-harness\\tools\\fixtures\\arch\\clean", |
| +добавлено | "config": "<HOME>\\.agent-harness\\tools\\fixtures\\arch\\clean\\architecture.json", |
| +добавлено | "verdict": "passed", |
| +добавлено | "stats": { |
| +добавлено | "files": 5, |
| +добавлено | "edges": 7, |
| +добавлено | "external": 0 |
| +добавлено | }, |
| +добавлено | "byRule": {}, |
| +добавлено | "errors": [], |
| +добавлено | "warnings": [], |
| +добавлено | "finishedAt": "2026-11-05T05:23:12.590Z" |
| +добавлено | } |
| +добавлено | { |
| +добавлено | "runId": "2026-11-05T05-24-25-217Z", |
| +добавлено | "cwd": "<HOME>\\.agent-harness\\tools\\fixtures\\arch\\clean", |
| +добавлено | "config": "<HOME>\\.agent-harness\\tools\\fixtures\\arch\\clean\\architecture.json", |
| +добавлено | "verdict": "passed", |
| +добавлено | "stats": { |
| +добавлено | "files": 5, |
| +добавлено | "edges": 7, |
| +добавлено | "external": 0 |
| +добавлено | }, |
| +добавлено | "byRule": {}, |
| +добавлено | "errors": [], |
| +добавлено | "warnings": [], |
| +добавлено | "finishedAt": "2026-11-05T05:24:25.218Z" |
| +добавлено | } |
| +добавлено | { |
| +добавлено | "runId": "2026-11-05T05-24-32-631Z", |
| +добавлено | "cwd": "<HOME>\\.agent-harness\\tools\\fixtures\\arch\\clean", |
| +добавлено | "config": "<HOME>\\.agent-harness\\tools\\fixtures\\arch\\clean\\architecture.json", |
| +добавлено | "verdict": "passed", |
| +добавлено | "stats": { |
| +добавлено | "files": 5, |
| +добавлено | "edges": 7, |
| +добавлено | "external": 0 |
| +добавлено | }, |
| +добавлено | "byRule": {}, |
| +добавлено | "errors": [], |
| +добавлено | "warnings": [], |
| +добавлено | "finishedAt": "2026-11-05T05:24:32.632Z" |
| +добавлено | } |
| +добавлено | { |
| +добавлено | "runId": "2026-11-05T05-25-15-444Z", |
| +добавлено | "cwd": "<HOME>\\.agent-harness\\tools\\fixtures\\arch\\clean", |
| +добавлено | "config": "<HOME>\\.agent-harness\\tools\\fixtures\\arch\\clean\\architecture.json", |
| +добавлено | "verdict": "passed", |
| +добавлено | "stats": { |
| +добавлено | "files": 5, |
| +добавлено | "edges": 7, |
| +добавлено | "external": 0 |
| +добавлено | }, |
| +добавлено | "byRule": {}, |
| +добавлено | "errors": [], |
| +добавлено | "warnings": [], |
| +добавлено | "finishedAt": "2026-11-05T05:25:15.444Z" |
| +добавлено | } |
| +добавлено | { |
| +добавлено | "runId": "2026-11-05T05-27-39-273Z", |
| +добавлено | "cwd": "<HOME>\\.agent-harness\\tools\\fixtures\\arch\\clean", |
| +добавлено | "config": "<HOME>\\.agent-harness\\tools\\fixtures\\arch\\clean\\architecture.json", |
| +добавлено | "verdict": "passed", |
| +добавлено | "stats": { |
| +добавлено | "files": 5, |
| +добавлено | "edges": 7, |
| +добавлено | "external": 0 |
| +добавлено | }, |
| +добавлено | "byRule": {}, |
| +добавлено | "errors": [], |
| +добавлено | "warnings": [], |
| +добавлено | "finishedAt": "2026-11-05T05:27:39.274Z" |
| +добавлено | } |
| +добавлено | { |
| +добавлено | "runId": "2026-11-05T05-27-39-273Z", |
| +добавлено | "cwd": "<HOME>\\.agent-harness\\tools\\fixtures\\arch\\clean", |
| +добавлено | "config": "<HOME>\\.agent-harness\\tools\\fixtures\\arch\\clean\\architecture.json", |
| +добавлено | "verdict": "passed", |
| +добавлено | "stats": { |
| +добавлено | "files": 5, |
| +добавлено | "edges": 7, |
| +добавлено | "external": 0 |
| +добавлено | }, |
| +добавлено | "byRule": {}, |
| +добавлено | "errors": [], |
| +добавлено | "warnings": [], |
| +добавлено | "finishedAt": "2026-11-05T05:27:39.274Z" |
| +добавлено | } |
| +добавлено | { |
| +добавлено | "runId": "2026-11-05T05-23-12-474Z", |
| +добавлено | "cwd": "<HOME>\\.agent-harness\\tools\\fixtures\\arch\\clean", |
| +добавлено | "packageManager": null, |
| +добавлено | "frontend": false, |
| +добавлено | "architecture": true, |
| +добавлено | "config": "<HOME>\\.agent-harness\\.agent-gates.json", |
| +добавлено | "verdict": "passed", |
| +добавлено | "missingRequired": [], |
| +добавлено | "unverifiedRequired": [], |
| +добавлено | "finishedAt": "2026-11-05T05:23:12.620Z", |
| +добавлено | "results": [ |
| +добавлено | { |
| +добавлено | "name": "architecture", |
| +добавлено | "command": "node \"<HOME>\\.agent-harness/tools/arch.mjs\" check", |
| +добавлено | "required": true, |
| +добавлено | "log": ".agent-state\\artifacts\\gates-2026-11-05T05-23-12-474Z\\architecture.log", |
| +добавлено | "status": "passed", |
| +добавлено | "exitCode": 0, |
| +добавлено | "durationMs": 143 |
| +добавлено | } |
| +добавлено | ] |
| +добавлено | } |
| +добавлено | { |
| +добавлено | "runId": "2026-11-05T05-23-12-474Z", |
| +добавлено | "cwd": "<HOME>\\.agent-harness\\tools\\fixtures\\arch\\clean", |
| +добавлено | "packageManager": null, |
| +добавлено | "frontend": false, |
| +добавлено | "architecture": true, |
| +добавлено | "config": "<HOME>\\.agent-harness\\.agent-gates.json", |
| +добавлено | "verdict": "passed", |
| +добавлено | "missingRequired": [], |
| +добавлено | "unverifiedRequired": [], |
| +добавлено | "finishedAt": "2026-11-05T05:23:12.620Z", |
| +добавлено | "results": [ |
| +добавлено | { |
| +добавлено | "name": "architecture", |
| +добавлено | "command": "node \"<HOME>\\.agent-harness/tools/arch.mjs\" check", |
| +добавлено | "required": true, |
| +добавлено | "log": ".agent-state\\artifacts\\gates-2026-11-05T05-23-12-474Z\\architecture.log", |
| +добавлено | "status": "passed", |
| +добавлено | "exitCode": 0, |
| +добавлено | "durationMs": 143 |
| +добавлено | } |
| +добавлено | ] |
| +добавлено | } |
| +добавлено | {"at":"2026-11-05T05:22:39.938Z","type":"arch.checked","runId":"2026-11-05T05-22-39-926Z","verdict":"passed","errors":0} |
| +добавлено | {"at":"2026-11-05T05:23:06.667Z","type":"arch.checked","runId":"2026-11-05T05-23-06-663Z","verdict":"passed","errors":0} |
| +добавлено | {"at":"2026-11-05T05:23:12.593Z","type":"arch.checked","runId":"2026-11-05T05-23-12-588Z","verdict":"passed","errors":0} |
| +добавлено | {"at":"2026-11-05T05:23:12.624Z","type":"gates.finished","runId":"2026-11-05T05-23-12-474Z","verdict":"passed"} |
| +добавлено | {"at":"2026-11-05T05:24:25.220Z","type":"arch.checked","runId":"2026-11-05T05-24-25-217Z","verdict":"passed","errors":0} |
| +добавлено | {"at":"2026-11-05T05:24:32.634Z","type":"arch.checked","runId":"2026-11-05T05-24-32-631Z","verdict":"passed","errors":0} |
| +добавлено | {"at":"2026-11-05T05:25:15.447Z","type":"arch.checked","runId":"2026-11-05T05-25-15-444Z","verdict":"passed","errors":0} |
| +добавлено | {"at":"2026-11-05T05:27:39.276Z","type":"arch.checked","runId":"2026-11-05T05-27-39-273Z","verdict":"passed","errors":0} |
| +добавлено | { |
| +добавлено | "layers": [ |
| +добавлено | { "name": "domain", "path": "src/domain", "mayImport": ["domain"] }, |
| +добавлено | { "name": "application", "path": "src/application", "mayImport": ["domain", "application"] }, |
| +добавлено | { "name": "infrastructure", "path": "src/infrastructure", "mayImport": ["domain", "application", "infrastructure"] }, |
| +добавлено | { "name": "ui", "path": "src/ui", "mayImport": ["application", "domain", "ui"] } |
| +добавлено | ], |
| +добавлено | "forbidden": [ |
| +добавлено | { "from": "src/ui/**", "to": "src/infrastructure/**", "reason": "UI must not reach persistence directly" }, |
| +добавлено | { "from": "src/domain/**", "to": "src/ui/**", "reason": "domain must not know about UI" } |
| +добавлено | ], |
| +добавлено | "budgets": { "maxFileLines": 200, "maxFunctionLines": 30, "maxParams": 4, "maxNesting": 3 }, |
| +добавлено | "cycles": true, |
| +добавлено | "failOn": ["layer-violation", "forbidden-import", "cycle"] |
| +добавлено | } |
| +добавлено | import { createUser, type User } from '../domain/User'; |
| +добавлено | import type { UserRepository } from '../domain/UserRepository'; |
| +добавлено | |
| +добавлено | export function registerUser(repo: UserRepository, id: string, name: string): User { |
| +добавлено | const existing = repo.find(id); |
| +добавлено | if (existing) return existing; |
| +добавлено | const user = createUser(id, name); |
| +добавлено | repo.save(user); |
| +добавлено | return user; |
| +добавлено | } |
| +добавлено | export type User = { id: string; name: string }; |
| +добавлено | |
| +добавлено | export function createUser(id: string, name: string): User { |
| +добавлено | return { id, name }; |
| +добавлено | } |
| +добавлено | import type { User } from './User'; |
| +добавлено | |
| +добавлено | // Commented-out imports must not count as dependencies: |
| +добавлено | // import { renderRegistration } from '../ui/App'; |
| +добавлено | |
| +добавлено | export interface UserRepository { |
| +добавлено | find(id: string): User | null; |
| +добавлено | save(user: User): void; |
| +добавлено | } |
| +добавлено | #!/usr/bin/env node |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { HARNESS_ROOT, parseArgs, readJson, walkFiles, appendEvent, fail } from './lib.mjs'; |
| +добавлено | import { detectPackageManager, detectFrontend } from './gates.mjs'; |
| +добавлено | |
| +добавлено | const { flags } = parseArgs(process.argv.slice(2)); |
| +добавлено | const cwd = path.resolve(flags.cwd && flags.cwd !== true ? flags.cwd : process.cwd()); |
| +добавлено | const write = Boolean(flags.write); |
| +добавлено | const withUnit = flags.unit !== 'false' && flags['no-unit'] !== true; |
| +добавлено | |
| +добавлено | const pkgFile = path.join(cwd, 'package.json'); |
| +добавлено | const pkg = readJson(pkgFile, null); |
| +добавлено | if (!pkg) fail(`No package.json in ${cwd}`); |
| +добавлено | if (!detectFrontend(cwd) && !flags.force) fail('No frontend framework detected in package.json (use --force to scaffold anyway)'); |
| +добавлено | |
| +добавлено | const templates = path.join(HARNESS_ROOT, 'templates', 'frontend'); |
| +добавлено | if (!fs.existsSync(templates)) fail(`Templates missing at ${templates}; reinstall the harness`); |
| +добавлено | |
| +добавлено | const pm = detectPackageManager(cwd) ?? 'npm'; |
| +добавлено | const run = (script) => (pm === 'npm' ? `npm run ${script}` : `${pm} ${script}`); |
| +добавлено | const deps = { ...pkg.dependencies, ...pkg.devDependencies }; |
| +добавлено | const scripts = pkg.scripts ?? {}; |
| +добавлено | const isNext = 'next' in deps; |
| +добавлено | const devCmd = scripts.dev ? run('dev') : isNext ? `${pm === 'npm' ? 'npx' : `${pm} exec`} next dev` : run('start'); |
| +добавлено | const prodReady = Boolean(scripts.build && scripts.start); |
| +добавлено | const buildCmd = prodReady ? `${run('build')} && ` : ''; |
| +добавлено | const serveCmd = prodReady ? run('start') : devCmd; |
| +добавлено | const hasUnitRunner = ['vitest', 'jest'].some((d) => d in deps) || Boolean(scripts.test); |
| +добавлено | |
| +добавлено | const plan = { files: [], skipped: [], scripts: {}, devDependencies: [], gitignore: [] }; |
| +добавлено | |
| +добавлено | for (const file of walkFiles(templates, { skip: [] })) { |
| +добавлено | const relPath = path.relative(templates, file); |
| +добавлено | if (!withUnit || hasUnitRunner) if (/^vitest\./.test(relPath)) continue; |
| +добавлено | const dest = path.join(cwd, relPath); |
| +добавлено | if (fs.existsSync(dest)) { |
| +добавлено | plan.skipped.push(relPath); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | plan.files.push(relPath); |
| +добавлено | if (write) { |
| +добавлено | const content = fs.readFileSync(file, 'utf8').replaceAll('__DEV_CMD__', devCmd).replaceAll('__BUILD_CMD__', buildCmd).replaceAll('__SERVE_CMD__', serveCmd); |
| +добавлено | fs.mkdirSync(path.dirname(dest), { recursive: true }); |
| +добавлено | fs.writeFileSync(dest, content); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | const wantedScripts = { |
| +добавлено | 'test:e2e': 'playwright test --grep @e2e', |
| +добавлено | 'test:a11y': 'playwright test --grep @a11y', |
| +добавлено | 'test:visual': 'playwright test --grep @visual', |
| +добавлено | 'test:visual:update': 'playwright test --grep @visual --update-snapshots', |
| +добавлено | 'test:perf': 'lhci autorun', |
| +добавлено | 'test:journeys': 'node ~/.agent-harness/tools/journeys.mjs --cwd .', |
| +добавлено | }; |
| +добавлено | if (!scripts.typecheck && fs.existsSync(path.join(cwd, 'tsconfig.json'))) wantedScripts.typecheck = 'tsc --noEmit'; |
| +добавлено | if (withUnit && !hasUnitRunner) { |
| +добавлено | wantedScripts['test:unit'] = 'vitest run'; |
| +добавлено | wantedScripts.test = 'vitest run'; |
| +добавлено | } |
| +добавлено | for (const [name, cmd] of Object.entries(wantedScripts)) if (!scripts[name]) plan.scripts[name] = cmd; |
| +добавлено | |
| +добавлено | const wantedDeps = ['@playwright/test', '@axe-core/playwright', '@lhci/cli']; |
| +добавлено | if (withUnit && !hasUnitRunner) wantedDeps.push('vitest', '@vitejs/plugin-react', 'jsdom', '@testing-library/react', '@testing-library/jest-dom', '@testing-library/user-event'); |
| +добавлено | if (!('typescript' in deps) && fs.existsSync(path.join(cwd, 'tsconfig.json'))) wantedDeps.push('typescript'); |
| +добавлено | plan.devDependencies = wantedDeps.filter((d) => !(d in deps)); |
| +добавлено | |
| +добавлено | const gitignoreFile = path.join(cwd, '.gitignore'); |
| +добавлено | const gitignore = fs.existsSync(gitignoreFile) ? fs.readFileSync(gitignoreFile, 'utf8').split('\n') : []; |
| +добавлено | plan.gitignore = ['.agent-state/', '.agent-worktrees/', '.lighthouseci/', 'test-results/', 'playwright-report/'].filter((l) => !gitignore.includes(l)); |
| +добавлено | |
| +добавлено | if (write) { |
| +добавлено | if (Object.keys(plan.scripts).length) { |
| +добавлено | pkg.scripts = { ...scripts, ...plan.scripts }; |
| +добавлено | fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`); |
| +добавлено | } |
| +добавлено | if (plan.gitignore.length) fs.appendFileSync(gitignoreFile, `${gitignore.length && gitignore.at(-1) !== '' ? '\n' : ''}${plan.gitignore.join('\n')}\n`); |
| +добавлено | appendEvent(cwd, { type: 'frontend.init', files: plan.files, scripts: Object.keys(plan.scripts), devDependencies: plan.devDependencies }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const add = { pnpm: 'pnpm add -D', yarn: 'yarn add -D', bun: 'bun add -d', npm: 'npm i -D' }[pm] ?? 'npm i -D'; |
| +добавлено | const exec = pm === 'npm' ? 'npx' : `${pm} exec`; |
| +добавлено | console.log(`${write ? 'Applied' : '[dry-run] Would apply'} frontend quality contour in ${cwd} (pm: ${pm})\n`); |
| +добавлено | console.log(`files: ${plan.files.join(', ') || '—'}`); |
| +добавлено | if (plan.skipped.length) console.log(`kept: ${plan.skipped.join(', ')} (already exist)`); |
| +добавлено | console.log(`scripts: ${Object.keys(plan.scripts).join(', ') || '—'}`); |
| +добавлено | console.log(`ignore: ${plan.gitignore.join(' ') || '—'}`); |
| +добавлено | console.log('\nNext steps (installs need human approval):'); |
| +добавлено | if (plan.devDependencies.length) console.log(` 1. ${add} ${plan.devDependencies.join(' ')}`); |
| +добавлено | console.log(` 2. ${exec} playwright install --with-deps chromium`); |
| +добавлено | console.log(' 3. Add every route to e2e/routes.ts and ROUTES in lighthouserc.cjs; write at least one component test (*.test.tsx).'); |
| +добавлено | if (!prodReady) console.log(' note: no build+start scripts, Lighthouse will measure the dev server (numbers are pessimistic).'); |
| +добавлено | console.log(' Lighthouse needs Chrome: set CHROME_PATH if it is not in PATH.'); |
| +добавлено | console.log(` 4. Baselines on the CI platform, with approval: ${run('test:visual:update')}`); |
| +добавлено | console.log(' 5. node ~/.agent-harness/tools/gates.mjs'); |
| +добавлено | if (!write) console.log('\nRe-run with --write to apply.'); |
| +добавлено | #!/usr/bin/env node |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { spawn } from 'node:child_process'; |
| +добавлено | import { parseArgs, list, readJson, writeJsonAtomic, resolveConfig, stateDir, appendEvent, fail, HARNESS_ROOT } from './lib.mjs'; |
| +добавлено | |
| +добавлено | const LOCKFILES = [ |
| +добавлено | ['pnpm-lock.yaml', 'pnpm'], |
| +добавлено | ['bun.lock', 'bun'], |
| +добавлено | ['bun.lockb', 'bun'], |
| +добавлено | ['yarn.lock', 'yarn'], |
| +добавлено | ['package-lock.json', 'npm'], |
| +добавлено | ]; |
| +добавлено | |
| +добавлено | export function detectPackageManager(cwd) { |
| +добавлено | const pkg = readJson(path.join(cwd, 'package.json'), null); |
| +добавлено | if (pkg?.packageManager) return pkg.packageManager.split('@')[0]; |
| +добавлено | for (const [lockfile, pm] of LOCKFILES) if (fs.existsSync(path.join(cwd, lockfile))) return pm; |
| +добавлено | return pkg ? 'npm' : null; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const FRONTEND_DEPS = ['next', 'react', 'vue', 'nuxt', 'svelte', '@sveltejs/kit', 'astro', 'solid-js', '@angular/core', 'preact', '@remix-run/react', 'react-router']; |
| +добавлено | |
| +добавлено | export function detectFrontend(cwd) { |
| +добавлено | const pkg = readJson(path.join(cwd, 'package.json'), null); |
| +добавлено | if (!pkg) return false; |
| +добавлено | const deps = { ...pkg.dependencies, ...pkg.devDependencies }; |
| +добавлено | return FRONTEND_DEPS.some((d) => d in deps); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function isRequired(gate, ctx) { |
| +добавлено | if (gate.requiredWhen === 'frontend') return ctx.frontend; |
| +добавлено | if (gate.requiredWhen === 'typescript') return ctx.typescript; |
| +добавлено | if (gate.requiredWhen === 'architecture') return ctx.architecture; |
| +добавлено | return gate.required !== false; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function runScript(pm, script, cwd, timeoutSec, logFile) { |
| +добавлено | return runCommand(pm, ['run', script], cwd, timeoutSec, logFile); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function runCommand(bin, args, cwd, timeoutSec, logFile, forceShell = false) { |
| +добавлено | return new Promise((resolve) => { |
| +добавлено | const started = Date.now(); |
| +добавлено | const out = fs.createWriteStream(logFile); |
| +добавлено | const child = spawn(bin, args, { cwd, shell: forceShell || process.platform === 'win32', env: { ...process.env, CI: '1', FORCE_COLOR: '0' } }); |
| +добавлено | let timedOut = false; |
| +добавлено | const timer = setTimeout(() => { |
| +добавлено | timedOut = true; |
| +добавлено | child.kill('SIGTERM'); |
| +добавлено | setTimeout(() => child.kill('SIGKILL'), 5000).unref(); |
| +добавлено | }, timeoutSec * 1000); |
| +добавлено | child.stdout.pipe(out, { end: false }); |
| +добавлено | child.stderr.pipe(out, { end: false }); |
| +добавлено | child.on('error', (error) => { |
| +добавлено | clearTimeout(timer); |
| +добавлено | out.end(`\n[spawn error] ${error.message}\n`); |
| +добавлено | resolve({ status: 'failed', exitCode: null, durationMs: Date.now() - started, error: error.message }); |
| +добавлено | }); |
| +добавлено | child.on('close', (code) => { |
| +добавлено | clearTimeout(timer); |
| +добавлено | out.end(); |
| +добавлено | // exit code 2 is the harness convention for "could not verify" (missing config, no scope, etc.) |
| +добавлено | const status = timedOut ? 'timeout' : code === 0 ? 'passed' : code === 2 ? 'unverified' : 'failed'; |
| +добавлено | resolve({ status, exitCode: code, durationMs: Date.now() - started }); |
| +добавлено | }); |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function main() { |
| +добавлено | const { flags } = parseArgs(process.argv.slice(2)); |
| +добавлено | const cwd = path.resolve(flags.cwd && flags.cwd !== true ? flags.cwd : process.cwd()); |
| +добавлено | const configPath = flags.config && flags.config !== true ? flags.config : resolveConfig('.agent-gates.json', cwd); |
| +добавлено | if (!configPath) fail('No .agent-gates.json found in project, ~/.agent-harness or harness root'); |
| +добавлено | const config = readJson(configPath); |
| +добавлено | const only = list(flags.only); |
| +добавлено | const gates = config.gates.filter((g) => !only.length || only.includes(g.name)); |
| +добавлено | |
| +добавлено | const pm = detectPackageManager(cwd); |
| +добавлено | const scripts = readJson(path.join(cwd, 'package.json'), {}).scripts ?? {}; |
| +добавлено | const runId = new Date().toISOString().replace(/[:.]/g, '-'); |
| +добавлено | const artifactDir = path.join(stateDir(cwd), 'artifacts', `gates-${runId}`); |
| +добавлено | fs.mkdirSync(artifactDir, { recursive: true }); |
| +добавлено | |
| +добавлено | const ctx = { |
| +добавлено | frontend: detectFrontend(cwd), |
| +добавлено | typescript: fs.existsSync(path.join(cwd, 'tsconfig.json')), |
| +добавлено | architecture: ['architecture.json', '.agent-arch.json', 'architecture.jsonc'].some((f) => fs.existsSync(path.join(cwd, f))), |
| +добавлено | }; |
| +добавлено | const results = []; |
| +добавлено | for (const gate of gates) { |
| +добавлено | const required = isRequired(gate, ctx); |
| +добавлено | const command = typeof gate.command === 'string' && gate.command.trim() |
| +добавлено | ? gate.command.replaceAll('{harness}', HARNESS_ROOT) |
| +добавлено | : null; |
| +добавлено | const script = command ? null : (gate.scripts ?? [gate.name]).find((s) => scripts[s]); |
| +добавлено | if (!command && (!pm || !script)) { |
| +добавлено | results.push({ name: gate.name, status: 'skipped', reason: pm ? `no script among ${(gate.scripts ?? [gate.name]).join('|')}` : 'no package.json', required, hint: gate.hint ?? null }); |
| +добавлено | console.log(`- ${gate.name}: skipped${required ? ' (REQUIRED)' : ''}${required && gate.hint ? ` -> ${gate.hint}` : ''}`); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | const logFile = path.join(artifactDir, `${gate.name}.log`); |
| +добавлено | const timeoutSec = gate.timeoutSec ?? config.defaultTimeoutSec ?? 900; |
| +добавлено | console.log(`> ${gate.name}: ${command ?? `${pm} run ${script}`}`); |
| +добавлено | const res = command |
| +добавлено | ? await runCommand(command, [], cwd, timeoutSec, logFile, true) |
| +добавлено | : await runScript(pm, script, cwd, timeoutSec, logFile); |
| +добавлено | results.push({ name: gate.name, command: command ?? undefined, script: script ?? undefined, required, log: path.relative(cwd, logFile), ...res }); |
| +добавлено | console.log(` ${res.status} (${Math.round(res.durationMs / 1000)}s)`); |
| +добавлено | if (res.status !== 'passed' && required && config.failFast) break; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const requiredBroken = results.filter((r) => r.required && (r.status === 'failed' || r.status === 'timeout')); |
| +добавлено | const requiredSkipped = results.filter((r) => r.required && r.status === 'skipped'); |
| +добавлено | const requiredUnverified = results.filter((r) => r.required && r.status === 'unverified'); |
| +добавлено | const ran = results.filter((r) => r.status !== 'skipped'); |
| +добавлено | const verdict = requiredBroken.length ? 'failed' : ran.length === 0 || requiredSkipped.length || requiredUnverified.length ? 'unverified' : 'passed'; |
| +добавлено | const summary = { runId, cwd, packageManager: pm, frontend: ctx.frontend, architecture: ctx.architecture, config: configPath, verdict, missingRequired: requiredSkipped.map((r) => r.name), unverifiedRequired: requiredUnverified.map((r) => r.name), finishedAt: new Date().toISOString(), results }; |
| +добавлено | |
| +добавлено | writeJsonAtomic(path.join(artifactDir, 'summary.json'), summary); |
| +добавлено | writeJsonAtomic(path.join(stateDir(cwd), 'artifacts', 'gates-latest.json'), summary); |
| +добавлено | appendEvent(cwd, { type: 'gates.finished', runId, verdict }); |
| +добавлено | |
| +добавлено | console.log(`\nVerdict: ${verdict.toUpperCase()} artifacts: ${path.relative(cwd, artifactDir)}`); |
| +добавлено | if (verdict === 'unverified') { |
| +добавлено | console.log(ran.length === 0 ? 'No gate actually ran.' : `Required gate(s) have no script: ${requiredSkipped.map((r) => r.name).join(', ')}.`); |
| +добавлено | console.log('Report the result as unverified, not passed.'); |
| +добавлено | } |
| +добавлено | process.exit(verdict === 'passed' ? 0 : verdict === 'unverified' ? 2 : 1); |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith('gates.mjs')) { |
| +добавлено | main().catch((error) => fail(error.message)); |
| +добавлено | } |
| +добавлено | #!/usr/bin/env node |
| +добавлено | /** |
| +добавлено | * imagegen.mjs — генерирует изображения встроенной моделью шлюза ZCode. |
| +добавлено | * |
| +добавлено | * node ~/.agent-harness/tools/imagegen.mjs <out.png> "<prompt>" [size] [--ref <img>] |
| +добавлено | * |
| +добавлено | * Почему так, а не /v1/images/generations: шлюз отклоняет этот эндпоинт |
| +добавлено | * (400 invalid_request_error), а картинки отдаёт инструмент image_generation |
| +добавлено | * в /v1/responses. Модель — gpt/gpt-image-2.5. |
| +добавлено | * |
| +добавлено | * Ключ берётся из ~/.zcode/v2/provider_config.json в момент вызова: в коде, |
| +добавлено | * логах и репозитории его нет. Размеры: 1024x1024, 1536x1024, 1024x1536, auto. |
| +добавлено | * Без --ref модель рисует с нуля; с --ref правит присланную картинку. |
| +добавлено | */ |
| +добавлено | |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import os from 'node:os'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | |
| +добавлено | const CONFIG = path.join(os.homedir(), '.zcode', 'v2', 'provider_config.json'); |
| +добавлено | const IMAGE_MODEL = 'gpt/gpt-image-2.5'; |
| +добавлено | const TEXT_MODEL = 'gpt/gpt-6.1-sol'; |
| +добавлено | const VALID_SIZES = new Set(['auto', '1024x1024', '1536x1024', '1024x1536']); |
| +добавлено | |
| +добавлено | const argv = process.argv.slice(2); |
| +добавлено | let ref = null; |
| +добавлено | const positional = []; |
| +добавлено | for (let i = 0; i < argv.length; i++) { |
| +добавлено | if (argv[i] === '--ref') ref = argv[++i]; |
| +добавлено | else positional.push(argv[i]); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const [out, prompt, sizeArg] = positional; |
| +добавлено | const size = sizeArg ?? '1024x1024'; |
| +добавлено | |
| +добавлено | if (!out || !prompt) { |
| +добавлено | console.error('usage: imagegen.mjs <out.png> "<prompt>" [size] [--ref <img>]'); |
| +добавлено | process.exit(1); |
| +добавлено | } |
| +добавлено | if (!VALID_SIZES.has(size)) { |
| +добавлено | console.error(`недопустимый размер: ${size} (можно: ${[...VALID_SIZES].join(', ')})`); |
| +добавлено | process.exit(1); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function providers() { |
| +добавлено | let cfg; |
| +добавлено | try { |
| +добавлено | cfg = JSON.parse(fs.readFileSync(CONFIG, 'utf8')); |
| +добавлено | } catch { |
| +добавлено | return []; |
| +добавлено | } |
| +добавлено | const rules = cfg?.config?.providerConfigRules?.providerRules ?? []; |
| +добавлено | return rules |
| +добавлено | .map((r) => ({ |
| +добавлено | base: r?.config?.api?.baseUrl?.replace(/\/$/, ''), |
| +добавлено | type: r?.config?.api?.type, |
| +добавлено | key: r?.config?.access?.apiKey, |
| +добавлено | enabled: r?.enabled !== false, |
| +добавлено | })) |
| +добавлено | .filter((p) => p.enabled && p.type === 'openai-chat-completions' && p.base && p.key); |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function listModels(base, key) { |
| +добавлено | const res = await fetch(`${base}/models`, { headers: { Authorization: `Bearer ${key}` } }); |
| +добавлено | if (!res.ok) throw new Error(`models ${res.status}`); |
| +добавлено | const data = await res.json(); |
| +добавлено | return (data.data ?? []).map((m) => m.id); |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function pickGateway() { |
| +добавлено | for (const p of providers()) { |
| +добавлено | try { |
| +добавлено | const ids = await listModels(p.base, p.key); |
| +добавлено | if (ids.includes(IMAGE_MODEL)) return p; |
| +добавлено | } catch { |
| +добавлено | /* провайдер недоступен — пробуем следующий */ |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return null; |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function generate(gw, promptText, size, refPath, attempt = 1) { |
| +добавлено | const content = [{ type: 'input_text', text: `Generate an image: ${promptText}` }]; |
| +добавлено | if (refPath) { |
| +добавлено | const b64 = fs.readFileSync(refPath).toString('base64'); |
| +добавлено | const ext = path.extname(refPath).slice(1).toLowerCase() || 'png'; |
| +добавлено | const mime = ext === 'jpg' ? 'jpeg' : ext; |
| +добавлено | content.push({ type: 'input_image', image_url: `data:image/${mime};base64,${b64}` }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const res = await fetch(`${gw.base}/responses`, { |
| +добавлено | method: 'POST', |
| +добавлено | headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${gw.key}` }, |
| +добавлено | body: JSON.stringify({ |
| +добавлено | model: TEXT_MODEL, |
| +добавлено | input: [{ role: 'user', content }], |
| +добавлено | tools: [{ type: 'image_generation', size }], |
| +добавлено | }), |
| +добавлено | }); |
| +добавлено | |
| +добавлено | if (!res.ok) { |
| +добавлено | const body = await res.text(); |
| +добавлено | // 503/429 — шлюз перегружен, повторяем с растущей паузой; 4xx — нет смысла |
| +добавлено | if ((res.status === 503 || res.status === 429) && attempt < 6) { |
| +добавлено | const wait = Math.min(60, 8 * attempt); |
| +добавлено | console.error(` ${res.status}, ждём ${wait} с и пробуем снова (попытка ${attempt + 1})`); |
| +добавлено | await new Promise((r) => setTimeout(r, wait * 1000)); |
| +добавлено | return generate(gw, promptText, size, refPath, attempt + 1); |
| +добавлено | } |
| +добавлено | throw new Error(`HTTP ${res.status}: ${body.slice(0, 300)}`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const data = await res.json(); |
| +добавлено | const call = (data.output ?? []).find((o) => o.type === 'image_generation_call' && o.result); |
| +добавлено | if (!call) { |
| +добавлено | throw new Error(`в ответе нет картинки: ${(data.output ?? []).map((o) => o.type).join(', ')}`); |
| +добавлено | } |
| +добавлено | return Buffer.from(call.result, 'base64'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const gw = await pickGateway(); |
| +добавлено | if (!gw) { |
| +добавлено | console.error( |
| +добавлено | 'Шлюз со встроенной генерацией не найден. Проверьте, что в настройках ZCode ' + |
| +добавлено | 'подключён провайдер (Settings → Models), и повторите.', |
| +добавлено | ); |
| +добавлено | process.exit(2); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const started = Date.now(); |
| +добавлено | try { |
| +добавлено | const png = await generate(gw, prompt, size, ref); |
| +добавлено | fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true }); |
| +добавлено | fs.writeFileSync(out, png); |
| +добавлено | const kb = Math.round(png.length / 1024); |
| +добавлено | const sec = ((Date.now() - started) / 1000).toFixed(1); |
| +добавлено | console.log(`OK ${out} — ${kb} KB, ${sec} с, ${size}${ref ? ', с референсом' : ''}`); |
| +добавлено | } catch (err) { |
| +добавлено | console.error(`Не вышло: ${err.message}`); |
| +добавлено | process.exit(3); |
| +добавлено | } |
| +добавлено | #!/usr/bin/env node |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { HARNESS_ROOT, homeDir, parseArgs, list, walkFiles, sha256, writeJsonAtomic, fail } from './lib.mjs'; |
| +добавлено | import { loadManifest, validateSkillsDir, parity } from './skills.mjs'; |
| +добавлено | |
| +добавлено | const { flags } = parseArgs(process.argv.slice(2)); |
| +добавлено | const dryRun = Boolean(flags['dry-run']); |
| +добавлено | const home = homeDir(); |
| +добавлено | const manifest = loadManifest(); |
| +добавлено | const stamp = new Date().toISOString().replace(/[:.]/g, '-'); |
| +добавлено | const backupRoot = path.join(home, '.agent-harness', 'backups', stamp); |
| +добавлено | const expand = (p) => p.replace(/^~(?=$|\/)/, home); |
| +добавлено | const log = { written: [], unchanged: [], backedUp: [], skipped: [] }; |
| +добавлено | |
| +добавлено | const universal = manifest.install.universal ?? {}; |
| +добавлено | const known = ['pi', 'opencode', ...Object.keys(universal)]; |
| +добавлено | const detected = Object.entries(universal) |
| +добавлено | .filter(([, cfg]) => !cfg.detect.length || cfg.detect.some((p) => fs.existsSync(expand(p)))) |
| +добавлено | .map(([name]) => name); |
| +добавлено | const requested = list(flags.target); |
| +добавлено | const targets = requested.includes('all') |
| +добавлено | ? known |
| +добавлено | : requested.length |
| +добавлено | ? requested |
| +добавлено | : ['pi', 'opencode', ...detected]; |
| +добавлено | const customSkillDirs = list(flags['skills-dir']); |
| +добавлено | |
| +добавлено | for (const t of targets) if (!known.includes(t)) fail(`Unknown target ${t}. Known: ${known.join(', ')}, all`); |
| +добавлено | |
| +добавлено | const preflight = [ |
| +добавлено | ...validateSkillsDir(path.join(HARNESS_ROOT, manifest.paths.piSkills)), |
| +добавлено | ...validateSkillsDir(path.join(HARNESS_ROOT, manifest.paths.opencodeSkills)), |
| +добавлено | ...parity(manifest), |
| +добавлено | ].filter((i) => i.level === 'error'); |
| +добавлено | if (preflight.length) { |
| +добавлено | for (const i of preflight) console.error(`ERROR ${i.where}: ${i.message}`); |
| +добавлено | fail('Harness is inconsistent; fix it before installing (node tools/skills.mjs validate).'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function place(src, dest) { |
| +добавлено | if (fs.existsSync(dest)) { |
| +добавлено | if (sha256(src) === sha256(dest)) { |
| +добавлено | log.unchanged.push(dest); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | const backup = path.join(backupRoot, path.relative(home, dest)); |
| +добавлено | if (!dryRun) { |
| +добавлено | fs.mkdirSync(path.dirname(backup), { recursive: true }); |
| +добавлено | fs.copyFileSync(dest, backup); |
| +добавлено | } |
| +добавлено | log.backedUp.push(dest); |
| +добавлено | } |
| +добавлено | if (!dryRun) { |
| +добавлено | fs.mkdirSync(path.dirname(dest), { recursive: true }); |
| +добавлено | fs.copyFileSync(src, dest); |
| +добавлено | } |
| +добавлено | log.written.push(dest); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function placeTree(srcRel, destTilde) { |
| +добавлено | const src = path.join(HARNESS_ROOT, srcRel); |
| +добавлено | if (!fs.existsSync(src)) return; |
| +добавлено | for (const file of walkFiles(src, { skip: [] })) place(file, path.join(expand(destTilde), path.relative(src, file))); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function placeIfMissing(srcRel, destTilde, alsoBlockedBy = []) { |
| +добавлено | const dest = expand(destTilde); |
| +добавлено | const blocker = [dest, ...alsoBlockedBy.map(expand)].find((p) => fs.existsSync(p)); |
| +добавлено | if (blocker) { |
| +добавлено | log.skipped.push(`${blocker} (exists, not touched)`); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | place(path.join(HARNESS_ROOT, srcRel), dest); |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (targets.includes('pi')) { |
| +добавлено | const cfg = manifest.install.pi; |
| +добавлено | placeTree(manifest.paths.piSkills, cfg.skills); |
| +добавлено | placeTree(manifest.paths.piAgents, cfg.agents); |
| +добавлено | placeTree(manifest.paths.opencodeCommands, cfg.prompts); |
| +добавлено | for (const [src, dest] of Object.entries(cfg.configExamples)) placeIfMissing(src, dest); |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (targets.includes('opencode')) { |
| +добавлено | const cfg = manifest.install.opencode; |
| +добавлено | placeTree(manifest.paths.opencodeSkills, cfg.skills); |
| +добавлено | placeTree(manifest.paths.opencodeAgents, cfg.agents); |
| +добавлено | placeTree(manifest.paths.opencodeCommands, cfg.commands); |
| +добавлено | for (const [src, dest] of Object.entries(cfg.configExamples)) placeIfMissing(src, dest, ['~/.config/opencode/opencode.json']); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function writeGenerated(content, dest, { force = false } = {}) { |
| +добавлено | if (fs.existsSync(dest) && fs.readFileSync(dest, 'utf8') === content) { |
| +добавлено | log.unchanged.push(dest); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | if (fs.existsSync(dest) && !force) { |
| +добавлено | if (!dryRun) fs.writeFileSync(`${dest}.harness-new`, content); |
| +добавлено | log.skipped.push(`${dest} differs: new version saved as ${path.basename(dest)}.harness-new (merge by hand or rerun with --force-agents)`); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | if (fs.existsSync(dest)) { |
| +добавлено | const backup = path.join(backupRoot, path.relative(home, dest)); |
| +добавлено | if (!dryRun) { |
| +добавлено | fs.mkdirSync(path.dirname(backup), { recursive: true }); |
| +добавлено | fs.copyFileSync(dest, backup); |
| +добавлено | } |
| +добавлено | log.backedUp.push(dest); |
| +добавлено | } |
| +добавлено | if (!dryRun) { |
| +добавлено | fs.mkdirSync(path.dirname(dest), { recursive: true }); |
| +добавлено | fs.writeFileSync(dest, content); |
| +добавлено | } |
| +добавлено | log.written.push(dest); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function portableAgent(file) { |
| +добавлено | const raw = fs.readFileSync(file, 'utf8'); |
| +добавлено | const match = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/); |
| +добавлено | if (!match) return raw; |
| +добавлено | const keep = match[1].split('\n').filter((line) => /^(name|description):/.test(line)); |
| +добавлено | if (!keep.some((line) => line.startsWith('name:'))) keep.unshift(`name: ${path.basename(file, '.md')}`); |
| +добавлено | return `---\n${keep.join('\n')}\n---\n${match[2]}`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const instructionsImport = '# Harness\n\n@~/AGENTS.md\n@~/AGENTS-SUMMARY.md\n'; |
| +добавлено | |
| +добавлено | for (const name of targets.filter((t) => universal[t])) { |
| +добавлено | const cfg = universal[name]; |
| +добавлено | placeTree(manifest.paths.opencodeSkills, cfg.skills); |
| +добавлено | if (cfg.agents) { |
| +добавлено | const src = path.join(HARNESS_ROOT, manifest.paths.opencodeAgents); |
| +добавлено | for (const file of walkFiles(src, { skip: [] })) { |
| +добавлено | writeGenerated(portableAgent(file), path.join(expand(cfg.agents), path.relative(src, file))); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | if (cfg.commands) placeTree(manifest.paths.opencodeCommands, cfg.commands); |
| +добавлено | if (cfg.instructions) { |
| +добавлено | const dest = expand(cfg.instructions); |
| +добавлено | const force = Boolean(flags['force-agents']); |
| +добавлено | if (cfg.instructionsMode === 'import') writeGenerated(instructionsImport, dest, { force }); |
| +добавлено | else writeGenerated(fs.readFileSync(path.join(HARNESS_ROOT, cfg.instructionsSource ?? 'AGENTS.md'), 'utf8'), dest, { force }); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | for (const dir of customSkillDirs) placeTree(manifest.paths.opencodeSkills, dir); |
| +добавлено | |
| +добавлено | const runtime = expand(manifest.install.runtime); |
| +добавлено | placeTree(manifest.paths.tools, path.join(runtime, 'tools')); |
| +добавлено | for (const f of ['harness.json', '.agent-gates.json', '.release-policy.json', 'VERSION.md']) place(path.join(HARNESS_ROOT, f), path.join(runtime, f)); |
| +добавлено | placeTree('bench', path.join(runtime, 'bench')); |
| +добавлено | placeTree(manifest.paths.templates ?? 'templates', path.join(runtime, 'templates')); |
| +добавлено | place(path.join(HARNESS_ROOT, 'opencode', 'opencode.official.jsonc.example'), path.join(runtime, 'examples', 'opencode.official.jsonc.example')); |
| +добавлено | place(path.join(HARNESS_ROOT, 'zcode', 'mcp.example.json'), path.join(runtime, 'zcode', 'mcp.example.json')); |
| +добавлено | |
| +добавлено | const agentsTarget = path.join(home, 'AGENTS.md'); |
| +добавлено | const agentsSrc = path.join(HARNESS_ROOT, 'AGENTS.md'); |
| +добавлено | if (!fs.existsSync(agentsTarget)) place(agentsSrc, agentsTarget); |
| +добавлено | else if (sha256(agentsSrc) === sha256(agentsTarget)) log.unchanged.push(agentsTarget); |
| +добавлено | else if (flags['force-agents']) place(agentsSrc, agentsTarget); |
| +добавлено | else { |
| +добавлено | if (!dryRun) fs.copyFileSync(agentsSrc, `${agentsTarget}.harness-new`); |
| +добавлено | log.skipped.push(`${agentsTarget} differs: new version saved as AGENTS.md.harness-new (merge by hand or rerun with --force-agents)`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (!dryRun) { |
| +добавлено | writeJsonAtomic(path.join(runtime, 'installed.json'), { |
| +добавлено | version: manifest.version, |
| +добавлено | at: new Date().toISOString(), |
| +добавлено | targets, |
| +добавлено | files: log.written.concat(log.unchanged).filter((f) => fs.existsSync(f)).map((f) => ({ path: f, sha256: sha256(f) })), |
| +добавлено | backups: log.backedUp.length ? backupRoot : null, |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | console.log(`${dryRun ? '[dry-run] ' : ''}aggg-harness ${manifest.version} -> ${targets.join(', ')}`); |
| +добавлено | console.log(` written: ${log.written.length}`); |
| +добавлено | console.log(` unchanged: ${log.unchanged.length}`); |
| +добавлено | if (log.backedUp.length) console.log(` backed up: ${log.backedUp.length} -> ${backupRoot}`); |
| +добавлено | for (const s of log.skipped) console.log(` skipped: ${s}`); |
| +добавлено | console.log(`\nNext: node "${path.join(runtime, 'tools', 'doctor.mjs')}"`); |
| +добавлено | #!/usr/bin/env bash |
| +добавлено | # Harness installer — разводит канон обвязки по всем агентским клиентам. |
| +добавлено | # |
| +добавлено | # Канон (единственный источник правды): |
| +добавлено | # ~/.agents/skills/<имя>/SKILL.md — скиллы |
| +добавлено | # ~/AGENTS.md — мастер-контракт (стиль, память, контур) |
| +добавлено | # ~/.AGENTS.md — глобальные правила для Freebuff/Codebuff |
| +добавлено | # ~/AGENTS-SUMMARY.md, ~/MEMORY.md — сводка и карта |
| +добавлено | # ~/.config/mcp/mcp.json — общий набор MCP-серверов |
| +добавлено | # |
| +добавлено | # Что делает: на каждого клиента кладёт junction <клиент>/skills -> ~/.agents/skills |
| +добавлено | # и глобальный файл правил (если его ещё нет). Ничего чужого не перезаписывает. |
| +добавлено | # |
| +добавлено | # Использование: |
| +добавлено | # bash ~/.agent-harness/tools/install.sh # установить/допоставить |
| +добавлено | # bash ~/.agent-harness/tools/install.sh --check # только отчёт |
| +добавлено | # bash ~/.agent-harness/tools/install.sh --force # перезаписать файлы правил |
| +добавлено | set -u |
| +добавлено | |
| +добавлено | H="${HOME:-/c<HOME>" |
| +добавлено | CANON="$H/.agents/skills" |
| +добавлено | FP_GLOBAL="$H/.AGENTS.md" |
| +добавлено | MCP_SRC="$H/.config/mcp/mcp.json" |
| +добавлено | MODE="install" |
| +добавлено | FORCE=0 |
| +добавлено | COPY=0 |
| +добавлено | for a in "$@"; do |
| +добавлено | case "$a" in |
| +добавлено | --check) MODE="check" ;; |
| +добавлено | --force) FORCE=1 ;; |
| +добавлено | --copy) COPY=1 ;; |
| +добавлено | -h|--help) sed -n '2,26p' "$0"; exit 0 ;; |
| +добавлено | *) echo "неизвестный аргумент: $a" >&2; exit 2 ;; |
| +добавлено | esac |
| +добавлено | done |
| +добавлено | |
| +добавлено | if [ ! -d "$CANON" ]; then |
| +добавлено | echo "нет канона скиллов: $CANON" >&2 |
| +добавлено | exit 1 |
| +добавлено | fi |
| +добавлено | |
| +добавлено | # клиент | папка скиллов (от $H) | файл глобальных правил (от $H) | формат mcp |
| +добавлено | CLIENTS=( |
| +добавлено | "freebuff||.AGENTS.md|" |
| +добавлено | "zcode|.zcode/skills|.zcode/AGENTS.md|zcode" |
| +добавлено | "opencode|.config/opencode/skills|.config/opencode/AGENTS.md|" |
| +добавлено | "claude-code|.claude/skills|.claude/CLAUDE.md|" |
| +добавлено | "codex|.codex/skills|.codex/AGENTS.md|" |
| +добавлено | "gemini-cli|.gemini/skills|.gemini/GEMINI.md|" |
| +добавлено | "cursor|.cursor/skills|.cursor/AGENTS.md|" |
| +добавлено | "copilot|.copilot/skills|.copilot/copilot-instructions.md|" |
| +добавлено | "crush|.config/crush/skills|.config/crush/CRUSH.md|" |
| +добавлено | "pi|.pi/agent/skills|.pi/agent/AGENTS.md|" |
| +добавлено | ) |
| +добавлено | |
| +добавлено | win_path() { cygpath -w "$1" 2>/dev/null || printf '%s' "$1"; } |
| +добавлено | skill_count() { find "$1/" -maxdepth 3 -name SKILL.md 2>/dev/null | wc -l | tr -d ' '; } |
| +добавлено | |
| +добавлено | link_skills() { # $1 = абсолютный путь папки скиллов клиента |
| +добавлено | local dst="$1" |
| +добавлено | if [ -d "$dst" ] && [ ! -L "$dst" ]; then |
| +добавлено | local n; n=$(skill_count "$dst") |
| +добавлено | if [ "$n" = "0" ]; then |
| +добавлено | rmdir "$dst" 2>/dev/null |
| +добавлено | else |
| +добавлено | echo " skills : своя папка ($n скиллов) — не трогаю" |
| +добавлено | return 0 |
| +добавлено | fi |
| +добавлено | fi |
| +добавлено | if [ -L "$dst" ]; then |
| +добавлено | local tgt; tgt=$(readlink -f "$dst" 2>/dev/null || readlink "$dst") |
| +добавлено | if [ "$tgt" = "$(readlink -f "$CANON")" ]; then |
| +добавлено | echo " skills : уже связано -> ~/.agents/skills" |
| +добавлено | else |
| +добавлено | echo " skills : ссылка на $tgt — не трогаю" |
| +добавлено | fi |
| +добавлено | return 0 |
| +добавлено | fi |
| +добавлено | mkdir -p "$(dirname "$dst")" |
| +добавлено | if [ "$MODE" = "check" ]; then |
| +добавлено | echo " skills : НЕТ (связал бы с ~/.agents/skills)" |
| +добавлено | return 0 |
| +добавлено | fi |
| +добавлено | if cmd //c "mklink /J $(win_path "$dst") $(win_path "$CANON")" >/dev/null 2>&1; then |
| +добавлено | echo " skills : связал -> ~/.agents/skills ($(skill_count "$CANON") шт.)" |
| +добавлено | elif [ "$COPY" -eq 1 ]; then |
| +добавлено | cp -r "$CANON" "$dst" 2>/dev/null && echo " skills : скопировал ($(skill_count "$dst") шт.)" |
| +добавлено | else |
| +добавлено | echo " skills : ОШИБКА junction (можно --copy, но это +$(( $(du -sm "$CANON" | cut -f1) )) МБ на клиента)" |
| +добавлено | fi |
| +добавлено | } |
| +добавлено | |
| +добавлено | write_rules() { # $1 = файл правил, $2 = папка скиллов клиента или "" |
| +добавлено | local f="$1" skills_rel="$2" |
| +добавлено | if [ -f "$f" ] && [ "$FORCE" -ne 1 ]; then |
| +добавлено | echo " rules : есть ($(wc -l <"$f" | tr -d ' ') строк) — не трогаю" |
| +добавлено | return 0 |
| +добавлено | fi |
| +добавлено | if [ "$MODE" = "check" ] && [ ! -f "$f" ]; then |
| +добавлено | echo " rules : НЕТ ($f)" |
| +добавлено | return 0 |
| +добавлено | fi |
| +добавлено | mkdir -p "$(dirname "$f")" |
| +добавлено | { |
| +добавлено | sed -n '1,200p' "$FP_GLOBAL" |
| +добавлено | echo |
| +добавлено | echo "---" |
| +добавлено | echo "Скиллы: \`${skills_rel:-~/.agents/skills}\` — канон \`~/.agents/skills\` ($(skill_count "$CANON") шт.)." |
| +добавлено | echo "Память: \`~/AGENTS.md\` (контракт), \`~/AGENTS-SUMMARY.md\` (сводка), \`~/MEMORY.md\` (карта), \`~/Session-Context/\` (выжимки)." |
| +добавлено | echo "Инструменты: \`~/.agent-harness/tools/\`." |
| +добавлено | } > "$f" |
| +добавлено | echo " rules : записал ($f)" |
| +добавлено | } |
| +добавлено | |
| +добавлено | echo "канон: $CANON ($(skill_count "$CANON") скиллов) | режим: $MODE" |
| +добавлено | echo |
| +добавлено | for row in "${CLIENTS[@]}"; do |
| +добавлено | IFS='|' read -r id sdir rfile mcp <<<"$row" |
| +добавлено | echo "[$id]" |
| +добавлено | [ -n "$sdir" ] && link_skills "$H/$sdir" |
| +добавлено | [ -z "$sdir" ] && echo " skills : через аккаунт Freebuff (облако), локально не нужно" |
| +добавлено | [ -n "$rfile" ] && write_rules "$H/$rfile" "${sdir:+~/$sdir}" |
| +добавлено | case "$mcp" in |
| +добавлено | zcode) |
| +добавлено | # ZCode читает пользовательский MCP из ~/.agents/mcp.json (ключ mcpServers), |
| +добавлено | # а нативный ~/.zcode/cli/config.json ждёт mcp.servers. Держим один источник — |
| +добавлено | # ~/.agents/mcp.json: его же импортируют Claude Code / Codex / opencode. |
| +добавлено | shared="$H/.agents/mcp.json" |
| +добавлено | if [ -f "$shared" ]; then |
| +добавлено | echo " mcp : ~/.agents/mcp.json уже есть — не трогаю" |
| +добавлено | elif [ "$MODE" = "check" ]; then |
| +добавлено | echo " mcp : НЕТ (~/.agents/mcp.json из ~/.config/mcp/mcp.json)" |
| +добавлено | else |
| +добавлено | cp "$MCP_SRC" "$shared" && echo " mcp : записал ~/.agents/mcp.json ($(grep -c '"command"' "$shared") серверов)" |
| +добавлено | fi |
| +добавлено | if [ -f "$H/.zcode/cli/config.json" ] && grep -q '"mcp"' "$H/.zcode/cli/config.json" 2>/dev/null; then |
| +добавлено | echo " mcp : ВНИМАНИЕ — в ~/.zcode/cli/config.json есть свой mcp.servers, он перекрывает .agents/mcp.json" |
| +добавлено | fi |
| +добавлено | ;; |
| +добавлено | esac |
| +добавлено | done |
| +добавлено | echo |
| +добавлено | echo "проверка: bash ~/.agent-harness/tools/install.sh --check" |
| +добавлено | #!/usr/bin/env node |
| +добавлено | // tools/journeys.mjs — раннер сценарных frontend-journeys. |
| +добавлено | // |
| +добавлено | // Использование: |
| +добавлено | // node ~/.agent-harness/tools/journeys.mjs --cwd <проект> [--url http://...] |
| +добавлено | // [--journey auth,theme] [--list] [--headed] [--seed 42] [--update-snapshots] |
| +добавлено | // |
| +добавлено | // Конфиг проекта: journeys.config.json (url, serve, storageContract, selectors, perf, visual). |
| +добавлено | // Артефакты: .agent-state/artifacts/journeys-<ts>/ (скриншоты, summary.json, report.md). |
| +добавлено | // Exit codes: 0 — passed, 1 — failed, 2 — unverified (нет playwright/конфига/journeys). |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { spawn } from 'node:child_process'; |
| +добавлено | import { parseArgs, list, readJson, writeJsonAtomic, stateDir, appendEvent, fail } from './lib.mjs'; |
| +добавлено | import { discoverJourneys } from '../journeys/index.mjs'; |
| +добавлено | import { loadPlaywright, axeSource, runStep, makeCtx } from '../journeys/lib/runtime.mjs'; |
| +добавлено | import { deterministicInitScript } from '../journeys/fixtures/deterministic.mjs'; |
| +добавлено | import { cleanStorage } from '../journeys/fixtures/storage.mjs'; |
| +добавлено | import { viewport } from '../journeys/fixtures/viewports.mjs'; |
| +добавлено | |
| +добавлено | async function waitForUrl(url, timeoutMs = 15000) { |
| +добавлено | const deadline = Date.now() + timeoutMs; |
| +добавлено | while (Date.now() < deadline) { |
| +добавлено | try { |
| +добавлено | const res = await fetch(url, { method: 'HEAD' }); |
| +добавлено | if (res.ok) return true; |
| +добавлено | } catch { /* ещё не поднялся */ } |
| +добавлено | await new Promise((r) => setTimeout(r, 400)); |
| +добавлено | } |
| +добавлено | return false; |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function main() { |
| +добавлено | const { flags } = parseArgs(process.argv.slice(2)); |
| +добавлено | const cwd = path.resolve(flags.cwd && flags.cwd !== true ? flags.cwd : process.cwd()); |
| +добавлено | const config = readJson(path.join(cwd, 'journeys.config.json'), {}); |
| +добавлено | const seed = Number(flags.seed ?? config.seed ?? 42); |
| +добавлено | |
| +добавлено | const journeys = await discoverJourneys(); |
| +добавлено | |
| +добавлено | if (flags.list) { |
| +добавлено | for (const j of journeys) { |
| +добавлено | console.log(`${j.id}\n ${j.title}\n предусловия: ${j.preconditions.join('; ')}`); |
| +добавлено | } |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const url = flags.url && flags.url !== true ? flags.url : config.url; |
| +добавлено | if (!url) fail('Не задан URL: --url http://... или "url" в journeys.config.json', 2); |
| +добавлено | |
| +добавлено | const playwright = await loadPlaywright(cwd); |
| +добавлено | if (!playwright) { |
| +добавлено | console.log('playwright не найден ни в проекте, ни в ~/node_modules.'); |
| +добавлено | console.log('Verdict: UNVERIFIED — поставьте playwright (npm i -D playwright) и повторите.'); |
| +добавлено | process.exit(2); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- dev-сервер: поднимаем, если задан и url недоступен --- |
| +добавлено | let server = null; |
| +добавлено | if (!(await waitForUrl(url, 3000))) { |
| +добавлено | if (!config.serve) fail(`URL ${url} недоступен и "serve" в journeys.config.json не задан`, 2); |
| +добавлено | server = spawn(config.serve, { cwd, shell: true, stdio: 'ignore' }); |
| +добавлено | if (!(await waitForUrl(url))) fail(`serve не поднял ${url}: ${config.serve}`, 2); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const only = list(flags.journey); |
| +добавлено | const selected = journeys.filter((j) => !only.length || only.includes(j.id)); |
| +добавлено | if (!selected.length) fail(`Нет journeys под фильтр: ${only.join(', ')}`, 2); |
| +добавлено | |
| +добавлено | const runId = new Date().toISOString().replace(/[:.]/g, '-'); |
| +добавлено | const artifactsDir = path.join(stateDir(cwd), 'artifacts', `journeys-${runId}`); |
| +добавлено | const baselineDir = path.join(stateDir(cwd), 'journeys-baseline'); |
| +добавлено | fs.mkdirSync(artifactsDir, { recursive: true }); |
| +добавлено | |
| +добавлено | const axeSrc = axeSource(cwd); |
| +добавлено | const browser = await playwright.chromium.launch({ headless: !flags.headed }); |
| +добавлено | |
| +добавлено | const results = []; |
| +добавлено | try { |
| +добавлено | for (const journey of selected) { |
| +добавлено | console.log(`\n> ${journey.id}: ${journey.title}`); |
| +добавлено | const context = await browser.newContext({ viewport: viewport('desktop') }); |
| +добавлено | await context.addInitScript( |
| +добавлено | deterministicInitScript(seed, journey.fixtures?.clock ?? null, { startPaused: Boolean(journey.fixtures?.freezeOnLoad) }) |
| +добавлено | ); |
| +добавлено | if (journey.fixtures?.cleanStorage) await cleanStorage(context); |
| +добавлено | |
| +добавлено | const page = await context.newPage(); |
| +добавлено | const pageErrors = []; |
| +добавлено | page.on('pageerror', (e) => pageErrors.push(e.message)); |
| +добавлено | |
| +добавлено | const ctx = { |
| +добавлено | ...makeCtx({ page, journey, config, artifactsDir, axeSrc, updateSnapshots: Boolean(flags['update-snapshots']) }), |
| +добавлено | artifactsDir, |
| +добавлено | baselineDir, |
| +добавлено | seed, |
| +добавлено | async setViewport(name) { |
| +добавлено | await page.setViewportSize(viewport(name)); |
| +добавлено | }, |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const jr = { id: journey.id, title: journey.title, status: 'passed', steps: [], pageErrors }; |
| +добавлено | try { |
| +добавлено | await page.goto(url, { waitUntil: 'networkidle', timeout: 30000 }); |
| +добавлено | } catch { |
| +добавлено | await page.goto(url, { waitUntil: 'load', timeout: 30000 }); |
| +добавлено | } |
| +добавлено | await page.waitForTimeout(800); |
| +добавлено | |
| +добавлено | let broken = false; |
| +добавлено | for (const step of journey.steps(config)) { |
| +добавлено | if (broken) { |
| +добавлено | jr.steps.push({ name: step.name, status: 'skipped', reason: 'предыдущий шаг упал' }); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | const res = await runStep(step, page, ctx); |
| +добавлено | if (res.status === 'failed' && step.optional) res.status = 'warning'; |
| +добавлено | if (res.a11y && res.a11y.status === 'failed') { |
| +добавлено | res.status = step.optional ? 'warning' : 'failed'; |
| +добавлено | res.error = `axe: ${res.a11y.violations.map((v) => `${v.impact}:${v.id}(${v.nodes})`).join(', ')}`; |
| +добавлено | } |
| +добавлено | jr.steps.push(res); |
| +добавлено | const mark = { passed: 'ok', failed: 'FAIL', warning: 'warn', skipped: 'skip' }[res.status]; |
| +добавлено | console.log(` [${mark}] ${step.name}${res.error ? ` — ${res.error}` : ''}`); |
| +добавлено | if (res.status === 'failed') { jr.status = 'failed'; broken = true; } |
| +добавлено | } |
| +добавлено | if (jr.steps.some((s) => s.status === 'warning') && jr.status === 'passed') jr.status = 'warning'; |
| +добавлено | await context.close(); |
| +добавлено | results.push(jr); |
| +добавлено | } |
| +добавлено | } finally { |
| +добавлено | await browser.close(); |
| +добавлено | server?.kill(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const failed = results.filter((r) => r.status === 'failed'); |
| +добавлено | const warned = results.filter((r) => r.status === 'warning'); |
| +добавлено | const verdict = failed.length ? 'failed' : 'passed'; |
| +добавлено | |
| +добавлено | const summary = { |
| +добавлено | runId, cwd, url, seed, verdict, |
| +добавлено | journeys: results.map(({ id, status, title }) => ({ id, status, title })), |
| +добавлено | warnings: warned.map((r) => r.id), |
| +добавлено | finishedAt: new Date().toISOString(), |
| +добавлено | results, |
| +добавлено | }; |
| +добавлено | writeJsonAtomic(path.join(artifactsDir, 'summary.json'), summary); |
| +добавлено | writeJsonAtomic(path.join(stateDir(cwd), 'artifacts', 'journeys-latest.json'), summary); |
| +добавлено | |
| +добавлено | const report = [ |
| +добавлено | `# Journeys report — ${runId}`, |
| +добавлено | ``, |
| +добавлено | `URL: ${url} · seed: ${seed} · verdict: **${verdict.toUpperCase()}**`, |
| +добавлено | ``, |
| +добавлено | ...results.map((r) => [ |
| +добавлено | `## ${r.id} — ${r.status}`, |
| +добавлено | ``, |
| +добавлено | ...r.steps.map((s) => `- [${s.status}] ${s.name}${s.error ? ` — ${s.error}` : ''}${s.screenshot ? ` (📷 ${s.screenshot})` : ''}`), |
| +добавлено | r.pageErrors.length ? `\npage errors: ${r.pageErrors.join(' | ')}` : '', |
| +добавлено | ``, |
| +добавлено | ].join('\n')), |
| +добавлено | ].join('\n'); |
| +добавлено | fs.writeFileSync(path.join(artifactsDir, 'report.md'), report); |
| +добавлено | |
| +добавлено | appendEvent(cwd, { type: 'journeys.finished', runId, verdict }); |
| +добавлено | console.log(`\nVerdict: ${verdict.toUpperCase()} artifacts: ${path.relative(cwd, artifactsDir)}`); |
| +добавлено | if (warned.length) console.log(`Warnings (known gaps): ${warned.map((r) => r.id).join(', ')}`); |
| +добавлено | process.exit(verdict === 'passed' ? 0 : 1); |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith('journeys.mjs')) { |
| +добавлено | main().catch((error) => fail(error.message)); |
| +добавлено | } |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import os from 'node:os'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import crypto from 'node:crypto'; |
| +добавлено | import { fileURLToPath } from 'node:url'; |
| +добавлено | |
| +добавлено | export const HARNESS_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); |
| +добавлено | |
| +добавлено | export function homeDir() { |
| +добавлено | return process.env.HARNESS_HOME || os.homedir(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function stateDir(cwd = process.cwd()) { |
| +добавлено | return path.join(cwd, '.agent-state'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function parseArgs(argv) { |
| +добавлено | const positional = []; |
| +добавлено | const flags = {}; |
| +добавлено | for (let i = 0; i < argv.length; i += 1) { |
| +добавлено | const token = argv[i]; |
| +добавлено | if (!token.startsWith('--')) { |
| +добавлено | positional.push(token); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | const eq = token.indexOf('='); |
| +добавлено | if (eq !== -1) { |
| +добавлено | flags[token.slice(2, eq)] = token.slice(eq + 1); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | const key = token.slice(2); |
| +добавлено | const next = argv[i + 1]; |
| +добавлено | if (next === undefined || next.startsWith('--')) { |
| +добавлено | flags[key] = true; |
| +добавлено | } else { |
| +добавлено | flags[key] = next; |
| +добавлено | i += 1; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return { positional, flags }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function list(value) { |
| +добавлено | if (value === undefined || value === true || value === '') return []; |
| +добавлено | return String(value).split(',').map((s) => s.trim()).filter(Boolean); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function readJson(file, fallback) { |
| +добавлено | try { |
| +добавлено | return JSON.parse(fs.readFileSync(file, 'utf8')); |
| +добавлено | } catch (error) { |
| +добавлено | if (error.code === 'ENOENT' && fallback !== undefined) return fallback; |
| +добавлено | throw new Error(`Cannot read JSON ${file}: ${error.message}`); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function stripJsonComments(text) { |
| +добавлено | let out = ''; |
| +добавлено | let inString = false; |
| +добавлено | for (let i = 0; i < text.length; i += 1) { |
| +добавлено | const ch = text[i]; |
| +добавлено | const next = text[i + 1]; |
| +добавлено | if (inString) { |
| +добавлено | out += ch; |
| +добавлено | if (ch === '\\') { out += next ?? ''; i += 1; } else if (ch === '"') inString = false; |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | if (ch === '"') { inString = true; out += ch; continue; } |
| +добавлено | if (ch === '/' && next === '/') { while (i < text.length && text[i] !== '\n') i += 1; out += '\n'; continue; } |
| +добавлено | if (ch === '/' && next === '*') { i += 2; while (i < text.length && !(text[i] === '*' && text[i + 1] === '/')) i += 1; i += 1; continue; } |
| +добавлено | out += ch; |
| +добавлено | } |
| +добавлено | return out.replace(/,(\s*[}\]])/g, '$1'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function readJsonc(file) { |
| +добавлено | return JSON.parse(stripJsonComments(fs.readFileSync(file, 'utf8'))); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function writeJsonAtomic(file, data) { |
| +добавлено | fs.mkdirSync(path.dirname(file), { recursive: true }); |
| +добавлено | const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`; |
| +добавлено | fs.writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`); |
| +добавлено | fs.renameSync(tmp, file); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function sleepSync(ms) { |
| +добавлено | Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function withLock(lockPath, fn, { timeoutMs = 15000, staleMs = 30000 } = {}) { |
| +добавлено | fs.mkdirSync(path.dirname(lockPath), { recursive: true }); |
| +добавлено | const started = Date.now(); |
| +добавлено | for (;;) { |
| +добавлено | try { |
| +добавлено | fs.mkdirSync(lockPath); |
| +добавлено | fs.writeFileSync(path.join(lockPath, 'owner'), `${process.pid} ${new Date().toISOString()}`); |
| +добавлено | break; |
| +добавлено | } catch (error) { |
| +добавлено | if (error.code !== 'EEXIST') throw error; |
| +добавлено | try { |
| +добавлено | const age = Date.now() - fs.statSync(lockPath).mtimeMs; |
| +добавлено | if (age > staleMs) { |
| +добавлено | fs.rmSync(lockPath, { recursive: true, force: true }); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | } catch { |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | if (Date.now() - started > timeoutMs) throw new Error(`Lock timeout: ${lockPath}`); |
| +добавлено | sleepSync(25 + Math.floor(Math.random() * 50)); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | try { |
| +добавлено | return fn(); |
| +добавлено | } finally { |
| +добавлено | fs.rmSync(lockPath, { recursive: true, force: true }); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function appendEvent(cwd, event) { |
| +добавлено | const dir = stateDir(cwd); |
| +добавлено | fs.mkdirSync(dir, { recursive: true }); |
| +добавлено | fs.appendFileSync(path.join(dir, 'events.jsonl'), `${JSON.stringify({ at: new Date().toISOString(), ...event })}\n`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function wildcardToRegExp(pattern) { |
| +добавлено | const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.'); |
| +добавлено | return new RegExp(`^${escaped}$`, 's'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function sha256(file) { |
| +добавлено | return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function walkFiles(dir, { skip = ['node_modules', '.git', '.agent-state', '.agent-worktrees', '.next', 'dist'] } = {}) { |
| +добавлено | const out = []; |
| +добавлено | if (!fs.existsSync(dir)) return out; |
| +добавлено | const stack = [dir]; |
| +добавлено | while (stack.length) { |
| +добавлено | const current = stack.pop(); |
| +добавлено | for (const entry of fs.readdirSync(current, { withFileTypes: true })) { |
| +добавлено | if (skip.includes(entry.name)) continue; |
| +добавлено | const full = path.join(current, entry.name); |
| +добавлено | if (entry.isDirectory()) stack.push(full); |
| +добавлено | else if (entry.isFile()) out.push(full); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return out.sort(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function copyDir(src, dest, { onFile } = {}) { |
| +добавлено | for (const file of walkFiles(src, { skip: [] })) { |
| +добавлено | const rel = path.relative(src, file); |
| +добавлено | const target = path.join(dest, rel); |
| +добавлено | if (onFile && onFile(file, target) === false) continue; |
| +добавлено | fs.mkdirSync(path.dirname(target), { recursive: true }); |
| +добавлено | fs.copyFileSync(file, target); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function resolveConfig(name, cwd = process.cwd()) { |
| +добавлено | const candidates = [ |
| +добавлено | path.join(cwd, name), |
| +добавлено | path.join(homeDir(), '.agent-harness', name), |
| +добавлено | path.join(HARNESS_ROOT, name), |
| +добавлено | ]; |
| +добавлено | return candidates.find((p) => fs.existsSync(p)) ?? null; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function fail(message, code = 1) { |
| +добавлено | console.error(`error: ${message}`); |
| +добавлено | process.exit(code); |
| +добавлено | } |
| +добавлено | #!/usr/bin/env node |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { parseArgs, list, readJson, writeJsonAtomic, withLock, appendEvent, stateDir, fail } from './lib.mjs'; |
| +добавлено | |
| +добавлено | const RISKS = ['read', 'write', 'sensitive', 'destructive']; |
| +добавлено | const NEEDS_APPROVAL = new Set(['sensitive', 'destructive']); |
| +добавлено | const ERROR_CLASSES = ['transient', 'permanent', 'policy', 'timeout']; |
| +добавлено | const TERMINAL = new Set(['done', 'failed', 'cancelled']); |
| +добавлено | |
| +добавлено | const cwd = process.cwd(); |
| +добавлено | const dir = stateDir(cwd); |
| +добавлено | const file = path.join(dir, 'tasks.json'); |
| +добавлено | const lock = path.join(dir, 'tasks.lock'); |
| +добавлено | |
| +добавлено | function emptyState() { |
| +добавлено | return { version: 2, seq: 0, budget: { maxTasks: 50, maxAttempts: 3, defaultTimeoutMin: 30 }, tasks: {} }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function load() { |
| +добавлено | const state = readJson(file, emptyState()); |
| +добавлено | if (state.version !== 2) fail(`Unsupported state version in ${file}. Move it away and run init.`); |
| +добавлено | return state; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function mutate(fn) { |
| +добавлено | return withLock(lock, () => { |
| +добавлено | const state = load(); |
| +добавлено | const result = fn(state); |
| +добавлено | writeJsonAtomic(file, state); |
| +добавлено | return result; |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function now() { |
| +добавлено | return new Date().toISOString(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function requireTask(state, id) { |
| +добавлено | const task = state.tasks[id]; |
| +добавлено | if (!task) fail(`Unknown task ${id}`); |
| +добавлено | return task; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function requireOwner(task, agent, force) { |
| +добавлено | if (force) return; |
| +добавлено | if (!agent) fail('--agent is required'); |
| +добавлено | if (task.owner !== agent) fail(`Task ${task.id} is owned by ${task.owner ?? 'nobody'}, not ${agent}`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function touch(task, patch) { |
| +добавлено | Object.assign(task, patch, { updatedAt: now() }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function reclaimExpired(state) { |
| +добавлено | const reclaimed = []; |
| +добавлено | const current = Date.now(); |
| +добавлено | for (const task of Object.values(state.tasks)) { |
| +добавлено | if (task.status !== 'running' || !task.leaseUntil) continue; |
| +добавлено | if (Date.parse(task.leaseUntil) > current) continue; |
| +добавлено | applyFailure(task, 'timeout', `Lease expired for ${task.owner}`); |
| +добавлено | reclaimed.push(task.id); |
| +добавлено | } |
| +добавлено | return reclaimed; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function applyFailure(task, errorClass, message) { |
| +добавлено | const retryable = errorClass === 'transient' || errorClass === 'timeout'; |
| +добавлено | const canRetry = retryable && task.attempts < task.maxAttempts; |
| +добавлено | touch(task, { |
| +добавлено | status: canRetry ? 'pending' : 'failed', |
| +добавлено | owner: null, |
| +добавлено | leaseUntil: null, |
| +добавлено | lastError: { class: errorClass, message, at: now() }, |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function depsState(state, task) { |
| +добавлено | const deps = task.deps.map((id) => state.tasks[id]); |
| +добавлено | if (deps.some((d) => !d || d.status === 'failed' || d.status === 'cancelled')) return 'broken'; |
| +добавлено | if (deps.every((d) => d.status === 'done')) return 'ready'; |
| +добавлено | return 'waiting'; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function printTable(state) { |
| +добавлено | const rows = Object.values(state.tasks); |
| +добавлено | if (!rows.length) { |
| +добавлено | console.log('No tasks.'); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | for (const t of rows) { |
| +добавлено | const deps = t.deps.length ? ` deps=${t.deps.join(',')}(${depsState(state, t)})` : ''; |
| +добавлено | const owner = t.owner ? ` owner=${t.owner}` : ''; |
| +добавлено | const err = t.lastError ? ` lastError=${t.lastError.class}` : ''; |
| +добавлено | const verified = t.status === 'done' ? (t.verified ? ' verified' : ' UNVERIFIED') : ''; |
| +добавлено | console.log(`${t.id} ${t.status.padEnd(17)} ${t.role.padEnd(10)} risk=${t.risk} try=${t.attempts}/${t.maxAttempts}${owner}${deps}${err}${verified} ${t.title}`); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | const commands = { |
| +добавлено | init(flags) { |
| +добавлено | mutate((state) => { |
| +добавлено | if (flags['max-tasks']) state.budget.maxTasks = Number(flags['max-tasks']); |
| +добавлено | if (flags['max-attempts']) state.budget.maxAttempts = Number(flags['max-attempts']); |
| +добавлено | if (flags['timeout']) state.budget.defaultTimeoutMin = Number(flags.timeout); |
| +добавлено | console.log(`Initialized ${file}`, JSON.stringify(state.budget)); |
| +добавлено | }); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | add(flags) { |
| +добавлено | if (!flags.title || flags.title === true) fail('--title is required'); |
| +добавлено | const risk = flags.risk ?? 'write'; |
| +добавлено | if (!RISKS.includes(risk)) fail(`--risk must be one of ${RISKS.join(', ')}`); |
| +добавлено | const task = mutate((state) => { |
| +добавлено | const active = Object.values(state.tasks).filter((t) => t.status !== 'cancelled').length; |
| +добавлено | if (active >= state.budget.maxTasks) fail(`Budget exceeded: maxTasks=${state.budget.maxTasks}`); |
| +добавлено | const deps = list(flags.deps); |
| +добавлено | for (const dep of deps) if (!state.tasks[dep]) fail(`Unknown dependency ${dep}`); |
| +добавлено | state.seq += 1; |
| +добавлено | const id = `T-${String(state.seq).padStart(4, '0')}`; |
| +добавлено | const created = { |
| +добавлено | id, |
| +добавлено | title: flags.title, |
| +добавлено | role: flags.role && flags.role !== true ? flags.role : 'builder', |
| +добавлено | risk, |
| +добавлено | deps, |
| +добавлено | status: NEEDS_APPROVAL.has(risk) ? 'awaiting_approval' : 'pending', |
| +добавлено | attempts: 0, |
| +добавлено | maxAttempts: Number(flags['max-attempts'] ?? state.budget.maxAttempts), |
| +добавлено | timeoutMin: Number(flags.timeout ?? state.budget.defaultTimeoutMin), |
| +добавлено | owner: null, |
| +добавлено | leaseUntil: null, |
| +добавлено | approval: null, |
| +добавлено | verified: false, |
| +добавлено | evidence: [], |
| +добавлено | notes: [], |
| +добавлено | next: flags.next && flags.next !== true ? flags.next : null, |
| +добавлено | lastError: null, |
| +добавлено | createdAt: now(), |
| +добавлено | updatedAt: now(), |
| +добавлено | }; |
| +добавлено | state.tasks[id] = created; |
| +добавлено | return created; |
| +добавлено | }); |
| +добавлено | appendEvent(cwd, { type: 'task.added', id: task.id, risk: task.risk, role: task.role }); |
| +добавлено | console.log(task.id); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | approve(flags) { |
| +добавлено | if (!flags.id || !flags.by || flags.by === true) fail('--id and --by are required'); |
| +добавлено | mutate((state) => { |
| +добавлено | const task = requireTask(state, flags.id); |
| +добавлено | if (task.status !== 'awaiting_approval') fail(`Task ${task.id} is ${task.status}, not awaiting_approval`); |
| +добавлено | touch(task, { status: 'pending', approval: { by: flags.by, note: flags.note ?? null, at: now() } }); |
| +добавлено | }); |
| +добавлено | appendEvent(cwd, { type: 'task.approved', id: flags.id, by: flags.by }); |
| +добавлено | console.log(`Approved ${flags.id} by ${flags.by}`); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | claim(flags) { |
| +добавлено | if (!flags.agent || flags.agent === true) fail('--agent is required'); |
| +добавлено | const role = flags.role && flags.role !== true ? flags.role : null; |
| +добавлено | const wantedId = flags.id && flags.id !== true ? flags.id : null; |
| +добавлено | const claimed = mutate((state) => { |
| +добавлено | const reclaimed = reclaimExpired(state); |
| +добавлено | for (const id of reclaimed) appendEvent(cwd, { type: 'task.reclaimed', id }); |
| +добавлено | let candidate; |
| +добавлено | if (wantedId) { |
| +добавлено | const task = state.tasks[wantedId]; |
| +добавлено | if (!task) fail(`Unknown task ${wantedId}`); |
| +добавлено | if (task.status !== 'pending') fail(`Task ${wantedId} is ${task.status}, not pending`); |
| +добавлено | const deps = depsState(state, task); |
| +добавлено | if (deps !== 'ready') fail(`Task ${wantedId} deps are ${deps}`); |
| +добавлено | candidate = task; |
| +добавлено | } else { |
| +добавлено | candidate = Object.values(state.tasks).find( |
| +добавлено | (t) => t.status === 'pending' && (!role || t.role === role) && depsState(state, t) === 'ready', |
| +добавлено | ); |
| +добавлено | } |
| +добавлено | if (!candidate) return null; |
| +добавлено | const lease = new Date(Date.now() + candidate.timeoutMin * 60_000).toISOString(); |
| +добавлено | touch(candidate, { status: 'running', owner: flags.agent, attempts: candidate.attempts + 1, leaseUntil: lease }); |
| +добавлено | return candidate; |
| +добавлено | }); |
| +добавлено | if (!claimed) { |
| +добавлено | console.log('No claimable task.'); |
| +добавлено | process.exit(3); |
| +добавлено | } |
| +добавлено | appendEvent(cwd, { type: 'task.claimed', id: claimed.id, agent: flags.agent, attempt: claimed.attempts }); |
| +добавлено | console.log(JSON.stringify(claimed, null, 2)); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | heartbeat(flags) { |
| +добавлено | mutate((state) => { |
| +добавлено | const task = requireTask(state, flags.id); |
| +добавлено | if (task.status !== 'running') fail(`Task ${task.id} is ${task.status}`); |
| +добавлено | requireOwner(task, flags.agent, false); |
| +добавлено | touch(task, { leaseUntil: new Date(Date.now() + task.timeoutMin * 60_000).toISOString() }); |
| +добавлено | }); |
| +добавлено | console.log(`Lease extended for ${flags.id}`); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | note(flags) { |
| +добавлено | if (!flags.text || flags.text === true) fail('--text is required'); |
| +добавлено | mutate((state) => { |
| +добавлено | const task = requireTask(state, flags.id); |
| +добавлено | task.notes.push({ at: now(), by: flags.agent ?? null, text: flags.text }); |
| +добавлено | if (flags.next && flags.next !== true) task.next = flags.next; |
| +добавлено | touch(task, {}); |
| +добавлено | }); |
| +добавлено | console.log(`Note added to ${flags.id}`); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | finish(flags) { |
| +добавлено | const evidence = list(flags.evidence); |
| +добавлено | const unverified = Boolean(flags.unverified); |
| +добавлено | if (!evidence.length && !unverified) fail('Provide --evidence path1,path2 or mark explicitly with --unverified'); |
| +добавлено | mutate((state) => { |
| +добавлено | const task = requireTask(state, flags.id); |
| +добавлено | if (task.status !== 'running') fail(`Task ${task.id} is ${task.status}, not running`); |
| +добавлено | requireOwner(task, flags.agent, Boolean(flags.force)); |
| +добавлено | task.evidence.push(...evidence); |
| +добавлено | if (flags.note && flags.note !== true) task.notes.push({ at: now(), by: flags.agent ?? null, text: flags.note }); |
| +добавлено | touch(task, { status: 'done', owner: null, leaseUntil: null, verified: evidence.length > 0 && !unverified }); |
| +добавлено | }); |
| +добавлено | appendEvent(cwd, { type: 'task.finished', id: flags.id, verified: evidence.length > 0 && !unverified }); |
| +добавлено | console.log(`Finished ${flags.id}${unverified ? ' (UNVERIFIED)' : ''}`); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | fail(flags) { |
| +добавлено | const errorClass = flags.class ?? 'permanent'; |
| +добавлено | if (!ERROR_CLASSES.includes(errorClass)) fail(`--class must be one of ${ERROR_CLASSES.join(', ')}`); |
| +добавлено | const task = mutate((state) => { |
| +добавлено | const t = requireTask(state, flags.id); |
| +добавлено | if (t.status !== 'running') fail(`Task ${t.id} is ${t.status}, not running`); |
| +добавлено | requireOwner(t, flags.agent, Boolean(flags.force)); |
| +добавлено | applyFailure(t, errorClass, flags.error && flags.error !== true ? flags.error : 'unspecified'); |
| +добавлено | return t; |
| +добавлено | }); |
| +добавлено | appendEvent(cwd, { type: 'task.failed', id: task.id, class: errorClass, status: task.status }); |
| +добавлено | console.log(`${task.id} -> ${task.status}${task.status === 'pending' ? ` (retry ${task.attempts}/${task.maxAttempts})` : ''}`); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | cancel(flags) { |
| +добавлено | mutate((state) => { |
| +добавлено | const task = requireTask(state, flags.id); |
| +добавлено | if (TERMINAL.has(task.status)) fail(`Task ${task.id} is already ${task.status}`); |
| +добавлено | task.notes.push({ at: now(), by: flags.by ?? null, text: `cancelled: ${flags.reason ?? 'no reason'}` }); |
| +добавлено | touch(task, { status: 'cancelled', owner: null, leaseUntil: null }); |
| +добавлено | }); |
| +добавлено | appendEvent(cwd, { type: 'task.cancelled', id: flags.id }); |
| +добавлено | console.log(`Cancelled ${flags.id}`); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | reclaim() { |
| +добавлено | const reclaimed = mutate((state) => reclaimExpired(state)); |
| +добавлено | for (const id of reclaimed) appendEvent(cwd, { type: 'task.reclaimed', id }); |
| +добавлено | console.log(reclaimed.length ? `Reclaimed: ${reclaimed.join(', ')}` : 'Nothing to reclaim.'); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | reopen(flags) { |
| +добавлено | mutate((state) => { |
| +добавлено | const task = requireTask(state, flags.id); |
| +добавлено | if (task.status !== 'failed' && task.status !== 'cancelled') fail(`Task ${task.id} is ${task.status}, not failed/cancelled`); |
| +добавлено | const reset = Boolean(flags['reset-attempts']); |
| +добавлено | touch(task, { |
| +добавлено | status: NEEDS_APPROVAL.has(task.risk) ? 'awaiting_approval' : 'pending', |
| +добавлено | owner: null, |
| +добавлено | leaseUntil: null, |
| +добавлено | attempts: reset ? 0 : task.attempts, |
| +добавлено | lastError: null, |
| +добавлено | verified: false, |
| +добавлено | }); |
| +добавлено | task.notes.push({ at: now(), by: flags.by ?? null, text: `reopened${reset ? ' (attempts reset)' : ''}` }); |
| +добавлено | }); |
| +добавлено | appendEvent(cwd, { type: 'task.reopened', id: flags.id }); |
| +добавлено | console.log(`Reopened ${flags.id}`); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | show(flags) { |
| +добавлено | const task = requireTask(load(), flags.id); |
| +добавлено | console.log(JSON.stringify(task, null, 2)); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | events(flags) { |
| +добавлено | const eventsFile = path.join(dir, 'events.jsonl'); |
| +добавлено | if (!fs.existsSync(eventsFile)) { |
| +добавлено | console.log('(no events)'); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | const tail = Number(flags.tail ?? 20); |
| +добавлено | console.log(fs.readFileSync(eventsFile, 'utf8').trim().split('\n').slice(-tail).join('\n')); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | status(flags) { |
| +добавлено | const state = load(); |
| +добавлено | if (flags.json) { |
| +добавлено | console.log(JSON.stringify(state, null, 2)); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | console.log(`Budget: maxTasks=${state.budget.maxTasks} maxAttempts=${state.budget.maxAttempts} timeout=${state.budget.defaultTimeoutMin}m`); |
| +добавлено | printTable(state); |
| +добавлено | }, |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const HELP = `Usage: node orchestrator.mjs <command> [flags] |
| +добавлено | |
| +добавлено | init [--max-tasks 50] [--max-attempts 3] [--timeout 30] |
| +добавлено | add --title "..." [--role builder] [--risk read|write|sensitive|destructive] |
| +добавлено | [--deps T-0001,T-0002] [--max-attempts N] [--timeout MIN] [--next "..."] |
| +добавлено | approve --id T-0001 --by <human> (sensitive/destructive tasks only) |
| +добавлено | claim --agent <name> [--role <role>] [--id T-0001] exit 3 when nothing is claimable |
| +добавлено | heartbeat --id T-0001 --agent <name> |
| +добавлено | note --id T-0001 --text "..." [--next "..."] [--agent <name>] |
| +добавлено | finish --id T-0001 --agent <name> --evidence a,b | --unverified [--note "..."] |
| +добавлено | fail --id T-0001 --agent <name> --class transient|permanent|policy|timeout --error "..." |
| +добавлено | cancel --id T-0001 [--reason "..."] |
| +добавлено | reopen --id T-0001 [--by <name>] [--reset-attempts] failed/cancelled -> pending |
| +добавлено | reclaim return expired leases to the queue |
| +добавлено | show --id T-0001 |
| +добавлено | events [--tail 20] |
| +добавлено | status [--json] |
| +добавлено | |
| +добавлено | State: ./.agent-state/tasks.json (locked, atomic writes). Events: ./.agent-state/events.jsonl`; |
| +добавлено | |
| +добавлено | const { positional, flags } = parseArgs(process.argv.slice(2)); |
| +добавлено | const command = commands[positional[0]]; |
| +добавлено | if (!command) { |
| +добавлено | console.log(HELP); |
| +добавлено | process.exit(positional[0] ? 1 : 0); |
| +добавлено | } |
| +добавлено | command(flags); |
| +добавлено | #!/usr/bin/env node |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { spawnSync } from 'node:child_process'; |
| +добавлено | import { parseArgs, readJson, writeJsonAtomic, resolveConfig, wildcardToRegExp, walkFiles, stateDir, appendEvent, fail } from './lib.mjs'; |
| +добавлено | |
| +добавлено | const RANK = { allow: 0, ask: 1, deny: 2 }; |
| +добавлено | |
| +добавлено | export const SECRET_RULES = [ |
| +добавлено | { id: 'private-key', re: /-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----/ }, |
| +добавлено | { id: 'aws-access-key', re: /\bAKIA[0-9A-Z]{16}\b/ }, |
| +добавлено | { id: 'github-token', re: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,}\b|\bgithub_pat_[A-Za-z0-9_]{60,}\b/ }, |
| +добавлено | { id: 'openai-key', re: /\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}\b/ }, |
| +добавлено | { id: 'anthropic-key', re: /\bsk-ant-[A-Za-z0-9_-]{32,}\b/ }, |
| +добавлено | { id: 'tavily-key', re: /\btvly-[A-Za-z0-9_-]{20,}\b/ }, |
| +добавлено | { id: 'google-api-key', re: /\bAIza[0-9A-Za-z_-]{35}\b/ }, |
| +добавлено | { id: 'slack-token', re: /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/ }, |
| +добавлено | { id: 'jwt', re: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/ }, |
| +добавлено | { |
| +добавлено | id: 'generic-assignment', |
| +добавлено | re: /(?:api[_-]?key|secret|token|password|passwd)["']?\s*[:=]\s*["']([^"'\s]{12,})["']/i, |
| +добавлено | placeholder: /ВСТАВЬ|INSERT|YOUR_|your-|xxx|changeme|example|placeholder|\$\{|\{env:|<[^>]+>/i, |
| +добавлено | }, |
| +добавлено | ]; |
| +добавлено | |
| +добавлено | export function loadPolicy(cwd = process.cwd()) { |
| +добавлено | const file = resolveConfig('.release-policy.json', cwd); |
| +добавлено | if (!file) fail('No .release-policy.json found'); |
| +добавлено | return { file, policy: readJson(file) }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const SECRET_FILE_RE = /(?:^|[\s/'"=<>:@])(?:\.env(?:\.[\w-]+)*|[\w.-]*\.pem|[\w.-]*\.key|id_rsa[\w.-]*|id_ed25519[\w.-]*|id_ecdsa[\w.-]*|\.npmrc|\.netrc|\.pgpass|credentials(?:\.json)?|auth\.json)(?=$|[\s'"|;&)<>])/; |
| +добавлено | const SECRET_FILE_ALLOW_RE = /\.env\.(?:example|sample|template|dist|defaults)\b|auth\.json\.example\b/; |
| +добавлено | |
| +добавлено | export function touchesSecretFile(text) { |
| +добавлено | const cleaned = text.replace(new RegExp(SECRET_FILE_ALLOW_RE.source, 'g'), ' '); |
| +добавлено | return SECRET_FILE_RE.test(cleaned); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function unwrapShell(command) { |
| +добавлено | const nested = []; |
| +добавлено | const re = /\b(?:bash|sh|zsh|dash)\s+(?:-\w+\s+)*-c\s+(['"])([\s\S]*?)\1/g; |
| +добавлено | for (const m of command.matchAll(re)) nested.push(m[2]); |
| +добавлено | for (const m of command.matchAll(/\$\(([^()]*)\)|`([^`]*)`/g)) nested.push(m[1] ?? m[2]); |
| +добавлено | return nested; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function splitSegments(command) { |
| +добавлено | const parts = [command, ...unwrapShell(command)]; |
| +добавлено | return parts |
| +добавлено | .flatMap((part) => part.split(/\s*(?:&&|\|\||;|\||\n)\s*/)) |
| +добавлено | .map((s) => s.trim().replace(/^(?:sudo\s+(?:-\S+\s+)*|env\s+(?:\S+=\S+\s+)*|command\s+|exec\s+|nohup\s+|time\s+)/, '')) |
| +добавлено | .filter(Boolean); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function matchList(patterns, text) { |
| +добавлено | return (patterns ?? []).find((p) => wildcardToRegExp(p).test(text)) ?? null; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function classify(command, policy) { |
| +добавлено | const rules = policy.commands ?? {}; |
| +добавлено | if (rules.denySecretFiles !== false && touchesSecretFile(command)) { |
| +добавлено | return { decision: 'deny', rule: '(secret-file)', segment: command.trim() }; |
| +добавлено | } |
| +добавлено | const checks = [command.trim(), ...splitSegments(command)]; |
| +добавлено | let decision = { decision: 'allow', rule: null, segment: null }; |
| +добавлено | let anyAllowed = false; |
| +добавлено | for (const text of checks) { |
| +добавлено | const deny = matchList(rules.deny, text); |
| +добавлено | const ask = matchList(rules.ask, text); |
| +добавлено | const allow = matchList(rules.allow, text); |
| +добавлено | let current; |
| +добавлено | if (deny) current = { decision: 'deny', rule: deny, segment: text }; |
| +добавлено | else if (ask) current = { decision: 'ask', rule: ask, segment: text }; |
| +добавлено | else if (allow) { |
| +добавлено | anyAllowed = true; |
| +добавлено | continue; |
| +добавлено | } else if (text === command.trim()) continue; |
| +добавлено | else current = { decision: rules.default ?? 'ask', rule: '(default)', segment: text }; |
| +добавлено | if (RANK[current.decision] > RANK[decision.decision]) decision = current; |
| +добавлено | } |
| +добавлено | if (!anyAllowed && decision.decision === 'allow') decision = { decision: rules.default ?? 'ask', rule: '(default)', segment: command.trim() }; |
| +добавлено | return decision; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function scanText(text) { |
| +добавлено | const findings = []; |
| +добавлено | const lines = text.split('\n'); |
| +добавлено | lines.forEach((line, index) => { |
| +добавлено | for (const rule of SECRET_RULES) { |
| +добавлено | const match = line.match(rule.re); |
| +добавлено | if (!match) continue; |
| +добавлено | if (rule.placeholder && rule.placeholder.test(match[0])) continue; |
| +добавлено | const value = match[1] ?? match[0]; |
| +добавлено | findings.push({ line: index + 1, rule: rule.id, preview: `${value.slice(0, 4)}…${'*'.repeat(6)}` }); |
| +добавлено | } |
| +добавлено | }); |
| +добавлено | return findings; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function scanFiles(files) { |
| +добавлено | const results = []; |
| +добавлено | for (const file of files) { |
| +добавлено | let stat; |
| +добавлено | try { |
| +добавлено | stat = fs.statSync(file); |
| +добавлено | } catch { |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | if (!stat.isFile() || stat.size > 1_000_000) continue; |
| +добавлено | const buf = fs.readFileSync(file); |
| +добавлено | if (buf.includes(0)) continue; |
| +добавлено | for (const f of scanText(buf.toString('utf8'))) results.push({ file, ...f }); |
| +добавлено | } |
| +добавлено | return results; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function gitFiles(cwd, staged) { |
| +добавлено | const args = staged ? ['diff', '--cached', '--name-only', '--diff-filter=ACM'] : ['ls-files', '--cached', '--others', '--exclude-standard']; |
| +добавлено | const res = spawnSync('git', args, { cwd, encoding: 'utf8' }); |
| +добавлено | if (res.status !== 0) return null; |
| +добавлено | return res.stdout.split('\n').filter(Boolean).map((f) => path.join(cwd, f)); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function opencodePermission(policy) { |
| +добавлено | const rules = policy.commands ?? {}; |
| +добавлено | const bash = { '*': rules.default ?? 'ask' }; |
| +добавлено | for (const p of rules.allow ?? []) bash[p] = 'allow'; |
| +добавлено | for (const p of rules.ask ?? []) bash[p] = 'ask'; |
| +добавлено | for (const p of rules.deny ?? []) bash[p] = 'deny'; |
| +добавлено | return { |
| +добавлено | permission: { |
| +добавлено | bash, |
| +добавлено | edit: 'allow', |
| +добавлено | read: { |
| +добавлено | '*': 'allow', |
| +добавлено | '*.env': 'deny', |
| +добавлено | '*.env.*': 'deny', |
| +добавлено | '*.env.example': 'allow', |
| +добавлено | '*.env.sample': 'allow', |
| +добавлено | '*.env.template': 'allow', |
| +добавлено | '*.pem': 'deny', |
| +добавлено | '*.key': 'deny', |
| +добавлено | '*id_rsa*': 'deny', |
| +добавлено | '*id_ed25519*': 'deny', |
| +добавлено | '*id_ecdsa*': 'deny', |
| +добавлено | '*.npmrc': 'deny', |
| +добавлено | '*.netrc': 'deny', |
| +добавлено | '*.pgpass': 'deny', |
| +добавлено | }, |
| +добавлено | external_directory: 'ask', |
| +добавлено | doom_loop: 'ask', |
| +добавлено | }, |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const cwd = process.cwd(); |
| +добавлено | const commands = { |
| +добавлено | check([command]) { |
| +добавлено | if (!command) fail('Usage: policy.mjs check "<command>"'); |
| +добавлено | const { policy } = loadPolicy(cwd); |
| +добавлено | const result = classify(command, policy); |
| +добавлено | console.log(JSON.stringify(result)); |
| +добавлено | process.exit(result.decision === 'allow' ? 0 : result.decision === 'ask' ? 2 : 3); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | scan(paths, flags) { |
| +добавлено | let files; |
| +добавлено | if (paths.length) files = paths.flatMap((p) => (fs.statSync(p).isDirectory() ? walkFiles(p) : [path.resolve(p)])); |
| +добавлено | else files = gitFiles(cwd, Boolean(flags.staged)) ?? walkFiles(cwd); |
| +добавлено | const findings = scanFiles(files); |
| +добавлено | for (const f of findings) console.log(`${path.relative(cwd, f.file)}:${f.line} ${f.rule} ${f.preview}`); |
| +добавлено | console.log(findings.length ? `\n${findings.length} potential secret(s). Remove them and rotate the keys.` : `No secrets found in ${files.length} file(s).`); |
| +добавлено | process.exit(findings.length ? 1 : 0); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | 'approve-release'(_, flags) { |
| +добавлено | if (!flags.by || flags.by === true) fail('--by <human> is required'); |
| +добавлено | if (!flags.rollback || flags.rollback === true || !fs.existsSync(flags.rollback)) fail('--rollback <file> must point to an existing rollback plan'); |
| +добавлено | const head = spawnSync('git', ['rev-parse', 'HEAD'], { cwd, encoding: 'utf8' }).stdout.trim() || null; |
| +добавлено | const record = { by: flags.by, rollback: flags.rollback, target: flags.target ?? null, head, at: new Date().toISOString() }; |
| +добавлено | writeJsonAtomic(path.join(stateDir(cwd), 'approvals', 'release.json'), record); |
| +добавлено | appendEvent(cwd, { type: 'release.approved', by: flags.by, head }); |
| +добавлено | console.log(`Release approved by ${flags.by} for ${head ?? 'non-git workspace'}`); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | release() { |
| +добавлено | const { policy } = loadPolicy(cwd); |
| +добавлено | const rules = policy.release ?? {}; |
| +добавлено | const checks = []; |
| +добавлено | const add = (name, ok, detail) => checks.push({ name, ok, detail }); |
| +добавлено | |
| +добавлено | const status = spawnSync('git', ['status', '--porcelain'], { cwd, encoding: 'utf8' }); |
| +добавлено | const head = spawnSync('git', ['rev-parse', 'HEAD'], { cwd, encoding: 'utf8' }).stdout.trim(); |
| +добавлено | if (rules.requireCleanTree) add('clean-tree', status.status === 0 && !status.stdout.trim(), status.status === 0 ? `${status.stdout.split('\n').filter(Boolean).length} changed file(s)` : 'not a git repo'); |
| +добавлено | |
| +добавлено | if (rules.requireGatesPassed) { |
| +добавлено | const gates = readJson(path.join(stateDir(cwd), 'artifacts', 'gates-latest.json'), null); |
| +добавлено | const ageMin = gates ? (Date.now() - Date.parse(gates.finishedAt)) / 60000 : Infinity; |
| +добавлено | add('gates-passed', gates?.verdict === 'passed' && ageMin <= (rules.gatesMaxAgeMinutes ?? 60), gates ? `${gates.verdict}, ${Math.round(ageMin)} min ago` : 'no gates run'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const secrets = scanFiles(gitFiles(cwd, false) ?? walkFiles(cwd)); |
| +добавлено | add('no-secrets', secrets.length === 0, `${secrets.length} finding(s)`); |
| +добавлено | |
| +добавлено | if (rules.requireApproval || rules.requireRollbackPlan) { |
| +добавлено | const approval = readJson(path.join(stateDir(cwd), 'approvals', 'release.json'), null); |
| +добавлено | if (rules.requireApproval) add('approval', Boolean(approval) && (!approval.head || approval.head === head), approval ? `by ${approval.by} for ${approval.head?.slice(0, 10)}` : 'missing'); |
| +добавлено | if (rules.requireRollbackPlan) add('rollback-plan', Boolean(approval?.rollback && fs.existsSync(path.resolve(cwd, approval.rollback))), approval?.rollback ?? 'missing'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | for (const c of checks) console.log(`${c.ok ? 'PASS' : 'FAIL'} ${c.name.padEnd(14)} ${c.detail}`); |
| +добавлено | const ok = checks.every((c) => c.ok); |
| +добавлено | console.log(`\nRelease gate: ${ok ? 'OPEN' : 'BLOCKED'}`); |
| +добавлено | process.exit(ok ? 0 : 1); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | 'opencode-permission'() { |
| +добавлено | const { policy } = loadPolicy(cwd); |
| +добавлено | console.log(JSON.stringify(opencodePermission(policy), null, 2)); |
| +добавлено | }, |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const HELP = `Usage: node policy.mjs <command> |
| +добавлено | |
| +добавлено | check "<shell command>" exit 0 allow, 2 ask (needs human approval), 3 deny |
| +добавлено | scan [paths...] [--staged] secret scan of git files (or given paths); exit 1 on findings |
| +добавлено | approve-release --by <human> --rollback <file> [--target prod] |
| +добавлено | release verify clean tree, fresh passing gates, no secrets, approval, rollback |
| +добавлено | opencode-permission print an OpenCode "permission" block generated from the policy |
| +добавлено | |
| +добавлено | Policy file: ./.release-policy.json, else ~/.agent-harness/.release-policy.json`; |
| +добавлено | |
| +добавлено | const isMain = process.argv[1]?.endsWith('policy.mjs'); |
| +добавлено | if (isMain) { |
| +добавлено | const { positional, flags } = parseArgs(process.argv.slice(2)); |
| +добавлено | const command = commands[positional[0]]; |
| +добавлено | if (!command) { |
| +добавлено | console.log(HELP); |
| +добавлено | process.exit(positional[0] ? 1 : 0); |
| +добавлено | } |
| +добавлено | command(positional.slice(1), flags); |
| +добавлено | } |
| +добавлено | #!/usr/bin/env node |
| +добавлено | // Scope gate: every changed file must fall inside the declared blast radius. |
| +добавлено | // Config: architecture.json -> { "scope": { "allowed": [...], "forbidden": [...] } } |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { spawnSync } from 'node:child_process'; |
| +добавлено | import { parseArgs, list, readJsonc, writeJsonAtomic, wildcardToRegExp, stateDir, appendEvent, fail, homeDir } from './lib.mjs'; |
| +добавлено | |
| +добавлено | function toPosix(p) { |
| +добавлено | return p.split(path.sep).join('/'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function loadScope(cwd, explicit) { |
| +добавлено | if (explicit && explicit !== true) { |
| +добавлено | if (!fs.existsSync(explicit)) fail(`Config not found: ${explicit}`); |
| +добавлено | return { path: path.resolve(explicit), scope: readJsonc(explicit).scope ?? readJsonc(explicit) }; |
| +добавлено | } |
| +добавлено | const candidates = [ |
| +добавлено | path.join(cwd, 'architecture.json'), |
| +добавлено | path.join(cwd, '.agent-arch.json'), |
| +добавлено | path.join(homeDir(), '.agent-harness', 'architecture.json'), |
| +добавлено | ]; |
| +добавлено | const found = candidates.find((p) => fs.existsSync(p)); |
| +добавлено | if (!found) return null; |
| +добавлено | const config = readJsonc(found); |
| +добавлено | if (!config.scope) return null; |
| +добавлено | return { path: found, scope: config.scope }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function git(cwd, args) { |
| +добавлено | const res = spawnSync('git', ['-C', cwd, ...args], { encoding: 'utf8' }); |
| +добавлено | if (res.status !== 0) { |
| +добавлено | const message = (res.stderr ?? '').trim() || `git ${args.join(' ')} failed`; |
| +добавлено | return { ok: false, message }; |
| +добавлено | } |
| +добавлено | return { ok: true, out: res.stdout ?? '' }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const IGNORED = ['.agent-state/', 'node_modules/', 'dist/', 'build/', '.next/', 'coverage/']; |
| +добавлено | |
| +добавлено | function ignored(rel) { |
| +добавлено | return IGNORED.some((prefix) => rel === prefix.slice(0, -1) || rel.startsWith(prefix)); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function changedFiles(cwd, base) { |
| +добавлено | if (base && base !== true) { |
| +добавлено | const diff = git(cwd, ['diff', '--name-only', `${base}...HEAD`]); |
| +добавлено | if (!diff.ok) return diff; |
| +добавлено | const untracked = git(cwd, ['ls-files', '--others', '--exclude-standard']); |
| +добавлено | if (!untracked.ok) return untracked; |
| +добавлено | return { ok: true, files: [...diff.out.split('\n'), ...untracked.out.split('\n')].map((s) => s.trim()).filter(Boolean).filter((f) => !ignored(f)) }; |
| +добавлено | } |
| +добавлено | const status = git(cwd, ['status', '--porcelain=v1', '-uall']); |
| +добавлено | if (!status.ok) return status; |
| +добавлено | const files = []; |
| +добавлено | for (const line of status.out.split('\n')) { |
| +добавлено | if (!line.trim()) continue; |
| +добавлено | let file = line.slice(3).trim(); |
| +добавлено | if (file.includes(' -> ')) file = file.split(' -> ').pop().trim(); |
| +добавлено | if (file.startsWith('"') && file.endsWith('"')) file = file.slice(1, -1); |
| +добавлено | files.push(toPosix(file).replace(/\\/g, '/')); |
| +добавлено | } |
| +добавлено | return { ok: true, files: [...new Set(files)].filter((f) => !ignored(f)) }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function matchesAny(rel, matchers) { |
| +добавлено | return matchers.find((re) => re.test(rel)) ?? null; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function main() { |
| +добавлено | const { flags } = parseArgs(process.argv.slice(2)); |
| +добавлено | const cwd = path.resolve(flags.cwd && flags.cwd !== true ? flags.cwd : process.cwd()); |
| +добавлено | const loaded = loadScope(cwd, flags.config); |
| +добавлено | const allowedGlobs = list(flags.allowed).length ? list(flags.allowed) : loaded?.scope?.allowed ?? []; |
| +добавлено | const forbiddenGlobs = list(flags.forbidden).length ? list(flags.forbidden) : loaded?.scope?.forbidden ?? []; |
| +добавлено | |
| +добавлено | if (!allowedGlobs.length && !forbiddenGlobs.length) { |
| +добавлено | console.error('error: no scope declared — pass --allowed / --forbidden or add "scope" to architecture.json'); |
| +добавлено | return 2; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const changes = changedFiles(cwd, flags.base); |
| +добавлено | if (!changes.ok) { |
| +добавлено | console.error(`error: ${changes.message}`); |
| +добавлено | console.error('Scope gate is unverified: report it as unverified, not passed.'); |
| +добавлено | return 2; |
| +добавлено | } |
| +добавлено | if (!changes.files.length) { |
| +добавлено | console.log('No changed files.'); |
| +добавлено | return 0; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const allowed = allowedGlobs.map(wildcardToRegExp); |
| +добавлено | const forbidden = forbiddenGlobs.map(wildcardToRegExp); |
| +добавлено | const violations = []; |
| +добавлено | const inScope = []; |
| +добавлено | for (const file of changes.files) { |
| +добавлено | if (matchesAny(file, forbidden)) { |
| +добавлено | violations.push({ file, reason: 'in forbidden area' }); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | if (allowed.length && !matchesAny(file, allowed)) { |
| +добавлено | violations.push({ file, reason: 'outside allowed scope' }); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | inScope.push(file); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const summary = { |
| +добавлено | at: new Date().toISOString(), |
| +добавлено | verdict: violations.length ? 'failed' : 'passed', |
| +добавлено | base: flags.base && flags.base !== true ? flags.base : null, |
| +добавлено | allowed: allowedGlobs, |
| +добавлено | forbidden: forbiddenGlobs, |
| +добавлено | changed: changes.files.length, |
| +добавлено | inScope, |
| +добавлено | violations, |
| +добавлено | }; |
| +добавлено | const artifactDir = path.join(stateDir(cwd), 'artifacts'); |
| +добавлено | writeJsonAtomic(path.join(artifactDir, 'scope-latest.json'), summary); |
| +добавлено | appendEvent(cwd, { type: 'scope.checked', verdict: summary.verdict, changed: changes.files.length, violations: violations.length }); |
| +добавлено | |
| +добавлено | if (flags.json) { |
| +добавлено | console.log(JSON.stringify(summary, null, 2)); |
| +добавлено | } else { |
| +добавлено | console.log(`Changed: ${changes.files.length} in scope: ${inScope.length} violations: ${violations.length}`); |
| +добавлено | for (const v of violations) console.log(` OUT OF SCOPE: ${v.file} (${v.reason})`); |
| +добавлено | if (violations.length) console.log('\nRevert out-of-scope changes or declare them explicitly before claiming the task is done.'); |
| +добавлено | console.log(`\nVerdict: ${summary.verdict.toUpperCase()}`); |
| +добавлено | } |
| +добавлено | return violations.length ? 1 : 0; |
| +добавлено | } |
| +добавлено | |
| +добавлено | process.exitCode = main(); |
| +добавлено | #!/usr/bin/env node |
| +добавлено | // Repeatable evidence for the architecture circuit. Run: node tools/selftest.mjs |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import os from 'node:os'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { spawnSync } from 'node:child_process'; |
| +добавлено | import { fileURLToPath } from 'node:url'; |
| +добавлено | |
| +добавлено | const TOOLS = path.dirname(fileURLToPath(import.meta.url)); |
| +добавлено | const ARCH = path.join(TOOLS, 'arch.mjs'); |
| +добавлено | const SCOPE = path.join(TOOLS, 'scope.mjs'); |
| +добавлено | const GATES = path.join(TOOLS, 'gates.mjs'); |
| +добавлено | const FIXTURES = path.join(TOOLS, 'fixtures', 'arch'); |
| +добавлено | |
| +добавлено | function run(script, args, cwd) { |
| +добавлено | const res = spawnSync(process.execPath, [script, ...args], { cwd, encoding: 'utf8' }); |
| +добавлено | return { code: res.status, out: `${res.stdout ?? ''}${res.stderr ?? ''}` }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function git(args, cwd) { |
| +добавлено | return spawnSync('git', args, { cwd, encoding: 'utf8' }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function tempDir(prefix) { |
| +добавлено | return fs.mkdtempSync(path.join(os.tmpdir(), prefix)); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const results = []; |
| +добавлено | function check(name, ok, detail) { |
| +добавлено | results.push({ name, ok, detail }); |
| +добавлено | console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${ok ? '' : `\n ${detail}`}`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // 1. clean project passes |
| +добавлено | { |
| +добавлено | const r = run(ARCH, ['check', '--cwd', path.join(FIXTURES, 'clean')]); |
| +добавлено | check('clean project: architecture passed', r.code === 0, `exit=${r.code}\n${r.out}`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // 2. violating project fails and names each rule |
| +добавлено | { |
| +добавлено | const r = run(ARCH, ['check', '--cwd', path.join(FIXTURES, 'dirty')]); |
| +добавлено | const rules = ['forbidden-import', 'cycle', 'function-too-long', 'deep-nesting']; |
| +добавлено | const missing = rules.filter((rule) => !r.out.includes(rule)); |
| +добавлено | check('dirty project: exit 1 and reports all rule classes', r.code === 1 && missing.length === 0, `exit=${r.code} missing=[${missing.join(', ')}]`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // 3. no config means unverified, never passed |
| +добавлено | { |
| +добавлено | const dir = tempDir('arch-noconfig-'); |
| +добавлено | const r = run(ARCH, ['check', '--cwd', dir]); |
| +добавлено | fs.rmSync(dir, { recursive: true, force: true }); |
| +добавлено | check('no architecture config: exit 2 (unverified)', r.code === 2, `exit=${r.code}\n${r.out}`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // 4. empty map is unverified, not a pass |
| +добавлено | { |
| +добавлено | const dir = tempDir('arch-empty-'); |
| +добавлено | fs.writeFileSync(path.join(dir, 'architecture.json'), JSON.stringify({ layers: [{ name: 'app', path: 'src', mayImport: ['app'] }] })); |
| +добавлено | fs.mkdirSync(path.join(dir, 'src')); |
| +добавлено | const r = run(ARCH, ['check', '--cwd', dir]); |
| +добавлено | fs.rmSync(dir, { recursive: true, force: true }); |
| +добавлено | check('empty module map: exit 2 (unverified)', r.code === 2, `exit=${r.code}\n${r.out}`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // 5. init writes a usable config |
| +добавлено | { |
| +добавлено | const dir = tempDir('arch-init-'); |
| +добавлено | fs.mkdirSync(path.join(dir, 'src', 'ui'), { recursive: true }); |
| +добавлено | fs.writeFileSync(path.join(dir, 'src', 'ui', 'App.ts'), 'export const app = 1;\n'); |
| +добавлено | const init = run(ARCH, ['init', '--cwd', dir]); |
| +добавлено | const checkRun = run(ARCH, ['check', '--cwd', dir]); |
| +добавлено | const written = fs.existsSync(path.join(dir, 'architecture.json')); |
| +добавлено | fs.rmSync(dir, { recursive: true, force: true }); |
| +добавлено | check('init writes config and check runs', init.code === 0 && written && checkRun.code !== 2, `init=${init.code} check=${checkRun.code}`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // 6. scope gate: forbidden change rejected, allowed change accepted |
| +добавлено | { |
| +добавлено | const dir = tempDir('scope-repo-'); |
| +добавлено | git(['init', '-q'], dir); |
| +добавлено | git(['config', 'user.email', 'selftest@local'], dir); |
| +добавлено | git(['config', 'user.name', 'selftest'], dir); |
| +добавлено | fs.mkdirSync(path.join(dir, 'src', 'orders'), { recursive: true }); |
| +добавлено | fs.mkdirSync(path.join(dir, 'src', 'auth'), { recursive: true }); |
| +добавлено | fs.writeFileSync(path.join(dir, 'src', 'orders', 'a.ts'), 'export const a = 1;\n'); |
| +добавлено | fs.writeFileSync(path.join(dir, 'src', 'auth', 'b.ts'), 'export const b = 1;\n'); |
| +добавлено | fs.writeFileSync(path.join(dir, 'architecture.json'), JSON.stringify({ scope: { allowed: ['src/orders/**'], forbidden: ['src/auth/**'] } })); |
| +добавлено | git(['add', '-A'], dir); |
| +добавлено | const committed = git(['commit', '-qm', 'init'], dir).status === 0; |
| +добавлено | |
| +добавлено | fs.writeFileSync(path.join(dir, 'src', 'orders', 'a.ts'), 'export const a = 2;\n'); |
| +добавлено | const allowedRun = run(SCOPE, ['--cwd', dir]); |
| +добавлено | |
| +добавлено | fs.writeFileSync(path.join(dir, 'src', 'auth', 'b.ts'), 'export const b = 2;\n'); |
| +добавлено | const forbiddenRun = run(SCOPE, ['--cwd', dir]); |
| +добавлено | fs.rmSync(dir, { recursive: true, force: true }); |
| +добавлено | |
| +добавлено | check('scope: allowed change passes, forbidden change fails', committed && allowedRun.code === 0 && forbiddenRun.code === 1 && forbiddenRun.out.includes('src/auth/b.ts'), `commit=${committed} allowed=${allowedRun.code} forbidden=${forbiddenRun.code}\n${forbiddenRun.out}`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // 7. scope without declaration is unverified |
| +добавлено | { |
| +добавлено | const dir = tempDir('scope-empty-'); |
| +добавлено | git(['init', '-q'], dir); |
| +добавлено | const r = run(SCOPE, ['--cwd', dir]); |
| +добавлено | fs.rmSync(dir, { recursive: true, force: true }); |
| +добавлено | check('scope without declaration: exit 2 (unverified)', r.code === 2, `exit=${r.code}\n${r.out}`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // 8. gates.mjs runs command gates and fails the verdict on violations |
| +добавлено | { |
| +добавлено | const r = run(GATES, ['--cwd', path.join(FIXTURES, 'dirty'), '--only', 'architecture']); |
| +добавлено | check('gates: architecture command gate fails the verdict', r.code === 1 && /architecture:.*\n\s+failed/s.test(r.out), `exit=${r.code}\n${r.out}`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const failed = results.filter((r) => !r.ok); |
| +добавлено | console.log(`\n${results.length - failed.length}/${results.length} checks passed`); |
| +добавлено | process.exit(failed.length ? 1 : 0); |
| +добавлено | #!/usr/bin/env node |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { HARNESS_ROOT, parseArgs, readJson, copyDir, walkFiles, sha256 } from './lib.mjs'; |
| +добавлено | |
| +добавлено | const NAME_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/; |
| +добавлено | |
| +добавлено | export function parseFrontmatter(text) { |
| +добавлено | if (!text.startsWith('---\n') && !text.startsWith('---\r\n')) return null; |
| +добавлено | const end = text.indexOf('\n---', 4); |
| +добавлено | if (end === -1) return null; |
| +добавлено | const lines = text.slice(text.indexOf('\n') + 1, end).split(/\r?\n/); |
| +добавлено | const data = {}; |
| +добавлено | for (let i = 0; i < lines.length; i += 1) { |
| +добавлено | const m = lines[i].match(/^([A-Za-z][\w-]*):\s*(.*)$/); |
| +добавлено | if (!m) continue; |
| +добавлено | const [, key, raw] = m; |
| +добавлено | if (/^[>|][-+]?$/.test(raw)) { |
| +добавлено | const block = []; |
| +добавлено | while (i + 1 < lines.length && (/^\s+\S/.test(lines[i + 1]) || lines[i + 1].trim() === '')) block.push(lines[(i += 1)].trim()); |
| +добавлено | data[key] = raw.startsWith('>') ? block.join(' ').replace(/\s+/g, ' ').trim() : block.join('\n').trim(); |
| +добавлено | } else { |
| +добавлено | data[key] = raw.replace(/^["']|["']$/g, '').trim(); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return { data, body: text.slice(end + 4) }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function skillDirs(root) { |
| +добавлено | if (!fs.existsSync(root)) return []; |
| +добавлено | return fs.readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function validateSkillsDir(root) { |
| +добавлено | const issues = []; |
| +добавлено | for (const dir of skillDirs(root)) { |
| +добавлено | const file = path.join(root, dir, 'SKILL.md'); |
| +добавлено | const where = path.relative(HARNESS_ROOT, file) || file; |
| +добавлено | if (!fs.existsSync(file)) { |
| +добавлено | issues.push({ level: 'error', where, message: 'missing SKILL.md' }); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | const text = fs.readFileSync(file, 'utf8'); |
| +добавлено | const fm = parseFrontmatter(text); |
| +добавлено | if (!fm) { |
| +добавлено | issues.push({ level: 'error', where, message: 'missing YAML frontmatter (agent will never discover this skill)' }); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | const { name, description } = fm.data; |
| +добавлено | if (!name) issues.push({ level: 'error', where, message: 'frontmatter.name is required' }); |
| +добавлено | else if (!NAME_RE.test(name) || name.length > 64) issues.push({ level: 'error', where, message: `invalid name "${name}"` }); |
| +добавлено | else if (name !== dir) issues.push({ level: 'error', where, message: `name "${name}" must match directory "${dir}" (OpenCode requirement)` }); |
| +добавлено | if (!description) issues.push({ level: 'error', where, message: 'frontmatter.description is required' }); |
| +добавлено | else if (description.length > 1024) issues.push({ level: 'error', where, message: `description is ${description.length} chars (max 1024)` }); |
| +добавлено | else if (description.length < 40) issues.push({ level: 'warn', where, message: 'description is too short for reliable routing' }); |
| +добавлено | const bodyLines = fm.body.split('\n').filter((l) => l.trim()).length; |
| +добавлено | if (bodyLines < 12) issues.push({ level: 'warn', where, message: `body has only ${bodyLines} non-empty lines` }); |
| +добавлено | const linkable = fm.body.replace(/```[\s\S]*?```/g, '').replace(/`[^`\n]*`/g, ''); |
| +добавлено | for (const ref of linkable.matchAll(/\]\((?!https?:|#|mailto:)([^)\s]+\.md)\)/g)) { |
| +добавлено | if (!fs.existsSync(path.join(root, dir, ref[1]))) issues.push({ level: 'error', where, message: `broken link ${ref[1]}` }); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return issues; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function parity(manifest) { |
| +добавлено | const pi = path.join(HARNESS_ROOT, manifest.paths.piSkills); |
| +добавлено | const oc = path.join(HARNESS_ROOT, manifest.paths.opencodeSkills); |
| +добавлено | const issues = []; |
| +добавлено | const a = skillDirs(pi); |
| +добавлено | const b = skillDirs(oc); |
| +добавлено | for (const name of a.filter((n) => !b.includes(n))) issues.push({ level: 'error', where: name, message: 'present in Pi, missing in OpenCode (run: node tools/skills.mjs sync)' }); |
| +добавлено | for (const name of b.filter((n) => !a.includes(n))) issues.push({ level: 'error', where: name, message: 'present in OpenCode, missing in Pi' }); |
| +добавлено | for (const name of a.filter((n) => b.includes(n) && !manifest.platformSpecificSkills.includes(n))) { |
| +добавлено | const fa = walkFiles(path.join(pi, name), { skip: [] }).map((f) => path.relative(path.join(pi, name), f)); |
| +добавлено | const fb = walkFiles(path.join(oc, name), { skip: [] }).map((f) => path.relative(path.join(oc, name), f)); |
| +добавлено | const differs = fa.length !== fb.length || fa.some((rel) => !fb.includes(rel) || sha256(path.join(pi, name, rel)) !== sha256(path.join(oc, name, rel))); |
| +добавлено | if (differs) issues.push({ level: 'error', where: name, message: 'Pi and OpenCode copies differ (run: node tools/skills.mjs sync)' }); |
| +добавлено | } |
| +добавлено | return issues; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function sync(manifest) { |
| +добавлено | const pi = path.join(HARNESS_ROOT, manifest.paths.piSkills); |
| +добавлено | const oc = path.join(HARNESS_ROOT, manifest.paths.opencodeSkills); |
| +добавлено | const synced = []; |
| +добавлено | for (const name of skillDirs(pi)) { |
| +добавлено | if (manifest.platformSpecificSkills.includes(name) && fs.existsSync(path.join(oc, name))) continue; |
| +добавлено | fs.rmSync(path.join(oc, name), { recursive: true, force: true }); |
| +добавлено | copyDir(path.join(pi, name), path.join(oc, name)); |
| +добавлено | synced.push(name); |
| +добавлено | } |
| +добавлено | return synced; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function loadManifest() { |
| +добавлено | return readJson(path.join(HARNESS_ROOT, 'harness.json')); |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (process.argv[1]?.endsWith('skills.mjs')) { |
| +добавлено | const { positional } = parseArgs(process.argv.slice(2)); |
| +добавлено | const manifest = loadManifest(); |
| +добавлено | if (positional[0] === 'sync') { |
| +добавлено | console.log(`Synced to OpenCode: ${sync(manifest).join(', ')}`); |
| +добавлено | console.log(`Kept platform-specific: ${manifest.platformSpecificSkills.join(', ')}`); |
| +добавлено | } else if (positional[0] === 'validate' || !positional[0]) { |
| +добавлено | const issues = [ |
| +добавлено | ...validateSkillsDir(path.join(HARNESS_ROOT, manifest.paths.piSkills)), |
| +добавлено | ...validateSkillsDir(path.join(HARNESS_ROOT, manifest.paths.opencodeSkills)), |
| +добавлено | ...parity(manifest), |
| +добавлено | ]; |
| +добавлено | for (const i of issues) console.log(`${i.level.toUpperCase().padEnd(5)} ${i.where}: ${i.message}`); |
| +добавлено | const errors = issues.filter((i) => i.level === 'error').length; |
| +добавлено | console.log(errors ? `\n${errors} error(s).` : `\nSkills OK (${issues.length} warning(s)).`); |
| +добавлено | process.exit(errors ? 1 : 0); |
| +добавлено | } else { |
| +добавлено | console.log('Usage: node skills.mjs [validate|sync]'); |
| +добавлено | process.exit(1); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | #!/usr/bin/env node |
| +добавлено | /** |
| +добавлено | * spells.mjs — ставит движок боевых эффектов Ultra-Elements (Humpalumps, MIT) |
| +добавлено | * в проект на three.js одной командой: 39 заклинаний, 10 стихий, 3 гибрида. |
| +добавлено | * |
| +добавлено | * node ~/.agent-harness/tools/spells.mjs [projectDir] [--force] [--dry] |
| +добавлено | * |
| +добавлено | * Что делает: |
| +добавлено | * 1) копирует эталонные модули движка в <project>/src/uw/ (с LICENSE и |
| +добавлено | * THIRD_PARTY_NOTICES — атрибуция обязательна по MIT); |
| +добавлено | * 2) кладёт интеграционный слой <project>/src/world/world.ts и страницу |
| +добавлено | * проверки uw-check.html + src/uwcheck.ts; |
| +добавлено | * 3) правит package.json (three r186), tsconfig.json (allowJs/checkJs) |
| +добавлено | * и vite.config (алиас three/addons → three/examples/jsm). |
| +добавлено | * |
| +добавлено | * Ничего не перезаписывает без --force. Печатает каждый шаг. |
| +добавлено | */ |
| +добавлено | |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { fileURLToPath } from 'node:url'; |
| +добавлено | |
| +добавлено | const HERE = path.dirname(fileURLToPath(import.meta.url)); |
| +добавлено | // ассеты лежат рядом с инструментом: install.mjs кладёт дерево tools целиком, |
| +добавлено | // поэтому payload переезжает в любой рантайм вместе с инструментом |
| +добавлено | const ASSETS = path.join(HERE, 'spells-assets'); |
| +добавлено | const THREE_VERSION = '^0.186.1'; |
| +добавлено | const TYPES_VERSION = '^0.186.0'; |
| +добавлено | const ALIAS_LINE = |
| +добавлено | " alias: { 'three/addons': fileURLToPath(new URL('./node_modules/three/examples/jsm', import.meta.url)) },"; |
| +добавлено | |
| +добавлено | const argv = process.argv.slice(2); |
| +добавлено | const flags = new Set(argv.filter((a) => a.startsWith('--'))); |
| +добавлено | const positional = argv.filter((a) => !a.startsWith('--')); |
| +добавлено | const root = path.resolve(positional[0] ?? process.cwd()); |
| +добавлено | const FORCE = flags.has('--force'); |
| +добавлено | const DRY = flags.has('--dry'); |
| +добавлено | |
| +добавлено | const log = (msg) => console.log(` ${msg}`); |
| +добавлено | const head = (msg) => console.log(`\n${msg}`); |
| +добавлено | |
| +добавлено | let failed = false; |
| +добавлено | const warn = (msg) => { |
| +добавлено | failed = true; |
| +добавлено | console.log(` ! ${msg}`); |
| +добавлено | }; |
| +добавлено | |
| +добавлено | function copyFile(rel, destRel) { |
| +добавлено | const src = path.join(ASSETS, rel); |
| +добавлено | const dest = path.join(root, destRel); |
| +добавлено | if (fs.existsSync(dest) && !FORCE) { |
| +добавлено | log(`есть, оставляю: ${destRel}`); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | fs.mkdirSync(path.dirname(dest), { recursive: true }); |
| +добавлено | fs.copyFileSync(src, dest); |
| +добавлено | log(`скопировал: ${destRel}`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function copyTree(rel, destRel) { |
| +добавлено | const src = path.join(ASSETS, rel); |
| +добавлено | for (const entry of fs.readdirSync(src, { withFileTypes: true })) { |
| +добавлено | const from = `${rel}/${entry.name}`; |
| +добавлено | const to = `${destRel}/${entry.name}`; |
| +добавлено | if (entry.isDirectory()) copyTree(from, to); |
| +добавлено | else copyFile(from, to); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | function readJson(file) { |
| +добавлено | try { |
| +добавлено | return JSON.parse(fs.readFileSync(file, 'utf8')); |
| +добавлено | } catch { |
| +добавлено | return null; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- проверки ------------------------------------------------------------- |
| +добавлено | |
| +добавлено | if (!fs.existsSync(root)) { |
| +добавлено | console.error(`Каталог проекта не найден: ${root}`); |
| +добавлено | process.exit(1); |
| +добавлено | } |
| +добавлено | if (!fs.existsSync(ASSETS)) { |
| +добавлено | console.error(`Нет эталонных ассетов: ${ASSETS}`); |
| +добавлено | process.exit(1); |
| +добавлено | } |
| +добавлено | const pkgPath = path.join(root, 'package.json'); |
| +добавлено | if (!fs.existsSync(pkgPath)) { |
| +добавлено | console.error(`Это не проект Node: нет package.json в ${root}`); |
| +добавлено | process.exit(1); |
| +добавлено | } |
| +добавлено | |
| +добавлено | console.log(`Ultra-Elements → ${root}${DRY ? ' (пробный прогон)' : ''}`); |
| +добавлено | |
| +добавлено | if (DRY) { |
| +добавлено | head('Что будет сделано:'); |
| +добавлено | log('src/ue/** (движок заклинаний), src/world/spells.ts (хост)'); |
| +добавлено | log(`package.json: three → ${THREE_VERSION}`); |
| +добавлено | log('tsconfig.json: allowJs + checkJs=false'); |
| +добавлено | log('vite.config: алиас three/addons'); |
| +добавлено | process.exit(0); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- 1. код движка -------------------------------------------------------- |
| +добавлено | |
| +добавлено | head('1. Движок (src/ue)'); |
| +добавлено | copyTree('ue', 'src/ue'); |
| +добавлено | |
| +добавлено | // --- 2. интеграция и проверка -------------------------------------------- |
| +добавлено | |
| +добавлено | head('2. Хост эффектов'); |
| +добавлено | copyFile('spells.ts', 'src/world/spells.ts'); |
| +добавлено | |
| +добавлено | // --- 3. package.json ----------------------------------------------------- |
| +добавлено | |
| +добавлено | head('3. package.json'); |
| +добавлено | const pkg = readJson(pkgPath); |
| +добавлено | if (!pkg) { |
| +добавлено | warn('package.json не разобрался как JSON — пропишите зависимость вручную'); |
| +добавлено | } else { |
| +добавлено | pkg.dependencies = pkg.dependencies ?? {}; |
| +добавлено | if (pkg.dependencies.three === THREE_VERSION) log(`three уже ${THREE_VERSION}`); |
| +добавлено | else { |
| +добавлено | pkg.dependencies.three = THREE_VERSION; |
| +добавлено | log(`three → ${THREE_VERSION}`); |
| +добавлено | } |
| +добавлено | if (pkg.devDependencies && pkg.devDependencies['@types/three']) { |
| +добавлено | pkg.devDependencies['@types/three'] = TYPES_VERSION; |
| +добавлено | log(`@types/three → ${TYPES_VERSION}`); |
| +добавлено | } |
| +добавлено | const nextPkg = JSON.stringify(pkg, null, 2) + '\n'; |
| +добавлено | if (nextPkg === fs.readFileSync(pkgPath, 'utf8')) log('package.json уже в порядке'); |
| +добавлено | else fs.writeFileSync(pkgPath, nextPkg); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- 4. tsconfig.json ---------------------------------------------------- |
| +добавлено | |
| +добавлено | head('4. tsconfig.json'); |
| +добавлено | const tsPath = ['tsconfig.json', 'tsconfig.app.json'] |
| +добавлено | .map((f) => path.join(root, f)) |
| +добавлено | .find((f) => fs.existsSync(f)); |
| +добавлено | if (!tsPath) { |
| +добавлено | warn('tsconfig не найден — если проект на TypeScript, добавьте allowJs и checkJs=false'); |
| +добавлено | } else { |
| +добавлено | const raw = fs.readFileSync(tsPath, 'utf8'); |
| +добавлено | if (/"allowJs"\s*:\s*true/.test(raw) && /"checkJs"\s*:\s*false/.test(raw)) { |
| +добавлено | log(`уже настроен: ${path.basename(tsPath)}`); |
| +добавлено | } else { |
| +добавлено | let next = raw; |
| +добавлено | if (/"compilerOptions"\s*:\s*\{/.test(next)) { |
| +добавлено | next = next.replace( |
| +добавлено | /"compilerOptions"\s*:\s*\{/, |
| +добавлено | '"compilerOptions": {\n "allowJs": true,\n "checkJs": false,', |
| +добавлено | ); |
| +добавлено | fs.writeFileSync(tsPath, next); |
| +добавлено | log(`allowJs + checkJs=false → ${path.basename(tsPath)}`); |
| +добавлено | } else { |
| +добавлено | warn(`${path.basename(tsPath)}: не нашёл compilerOptions — добавьте allowJs/checkJs вручную`); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- 5. vite.config ------------------------------------------------------ |
| +добавлено | |
| +добавлено | head('5. vite.config'); |
| +добавлено | const vitePath = ['vite.config.ts', 'vite.config.js', 'vite.config.mjs'] |
| +добавлено | .map((f) => path.join(root, f)) |
| +добавлено | .find((f) => fs.existsSync(f)); |
| +добавлено | |
| +добавлено | if (!vitePath) { |
| +добавлено | const file = path.join(root, 'vite.config.ts'); |
| +добавлено | fs.writeFileSync( |
| +добавлено | file, |
| +добавлено | `import { defineConfig } from 'vite';\nimport { fileURLToPath } from 'node:url';\n\nexport default defineConfig({\n resolve: {\n${ALIAS_LINE}\n },\n});\n`, |
| +добавлено | ); |
| +добавлено | log('создал vite.config.ts с алиасом three/addons'); |
| +добавлено | } else { |
| +добавлено | const raw = fs.readFileSync(vitePath, 'utf8'); |
| +добавлено | if (raw.includes('three/addons')) { |
| +добавлено | log(`алиас уже есть: ${path.basename(vitePath)}`); |
| +добавлено | } else if (/resolve\s*:\s*\{/.test(raw)) { |
| +добавлено | let next = raw.replace(/resolve\s*:\s*\{/, `resolve: {\n${ALIAS_LINE}`); |
| +добавлено | if (!/from 'node:url'/.test(next)) { |
| +добавлено | next = `import { fileURLToPath } from 'node:url';\n` + next; |
| +добавлено | } |
| +добавлено | fs.writeFileSync(vitePath, next); |
| +добавлено | log(`алиас three/addons → ${path.basename(vitePath)}`); |
| +добавлено | } else { |
| +добавлено | // Нет блока resolve — вставляем его в объект конфига. |
| +добавлено | const cfgMatch = /defineConfig\(\s*\{/.exec(raw) ?? /export\s+default\s*\{/.exec(raw); |
| +добавлено | if (cfgMatch) { |
| +добавлено | const at = cfgMatch.index + cfgMatch[0].length; |
| +добавлено | let next = `${raw.slice(0, at)}\n resolve: {\n${ALIAS_LINE}\n },${raw.slice(at)}`; |
| +добавлено | if (!/from 'node:url'/.test(next)) { |
| +добавлено | next = `import { fileURLToPath } from 'node:url';\n` + next; |
| +добавлено | } |
| +добавлено | fs.writeFileSync(vitePath, next); |
| +добавлено | log(`добавил resolve + алиас three/addons → ${path.basename(vitePath)}`); |
| +добавлено | } else { |
| +добавлено | warn( |
| +добавлено | `${path.basename(vitePath)}: не разобрал конфиг — добавьте вручную:\n` + |
| +добавлено | ` resolve: {\n${ALIAS_LINE}\n },`, |
| +добавлено | ); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- итог ---------------------------------------------------------------- |
| +добавлено | |
| +добавлено | head('Дальше:'); |
| +добавлено | log(`cd ${root} && npm install`); |
| +добавлено | log('npm run dev, затем привяжите хост к своему миру:'); |
| +добавлено | log(' new SpellHost({ renderer, camera, skyCube, sunDir, sunColor, groundCenter, tier, groundHeight })'); |
| +добавлено | log(' spells.update(dt, camera) -> spells.composite(frame) после сцены и воды'); |
| +добавлено | log('адаптеры (арена, цели, каналирование, прогрев) — в скилле ultra-elements'); |
| +добавлено | console.log(` |
| +добавлено | Лицензия: MIT. В src/ue/ уже лежат LICENSE и THIRD_PARTY_NOTICES.md — |
| +добавлено | не удаляйте их: там credit'ы зависимостей движка.`); |
| +добавлено | |
| +добавлено | process.exit(failed ? 2 : 0); |
| +добавлено | #!/usr/bin/env node |
| +добавлено | /** |
| +добавлено | * water.mjs — ставит океан/небо/мир Ultra-Water (Humpalumps, MIT) в трехмерный |
| +добавлено | * проект на three.js одной командой. |
| +добавлено | * |
| +добавлено | * node ~/.agent-harness/tools/water.mjs [projectDir] [--force] [--dry] |
| +добавлено | * |
| +добавлено | * Что делает: |
| +добавлено | * 1) копирует эталонные модули движка в <project>/src/uw/ (с LICENSE и |
| +добавлено | * THIRD_PARTY_NOTICES — атрибуция обязательна по MIT); |
| +добавлено | * 2) кладёт интеграционный слой <project>/src/world/world.ts и страницу |
| +добавлено | * проверки uw-check.html + src/uwcheck.ts; |
| +добавлено | * 3) правит package.json (three r186), tsconfig.json (allowJs/checkJs) |
| +добавлено | * и vite.config (алиас three/addons → three/examples/jsm). |
| +добавлено | * |
| +добавлено | * Ничего не перезаписывает без --force. Печатает каждый шаг. |
| +добавлено | */ |
| +добавлено | |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { fileURLToPath } from 'node:url'; |
| +добавлено | |
| +добавлено | const HERE = path.dirname(fileURLToPath(import.meta.url)); |
| +добавлено | // ассеты лежат рядом с инструментом: install.mjs кладёт дерево tools целиком, |
| +добавлено | // поэтому payload переезжает в любой рантайм вместе с инструментом |
| +добавлено | const ASSETS = path.join(HERE, 'water-assets'); |
| +добавлено | const THREE_VERSION = '^0.186.1'; |
| +добавлено | const TYPES_VERSION = '^0.186.0'; |
| +добавлено | const ALIAS_LINE = |
| +добавлено | " alias: { 'three/addons': fileURLToPath(new URL('./node_modules/three/examples/jsm', import.meta.url)) },"; |
| +добавлено | |
| +добавлено | const argv = process.argv.slice(2); |
| +добавлено | const flags = new Set(argv.filter((a) => a.startsWith('--'))); |
| +добавлено | const positional = argv.filter((a) => !a.startsWith('--')); |
| +добавлено | const root = path.resolve(positional[0] ?? process.cwd()); |
| +добавлено | const FORCE = flags.has('--force'); |
| +добавлено | const DRY = flags.has('--dry'); |
| +добавлено | |
| +добавлено | const log = (msg) => console.log(` ${msg}`); |
| +добавлено | const head = (msg) => console.log(`\n${msg}`); |
| +добавлено | |
| +добавлено | let failed = false; |
| +добавлено | const warn = (msg) => { |
| +добавлено | failed = true; |
| +добавлено | console.log(` ! ${msg}`); |
| +добавлено | }; |
| +добавлено | |
| +добавлено | function copyFile(rel, destRel) { |
| +добавлено | const src = path.join(ASSETS, rel); |
| +добавлено | const dest = path.join(root, destRel); |
| +добавлено | if (fs.existsSync(dest) && !FORCE) { |
| +добавлено | log(`есть, оставляю: ${destRel}`); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | fs.mkdirSync(path.dirname(dest), { recursive: true }); |
| +добавлено | fs.copyFileSync(src, dest); |
| +добавлено | log(`скопировал: ${destRel}`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function copyTree(rel, destRel) { |
| +добавлено | const src = path.join(ASSETS, rel); |
| +добавлено | for (const entry of fs.readdirSync(src, { withFileTypes: true })) { |
| +добавлено | const from = `${rel}/${entry.name}`; |
| +добавлено | const to = `${destRel}/${entry.name}`; |
| +добавлено | if (entry.isDirectory()) copyTree(from, to); |
| +добавлено | else copyFile(from, to); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | function readJson(file) { |
| +добавлено | try { |
| +добавлено | return JSON.parse(fs.readFileSync(file, 'utf8')); |
| +добавлено | } catch { |
| +добавлено | return null; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- проверки ------------------------------------------------------------- |
| +добавлено | |
| +добавлено | if (!fs.existsSync(root)) { |
| +добавлено | console.error(`Каталог проекта не найден: ${root}`); |
| +добавлено | process.exit(1); |
| +добавлено | } |
| +добавлено | if (!fs.existsSync(ASSETS)) { |
| +добавлено | console.error(`Нет эталонных ассетов: ${ASSETS}`); |
| +добавлено | process.exit(1); |
| +добавлено | } |
| +добавлено | const pkgPath = path.join(root, 'package.json'); |
| +добавлено | if (!fs.existsSync(pkgPath)) { |
| +добавлено | console.error(`Это не проект Node: нет package.json в ${root}`); |
| +добавлено | process.exit(1); |
| +добавлено | } |
| +добавлено | |
| +добавлено | console.log(`Ultra-Water → ${root}${DRY ? ' (пробный прогон)' : ''}`); |
| +добавлено | |
| +добавлено | if (DRY) { |
| +добавлено | head('Что будет сделано:'); |
| +добавлено | log('src/uw/** (движок), src/world/world.ts, uw-check.html, src/uwcheck.ts'); |
| +добавлено | log(`package.json: three → ${THREE_VERSION}`); |
| +добавлено | log('tsconfig.json: allowJs + checkJs=false'); |
| +добавлено | log('vite.config: алиас three/addons'); |
| +добавлено | process.exit(0); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- 1. код движка -------------------------------------------------------- |
| +добавлено | |
| +добавлено | head('1. Движок (src/uw)'); |
| +добавлено | copyTree('uw', 'src/uw'); |
| +добавлено | |
| +добавлено | // --- 2. интеграция и проверка -------------------------------------------- |
| +добавлено | |
| +добавлено | head('2. Интеграция'); |
| +добавлено | copyFile('world.ts', 'src/world/world.ts'); |
| +добавлено | copyFile('uwcheck.ts', 'src/uwcheck.ts'); |
| +добавлено | copyFile('uw-check.html', 'uw-check.html'); |
| +добавлено | |
| +добавлено | // --- 3. package.json ----------------------------------------------------- |
| +добавлено | |
| +добавлено | head('3. package.json'); |
| +добавлено | const pkg = readJson(pkgPath); |
| +добавлено | if (!pkg) { |
| +добавлено | warn('package.json не разобрался как JSON — пропишите зависимость вручную'); |
| +добавлено | } else { |
| +добавлено | pkg.dependencies = pkg.dependencies ?? {}; |
| +добавлено | if (pkg.dependencies.three === THREE_VERSION) log(`three уже ${THREE_VERSION}`); |
| +добавлено | else { |
| +добавлено | pkg.dependencies.three = THREE_VERSION; |
| +добавлено | log(`three → ${THREE_VERSION}`); |
| +добавлено | } |
| +добавлено | if (pkg.devDependencies && pkg.devDependencies['@types/three']) { |
| +добавлено | pkg.devDependencies['@types/three'] = TYPES_VERSION; |
| +добавлено | log(`@types/three → ${TYPES_VERSION}`); |
| +добавлено | } |
| +добавлено | const nextPkg = JSON.stringify(pkg, null, 2) + '\n'; |
| +добавлено | if (nextPkg === fs.readFileSync(pkgPath, 'utf8')) log('package.json уже в порядке'); |
| +добавлено | else fs.writeFileSync(pkgPath, nextPkg); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- 4. tsconfig.json ---------------------------------------------------- |
| +добавлено | |
| +добавлено | head('4. tsconfig.json'); |
| +добавлено | const tsPath = ['tsconfig.json', 'tsconfig.app.json'] |
| +добавлено | .map((f) => path.join(root, f)) |
| +добавлено | .find((f) => fs.existsSync(f)); |
| +добавлено | if (!tsPath) { |
| +добавлено | warn('tsconfig не найден — если проект на TypeScript, добавьте allowJs и checkJs=false'); |
| +добавлено | } else { |
| +добавлено | const raw = fs.readFileSync(tsPath, 'utf8'); |
| +добавлено | if (/"allowJs"\s*:\s*true/.test(raw) && /"checkJs"\s*:\s*false/.test(raw)) { |
| +добавлено | log(`уже настроен: ${path.basename(tsPath)}`); |
| +добавлено | } else { |
| +добавлено | let next = raw; |
| +добавлено | if (/"compilerOptions"\s*:\s*\{/.test(next)) { |
| +добавлено | next = next.replace( |
| +добавлено | /"compilerOptions"\s*:\s*\{/, |
| +добавлено | '"compilerOptions": {\n "allowJs": true,\n "checkJs": false,', |
| +добавлено | ); |
| +добавлено | fs.writeFileSync(tsPath, next); |
| +добавлено | log(`allowJs + checkJs=false → ${path.basename(tsPath)}`); |
| +добавлено | } else { |
| +добавлено | warn(`${path.basename(tsPath)}: не нашёл compilerOptions — добавьте allowJs/checkJs вручную`); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- 5. vite.config ------------------------------------------------------ |
| +добавлено | |
| +добавлено | head('5. vite.config'); |
| +добавлено | const vitePath = ['vite.config.ts', 'vite.config.js', 'vite.config.mjs'] |
| +добавлено | .map((f) => path.join(root, f)) |
| +добавлено | .find((f) => fs.existsSync(f)); |
| +добавлено | |
| +добавлено | if (!vitePath) { |
| +добавлено | const file = path.join(root, 'vite.config.ts'); |
| +добавлено | fs.writeFileSync( |
| +добавлено | file, |
| +добавлено | `import { defineConfig } from 'vite';\nimport { fileURLToPath } from 'node:url';\n\nexport default defineConfig({\n resolve: {\n${ALIAS_LINE}\n },\n});\n`, |
| +добавлено | ); |
| +добавлено | log('создал vite.config.ts с алиасом three/addons'); |
| +добавлено | } else { |
| +добавлено | const raw = fs.readFileSync(vitePath, 'utf8'); |
| +добавлено | if (raw.includes('three/addons')) { |
| +добавлено | log(`алиас уже есть: ${path.basename(vitePath)}`); |
| +добавлено | } else if (/resolve\s*:\s*\{/.test(raw)) { |
| +добавлено | let next = raw.replace(/resolve\s*:\s*\{/, `resolve: {\n${ALIAS_LINE}`); |
| +добавлено | if (!/from 'node:url'/.test(next)) { |
| +добавлено | next = `import { fileURLToPath } from 'node:url';\n` + next; |
| +добавлено | } |
| +добавлено | fs.writeFileSync(vitePath, next); |
| +добавлено | log(`алиас three/addons → ${path.basename(vitePath)}`); |
| +добавлено | } else { |
| +добавлено | // Нет блока resolve — вставляем его в объект конфига. |
| +добавлено | const cfgMatch = /defineConfig\(\s*\{/.exec(raw) ?? /export\s+default\s*\{/.exec(raw); |
| +добавлено | if (cfgMatch) { |
| +добавлено | const at = cfgMatch.index + cfgMatch[0].length; |
| +добавлено | let next = `${raw.slice(0, at)}\n resolve: {\n${ALIAS_LINE}\n },${raw.slice(at)}`; |
| +добавлено | if (!/from 'node:url'/.test(next)) { |
| +добавлено | next = `import { fileURLToPath } from 'node:url';\n` + next; |
| +добавлено | } |
| +добавлено | fs.writeFileSync(vitePath, next); |
| +добавлено | log(`добавил resolve + алиас three/addons → ${path.basename(vitePath)}`); |
| +добавлено | } else { |
| +добавлено | warn( |
| +добавлено | `${path.basename(vitePath)}: не разобрал конфиг — добавьте вручную:\n` + |
| +добавлено | ` resolve: {\n${ALIAS_LINE}\n },`, |
| +добавлено | ); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- итог ---------------------------------------------------------------- |
| +добавлено | |
| +добавлено | head('Дальше:'); |
| +добавлено | log(`cd ${root} && npm install`); |
| +добавлено | log('npm run dev → откройте /uw-check.html (изолированная проверка движка)'); |
| +добавлено | log('затем подключите свой слой: import { World } from "./world/world"'); |
| +добавлено | console.log(` |
| +добавлено | Лицензия: MIT. В src/uw/ уже лежат LICENSE и THIRD_PARTY_NOTICES.md — |
| +добавлено | не удаляйте их: внутри credit'ы three.js (AgX), D. Hoskins (hash), |
| +добавлено | S. Hillaire (атмосфера).`); |
| +добавлено | |
| +добавлено | process.exit(failed ? 2 : 0); |
| +добавлено | #!/usr/bin/env node |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { spawnSync } from 'node:child_process'; |
| +добавлено | import { fileURLToPath } from 'node:url'; |
| +добавлено | import { parseArgs, readJson, writeJsonAtomic, withLock, appendEvent, stateDir, fail } from './lib.mjs'; |
| +добавлено | |
| +добавлено | const NAME = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/; |
| +добавлено | |
| +добавлено | function git(args, cwd, { allowFail = false } = {}) { |
| +добавлено | const res = spawnSync('git', args, { cwd, encoding: 'utf8' }); |
| +добавлено | if (res.error) fail(`git not available: ${res.error.message}`); |
| +добавлено | if (res.status !== 0 && !allowFail) fail(`git ${args.join(' ')}\n${res.stderr.trim()}`); |
| +добавлено | return { ok: res.status === 0, out: res.stdout.trim(), err: res.stderr.trim() }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const cwd = process.cwd(); |
| +добавлено | const root = git(['rev-parse', '--show-toplevel'], cwd).out; |
| +добавлено | const registryFile = path.join(stateDir(root), 'worktrees.json'); |
| +добавлено | const registryLock = path.join(stateDir(root), 'worktrees.lock'); |
| +добавлено | const baseDir = path.join(root, '.agent-worktrees'); |
| +добавлено | |
| +добавлено | function registry(fn) { |
| +добавлено | return withLock(registryLock, () => { |
| +добавлено | const data = readJson(registryFile, { worktrees: {} }); |
| +добавлено | const result = fn(data); |
| +добавлено | writeJsonAtomic(registryFile, data); |
| +добавлено | return result; |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function ensureExcluded() { |
| +добавлено | const gitDir = git(['rev-parse', '--git-common-dir'], root).out; |
| +добавлено | const exclude = path.resolve(root, gitDir, 'info', 'exclude'); |
| +добавлено | fs.mkdirSync(path.dirname(exclude), { recursive: true }); |
| +добавлено | const current = fs.existsSync(exclude) ? fs.readFileSync(exclude, 'utf8') : ''; |
| +добавлено | const wanted = ['.agent-worktrees/', '.agent-state/'].filter((line) => !current.split('\n').includes(line)); |
| +добавлено | if (wanted.length) fs.appendFileSync(exclude, `${current.endsWith('\n') || !current ? '' : '\n'}${wanted.join('\n')}\n`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function requireName(name) { |
| +добавлено | if (!name || !NAME.test(name)) fail('Name must match [a-z0-9] with - or _ separators'); |
| +добавлено | return name; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const LOCKFILES = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock', 'bun.lockb']; |
| +добавлено | |
| +добавлено | function lockfileChanged(target, baseSha) { |
| +добавлено | const changed = git(['diff', '--name-only', `${baseSha}...HEAD`, '--', ...LOCKFILES, 'package.json'], target, { allowFail: true }).out; |
| +добавлено | return changed.split('\n').filter(Boolean); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function linkDeps(target) { |
| +добавлено | const src = path.join(root, 'node_modules'); |
| +добавлено | const dest = path.join(target, 'node_modules'); |
| +добавлено | if (!fs.existsSync(src)) return 'no root node_modules to link'; |
| +добавлено | if (fs.existsSync(dest)) return 'node_modules already present'; |
| +добавлено | fs.symlinkSync(src, dest, process.platform === 'win32' ? 'junction' : 'dir'); |
| +добавлено | return `linked ${path.relative(root, dest)} -> node_modules`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function lookup(name) { |
| +добавлено | const wt = readJson(registryFile, { worktrees: {} }).worktrees[requireName(name)]; |
| +добавлено | if (!wt) fail(`Unknown worktree ${name}`); |
| +добавлено | return wt; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const commands = { |
| +добавлено | create([name], flags) { |
| +добавлено | requireName(name); |
| +добавлено | const base = flags.base && flags.base !== true ? flags.base : 'HEAD'; |
| +добавлено | const baseSha = git(['rev-parse', base], root).out; |
| +добавлено | const target = path.join(baseDir, name); |
| +добавлено | const branch = `agent/${name}`; |
| +добавлено | if (fs.existsSync(target)) fail(`Worktree ${name} already exists at ${target}`); |
| +добавлено | ensureExcluded(); |
| +добавлено | git(['worktree', 'add', '-b', branch, target, baseSha], root); |
| +добавлено | registry((data) => { |
| +добавлено | data.worktrees[name] = { path: target, branch, base, baseSha, createdAt: new Date().toISOString() }; |
| +добавлено | }); |
| +добавлено | const deps = flags['link-deps'] ? linkDeps(target) : null; |
| +добавлено | appendEvent(root, { type: 'worktree.created', name, branch, baseSha }); |
| +добавлено | console.log(JSON.stringify({ name, path: target, branch, baseSha, deps }, null, 2)); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | integrate(names, flags) { |
| +добавлено | if (!names.length) fail('Usage: worktree.mjs integrate <name> [<name>...] [--base <ref>] [--deps link|none] [--no-gates]'); |
| +добавлено | const sources = names.map((n) => ({ name: n, ...lookup(n) })); |
| +добавлено | for (const s of sources) { |
| +добавлено | const dirty = fs.existsSync(s.path) ? git(['status', '--porcelain'], s.path).out : ''; |
| +добавлено | if (dirty) fail(`Worktree ${s.name} has uncommitted changes; builder must commit before integration.`); |
| +добавлено | } |
| +добавлено | const base = flags.base && flags.base !== true ? flags.base : 'HEAD'; |
| +добавлено | const baseSha = git(['rev-parse', base], root).out; |
| +добавлено | const name = flags.name && flags.name !== true ? requireName(flags.name) : `integration-${new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)}`; |
| +добавлено | const target = path.join(baseDir, name); |
| +добавлено | const branch = `agent/${name}`; |
| +добавлено | if (fs.existsSync(target)) fail(`Worktree ${name} already exists`); |
| +добавлено | ensureExcluded(); |
| +добавлено | git(['worktree', 'add', '-b', branch, target, baseSha], root); |
| +добавлено | |
| +добавлено | const merged = []; |
| +добавлено | let conflict = null; |
| +добавлено | for (const s of sources) { |
| +добавлено | const res = git(['merge', '--no-ff', '--no-edit', '-m', `integrate ${s.branch}`, s.branch], target, { allowFail: true }); |
| +добавлено | if (res.ok) { |
| +добавлено | merged.push(s.name); |
| +добавлено | console.log(`merged ${s.branch}`); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | const files = git(['diff', '--name-only', '--diff-filter=U'], target, { allowFail: true }).out.split('\n').filter(Boolean); |
| +добавлено | git(['merge', '--abort'], target, { allowFail: true }); |
| +добавлено | conflict = { with: s.name, branch: s.branch, files, mergedBefore: [...merged] }; |
| +добавлено | console.log(`CONFLICT ${s.branch}: ${files.join(', ') || res.err}`); |
| +добавлено | break; |
| +добавлено | } |
| +добавлено | |
| +добавлено | let deps = 'none'; |
| +добавлено | const lockChanges = lockfileChanged(target, baseSha); |
| +добавлено | if (!conflict && (flags.deps ?? 'link') === 'link') { |
| +добавлено | deps = lockChanges.length ? `NOT linked: ${lockChanges.join(', ')} changed, install deps in ${target} (needs approval)` : linkDeps(target); |
| +добавлено | } |
| +добавлено | |
| +добавлено | let gates = null; |
| +добавлено | if (!conflict && !flags['no-gates'] && !/NOT linked/.test(deps)) { |
| +добавлено | console.log(`\nRunning gates in ${path.relative(root, target)}`); |
| +добавлено | const res = spawnSync(process.execPath, [path.join(path.dirname(fileURLToPath(import.meta.url)), 'gates.mjs'), '--cwd', target], { stdio: 'inherit' }); |
| +добавлено | gates = res.status === 0 ? 'passed' : res.status === 2 ? 'unverified' : 'failed'; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const verdict = conflict ? 'conflict' : gates ?? 'unverified'; |
| +добавлено | const record = { name, path: target, branch, baseSha, sources: names, merged, conflict, deps, gates, verdict, at: new Date().toISOString() }; |
| +добавлено | registry((data) => { |
| +добавлено | data.worktrees[name] = { path: target, branch, base, baseSha, integration: true, sources: names, createdAt: record.at }; |
| +добавлено | }); |
| +добавлено | writeJsonAtomic(path.join(stateDir(root), 'artifacts', 'integration-latest.json'), record); |
| +добавлено | appendEvent(root, { type: 'worktree.integrated', name, merged, conflict: conflict?.with ?? null, verdict }); |
| +добавлено | console.log(`\nIntegration ${name}: ${verdict.toUpperCase()} deps: ${deps}`); |
| +добавлено | if (conflict) console.log(`Return ${conflict.with} to its builder with the conflicting files, or rebase it on ${merged.length ? branch : 'base'}.`); |
| +добавлено | else console.log(`Human merges ${branch} into the main branch after review; agents never do.`); |
| +добавлено | process.exit(verdict === 'passed' ? 0 : verdict === 'unverified' ? 2 : 1); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | list() { |
| +добавлено | const data = readJson(registryFile, { worktrees: {} }); |
| +добавлено | const live = git(['worktree', 'list', '--porcelain'], root).out; |
| +добавлено | const entries = Object.entries(data.worktrees); |
| +добавлено | if (!entries.length) { |
| +добавлено | console.log('No agent worktrees.'); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | for (const [name, wt] of entries) { |
| +добавлено | const exists = live.includes(`worktree ${wt.path}`) || live.includes(`worktree ${wt.path.replace(/\\/g, '/')}`); |
| +добавлено | const dirty = exists ? git(['status', '--porcelain'], wt.path, { allowFail: true }).out.split('\n').filter(Boolean).length : 0; |
| +добавлено | const ahead = exists ? git(['rev-list', '--count', `${wt.baseSha}..HEAD`], wt.path, { allowFail: true }).out : '?'; |
| +добавлено | console.log(`${name.padEnd(24)} ${exists ? 'live ' : 'GONE '} branch=${wt.branch} commits=${ahead} dirty=${dirty} ${wt.path}`); |
| +добавлено | } |
| +добавлено | }, |
| +добавлено | |
| +добавлено | diff([name]) { |
| +добавлено | requireName(name); |
| +добавлено | const wt = readJson(registryFile, { worktrees: {} }).worktrees[name]; |
| +добавлено | if (!wt) fail(`Unknown worktree ${name}`); |
| +добавлено | console.log(`# ${name}: committed changes since ${wt.baseSha.slice(0, 10)}`); |
| +добавлено | console.log(git(['diff', '--stat', `${wt.baseSha}...HEAD`], wt.path).out || '(none)'); |
| +добавлено | const dirty = git(['status', '--short'], wt.path).out; |
| +добавлено | console.log(`\n# uncommitted\n${dirty || '(clean)'}`); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | remove([name], flags) { |
| +добавлено | requireName(name); |
| +добавлено | const wt = readJson(registryFile, { worktrees: {} }).worktrees[name]; |
| +добавлено | if (!wt) fail(`Unknown worktree ${name}`); |
| +добавлено | if (fs.existsSync(wt.path)) { |
| +добавлено | const dirty = git(['status', '--porcelain'], wt.path).out; |
| +добавлено | if (dirty && !flags.force) fail(`Worktree ${name} has uncommitted changes. Commit/stash them or pass --force (approval required).`); |
| +добавлено | git(['worktree', 'remove', ...(flags.force ? ['--force'] : []), wt.path], root); |
| +добавлено | } |
| +добавлено | if (flags['delete-branch']) { |
| +добавлено | const res = git(['branch', '-d', wt.branch], root, { allowFail: true }); |
| +добавлено | console.log(res.ok ? `Deleted merged branch ${wt.branch}` : `Kept branch ${wt.branch}: not merged (${res.err})`); |
| +добавлено | } |
| +добавлено | registry((data) => { |
| +добавлено | delete data.worktrees[name]; |
| +добавлено | }); |
| +добавлено | appendEvent(root, { type: 'worktree.removed', name, force: Boolean(flags.force) }); |
| +добавлено | console.log(`Removed worktree ${name}`); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | prune() { |
| +добавлено | git(['worktree', 'prune'], root); |
| +добавлено | const pruned = registry((data) => { |
| +добавлено | const gone = Object.keys(data.worktrees).filter((n) => !fs.existsSync(data.worktrees[n].path)); |
| +добавлено | for (const n of gone) delete data.worktrees[n]; |
| +добавлено | return gone; |
| +добавлено | }); |
| +добавлено | console.log(pruned.length ? `Pruned: ${pruned.join(', ')}` : 'Nothing to prune.'); |
| +добавлено | }, |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const HELP = `Usage: node worktree.mjs <command> |
| +добавлено | |
| +добавлено | create <name> [--base <ref>] [--link-deps] |
| +добавлено | new branch agent/<name> in .agent-worktrees/<name>; |
| +добавлено | --link-deps symlinks the root node_modules |
| +добавлено | integrate <name>... [--base <ref>] [--deps link|none] [--no-gates] [--name <slug>] |
| +добавлено | merge agent branches into a fresh integration worktree, |
| +добавлено | stop on first conflict, then run gates there |
| +добавлено | list status of every agent worktree |
| +добавлено | diff <name> committed + uncommitted changes vs base |
| +добавлено | remove <name> [--force] [--delete-branch] |
| +добавлено | refuses dirty trees without --force; deletes branch only if merged |
| +добавлено | prune drop registry entries for vanished worktrees |
| +добавлено | |
| +добавлено | Merging stays a human/reviewer decision: review "diff", then merge the branch with git.`; |
| +добавлено | |
| +добавлено | const { positional, flags } = parseArgs(process.argv.slice(2)); |
| +добавлено | const command = commands[positional[0]]; |
| +добавлено | if (!command) { |
| +добавлено | console.log(HELP); |
| +добавлено | process.exit(positional[0] ? 1 : 0); |
| +добавлено | } |
| +добавлено | command(positional.slice(1), flags); |