@cassiomc1/forgeloop 2.1.0 → 2.2.0

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.
@@ -0,0 +1,36 @@
1
+ import { collectAssessmentFacts } from "../core/assessment/facts.js";
2
+ import { buildReviewPlan } from "../core/assessment/plan.js";
3
+
4
+ export const ASSESSMENT_SCHEMA_VERSION = 1;
5
+
6
+ export async function runAssess({ target = process.cwd() } = {}) {
7
+ const facts = await collectAssessmentFacts(target);
8
+ return {
9
+ schemaVersion: ASSESSMENT_SCHEMA_VERSION,
10
+ kind: "repository-assessment-plan",
11
+ authority: "DISCOVERY_ONLY",
12
+ evidenceAuthority: "NONE",
13
+ facts,
14
+ reviewPlan: buildReviewPlan(facts),
15
+ };
16
+ }
17
+
18
+ export function formatAssessResult(result) {
19
+ const { facts, reviewPlan } = result;
20
+ const lines = [
21
+ "FORGELOOP REPOSITORY ASSESSMENT (discovery only, nothing executed):",
22
+ `Stack: ${facts.stack.status === "DETECTED" ? facts.stack.frameworks.join(", ") || "none" : "not determined"}`,
23
+ `Tests discovered: ${facts.tests.total} in ${facts.tests.files} files`,
24
+ "Areas:",
25
+ ];
26
+ for (const area of reviewPlan.areas) lines.push(` - ${area.area}: ${area.guides.map((guide) => guide.id).join(", ")}`);
27
+ if (reviewPlan.areas.length === 0) lines.push(" - none detected");
28
+ lines.push("Candidate checks (NOT_EXECUTED):");
29
+ for (const check of reviewPlan.candidateChecks) lines.push(` - ${check.argv.join(" ")} [${check.purpose}; ${check.source}]`);
30
+ if (reviewPlan.candidateChecks.length === 0) lines.push(" - none detected");
31
+ lines.push("Observed gaps:");
32
+ for (const gap of reviewPlan.gaps) lines.push(` - ${gap.code}: ${gap.message}`);
33
+ if (reviewPlan.gaps.length === 0) lines.push(" - none");
34
+ lines.push("Next steps:", ...reviewPlan.nextSteps.map((step) => ` - ${step}`));
35
+ return `${lines.join("\n")}\n`;
36
+ }
@@ -0,0 +1,17 @@
1
+ import { exportEvidenceBundle } from "../core/evidence/export.js";
2
+
3
+ export async function runEvidenceExport({ target, packageRoot, taskId, evidenceDirectory } = {}) {
4
+ if (!taskId) throw Object.assign(new Error("--task is required for evidence-export"), { code: "E_CLI_INVOCATION_INVALID" });
5
+ return exportEvidenceBundle({ target, packageRoot, taskId, ...(evidenceDirectory ? { directory: evidenceDirectory } : {}) });
6
+ }
7
+
8
+ export function formatEvidenceExportResult(result) {
9
+ return [
10
+ `FORGELOOP EVIDENCE EXPORTED: ${result.taskId}`,
11
+ `PATH: ${result.path}`,
12
+ `COVERED PATHS: ${result.coveredPaths}`,
13
+ `SIGNED: ${result.signed ? "yes" : "no (CI reports INTEGRITY_ONLY)"}`,
14
+ "Commit this file with the change it covers.",
15
+ "",
16
+ ].join("\n");
17
+ }
@@ -0,0 +1,36 @@
1
+ import { verifyEvidenceRange } from "../core/evidence/verify.js";
2
+ import { formatEvidenceMarkdown } from "../core/evidence/markdown.js";
3
+
4
+ export async function runEvidenceVerify(options = {}) {
5
+ return verifyEvidenceRange({
6
+ target: options.target,
7
+ packageRoot: options.packageRoot,
8
+ revisionProvider: options.revisionProvider ?? "git",
9
+ baseRevision: options.baseRevision,
10
+ headRevision: options.headRevision,
11
+ ...(options.evidenceDirectory ? { directory: options.evidenceDirectory } : {}),
12
+ requireCompleteCoverage: options.allowPartialCoverage !== true,
13
+ requireSignature: options.requireSignature === true,
14
+ signerPolicy: {
15
+ identity: options.attestationIdentity,
16
+ issuer: options.attestationIssuer,
17
+ trustedRoot: options.trustedRoot,
18
+ },
19
+ exclusions: Array.isArray(options.evidenceExclusions) ? options.evidenceExclusions : [],
20
+ });
21
+ }
22
+
23
+ export function formatEvidenceVerifyResult(result, options = {}) {
24
+ if (options.evidenceFormat === "markdown") return formatEvidenceMarkdown(result);
25
+ return [
26
+ `FORGELOOP EVIDENCE VERIFICATION: ${result.status}`,
27
+ `LEVEL: ${result.level}`,
28
+ `CHANGED: ${result.changedPaths}`,
29
+ `COVERED: ${result.coveredPaths}`,
30
+ `UNCOVERED: ${result.uncoveredPaths.length}`,
31
+ `BUNDLES: ${result.bundles.length}`,
32
+ ...result.errors.map((error) => `${error.code}: ${error.message}`),
33
+ ...result.warnings.map((warning) => `WARNING: ${warning}`),
34
+ "",
35
+ ].join("\n");
36
+ }
@@ -0,0 +1,46 @@
1
+ import { mkdtemp, rm } from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ import { readSyncCredentials, remoteError, strongEtag, resolveRemote, resolveRepository, syncRequest, writeSyncState } from "../core/sync/remote.js";
6
+ import { MAX_SNAPSHOT_BYTES, openSnapshot, syncError, unpackDirectory } from "../core/sync/snapshot.js";
7
+ import { runStorageRestore } from "./storage-restore.js";
8
+
9
+ // Downloads, decrypts and restores the repository's snapshot. Remote state is
10
+ // untrusted: it must decrypt and authenticate under FORGELOOP_SYNC_KEY, every
11
+ // file digest must match, and activation goes through the verified
12
+ // storage-restore path (a fresh project, or explicit --replace-active).
13
+ export async function runSyncPull({ target, packageRoot, remote, repository, writersQuiesced = false, replaceActive = false, env = process.env, fetchImpl = fetch } = {}) {
14
+ if (writersQuiesced !== true) throw syncError("E_STORAGE_MIGRATION_QUIESCENCE_REQUIRED", "Stop every ForgeLoop writer for this project, then pass --writers-quiesced");
15
+ const { token, passphrase } = readSyncCredentials(env);
16
+ const resolvedRemote = resolveRemote(remote);
17
+ const resolvedRepository = await resolveRepository(target, repository);
18
+ const response = await syncRequest({ remote: resolvedRemote, repository: resolvedRepository, token, method: "GET", fetchImpl });
19
+ if (response.status === 404) throw syncError("E_SYNC_REMOTE", `No snapshot has been pushed for ${resolvedRepository}`);
20
+ if (!response.ok) throw await remoteError(response);
21
+ const etag = strongEtag(response.headers.get("etag"));
22
+ const body = Buffer.from(await response.arrayBuffer());
23
+ if (body.length > MAX_SNAPSHOT_BYTES) throw syncError("E_SYNC_TOO_LARGE", "Remote snapshot exceeds the size limit");
24
+ const { envelope, payload } = openSnapshot(body, { passphrase, repository: resolvedRepository });
25
+
26
+ const staging = await mkdtemp(path.join(os.tmpdir(), "forgeloop-sync-"));
27
+ try {
28
+ const source = path.join(staging, "backup");
29
+ const files = await unpackDirectory(payload, source);
30
+ const restore = await runStorageRestore({ target, source, writersQuiesced, replaceActive, packageRoot });
31
+ if (etag) await writeSyncState(target, { remote: resolvedRemote, repository: resolvedRepository, etag, direction: "pull", at: new Date().toISOString() }, { env });
32
+ return { status: "PULLED", repository: resolvedRepository, remote: resolvedRemote, etag, files: files.length, snapshotCreatedAt: envelope.createdAt ?? null, replaceActive, restore };
33
+ } finally {
34
+ await rm(staging, { recursive: true, force: true });
35
+ }
36
+ }
37
+
38
+ export function formatSyncPullResult(result) {
39
+ return [
40
+ `FORGELOOP SYNC PULLED: ${result.repository}`,
41
+ `SNAPSHOT: ${result.snapshotCreatedAt ?? "unknown time"} (${result.files} files, ETag ${result.etag ?? "unknown"})`,
42
+ `RESTORED: ${result.replaceActive ? "replaced the active state (outgoing state retained)" : "into a fresh project"}`,
43
+ "Run forgeloop task-list to resume. This machine is now the one allowed to push.",
44
+ "",
45
+ ].join("\n");
46
+ }
@@ -0,0 +1,49 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { readFile, rm } from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ import { readSyncCredentials, readSyncState, strongEtag, remoteError, resolveRemote, resolveRepository, syncRequest, writeSyncState } from "../core/sync/remote.js";
6
+ import { packDirectory, sealSnapshot } from "../core/sync/snapshot.js";
7
+ import { runStorageBackup } from "./storage-backup.js";
8
+
9
+ // Uploads an encrypted, attachment-inclusive backup of this project's ForgeLoop
10
+ // state. The write is conditional: the first push only creates, later pushes
11
+ // must match the ETag this machine last pushed or pulled.
12
+ export async function runSyncPush({ target, packageRoot, remote, repository, env = process.env, fetchImpl = fetch } = {}) {
13
+ const { token, passphrase } = readSyncCredentials(env);
14
+ const resolvedRemote = resolveRemote(remote);
15
+ const resolvedRepository = await resolveRepository(target, repository);
16
+ const staging = path.join(".forgeloop", `sync-staging-${randomUUID()}`);
17
+ let body;
18
+ let files;
19
+ try {
20
+ await runStorageBackup({ target, destination: staging, includeAttachments: true });
21
+ const payload = await packDirectory(path.join(target, staging));
22
+ files = payload.files.length;
23
+ const version = packageRoot ? JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8")).version ?? null : null;
24
+ body = sealSnapshot(payload, { passphrase, repository: resolvedRepository, forgeloopVersion: version });
25
+ } finally {
26
+ await rm(path.join(target, staging), { recursive: true, force: true });
27
+ }
28
+ const previous = await readSyncState(target, { remote: resolvedRemote, repository: resolvedRepository, env });
29
+ const response = await syncRequest({
30
+ remote: resolvedRemote, repository: resolvedRepository, token, method: "PUT", body, fetchImpl,
31
+ headers: previous ? { "if-match": strongEtag(previous.etag) } : { "if-none-match": "*" },
32
+ });
33
+ if (!response.ok) throw await remoteError(response);
34
+ const result = await response.json().catch(() => ({}));
35
+ const etag = strongEtag(typeof result.etag === "string" ? result.etag : response.headers.get("etag"));
36
+ if (etag) await writeSyncState(target, { remote: resolvedRemote, repository: resolvedRepository, etag, direction: "push", at: new Date().toISOString() }, { env });
37
+ return { status: "PUSHED", repository: resolvedRepository, remote: resolvedRemote, etag, files, bytes: body.length, firstPush: previous === null };
38
+ }
39
+
40
+ export function formatSyncPushResult(result) {
41
+ return [
42
+ `FORGELOOP SYNC PUSHED: ${result.repository}`,
43
+ `REMOTE: ${result.remote}`,
44
+ `FILES: ${result.files} (${result.bytes} encrypted bytes)`,
45
+ `ETAG: ${result.etag ?? "unknown"}`,
46
+ "Another machine can now run forgeloop sync-pull. Pushes from machines that have not pulled this version are refused.",
47
+ "",
48
+ ].join("\n");
49
+ }
@@ -0,0 +1,146 @@
1
+ import { access, readdir } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { detectProjectEvidence, readBounded } from "../project-detection.js";
4
+ import { discoverPolicy } from "../policy-discovery.js";
5
+ import { runTestInventory } from "../test-intelligence/service.js";
6
+
7
+ // Deterministic, read-only repository facts for `forgeloop assess`. Nothing here
8
+ // executes target repository code, writes files, or consults the decision plane.
9
+
10
+ export const ASSESSMENT_AREAS = Object.freeze(["backend", "database", "frontend", "infrastructure", "mobile"]);
11
+
12
+ const MAX_MANIFEST_BYTES = 1024 * 1024;
13
+
14
+ const FRONTEND_DEPENDENCIES = new Set([
15
+ "@angular/core", "@remix-run/react", "@sveltejs/kit", "astro", "jquery", "lit", "next", "nuxt",
16
+ "preact", "react", "react-dom", "solid-js", "svelte", "vue",
17
+ ]);
18
+ const BACKEND_DEPENDENCIES = new Set([
19
+ "@apollo/server", "@hapi/hapi", "@nestjs/core", "@trpc/server", "apollo-server", "express",
20
+ "fastify", "graphql-yoga", "hono", "koa", "restify",
21
+ ]);
22
+ const DATABASE_DEPENDENCIES = new Set([
23
+ "@prisma/client", "better-sqlite3", "drizzle-orm", "knex", "mongodb", "mongoose", "mysql2", "pg",
24
+ "prisma", "sequelize", "sqlite3", "typeorm",
25
+ ]);
26
+ const BACKEND_FRAMEWORKS = new Set(["dotnet", "go", "java", "php", "python", "rust"]);
27
+ const MOBILE_FRAMEWORKS = new Set(["flutter", "swift"]);
28
+
29
+ const CI_PATHS = Object.freeze([".circleci/config.yml", ".gitlab-ci.yml", "Jenkinsfile", "azure-pipelines.yml", "bitbucket-pipelines.yml"]);
30
+ const CONTAINER_PATHS = Object.freeze(["Dockerfile", "compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"]);
31
+ const NODE_LOCKFILES = Object.freeze(["bun.lockb", "bun.lock", "npm-shrinkwrap.json", "package-lock.json", "pnpm-lock.yaml", "yarn.lock"]);
32
+ const WEB_ENTRY_PATHS = Object.freeze(["index.html", "public/index.html", "src/index.html"]);
33
+
34
+ const sorted = (values) => [...new Set(values)].sort();
35
+ const toPosix = (value) => value.split(path.sep).join("/");
36
+
37
+ async function exists(target, relative) {
38
+ try { await access(path.join(target, relative)); return true; } catch { return false; }
39
+ }
40
+
41
+ async function existingPaths(target, candidates) {
42
+ const found = [];
43
+ for (const candidate of candidates) if (await exists(target, candidate)) found.push(candidate);
44
+ return found;
45
+ }
46
+
47
+ async function ciWorkflows(target) {
48
+ let entries = [];
49
+ try { entries = await readdir(path.join(target, ".github/workflows")); } catch { entries = []; }
50
+ const workflows = entries.filter((name) => /\.ya?ml$/u.test(name)).map((name) => `.github/workflows/${name}`);
51
+ return sorted([...workflows, ...await existingPaths(target, CI_PATHS)]);
52
+ }
53
+
54
+ async function readManifest(target, root) {
55
+ const relative = toPosix(path.join(root, "package.json"));
56
+ const text = await readBounded(path.join(target, relative), MAX_MANIFEST_BYTES);
57
+ if (text === null) return null;
58
+ try {
59
+ const manifest = JSON.parse(text);
60
+ return manifest && typeof manifest === "object" && !Array.isArray(manifest) ? { relative, manifest } : null;
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ async function packageManifests(target, projectRoots) {
67
+ const manifests = [];
68
+ for (const root of sorted([".", ...projectRoots])) {
69
+ const entry = await readManifest(target, root);
70
+ if (entry) manifests.push(entry);
71
+ }
72
+ return manifests;
73
+ }
74
+
75
+ function dependencyNames(manifest) {
76
+ return Object.keys({ ...manifest.dependencies, ...manifest.devDependencies, ...manifest.peerDependencies });
77
+ }
78
+
79
+ function matchDependencies(manifests, names) {
80
+ const signals = [];
81
+ for (const { relative, manifest } of manifests) {
82
+ for (const name of dependencyNames(manifest)) if (names.has(name)) signals.push(`${relative}:dependency=${name}`);
83
+ }
84
+ return signals;
85
+ }
86
+
87
+ function addArea(areas, area, signals) {
88
+ if (signals.length === 0) return;
89
+ areas[area] = sorted([...(areas[area] ?? []), ...signals]);
90
+ }
91
+
92
+ function classifyAreas({ manifests, frameworks, webEntries, sqlProjects, infrastructure }) {
93
+ const areas = {};
94
+ addArea(areas, "frontend", [...matchDependencies(manifests, FRONTEND_DEPENDENCIES), ...webEntries.map((entry) => `${entry}:web-entry`)]);
95
+ addArea(areas, "backend", [
96
+ ...matchDependencies(manifests, BACKEND_DEPENDENCIES),
97
+ ...frameworks.filter((name) => BACKEND_FRAMEWORKS.has(name)).map((name) => `framework=${name}`),
98
+ ]);
99
+ addArea(areas, "database", [
100
+ ...matchDependencies(manifests, DATABASE_DEPENDENCIES),
101
+ ...(sqlProjects ? ["framework=sql"] : []),
102
+ ]);
103
+ addArea(areas, "mobile", frameworks.filter((name) => MOBILE_FRAMEWORKS.has(name)).map((name) => `framework=${name}`));
104
+ addArea(areas, "infrastructure", [...infrastructure.ci, ...infrastructure.containers].map((entry) => `${entry}:present`));
105
+ return Object.fromEntries(ASSESSMENT_AREAS.filter((area) => areas[area]).map((area) => [area, areas[area]]));
106
+ }
107
+
108
+ function summarizeTests(inventory) {
109
+ const tests = Array.isArray(inventory?.tests) ? inventory.tests : [];
110
+ const byFramework = {};
111
+ for (const entry of tests) byFramework[entry.framework] = (byFramework[entry.framework] ?? 0) + 1;
112
+ return {
113
+ total: tests.length,
114
+ files: sorted(tests.map((entry) => entry.file)).length,
115
+ byFramework: Object.fromEntries(Object.keys(byFramework).sort().map((key) => [key, byFramework[key]])),
116
+ };
117
+ }
118
+
119
+ function stackFacts(evidence) {
120
+ if (!evidence) return { status: "NOT_DETERMINED", frameworks: [], projectRoots: [], evidence: null };
121
+ return { status: "DETECTED", frameworks: sorted(evidence.frameworks), projectRoots: sorted(evidence.projectRoots), evidence };
122
+ }
123
+
124
+ export async function collectAssessmentFacts(target) {
125
+ const evidence = await detectProjectEvidence(target);
126
+ const stack = stackFacts(evidence);
127
+ const [policy, inventory, manifests, ci, containers, lockfiles, webEntries] = await Promise.all([
128
+ discoverPolicy({ target }),
129
+ runTestInventory({ projectRoot: target }),
130
+ packageManifests(target, stack.projectRoots),
131
+ ciWorkflows(target),
132
+ existingPaths(target, CONTAINER_PATHS),
133
+ existingPaths(target, NODE_LOCKFILES),
134
+ existingPaths(target, WEB_ENTRY_PATHS),
135
+ ]);
136
+ const infrastructure = { ci, containers };
137
+ const areas = classifyAreas({ manifests, frameworks: stack.frameworks, webEntries, sqlProjects: stack.frameworks.includes("sql"), infrastructure });
138
+ return {
139
+ stack,
140
+ areas,
141
+ policy: { languages: sorted(policy.languages ?? []), testing: policy.testing, linting: policy.linting },
142
+ tests: summarizeTests(inventory),
143
+ manifests: manifests.map(({ relative, manifest }) => ({ path: relative, scripts: sorted(Object.keys(manifest.scripts ?? {})), dependencyCount: dependencyNames(manifest).length })),
144
+ repository: { ci, containers, lockfiles },
145
+ };
146
+ }
@@ -0,0 +1,133 @@
1
+ import { evaluateRoute } from "../router.js";
2
+ import { GUIDE_FILES } from "../guide-registry.js";
3
+
4
+ // Review plan for `forgeloop assess`. The plan routes guides and lists
5
+ // candidate checks; it never executes them and carries no evidence authority.
6
+
7
+ const AREA_ROUTES = Object.freeze({
8
+ backend: Object.freeze({ surfaces: ["api"], platforms: ["server"], risks: ["untrusted-input"] }),
9
+ database: Object.freeze({ surfaces: ["database"], platforms: ["server"], risks: [] }),
10
+ frontend: Object.freeze({ surfaces: ["ui"], platforms: ["web"], risks: [] }),
11
+ infrastructure: Object.freeze({ surfaces: ["ci"], platforms: ["ci"], risks: [] }),
12
+ mobile: Object.freeze({ surfaces: ["mobile"], platforms: ["mobile"], risks: [] }),
13
+ });
14
+
15
+ const SCRIPT_PURPOSES = Object.freeze({
16
+ build: "build", check: "check", lint: "lint", test: "test", typecheck: "typecheck", "type-check": "typecheck",
17
+ });
18
+
19
+ const FRAMEWORK_CHECKS = Object.freeze({
20
+ dotnet: [["dotnet", "test"]],
21
+ flutter: [["flutter", "analyze"], ["flutter", "test"]],
22
+ go: [["go", "test", "./..."], ["go", "vet", "./..."]],
23
+ rust: [["cargo", "clippy"], ["cargo", "test"]],
24
+ });
25
+
26
+ export const FINDING_CATEGORIES = Object.freeze([
27
+ "accessibility", "bug", "design", "maintainability", "performance", "security", "test-gap",
28
+ ]);
29
+ export const FINDING_SEVERITIES = Object.freeze(["critical", "high", "medium", "low"]);
30
+
31
+ export const FINDING_CONTRACT = Object.freeze({
32
+ schemaVersion: 1,
33
+ required: Object.freeze(["id", "area", "category", "severity", "title", "location", "evidence", "guide", "recommendation", "suggestedClaims", "suggestedVerification"]),
34
+ categories: FINDING_CATEGORIES,
35
+ severities: FINDING_SEVERITIES,
36
+ evidenceKinds: Object.freeze(["OBSERVED", "INFERRED"]),
37
+ rules: Object.freeze([
38
+ "location cites a repository-relative POSIX file and a 1-based line",
39
+ "OBSERVED evidence names a reproducible source: a quoted code excerpt or the argv and output of an executed check",
40
+ "INFERRED findings rank below OBSERVED findings of the same severity and never use severity critical",
41
+ "guide is the routed guide ID whose rule the finding applies",
42
+ "each accepted finding becomes its own ForgeLoop task with suggestedClaims as write claims",
43
+ ]),
44
+ });
45
+
46
+ function routeArea(area, evidence) {
47
+ const route = AREA_ROUTES[area];
48
+ const result = evaluateRoute({
49
+ workType: "code",
50
+ executableChange: true,
51
+ surfaces: route.surfaces,
52
+ platforms: route.platforms,
53
+ risks: route.risks,
54
+ ...(evidence ? { projectEvidence: evidence } : {}),
55
+ });
56
+ return { area, signals: route, guides: [...result.guides].sort() };
57
+ }
58
+
59
+ function guideEntries(ids) {
60
+ return [...new Set(ids)].sort().map((id) => ({ id, path: GUIDE_FILES[id] }));
61
+ }
62
+
63
+ function scriptArgv(name) {
64
+ return name === "test" ? ["npm", "test"] : ["npm", "run", name];
65
+ }
66
+
67
+ function manifestChecks(manifests) {
68
+ const checks = [];
69
+ for (const { path: manifestPath, scripts } of manifests) {
70
+ if (manifestPath !== "package.json") continue;
71
+ for (const name of scripts) {
72
+ if (SCRIPT_PURPOSES[name]) checks.push({ argv: scriptArgv(name), purpose: SCRIPT_PURPOSES[name], source: `package.json:scripts.${name}` });
73
+ }
74
+ }
75
+ return checks;
76
+ }
77
+
78
+ function policyChecks(policy) {
79
+ const checks = [];
80
+ if (policy.testing?.detected && policy.testing.command) checks.push({ argv: policy.testing.command, purpose: "test", source: "policy-discovery:testing" });
81
+ if (policy.linting?.detected && policy.linting.command) checks.push({ argv: policy.linting.command, purpose: "lint", source: "policy-discovery:linting" });
82
+ return checks;
83
+ }
84
+
85
+ function frameworkChecks(frameworks) {
86
+ return frameworks.flatMap((name) => (FRAMEWORK_CHECKS[name] ?? []).map((argv) => ({
87
+ argv, purpose: argv[1] === "test" ? "test" : "lint", source: `framework-convention:${name}`,
88
+ })));
89
+ }
90
+
91
+ export function candidateChecks(facts) {
92
+ const unique = new Map();
93
+ for (const check of [...policyChecks(facts.policy), ...manifestChecks(facts.manifests), ...frameworkChecks(facts.stack.frameworks)]) {
94
+ const key = check.argv.join("\u0000");
95
+ if (!unique.has(key)) unique.set(key, { ...check, argv: [...check.argv], status: "NOT_EXECUTED" });
96
+ }
97
+ return [...unique.values()].sort((a, b) => a.argv.join(" ").localeCompare(b.argv.join(" ")));
98
+ }
99
+
100
+ function gap(code, message, source) {
101
+ return { code, severity: "advisory", evidenceKind: "OBSERVED", source, message };
102
+ }
103
+
104
+ export function observedGaps(facts, checks) {
105
+ const purposes = new Set(checks.map((check) => check.purpose));
106
+ const gaps = [];
107
+ if (facts.stack.status === "NOT_DETERMINED") gaps.push(gap("STACK_NOT_DETERMINED", "Project detection could not determine the stack within its traversal budget; review areas may be incomplete.", "project-detection"));
108
+ if (facts.tests.total === 0) gaps.push(gap("TESTS_NOT_DETECTED", "No automated tests were discovered.", "test-inventory"));
109
+ if (!purposes.has("test")) gaps.push(gap("TEST_COMMAND_NOT_DETECTED", "No test command was discovered.", "candidate-checks"));
110
+ if (!purposes.has("lint")) gaps.push(gap("LINT_COMMAND_NOT_DETECTED", "No lint command was discovered.", "candidate-checks"));
111
+ if (facts.stack.frameworks.includes("typescript") && !purposes.has("typecheck")) gaps.push(gap("TYPECHECK_COMMAND_NOT_DETECTED", "TypeScript was detected without a typecheck script.", "package.json:scripts"));
112
+ if (facts.repository.ci.length === 0) gaps.push(gap("CI_NOT_DETECTED", "No continuous integration configuration was discovered.", "repository-files"));
113
+ if (facts.manifests.some((manifest) => manifest.dependencyCount > 0) && facts.repository.lockfiles.length === 0) gaps.push(gap("LOCKFILE_NOT_DETECTED", "package.json declares dependencies without a lockfile.", "repository-files"));
114
+ return gaps;
115
+ }
116
+
117
+ export function buildReviewPlan(facts) {
118
+ const areas = Object.keys(facts.areas).map((area) => routeArea(area, facts.stack.evidence));
119
+ const checks = candidateChecks(facts);
120
+ return {
121
+ areas: areas.map((entry) => ({ ...entry, guides: guideEntries(entry.guides), detectedBy: facts.areas[entry.area] })),
122
+ guides: guideEntries(areas.flatMap((entry) => entry.guides)),
123
+ candidateChecks: checks,
124
+ gaps: observedGaps(facts, checks),
125
+ findingContract: FINDING_CONTRACT,
126
+ nextSteps: [
127
+ "Read each routed guide before reviewing its area.",
128
+ "Review each area read-only and record findings that satisfy findingContract.",
129
+ "Run candidate checks only inside a ForgeLoop task with `forgeloop run-check`; they are NOT_EXECUTED here.",
130
+ "Create one ForgeLoop task per accepted finding with `forgeloop task-create --claim <path>`.",
131
+ ],
132
+ };
133
+ }
@@ -156,6 +156,30 @@ export const CLI_COMMAND_DEFINITIONS = Object.freeze({
156
156
  writes: ["<destination>"], removes: [], mayExecuteExternalProcess: false,
157
157
  description: "Creates an exclusive native SQLite backup, optionally including canonically referenced attachments in a retained directory.",
158
158
  }),
159
+ "sync-push": Object.freeze({
160
+ name: "sync-push", category: "project-maintenance", mutation: "MUTATING",
161
+ options: Object.freeze({
162
+ ...CLI_COMMON_OPTIONS,
163
+ "--remote": Object.freeze({ targetKey: "syncRemote", parseType: "string", takesValue: true, valueName: "url", missingValueMessage: "--remote requires a URL", description: "sync endpoint (default: https://forgeloop.monster/api/sync)" }),
164
+ "--repo": Object.freeze({ targetKey: "syncRepository", parseType: "string", takesValue: true, valueName: "owner/name", missingValueMessage: "--repo requires owner/name", description: "repository the snapshot belongs to (default: from the git origin)" }),
165
+ "--json": Object.freeze({ targetKey: "json", parseType: "boolean", takesValue: false, description: "emit the push result as JSON" }),
166
+ }),
167
+ writes: ["<user config>/forgeloop/sync/<project>.json"], removes: [], mayExecuteExternalProcess: true,
168
+ description: "Uploads a client-side encrypted (FORGELOOP_SYNC_KEY) backup of this project's ForgeLoop state to the sync remote, authenticated by FORGELOOP_SYNC_TOKEN. A push based on a stale remote version is refused with E_SYNC_CONFLICT.",
169
+ }),
170
+ "sync-pull": Object.freeze({
171
+ name: "sync-pull", category: "project-maintenance", mutation: "MUTATING",
172
+ options: Object.freeze({
173
+ ...CLI_COMMON_OPTIONS,
174
+ "--remote": Object.freeze({ targetKey: "syncRemote", parseType: "string", takesValue: true, valueName: "url", missingValueMessage: "--remote requires a URL", description: "sync endpoint (default: https://forgeloop.monster/api/sync)" }),
175
+ "--repo": Object.freeze({ targetKey: "syncRepository", parseType: "string", takesValue: true, valueName: "owner/name", missingValueMessage: "--repo requires owner/name", description: "repository the snapshot belongs to (default: from the git origin)" }),
176
+ "--replace-active": Object.freeze({ targetKey: "replaceActive", parseType: "boolean", takesValue: false, description: "replace existing local state; the outgoing state is retained and archived" }),
177
+ "--writers-quiesced": Object.freeze({ targetKey: "writersQuiesced", parseType: "boolean", takesValue: false, description: "assert that all writers have been externally stopped" }),
178
+ "--json": Object.freeze({ targetKey: "json", parseType: "boolean", takesValue: false, description: "emit the pull and restore result as JSON" }),
179
+ }),
180
+ writes: [".forgeloop/storage-restores", ".forgeloop/state.sqlite", ".forgeloop/attachments", ".forgeloop/storage-version.json", ".forgeloop/.storage-maintenance", "<user config>/forgeloop/sync/<project>.json"], removes: [], mayExecuteExternalProcess: true,
181
+ description: "Downloads, decrypts and verifies the repository's sync snapshot, then activates it through storage-restore: into a fresh project, or replacing local state only with --replace-active.",
182
+ }),
159
183
  "protocol-info": Object.freeze({
160
184
  name: "protocol-info",
161
185
  category: "diagnostics",
@@ -256,6 +280,17 @@ export const CLI_COMMAND_DEFINITIONS = Object.freeze({
256
280
  writes: [], removes: [], mayExecuteExternalProcess: false,
257
281
  description: "Discovers tests deterministically and assigns stable semantic test IDs without pruning authority.",
258
282
  }),
283
+ assess: Object.freeze({
284
+ name: "assess",
285
+ category: "diagnostics",
286
+ mutation: "READ_ONLY",
287
+ options: Object.freeze({
288
+ ...CLI_COMMON_OPTIONS,
289
+ "--json": Object.freeze({ targetKey: "json", parseType: "boolean", takesValue: false, description: "emit the repository assessment plan as JSON" }),
290
+ }),
291
+ writes: [], removes: [], mayExecuteExternalProcess: false,
292
+ description: "Assesses an existing repository read-only: stack, areas, tests, candidate checks, observed gaps, and a guide-routed review plan without executing target code.",
293
+ }),
259
294
  "test-utility": Object.freeze({
260
295
  name: "test-utility",
261
296
  category: "diagnostics",
@@ -1733,6 +1768,41 @@ export const CLI_COMMAND_DEFINITIONS = Object.freeze({
1733
1768
  mayExecuteExternalProcess: true,
1734
1769
  description: "Reports local ForgeLoop attestation status and trust level without network access.",
1735
1770
  }),
1771
+ "evidence-export": Object.freeze({
1772
+ name: "evidence-export",
1773
+ category: "attestation",
1774
+ mutation: "MUTATING",
1775
+ options: Object.freeze({
1776
+ ...CLI_COMMON_OPTIONS,
1777
+ ...CLI_TASK_OPTION,
1778
+ "--dir": Object.freeze({ targetKey: "evidenceDirectory", parseType: "string", takesValue: true, valueName: "path", missingValueMessage: "--dir requires a path", description: "tracked evidence directory (default: .forgeloop-evidence)" }),
1779
+ "--json": Object.freeze({ targetKey: "json", parseType: "boolean", takesValue: false, description: "emit the export result as JSON" }),
1780
+ }),
1781
+ writes: [".forgeloop-evidence/<taskId>.json"], removes: [], mayExecuteExternalProcess: false,
1782
+ description: "Exports a completed task's attestation as a portable, redacted evidence bundle to commit with the change.",
1783
+ }),
1784
+ "evidence-verify": Object.freeze({
1785
+ name: "evidence-verify",
1786
+ category: "attestation",
1787
+ mutation: "READ_ONLY",
1788
+ options: Object.freeze({
1789
+ ...CLI_COMMON_OPTIONS,
1790
+ "--revision-provider": Object.freeze({ targetKey: "revisionProvider", parseType: "string", takesValue: true, valueName: "provider", missingValueMessage: "--revision-provider requires a provider", description: "revision provider (default: git)" }),
1791
+ "--base": Object.freeze({ targetKey: "baseRevision", parseType: "string", takesValue: true, valueName: "revision", missingValueMessage: "--base requires a revision", description: "base revision of the verified range" }),
1792
+ "--head": Object.freeze({ targetKey: "headRevision", parseType: "string", takesValue: true, valueName: "revision", missingValueMessage: "--head requires a revision", description: "head revision of the verified range" }),
1793
+ "--dir": Object.freeze({ targetKey: "evidenceDirectory", parseType: "string", takesValue: true, valueName: "path", missingValueMessage: "--dir requires a path", description: "tracked evidence directory (default: .forgeloop-evidence)" }),
1794
+ "--exclude": Object.freeze({ targetKey: "evidenceExclusions", parseType: "string", takesValue: true, repeatable: true, valueName: "path", missingValueMessage: "--exclude requires a path", description: "changed path or dir/** excluded from coverage (verifier policy)" }),
1795
+ "--allow-partial-coverage": Object.freeze({ targetKey: "allowPartialCoverage", parseType: "boolean", takesValue: false, description: "report uncovered changed paths without failing" }),
1796
+ "--require-signature": Object.freeze({ targetKey: "requireSignature", parseType: "boolean", takesValue: false, description: "require a valid Sigstore signature for every bundle used" }),
1797
+ "--identity": Object.freeze({ targetKey: "attestationIdentity", parseType: "string", takesValue: true, valueName: "identity", missingValueMessage: "--identity requires an identity", description: "exact signer identity policy" }),
1798
+ "--issuer": Object.freeze({ targetKey: "attestationIssuer", parseType: "string", takesValue: true, valueName: "issuer", missingValueMessage: "--issuer requires an issuer", description: "exact signer issuer policy" }),
1799
+ "--trusted-root": Object.freeze({ targetKey: "trustedRoot", parseType: "string", takesValue: true, valueName: "path", missingValueMessage: "--trusted-root requires a path", description: "trusted signing root path" }),
1800
+ "--format": Object.freeze({ targetKey: "evidenceFormat", parseType: "string", takesValue: true, valueName: "text|markdown", missingValueMessage: "--format requires text or markdown", description: "human output format (default: text)" }),
1801
+ "--json": Object.freeze({ targetKey: "json", parseType: "boolean", takesValue: false, description: "emit the verification result as JSON" }),
1802
+ }),
1803
+ writes: [], removes: [], mayExecuteExternalProcess: true,
1804
+ description: "Verifies committed evidence bundles for a revision range without local ForgeLoop state; signatures raise the level from INTEGRITY_ONLY to ATTESTED.",
1805
+ }),
1736
1806
  "attestation-verify-range": Object.freeze({
1737
1807
  name: "attestation-verify-range",
1738
1808
  category: "attestation",
@@ -82,6 +82,9 @@ const runDecisionShow = async (...args) => (await import("../commands/decision-s
82
82
  const runContextPlan = async (...args) => (await import("../commands/context-plan.js")).runContextPlan(...args);
83
83
  const runModelRoute = async (...args) => (await import("../commands/model-route.js")).runModelRoute(...args);
84
84
  const runSemanticPlan = async (...args) => (await import("../commands/semantic-plan.js")).runSemanticPlan(...args);
85
+ const runEvidenceExport = async (...args) => (await import("../commands/evidence-export.js")).runEvidenceExport(...args);
86
+ const runEvidenceVerify = async (...args) => (await import("../commands/evidence-verify.js")).runEvidenceVerify(...args);
87
+ const runAssess = async (...args) => (await import("../commands/assess.js")).runAssess(...args);
85
88
  const runTestInventory = async (...args) => (await import("../commands/test-inventory.js")).runTestInventory(...args);
86
89
  const runTestUtility = async (...args) => (await import("../commands/test-utility.js")).runTestUtility(...args);
87
90
  const runTestPrunePlan = async (...args) => (await import("../commands/test-prune-plan.js")).runTestPrunePlan(...args);
@@ -147,6 +150,14 @@ const RAW_COMMAND_EXECUTORS = {
147
150
  const { runStorageMigrate } = await import("../commands/storage-migrate.js");
148
151
  return { result: await runStorageMigrate({ target, packageRoot, destination: options.destination, writersQuiesced: options.writersQuiesced }), exitCode: 0 };
149
152
  },
153
+ "sync-push": async ({ target, packageRoot, options }) => {
154
+ const { runSyncPush } = await import("../commands/sync-push.js");
155
+ return { result: await runSyncPush({ target, packageRoot, remote: options.syncRemote, repository: options.syncRepository }), exitCode: 0 };
156
+ },
157
+ "sync-pull": async ({ target, packageRoot, options }) => {
158
+ const { runSyncPull } = await import("../commands/sync-pull.js");
159
+ return { result: await runSyncPull({ target, packageRoot, remote: options.syncRemote, repository: options.syncRepository, writersQuiesced: options.writersQuiesced, replaceActive: options.replaceActive }), exitCode: 0 };
160
+ },
150
161
  "storage-backup": async ({ target, options }) => {
151
162
  const { runStorageBackup } = await import("../commands/storage-backup.js");
152
163
  return { result: await runStorageBackup({ target, destination: options.destination, includeAttachments: options.includeAttachments }), exitCode: 0 };
@@ -210,6 +221,10 @@ const RAW_COMMAND_EXECUTORS = {
210
221
  }),
211
222
  exitCode: 0,
212
223
  }),
224
+ assess: async ({ target }) => ({
225
+ result: await runAssess({ target }),
226
+ exitCode: 0,
227
+ }),
213
228
  "test-inventory": async ({ target }) => ({
214
229
  result: await runTestInventory({ target }),
215
230
  exitCode: 0,
@@ -412,6 +427,14 @@ const RAW_COMMAND_EXECUTORS = {
412
427
  const result = await runAttestationStatus({ target, packageRoot, taskId: options.taskId });
413
428
  return { result, exitCode: exitCodeForAttestationResult(result) };
414
429
  },
430
+ "evidence-export": async ({ target, packageRoot, options }) => ({
431
+ result: await runEvidenceExport({ target, packageRoot, taskId: options.taskId, evidenceDirectory: options.evidenceDirectory }),
432
+ exitCode: 0,
433
+ }),
434
+ "evidence-verify": async ({ target, packageRoot, options }) => {
435
+ const result = await runEvidenceVerify({ target, packageRoot, ...options });
436
+ return { result, exitCode: exitCodeForAttestationResult(result) };
437
+ },
415
438
  "attestation-verify-range": async ({ target, packageRoot, options }) => {
416
439
  const result = await runAttestationVerifyRange({ target, packageRoot, ...options });
417
440
  return { result, exitCode: exitCodeForAttestationResult(result) };
@@ -864,12 +887,12 @@ export const COMMAND_EXECUTORS = Object.fromEntries(Object.entries(RAW_COMMAND_E
864
887
  const { assertCanonicalPersistence } = await import("../storage/operational-context.js");
865
888
  assertCanonicalPersistence(context.runtimeContext?.forgeloopPersistence);
866
889
  }
867
- if (!context.target || name === "task-migrate" || name === "migrate-protocol" || name === "storage-migration-status" || name === "storage-rollback-resume" || name === "storage-rollback" || name === "storage-migrate" || name === "storage-migration-resume" || name === "storage-restore" || name === "storage-restore-resume") return executor(context);
890
+ if (!context.target || name === "task-migrate" || name === "migrate-protocol" || name === "storage-migration-status" || name === "storage-rollback-resume" || name === "storage-rollback" || name === "storage-migrate" || name === "storage-migration-resume" || name === "storage-restore" || name === "storage-restore-resume" || name === "sync-pull") return executor(context);
868
891
  const { withProjectStorage } = await import("../storage/project-boundary.js");
869
892
  const { CLI_COMMAND_DEFINITIONS } = await import("./cli-command-definitions.js");
870
- // Backup writes its destination, not the source store. Doctor repairs only
893
+ // Backup (and sync-push, which backs up) writes its destination, not the source store. Doctor repairs only
871
894
  // when explicitly requested; inspecting either must not migrate the source.
872
895
  const readOnly = CLI_COMMAND_DEFINITIONS[name]?.mutation === "READ_ONLY"
873
- || context.options?.dryRun === true || name === "storage-backup" || (name === "doctor" && context.options?.fix !== true);
896
+ || context.options?.dryRun === true || name === "storage-backup" || name === "sync-push" || (name === "doctor" && context.options?.fix !== true);
874
897
  return withProjectStorage(context.target, () => executor(context), { readOnly, runtimeContext: context.runtimeContext });
875
898
  }]));