forjajs 5.1.0 → 5.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +108 -0
- package/README.md +52 -4
- package/README.pt-BR.md +54 -4
- package/dist/apps/cli/src/index.d.ts +0 -1
- package/dist/apps/cli/src/index.js +43 -32
- package/dist/apps/dashboard/app/api/forja/[...path]/route.js +34 -1
- package/dist/apps/dashboard/app/api/forja/capabilities.d.ts +26 -0
- package/dist/apps/dashboard/app/api/forja/capabilities.js +39 -0
- package/dist/apps/dashboard/app/dashboard-client.jsx +607 -42
- package/dist/apps/server/src/forja-nest.module.d.ts +6 -0
- package/dist/apps/server/src/forja-nest.module.js +55 -0
- package/dist/apps/server/src/main.d.ts +21 -4
- package/dist/apps/server/src/main.js +79 -57
- package/dist/apps/server/src/task-planning-service.d.ts +29 -0
- package/dist/apps/server/src/task-planning-service.js +195 -0
- package/dist/apps/server/src/task-runtime-coordinator.d.ts +57 -0
- package/dist/apps/server/src/task-runtime-coordinator.js +229 -0
- package/dist/bin/forja.js +3 -2
- package/dist/lib/agent-evals.d.ts +138 -0
- package/dist/lib/agent-evals.js +365 -0
- package/dist/lib/cli-output.js +14 -2
- package/dist/lib/code-context.d.ts +33 -5
- package/dist/lib/code-context.js +70 -5
- package/dist/lib/context-builder.d.ts +49 -4
- package/dist/lib/context-builder.js +114 -47
- package/dist/lib/core/coverage-gate.d.ts +59 -0
- package/dist/lib/core/coverage-gate.js +58 -0
- package/dist/lib/core/doc-graph.d.ts +38 -0
- package/dist/lib/core/doc-graph.js +83 -0
- package/dist/lib/core/health.js +286 -5
- package/dist/lib/core/journey.js +26 -0
- package/dist/lib/core/registry.js +81 -6
- package/dist/lib/docs-reference.d.ts +35 -0
- package/dist/lib/docs-reference.js +57 -0
- package/dist/lib/exec.d.ts +55 -0
- package/dist/lib/exec.js +141 -0
- package/dist/lib/project-wiring.js +6 -2
- package/dist/lib/session-memory.d.ts +38 -0
- package/dist/lib/session-memory.js +206 -0
- package/dist/lib/spec-trace.d.ts +46 -0
- package/dist/lib/spec-trace.js +184 -0
- package/dist/packages/adapter-git/src/index.js +13 -4
- package/dist/packages/adapter-nest/src/index.d.ts +2 -1
- package/dist/packages/adapter-nest/src/index.js +59 -1
- package/dist/packages/adapter-sqlite/src/index.d.ts +15 -1
- package/dist/packages/adapter-sqlite/src/index.js +61 -1
- package/dist/packages/context/src/index.d.ts +2 -0
- package/dist/packages/context/src/index.js +36 -15
- package/dist/packages/contracts/src/index.d.ts +64 -0
- package/dist/packages/core/src/index.d.ts +9 -1
- package/dist/packages/core/src/index.js +28 -3
- package/dist/packages/graph/src/index.js +14 -5
- package/dist/packages/llm/src/index.js +7 -24
- package/dist/packages/mcp/src/index.d.ts +8 -0
- package/dist/packages/mcp/src/index.js +12 -1
- package/dist/packages/observability/src/index.d.ts +11 -0
- package/dist/packages/observability/src/index.js +3 -0
- package/dist/packages/orchestration/src/index.d.ts +15 -1
- package/dist/packages/orchestration/src/index.js +127 -21
- package/dist/packages/planner/src/index.d.ts +7 -1
- package/dist/packages/planner/src/index.js +67 -10
- package/dist/packages/planner/src/proposal-store.d.ts +30 -0
- package/dist/packages/planner/src/proposal-store.js +109 -0
- package/dist/packages/policy/src/index.d.ts +9 -16
- package/dist/packages/policy/src/index.js +114 -31
- package/dist/packages/runtime/src/index.d.ts +16 -2
- package/dist/packages/runtime/src/index.js +176 -61
- package/dist/scripts/build-smart-context.d.ts +2 -0
- package/dist/scripts/build-smart-context.js +12 -3
- package/dist/scripts/code-context.d.ts +3 -1
- package/dist/scripts/code-context.js +13 -3
- package/dist/scripts/coverage-gate.d.ts +2 -0
- package/dist/scripts/coverage-gate.js +101 -0
- package/dist/scripts/eval-agents.d.ts +11 -0
- package/dist/scripts/eval-agents.js +96 -0
- package/dist/scripts/gen-commands-doc.d.ts +2 -0
- package/dist/scripts/gen-commands-doc.js +18 -0
- package/dist/scripts/hook-session-memory.d.ts +9 -0
- package/dist/scripts/hook-session-memory.js +20 -0
- package/dist/scripts/hook-session-start.js +34 -0
- package/dist/scripts/llm-fit.js +15 -6
- package/dist/scripts/simulate.js +16 -4
- package/dist/scripts/spec-trace.d.ts +10 -0
- package/dist/scripts/spec-trace.js +73 -0
- package/dist/scripts/sync-universal-memory.js +69 -4
- package/dist/scripts/token-benchmark.d.ts +33 -1
- package/dist/scripts/token-benchmark.js +179 -5
- package/dist/scripts/token-economy.js +3 -1
- package/dist/scripts/tools-doctor.d.ts +16 -1
- package/dist/scripts/tools-doctor.js +58 -17
- package/docs/commands.md +155 -0
- package/docs/fluxo.md +11 -7
- package/docs/init-project.md +3 -1
- package/docs/llm-fit-loop.md +20 -0
- package/docs/manual-operacional-cli-sdd-gsd.md +3 -2
- package/docs/produto/factsheet-marketing.md +7 -5
- package/docs/produto/roteiro-demo.md +14 -5
- package/docs/quick-reference.md +3 -3
- package/docs/token-optimization.md +10 -6
- package/memory/90-decisions/0091-memoria-de-sessao-por-hooks.md +40 -0
- package/memory/90-decisions/0092-criterios-de-aceite-ligados-a-testes.md +37 -0
- package/memory/90-decisions/0093-avaliacoes-com-agentes-reais.md +40 -0
- package/package.json +4 -2
- package/specs/avaliacoes-de-agentes/spec.md +52 -0
- package/specs/criterios-ligados-a-testes/spec.md +42 -0
- package/specs/memoria-de-sessao/spec.md +48 -0
- package/specs/v6-agent-runtime-portable/spec.md +83 -0
- package/specs/v6-core-consolidation/spec.md +70 -0
- package/specs/v6-docs-drift/spec.md +85 -0
- package/specs/v6-quality-gates/spec.md +104 -0
- package/specs/v6-token-economy/spec.md +84 -0
- package/templates/evals/agents/adr.json +25 -0
- package/templates/evals/agents/memoria.json +32 -0
- package/templates/evals/agents/proxima-acao.json +29 -0
- package/templates/evals/agents/spec-nova.json +26 -0
- package/templates/evals/agents/teste-do-criterio.json +29 -0
- package/templates/project/AGENTS.md +7 -0
- package/templates/project/CLAUDE.md +3 -2
- package/templates/project/skills/testing/SKILL.md +1 -1
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/spec-trace.ts — critérios de aceite ligados aos testes que os citam (SPEC-053, ADR-0092).
|
|
3
|
+
*
|
|
4
|
+
* A ligação mora no teste: `SPEC-NNN AC-N` ou `<slug> AC-N` no nome ou num comentário; `AC-N`
|
|
5
|
+
* sozinho vale quando o arquivo cita uma única spec. Estático (não roda testes), qualquer stack.
|
|
6
|
+
*/
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { spawnSync } from 'node:child_process';
|
|
10
|
+
/** Status em que "pronto" já foi prometido: o `--strict` cobra a rastreabilidade. */
|
|
11
|
+
export const GATED_STATUSES = new Set(['approved', 'implementing', 'done']);
|
|
12
|
+
// `AC-1 (RF-01): …` também: agentes ligam o critério ao requisito entre parênteses.
|
|
13
|
+
const AC_LINE = /^\s*[-*]\s*(?:\[[ xX]\]\s*)?\**(AC-\d+)\**(?:\s*\([^)\n]*\))?\s*[:—–-]\s*(.+)$/;
|
|
14
|
+
const SPEC_ID = /\*\*ID\*\*:\s*(SPEC-\d+)/;
|
|
15
|
+
const STATUS = /-\s*\*\*Status\*\*:\s*([a-z-]+)/i;
|
|
16
|
+
const CODE_EXT = /\.(?:[cm]?[jt]sx?|py|go|rb|java|kt|cs|php|rs|swift|exs?)$/;
|
|
17
|
+
const TEST_NAME = /(?:\.(?:test|spec)\.[cm]?[jt]sx?$|^test_.+\.py$|_test\.(?:py|go)$|Tests?\.(?:java|kt|cs)$|_spec\.rb$)/;
|
|
18
|
+
const TEST_DIRS = new Set(['test', 'tests', '__tests__', 'spec']);
|
|
19
|
+
const SKIP_DIRS = new Set(['node_modules', 'dist', 'build', 'coverage', '.git', 'vendor', 'target', 'fixtures', '__fixtures__', '__snapshots__']);
|
|
20
|
+
/** Grupo qualificado: `SPEC-029 AC-5/AC-6`, `pagamentos AC-1, AC-2`, `SPEC-053 (AC-3)`. */
|
|
21
|
+
const QUALIFIED = /\b(SPEC-\d+|[a-z0-9]+(?:-[a-z0-9]+)*)[\s#:(]+(AC-\d+(?:\s*(?:\/|,|&|\be\b|\band\b)?\s*AC-\d+)*)/g;
|
|
22
|
+
const AC_TOKEN = /\bAC-\d+\b/g;
|
|
23
|
+
export function parseCriteria(specText) {
|
|
24
|
+
const out = [];
|
|
25
|
+
for (const line of specText.split(/\r?\n/)) {
|
|
26
|
+
const m = line.match(AC_LINE);
|
|
27
|
+
if (m && !out.some((c) => c.id === m[1]))
|
|
28
|
+
out.push({ id: m[1], text: m[2].trim() });
|
|
29
|
+
}
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
export function isTestFile(rel) {
|
|
33
|
+
const parts = rel.split('/');
|
|
34
|
+
if (parts.some((p) => SKIP_DIRS.has(p)))
|
|
35
|
+
return false;
|
|
36
|
+
const base = parts[parts.length - 1];
|
|
37
|
+
if (TEST_NAME.test(base))
|
|
38
|
+
return true;
|
|
39
|
+
return CODE_EXT.test(base) && parts.slice(0, -1).some((p) => TEST_DIRS.has(p));
|
|
40
|
+
}
|
|
41
|
+
function listFiles(root) {
|
|
42
|
+
const git = spawnSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
|
|
43
|
+
if (git.status === 0)
|
|
44
|
+
return git.stdout.split('\n').filter(Boolean);
|
|
45
|
+
const out = [];
|
|
46
|
+
const walk = (dir, rel) => {
|
|
47
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
48
|
+
if (e.name.startsWith('.') || SKIP_DIRS.has(e.name))
|
|
49
|
+
continue;
|
|
50
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
51
|
+
if (e.isDirectory())
|
|
52
|
+
walk(path.join(dir, e.name), r);
|
|
53
|
+
else if (e.isFile())
|
|
54
|
+
out.push(r);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
walk(root, '');
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
function loadSpecs(root) {
|
|
61
|
+
const dir = path.join(root, 'specs');
|
|
62
|
+
let slugs = [];
|
|
63
|
+
try {
|
|
64
|
+
slugs = fs.readdirSync(dir).filter((s) => !s.startsWith('_') && !s.startsWith('.'));
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return [];
|
|
68
|
+
}
|
|
69
|
+
const out = [];
|
|
70
|
+
for (const slug of slugs.sort()) {
|
|
71
|
+
let text;
|
|
72
|
+
try {
|
|
73
|
+
text = fs.readFileSync(path.join(dir, slug, 'spec.md'), 'utf8');
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
out.push({ slug, specId: text.match(SPEC_ID)?.[1] ?? null, status: text.match(STATUS)?.[1]?.toLowerCase() ?? 'unknown', criteria: parseCriteria(text) });
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
export function traceSpecs(root) {
|
|
83
|
+
const specs = loadSpecs(root);
|
|
84
|
+
const bySlug = new Map(specs.map((s) => [s.slug, s]));
|
|
85
|
+
const byId = new Map();
|
|
86
|
+
for (const s of specs)
|
|
87
|
+
if (s.specId && !byId.has(s.specId))
|
|
88
|
+
byId.set(s.specId, s);
|
|
89
|
+
const resolve = (q) => byId.get(q) ?? bySlug.get(q) ?? null;
|
|
90
|
+
const hits = new Map(); // `${slug}#AC-N` → refs
|
|
91
|
+
const orphans = new Map();
|
|
92
|
+
const ambiguous = [];
|
|
93
|
+
const has = (spec, ac) => spec.criteria.some((c) => c.id === ac);
|
|
94
|
+
const cite = (spec, ac, ref) => {
|
|
95
|
+
if (has(spec, ac)) {
|
|
96
|
+
const k = `${spec.slug}#${ac}`;
|
|
97
|
+
const list = hits.get(k) ?? [];
|
|
98
|
+
if (!list.some((r) => r.file === ref.file && r.line === ref.line))
|
|
99
|
+
list.push(ref);
|
|
100
|
+
hits.set(k, list);
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
const list = orphans.get(spec.slug) ?? [];
|
|
104
|
+
list.push({ ac, ref });
|
|
105
|
+
orphans.set(spec.slug, list);
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
const testFiles = listFiles(root).filter(isTestFile);
|
|
109
|
+
for (const rel of testFiles) {
|
|
110
|
+
let text;
|
|
111
|
+
try {
|
|
112
|
+
text = fs.readFileSync(path.join(root, rel), 'utf8');
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (!text.includes('AC-'))
|
|
118
|
+
continue;
|
|
119
|
+
// Specs que o arquivo cita: pelo ID, por `specs/<slug>` ou pelo slug com hífen (palavra única
|
|
120
|
+
// como "gates" ou "help" aparece em qualquer teste; só conta qualificada ou pelo caminho).
|
|
121
|
+
const live = text.replace(/spec-trace:off[\s\S]*?(?:spec-trace:on|$)/g, '');
|
|
122
|
+
const cited = new Set();
|
|
123
|
+
for (const m of live.matchAll(/\bSPEC-\d+\b/g)) {
|
|
124
|
+
const s = byId.get(m[0]);
|
|
125
|
+
if (s)
|
|
126
|
+
cited.add(s);
|
|
127
|
+
}
|
|
128
|
+
const base = path.basename(rel).replace(/\.(?:test|spec)\.[cm]?[jt]sx?$|\.[a-z]+$/, '').replace(/^test_|_test$/, '').replace(/_/g, '-');
|
|
129
|
+
for (const s of specs) {
|
|
130
|
+
if (base === s.slug || live.includes(`specs/${s.slug}`) || (s.slug.includes('-') && new RegExp(`\\b${s.slug}\\b`).test(live)))
|
|
131
|
+
cited.add(s);
|
|
132
|
+
}
|
|
133
|
+
// Fixtures que contêm citações de exemplo ficam entre `spec-trace:off` e `spec-trace:on`.
|
|
134
|
+
const lines = text.split('\n');
|
|
135
|
+
let off = false;
|
|
136
|
+
lines.forEach((line, i) => {
|
|
137
|
+
if (line.includes('spec-trace:off')) {
|
|
138
|
+
off = true;
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (line.includes('spec-trace:on')) {
|
|
142
|
+
off = false;
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (off || !line.includes('AC-'))
|
|
146
|
+
return;
|
|
147
|
+
const ref = { file: rel, line: i + 1 };
|
|
148
|
+
const consumed = [];
|
|
149
|
+
for (const m of line.matchAll(QUALIFIED)) {
|
|
150
|
+
const spec = resolve(m[1]);
|
|
151
|
+
if (!spec)
|
|
152
|
+
continue;
|
|
153
|
+
consumed.push([m.index, m.index + m[0].length]);
|
|
154
|
+
for (const ac of m[2].match(AC_TOKEN) ?? [])
|
|
155
|
+
cite(spec, ac, ref);
|
|
156
|
+
}
|
|
157
|
+
for (const m of line.matchAll(AC_TOKEN)) {
|
|
158
|
+
if (consumed.some(([a, b]) => m.index >= a && m.index < b))
|
|
159
|
+
continue;
|
|
160
|
+
// `AC-N` solto é ligação fraca: conta se o critério existe na única spec do arquivo; se não
|
|
161
|
+
// existe, provavelmente é de outra spec — ambíguo, não órfão (órfã é só a citação qualificada).
|
|
162
|
+
const only = cited.size === 1 ? [...cited][0] : null;
|
|
163
|
+
if (only && has(only, m[0]))
|
|
164
|
+
cite(only, m[0], ref);
|
|
165
|
+
else if (only)
|
|
166
|
+
ambiguous.push({ ac: m[0], ref, reason: `${m[0]} não existe em ${only.slug}, a única spec citada no arquivo` });
|
|
167
|
+
else
|
|
168
|
+
ambiguous.push({ ac: m[0], ref, reason: cited.size ? `arquivo cita ${cited.size} specs` : 'arquivo não cita nenhuma spec' });
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
return {
|
|
173
|
+
testFiles: testFiles.length,
|
|
174
|
+
ambiguous,
|
|
175
|
+
specs: specs.map((s) => {
|
|
176
|
+
const criteria = s.criteria.map((c) => ({ id: c.id, text: c.text, tests: hits.get(`${s.slug}#${c.id}`) ?? [] }));
|
|
177
|
+
return { slug: s.slug, specId: s.specId, status: s.status, criteria, uncovered: criteria.filter((c) => !c.tests.length).map((c) => c.id), orphans: orphans.get(s.slug) ?? [] };
|
|
178
|
+
}),
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
/** Specs que reprovam no `--strict`: status com "pronto" prometido e lacuna de rastreio. */
|
|
182
|
+
export function strictFailures(specs) {
|
|
183
|
+
return specs.filter((s) => GATED_STATUSES.has(s.status) && (s.uncovered.length > 0 || s.orphans.length > 0));
|
|
184
|
+
}
|
|
@@ -3,10 +3,15 @@ import path from 'node:path';
|
|
|
3
3
|
import { spawnSync } from 'node:child_process';
|
|
4
4
|
import { graphDocumentId } from '../../graph/src/index.js';
|
|
5
5
|
import { isPathWithinRoot } from '../../contracts/src/index.js';
|
|
6
|
+
import { resolveCommand, quoteCmdArg } from '../../../lib/exec.js';
|
|
6
7
|
export class SpawnCommandRunner {
|
|
7
8
|
run(command) {
|
|
8
9
|
const started = Date.now();
|
|
9
|
-
const
|
|
10
|
+
const resolved = resolveCommand(command.executable) ?? command.executable;
|
|
11
|
+
const isCmd = process.platform === 'win32' && /\.(cmd|bat)$/i.test(resolved);
|
|
12
|
+
const result = isCmd
|
|
13
|
+
? spawnSync(process.env.ComSpec ?? 'cmd.exe', ['/d', '/s', '/c', `""${resolved}" ${command.args.map(quoteCmdArg).join(' ')}"`], { cwd: command.cwd, env: sandboxEnvironment(command.env), encoding: 'utf8', windowsVerbatimArguments: true })
|
|
14
|
+
: spawnSync(resolved, [...command.args], { cwd: command.cwd, env: sandboxEnvironment(command.env), encoding: 'utf8' });
|
|
10
15
|
return { exitCode: result.status ?? 1, stdout: result.stdout ?? '', stderr: [result.stderr ?? '', result.error?.message ?? ''].filter(Boolean).join('\n'), durationMs: Date.now() - started };
|
|
11
16
|
}
|
|
12
17
|
}
|
|
@@ -56,7 +61,7 @@ function isIndexable(relative) {
|
|
|
56
61
|
*/
|
|
57
62
|
function sandboxEnvironment(overrides) {
|
|
58
63
|
const inherited = {};
|
|
59
|
-
for (const key of ['PATH', 'NODE_PATH', 'SystemRoot', 'TMPDIR', 'TMP', 'TEMP', 'HOME', 'USERPROFILE']) {
|
|
64
|
+
for (const key of ['PATH', 'NODE_PATH', 'SystemRoot', 'TMPDIR', 'TMP', 'TEMP', 'HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'COMSPEC', 'PATHEXT']) {
|
|
60
65
|
const value = process.env[key];
|
|
61
66
|
if (value !== undefined)
|
|
62
67
|
inherited[key] = value;
|
|
@@ -113,10 +118,14 @@ export class GitWorktreeBackend {
|
|
|
113
118
|
await this.options.patchApplier.revert(this.options.repositoryRoot, patch.stdout);
|
|
114
119
|
}
|
|
115
120
|
async reject(session) {
|
|
116
|
-
await this.runGit(['-C', this.options.repositoryRoot, 'worktree', 'remove', '--force', session.root]);
|
|
121
|
+
const r = await this.runGit(['-C', this.options.repositoryRoot, 'worktree', 'remove', '--force', session.root]);
|
|
122
|
+
if (r.exitCode !== 0)
|
|
123
|
+
await this.runGit(['-C', this.options.repositoryRoot, 'worktree', 'prune']);
|
|
117
124
|
}
|
|
118
125
|
async destroy(session) {
|
|
119
|
-
await this.runGit(['-C', this.options.repositoryRoot, 'worktree', 'remove', '--force', session.root]);
|
|
126
|
+
const r = await this.runGit(['-C', this.options.repositoryRoot, 'worktree', 'remove', '--force', session.root]);
|
|
127
|
+
if (r.exitCode !== 0)
|
|
128
|
+
await this.runGit(['-C', this.options.repositoryRoot, 'worktree', 'prune']);
|
|
120
129
|
}
|
|
121
130
|
async runGit(args) {
|
|
122
131
|
return this.runner.run({ executable: 'git', args });
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type McpServer } from '../../mcp/src/index.ts';
|
|
2
2
|
import type { ControlPlanePort } from '../../observability/src/index.ts';
|
|
3
3
|
export interface HttpRequest {
|
|
4
4
|
readonly method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
@@ -50,6 +50,7 @@ export interface NestModuleDefinition {
|
|
|
50
50
|
readonly routes: readonly string[];
|
|
51
51
|
}
|
|
52
52
|
export declare const FORJA_NEST_MODULES: readonly NestModuleDefinition[];
|
|
53
|
+
export declare function planningOpenApiPaths(): OpenApiDocument['paths'];
|
|
53
54
|
export declare class NestAdapterError extends Error {
|
|
54
55
|
constructor(message: string);
|
|
55
56
|
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { PLANNING_PROPOSE_SCHEMA, PLANNING_REVIEW_SCHEMA } from '../../mcp/src/index.js';
|
|
3
|
+
import { PlanningError } from '../../planner/src/proposal-store.js';
|
|
2
4
|
/**
|
|
3
5
|
* True for 127.0.0.0/8 and ::1 (with the common ::ffff:-mapped IPv4 form normalized first).
|
|
4
6
|
* `address === undefined` returns false — "unknown" is not "trusted" — but callers that only have
|
|
@@ -26,6 +28,7 @@ export const FORJA_NEST_MODULES = [
|
|
|
26
28
|
{ name: 'WorkspaceModule', routes: ['/health', '/api/workspace/status'] },
|
|
27
29
|
{ name: 'CapabilityModule', routes: ['/api/capabilities', '/api/capabilities/:id/execute'] },
|
|
28
30
|
{ name: 'RuntimeModule', routes: ['/api/executions/:id'] },
|
|
31
|
+
{ name: 'PlanningModule', routes: ['/api/plans', '/api/plans/:id', '/api/plans/:id/review'] },
|
|
29
32
|
{ name: 'GraphModule', routes: ['/api/graph/query', '/api/graph/impact'] },
|
|
30
33
|
{ name: 'ContextModule', routes: ['/api/context/build'] },
|
|
31
34
|
{ name: 'PolicyModule', routes: ['/api/policies'] },
|
|
@@ -38,6 +41,44 @@ export const FORJA_NEST_MODULES = [
|
|
|
38
41
|
{ name: 'ControlPlaneModule', routes: ['/api/control-plane/metrics'] },
|
|
39
42
|
{ name: 'McpModule', routes: ['/mcp/tools', '/mcp/resources'] },
|
|
40
43
|
];
|
|
44
|
+
export function planningOpenApiPaths() {
|
|
45
|
+
const string = { type: 'string' };
|
|
46
|
+
const strings = { type: 'array', items: string };
|
|
47
|
+
const timestamp = { type: 'string', format: 'date-time' };
|
|
48
|
+
const tokens = { type: 'integer', minimum: 0 };
|
|
49
|
+
const tokenBudget = PLANNING_PROPOSE_SCHEMA.properties.budget;
|
|
50
|
+
const knowledge = { type: 'string', enum: ['verified', 'inferred', 'hypothesis', 'contradicted', 'unknown'] };
|
|
51
|
+
const evidence = { type: 'object', required: ['id', 'source', 'locator', 'capturedAt', 'status'], properties: { id: string, source: string, locator: string, capturedAt: timestamp, status: knowledge, checksum: string } };
|
|
52
|
+
const evidenceItems = { type: 'array', items: evidence };
|
|
53
|
+
const contextItem = { type: 'object', required: ['id', 'source', 'locator', 'checksum', 'status', 'evidence'], properties: { id: string, source: { enum: ['memory', 'graph'] }, locator: string, content: string, checksum: string, status: knowledge, evidence: evidenceItems } };
|
|
54
|
+
const task = { type: 'object', required: ['id', 'sprintId', 'objective', 'acceptanceCriteria', 'allowedFiles', 'dependencyIds', 'budget', 'status'], properties: { id: string, sprintId: string, objective: string, acceptanceCriteria: strings, allowedFiles: strings, dependencyIds: strings, evidenceIds: strings, budget: tokenBudget, status: string } };
|
|
55
|
+
const step = { type: 'object', required: ['id', 'objective', 'acceptanceCriteria', 'allowedFiles', 'dependencyIds', 'evidenceIds', 'budget', 'status'], properties: { id: string, objective: string, acceptanceCriteria: strings, allowedFiles: strings, dependencyIds: strings, externalDependencyIds: strings, contextItemId: string, rationale: string, constraints: strings, evidenceIds: strings, risk: string, budget: tokenBudget, status: string } };
|
|
56
|
+
const proposal = {
|
|
57
|
+
type: 'object', required: ['id', 'version', 'digest', 'status', 'snapshot', 'budget', 'blockers'],
|
|
58
|
+
properties: {
|
|
59
|
+
id: string, version: { const: 1 }, digest: string, status: { type: 'string', enum: ['draft', 'blocked', 'approved', 'rejected'] },
|
|
60
|
+
schemaVersion: string, createdAt: timestamp, updatedAt: timestamp, correlationId: string, declaredEvidenceIds: strings,
|
|
61
|
+
executor: { type: 'object', required: ['id', 'name', 'role', 'autonomy'], properties: { id: string, name: string, role: string, autonomy: string } },
|
|
62
|
+
snapshot: { type: 'object', required: ['task', 'sprint', 'dependencies'], properties: {
|
|
63
|
+
task, dependencies: { type: 'array', items: task },
|
|
64
|
+
sprint: { type: 'object', properties: { id: string, objective: string, status: string, budget: tokenBudget, includedScope: strings, excludedScope: strings, completionCriteria: strings, taskIds: strings } },
|
|
65
|
+
handoff: { type: 'object', properties: { id: string, taskId: string, from: string, to: string, nextAgent: string, intent: string, objective: string, completedWork: strings, decisions: strings, constraints: strings, pending: strings, acceptance: strings, blockers: strings, evidenceIds: strings, status: string } },
|
|
66
|
+
} },
|
|
67
|
+
plan: { type: 'object', properties: { id: string, objective: string, steps: { type: 'array', items: step }, budget: tokenBudget, constraints: strings, decisions: strings, evidenceIds: strings } },
|
|
68
|
+
context: { type: 'object', properties: { id: string, checksum: string, references: evidenceItems, content: strings, items: { type: 'array', items: contextItem }, budget: tokenBudget } },
|
|
69
|
+
budget: { type: 'object', description: 'Conservative token estimates, not billed usage', required: ['limit', 'briefingTokens', 'contextTokens', 'allocation'], properties: { limit: tokenBudget, briefingTokens: tokens, contextTokens: tokens, allocation: tokenBudget } },
|
|
70
|
+
blockers: { type: 'array', items: { type: 'object', required: ['code', 'message'], properties: { code: string, message: string } } },
|
|
71
|
+
review: { type: 'object', required: ['decision', 'reviewerId', 'reason', 'digest', 'decidedAt'], properties: { decision: { enum: ['approved', 'rejected'] }, reviewerId: string, reason: string, digest: string, decidedAt: timestamp, sourcesVerifiedAt: timestamp } },
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
const responses = { '200': { description: 'Persisted planning proposal; never an execution', content: { 'application/json': { schema: proposal } } }, ...Object.fromEntries([400, 401, 403, 404, 409, 500, 503].map((status) => [String(status), { description: 'Planning error', content: { 'application/json': { schema: { type: 'object', required: ['error'], properties: { error: { type: 'object', required: ['code', 'message'], properties: { code: { type: 'string' }, message: { type: 'string' } } } } } } } }])) };
|
|
75
|
+
const parameters = [{ name: 'id', in: 'path', required: true, schema: { type: 'string', minLength: 1 } }];
|
|
76
|
+
return {
|
|
77
|
+
'/api/plans': { post: { operationId: 'planPropose', requestBody: { required: true, content: { 'application/json': { schema: PLANNING_PROPOSE_SCHEMA } } }, responses } },
|
|
78
|
+
'/api/plans/{id}': { get: { operationId: 'planGet', parameters, responses } },
|
|
79
|
+
'/api/plans/{id}/review': { post: { operationId: 'planReview', parameters, requestBody: { required: true, content: { 'application/json': { schema: PLANNING_REVIEW_SCHEMA } } }, responses } },
|
|
80
|
+
};
|
|
81
|
+
}
|
|
41
82
|
export class NestAdapterError extends Error {
|
|
42
83
|
constructor(message) { super(message); this.name = 'NestAdapterError'; }
|
|
43
84
|
}
|
|
@@ -56,6 +97,10 @@ export class ForjaNestAdapter {
|
|
|
56
97
|
return this.result(correlationId, result);
|
|
57
98
|
}
|
|
58
99
|
catch (error) {
|
|
100
|
+
if (request.path === '/api/plans' || request.path.startsWith('/api/plans/')) {
|
|
101
|
+
const status = error instanceof PlanningError ? { PLANNING_INVALID_INPUT: 400, PLANNING_NOT_FOUND: 404, PLANNING_DENIED: 403, PLANNING_CONFLICT: 409, PLANNING_STALE: 409, PLANNING_INVALID_SCOPE: 409, PLANNING_INVALID_REVIEW: 409, PLANNING_REVIEWER_UNAVAILABLE: 503 }[error.code] ?? 500 : 500;
|
|
102
|
+
return { status, headers: { 'content-type': 'application/json; charset=utf-8', 'x-correlation-id': correlationId }, body: { error: { code: status === 500 ? 'PLANNING_UNAVAILABLE' : error.code, message: status === 500 ? 'Planning service unavailable' : error.message } }, correlationId };
|
|
103
|
+
}
|
|
59
104
|
return this.error(correlationId, error instanceof Error ? error.message : 'Unknown HTTP adapter error');
|
|
60
105
|
}
|
|
61
106
|
}
|
|
@@ -79,10 +124,23 @@ export class ForjaNestAdapter {
|
|
|
79
124
|
}
|
|
80
125
|
modules() { return FORJA_NEST_MODULES; }
|
|
81
126
|
openApi() {
|
|
82
|
-
const paths = Object.fromEntries(FORJA_NEST_MODULES.flatMap((module) => module.routes.map((route) => [route, { description: `${module.name} route` }])));
|
|
127
|
+
const paths = { ...Object.fromEntries(FORJA_NEST_MODULES.filter((module) => module.name !== 'PlanningModule').flatMap((module) => module.routes.map((route) => [route, { description: `${module.name} route` }]))), ...planningOpenApiPaths() };
|
|
83
128
|
return { openapi: '3.1.0', info: { title: 'ForjaJS 2.0 API', version: '2.0.0' }, paths };
|
|
84
129
|
}
|
|
85
130
|
async dispatch(request) {
|
|
131
|
+
if (request.method === 'POST' && request.path === '/api/plans') {
|
|
132
|
+
if (typeof request.body !== 'object' || request.body === null || Array.isArray(request.body))
|
|
133
|
+
throw new PlanningError('PLANNING_INVALID_INPUT', 'Planning body must be an object');
|
|
134
|
+
const body = request.body;
|
|
135
|
+
return this.requireControlPlane().planPropose?.({ ...body, correlationId: request.correlationId ?? request.headers['x-correlation-id'] ?? body.correlationId }) ?? this.missing('planPropose');
|
|
136
|
+
}
|
|
137
|
+
const planRoute = /^\/api\/plans\/([^/]+)(\/review)?$/.exec(request.path);
|
|
138
|
+
if (planRoute !== null && request.method === 'GET' && planRoute[2] === undefined)
|
|
139
|
+
return this.requireControlPlane().planGet?.(planRoute[1]) ?? this.missing('planGet');
|
|
140
|
+
if (planRoute !== null && request.method === 'POST' && planRoute[2] !== undefined)
|
|
141
|
+
return this.requireControlPlane().planReview?.(planRoute[1], request.body) ?? this.missing('planReview');
|
|
142
|
+
if (request.path === '/api/plans' || request.path.startsWith('/api/plans/'))
|
|
143
|
+
throw new PlanningError('PLANNING_NOT_FOUND', 'Planning route not found');
|
|
86
144
|
if (request.method === 'GET' && request.path === '/health')
|
|
87
145
|
return { status: 'ok', service: 'forja-server', offline: true };
|
|
88
146
|
if (request.method === 'GET' && request.path === '/api/workspace/status')
|
|
@@ -4,12 +4,14 @@ import type { ProvenanceRecord } from '../../engineering/provenance/src/index.ts
|
|
|
4
4
|
import type { ApprovalStore } from '../../policy/src/index.ts';
|
|
5
5
|
import type { CheckpointStore, RuntimePersistence, RuntimePlanStep } from '../../runtime/src/index.ts';
|
|
6
6
|
import type { McpAuditEvent, McpAuditSink } from '../../mcp/src/index.ts';
|
|
7
|
-
import type
|
|
7
|
+
import { type ExecutionTransition, type OrchestrationStore } from '../../orchestration/src/index.ts';
|
|
8
8
|
import type { SandboxStore } from '../../sandbox/src/index.ts';
|
|
9
9
|
import type { ObservationStore } from '../../observability/src/index.ts';
|
|
10
10
|
import type { GraphStore } from '../../graph/src/index.ts';
|
|
11
11
|
import type { Evidence, GraphEdge, GraphNode } from '../../contracts/src/index.ts';
|
|
12
12
|
import type { ContextCache } from '../../context/src/index.ts';
|
|
13
|
+
import type { PlanningProposal, PlanningSnapshot } from '../../contracts/src/index.ts';
|
|
14
|
+
import { type PlanningStore } from '../../planner/src/proposal-store.ts';
|
|
13
15
|
export interface SqliteStatement {
|
|
14
16
|
run(...parameters: readonly unknown[]): {
|
|
15
17
|
readonly changes?: number;
|
|
@@ -47,7 +49,9 @@ export declare class SqliteJsonRepository {
|
|
|
47
49
|
}
|
|
48
50
|
export declare class SqliteOrchestrationStore implements OrchestrationStore {
|
|
49
51
|
private readonly repository;
|
|
52
|
+
private readonly db;
|
|
50
53
|
constructor(db: SqliteConnection);
|
|
54
|
+
transitionExecution(input: ExecutionTransition): void;
|
|
51
55
|
saveSprint(value: Sprint): void;
|
|
52
56
|
getSprint(id: EntityId): Sprint | undefined;
|
|
53
57
|
listSprints(): readonly Sprint[];
|
|
@@ -58,6 +62,16 @@ export declare class SqliteOrchestrationStore implements OrchestrationStore {
|
|
|
58
62
|
getHandoff(id: EntityId): Handoff | undefined;
|
|
59
63
|
listHandoffs(): readonly Handoff[];
|
|
60
64
|
}
|
|
65
|
+
export declare class SqlitePlanningStore implements PlanningStore {
|
|
66
|
+
private readonly db;
|
|
67
|
+
private readonly repository;
|
|
68
|
+
private readonly reader;
|
|
69
|
+
constructor(db: SqliteConnection);
|
|
70
|
+
create(proposal: PlanningProposal): void;
|
|
71
|
+
get(id: EntityId): PlanningProposal | undefined;
|
|
72
|
+
review(before: PlanningProposal, after: PlanningProposal, expectedSnapshot?: PlanningSnapshot): void;
|
|
73
|
+
private transaction;
|
|
74
|
+
}
|
|
61
75
|
export declare class SqliteSandboxStore implements SandboxStore {
|
|
62
76
|
private readonly repository;
|
|
63
77
|
constructor(db: SqliteConnection);
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { assertExecutionTransition } from '../../orchestration/src/index.js';
|
|
3
|
+
import { assertPlanningCreate, assertPlanningReview, clonePlanningValue } from '../../planner/src/proposal-store.js';
|
|
2
4
|
export const MIGRATIONS = [
|
|
3
5
|
{
|
|
4
6
|
version: 1,
|
|
@@ -82,7 +84,24 @@ export class SqliteJsonRepository {
|
|
|
82
84
|
}
|
|
83
85
|
export class SqliteOrchestrationStore {
|
|
84
86
|
repository;
|
|
85
|
-
|
|
87
|
+
db;
|
|
88
|
+
constructor(db) { this.db = db; this.repository = new SqliteJsonRepository(db); }
|
|
89
|
+
transitionExecution(input) {
|
|
90
|
+
// A savepoint also works inside an existing transaction. No handlers or awaits here.
|
|
91
|
+
this.db.exec('SAVEPOINT forja_execution_transition');
|
|
92
|
+
try {
|
|
93
|
+
assertExecutionTransition(input, this.getTask(input.beforeTask.id), input.beforeHandoff === undefined ? undefined : this.getHandoff(input.beforeHandoff.id));
|
|
94
|
+
this.saveTask(input.task);
|
|
95
|
+
if (input.handoff !== undefined)
|
|
96
|
+
this.saveHandoff(input.handoff);
|
|
97
|
+
this.db.exec('RELEASE SAVEPOINT forja_execution_transition');
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
this.db.exec('ROLLBACK TO SAVEPOINT forja_execution_transition');
|
|
101
|
+
this.db.exec('RELEASE SAVEPOINT forja_execution_transition');
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
86
105
|
saveSprint(value) { this.repository.put('sprint', value.id, value, value.updatedAt); }
|
|
87
106
|
getSprint(id) { return this.repository.get('sprint', id); }
|
|
88
107
|
listSprints() { return this.repository.list('sprint'); }
|
|
@@ -93,6 +112,47 @@ export class SqliteOrchestrationStore {
|
|
|
93
112
|
getHandoff(id) { return this.repository.get('handoff', id); }
|
|
94
113
|
listHandoffs() { return this.repository.list('handoff'); }
|
|
95
114
|
}
|
|
115
|
+
export class SqlitePlanningStore {
|
|
116
|
+
db;
|
|
117
|
+
repository;
|
|
118
|
+
reader;
|
|
119
|
+
constructor(db) {
|
|
120
|
+
this.db = db;
|
|
121
|
+
this.repository = new SqliteJsonRepository(db);
|
|
122
|
+
this.reader = new SqliteOrchestrationStore(db);
|
|
123
|
+
}
|
|
124
|
+
create(proposal) {
|
|
125
|
+
const next = clonePlanningValue(proposal);
|
|
126
|
+
this.transaction(() => {
|
|
127
|
+
assertPlanningCreate(next, this.get(next.id), this.reader);
|
|
128
|
+
this.repository.put('planning_proposal', next.id, next, next.updatedAt);
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
get(id) { return this.repository.get('planning_proposal', id); }
|
|
132
|
+
review(before, after, expectedSnapshot) {
|
|
133
|
+
const previous = clonePlanningValue(before);
|
|
134
|
+
const next = clonePlanningValue(after);
|
|
135
|
+
const expected = clonePlanningValue(expectedSnapshot);
|
|
136
|
+
this.transaction(() => {
|
|
137
|
+
if (assertPlanningReview(previous, next, this.get(previous.id), expected, this.reader)) {
|
|
138
|
+
this.repository.put('planning_proposal', next.id, next, next.updatedAt);
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
transaction(write) {
|
|
143
|
+
// Snapshot reads, CAS and proposal write share the same short, synchronous transaction.
|
|
144
|
+
this.db.exec('SAVEPOINT forja_planning_proposal');
|
|
145
|
+
try {
|
|
146
|
+
write();
|
|
147
|
+
this.db.exec('RELEASE SAVEPOINT forja_planning_proposal');
|
|
148
|
+
}
|
|
149
|
+
catch (error) {
|
|
150
|
+
this.db.exec('ROLLBACK TO SAVEPOINT forja_planning_proposal');
|
|
151
|
+
this.db.exec('RELEASE SAVEPOINT forja_planning_proposal');
|
|
152
|
+
throw error;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
96
156
|
export class SqliteSandboxStore {
|
|
97
157
|
repository;
|
|
98
158
|
constructor(db) { this.repository = new SqliteJsonRepository(db); }
|
|
@@ -21,6 +21,7 @@ export interface ContextBuildRequest {
|
|
|
21
21
|
readonly objective: string;
|
|
22
22
|
readonly budget: TokenBudget;
|
|
23
23
|
readonly includeContent?: boolean;
|
|
24
|
+
readonly includeProvenanceInBudget?: boolean;
|
|
24
25
|
readonly maxItems?: number;
|
|
25
26
|
readonly requireEvidence?: boolean;
|
|
26
27
|
readonly correlationId?: string;
|
|
@@ -53,6 +54,7 @@ export declare class ContextEngine {
|
|
|
53
54
|
build(request: ContextBuildRequest): Promise<ContextPackage>;
|
|
54
55
|
expand(checksum: string): string;
|
|
55
56
|
private isUsable;
|
|
57
|
+
private contextItem;
|
|
56
58
|
private estimateTokens;
|
|
57
59
|
private checksum;
|
|
58
60
|
private uniqueEvidence;
|
|
@@ -42,30 +42,38 @@ export class ContextEngine {
|
|
|
42
42
|
if (candidates.length === 0 && (request.requireEvidence ?? true))
|
|
43
43
|
throw new ContextEngineError('INSUFFICIENT_EVIDENCE', 'No current evidence matches the context objective');
|
|
44
44
|
const ranked = candidates
|
|
45
|
-
.map((candidate) => ({ candidate,
|
|
46
|
-
.sort((left, right) => right.candidate.relevance - left.candidate.relevance
|
|
45
|
+
.map((candidate) => ({ candidate, item: this.contextItem(candidate, request.includeContent !== false) }))
|
|
46
|
+
.sort((left, right) => right.candidate.relevance - left.candidate.relevance
|
|
47
|
+
|| left.item.locator.localeCompare(right.item.locator)
|
|
48
|
+
|| left.item.checksum.localeCompare(right.item.checksum)
|
|
49
|
+
|| JSON.stringify(left.item).localeCompare(JSON.stringify(right.item)));
|
|
47
50
|
const unique = new Map();
|
|
48
|
-
for (const
|
|
49
|
-
if (!unique.has(item.checksum))
|
|
50
|
-
unique.set(item.checksum,
|
|
51
|
+
for (const entry of ranked)
|
|
52
|
+
if (!unique.has(entry.item.checksum))
|
|
53
|
+
unique.set(entry.item.checksum, entry);
|
|
51
54
|
const availableTokens = request.budget.totalTokens - request.budget.usedTokens;
|
|
52
55
|
let usedTokens = 0;
|
|
53
56
|
let cacheHits = 0;
|
|
54
57
|
const selected = [];
|
|
55
|
-
for (const
|
|
56
|
-
const
|
|
58
|
+
for (const entry of [...unique.values()].slice(0, maxItems)) {
|
|
59
|
+
const { candidate, item } = entry;
|
|
60
|
+
const tokens = this.estimateTokens(request.includeProvenanceInBudget ? JSON.stringify(item) : candidate.content);
|
|
57
61
|
if (usedTokens + tokens > availableTokens)
|
|
58
62
|
continue;
|
|
59
|
-
|
|
63
|
+
// Supplied keys remain valid for expand(), but never establish content freshness.
|
|
64
|
+
const cacheKey = candidate.checksum ?? item.checksum;
|
|
65
|
+
if (this.dependencies.cache?.get(cacheKey) === candidate.content)
|
|
60
66
|
cacheHits += 1;
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
67
|
+
this.dependencies.cache?.set(cacheKey, candidate.content);
|
|
68
|
+
if (cacheKey !== item.checksum)
|
|
69
|
+
this.dependencies.cache?.set(item.checksum, candidate.content);
|
|
70
|
+
selected.push(entry);
|
|
64
71
|
usedTokens += tokens;
|
|
65
72
|
}
|
|
66
73
|
if (selected.length === 0 && (request.requireEvidence ?? true))
|
|
67
74
|
throw new ContextEngineError('CONTEXT_BUDGET_EXCEEDED', 'Context budget cannot fit any evidence');
|
|
68
|
-
const
|
|
75
|
+
const items = selected.map((entry) => entry.item);
|
|
76
|
+
const references = this.uniqueEvidence(items.flatMap((item) => item.evidence));
|
|
69
77
|
const content = request.includeContent === false ? [] : selected.map((item) => item.candidate.content);
|
|
70
78
|
const metrics = {
|
|
71
79
|
candidateCount: candidates.length,
|
|
@@ -81,8 +89,9 @@ export class ContextEngine {
|
|
|
81
89
|
id: randomUUID(),
|
|
82
90
|
references,
|
|
83
91
|
content,
|
|
92
|
+
items,
|
|
84
93
|
budget: { ...request.budget, usedTokens: request.budget.usedTokens + usedTokens },
|
|
85
|
-
checksum: this.checksum(JSON.stringify({ objective: request.objective,
|
|
94
|
+
checksum: this.checksum(JSON.stringify({ objective: request.objective, items, includeContent: request.includeContent !== false })),
|
|
86
95
|
metrics,
|
|
87
96
|
};
|
|
88
97
|
}
|
|
@@ -93,7 +102,18 @@ export class ContextEngine {
|
|
|
93
102
|
return content;
|
|
94
103
|
}
|
|
95
104
|
isUsable(candidate) {
|
|
96
|
-
return !candidate.obsolete && candidate.status !== 'contradicted' && candidate.content.trim().length > 0 && Number.isFinite(candidate.relevance) && candidate.evidence.length > 0;
|
|
105
|
+
return !candidate.obsolete && candidate.status !== 'contradicted' && candidate.content.trim().length > 0 && Number.isFinite(candidate.relevance) && candidate.evidence.length > 0 && candidate.evidence.every((item) => item.status !== 'contradicted');
|
|
106
|
+
}
|
|
107
|
+
contextItem(candidate, includeContent) {
|
|
108
|
+
return {
|
|
109
|
+
id: candidate.id,
|
|
110
|
+
source: candidate.source,
|
|
111
|
+
locator: candidate.locator,
|
|
112
|
+
...(includeContent ? { content: candidate.content } : {}),
|
|
113
|
+
checksum: this.checksum(candidate.content),
|
|
114
|
+
status: candidate.status,
|
|
115
|
+
evidence: [...candidate.evidence].sort((left, right) => left.id.localeCompare(right.id) || JSON.stringify(left).localeCompare(JSON.stringify(right))),
|
|
116
|
+
};
|
|
97
117
|
}
|
|
98
118
|
estimateTokens(content) {
|
|
99
119
|
return Math.max(1, Math.ceil(Buffer.byteLength(content, 'utf8') / 4));
|
|
@@ -103,7 +123,8 @@ export class ContextEngine {
|
|
|
103
123
|
}
|
|
104
124
|
uniqueEvidence(evidence) {
|
|
105
125
|
const unique = new Map();
|
|
106
|
-
|
|
126
|
+
const sorted = [...evidence].sort((left, right) => left.id.localeCompare(right.id) || JSON.stringify(left).localeCompare(JSON.stringify(right)));
|
|
127
|
+
for (const item of sorted)
|
|
107
128
|
if (!unique.has(item.id))
|
|
108
129
|
unique.set(item.id, item);
|
|
109
130
|
return [...unique.values()];
|