@cassiomc1/forgeloop 2.1.0 → 2.3.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.
- package/CONTRIBUTING.md +22 -2
- package/DOCS_INDEX.md +4 -13
- package/ENG/sec-code-eng.md +1 -1
- package/ENG/test-code-eng.md +32 -1
- package/LOOP_SYSTEM_DESIGN.md +2 -3
- package/QUALITY_SCORECARD.md +0 -1
- package/README.md +19 -48
- package/THIRD_PARTY_NOTICES.md +0 -15
- package/completions/_forgeloop +7 -1
- package/completions/forgeloop.bash +13 -1
- package/completions/forgeloop.fish +51 -1
- package/docs/AGENT_PROTOCOL_SUMMARY.md +7 -1
- package/docs/ARTIFACT_REFERENCE.md +1 -0
- package/docs/CLI_REFERENCE.md +111 -3
- package/docs/CODE_ATTESTATION.md +16 -7
- package/docs/DOCUMENTATION_GUIDE.md +10 -28
- package/docs/PACKAGE_CONTENTS.md +0 -3
- package/docs/RELEASE_CHECKLIST.md +81 -15
- package/docs/REVISION_PROVIDERS.md +3 -6
- package/docs/TROUBLESHOOTING.md +11 -0
- package/docs/documentation-manifest.json +0 -13
- package/package.json +2 -6
- package/schemas/config.schema.json +1 -0
- package/scripts/CI_VALIDATORS.md +2 -2
- package/src/cli.js +31 -0
- package/src/commands/assess.js +36 -0
- package/src/commands/attestation-create.js +21 -1
- package/src/commands/complete.js +3 -0
- package/src/commands/evidence-export.js +17 -0
- package/src/commands/evidence-publish.js +22 -0
- package/src/commands/evidence-verify.js +36 -0
- package/src/commands/sync-pull.js +111 -0
- package/src/commands/sync-push.js +52 -0
- package/src/core/assessment/facts.js +146 -0
- package/src/core/assessment/plan.js +133 -0
- package/src/core/audit.js +7 -0
- package/src/core/cli-command-definitions.js +88 -0
- package/src/core/command-executors.js +42 -5
- package/src/core/config.js +44 -37
- package/src/core/error-codes.js +70 -0
- package/src/core/evidence/auto-export.js +61 -0
- package/src/core/evidence/bundle-format.js +74 -0
- package/src/core/evidence/export.js +184 -0
- package/src/core/evidence/markdown.js +40 -0
- package/src/core/evidence/publish.js +187 -0
- package/src/core/evidence/verify.js +179 -0
- package/src/core/integration-invocation-policy.js +5 -2
- package/src/core/sync/merge.js +135 -0
- package/src/core/sync/remote.js +124 -0
- package/src/core/sync/snapshot.js +129 -0
- package/docs/assets/diagrams/forgeloop-code-attestation-flow.html +0 -13852
- package/docs/assets/diagrams/forgeloop-code-attestation-flow.receipt.json +0 -37
- package/docs/assets/diagrams/forgeloop-code-attestation-flow.svg +0 -5055
- package/docs/assets/diagrams/forgeloop-engineering-flow.html +0 -13837
- package/docs/assets/diagrams/forgeloop-engineering-flow.receipt.json +0 -37
- package/docs/assets/diagrams/forgeloop-engineering-flow.svg +0 -5011
- package/docs/assets/diagrams/forgeloop-verification-trust-flow.html +0 -13795
- package/docs/assets/diagrams/forgeloop-verification-trust-flow.receipt.json +0 -37
- package/docs/assets/diagrams/forgeloop-verification-trust-flow.svg +0 -4997
- package/docs/diagrams/README.md +0 -103
- package/docs/diagrams/forgeloop-code-attestation-flow.workflow.json +0 -451
- package/docs/diagrams/forgeloop-engineering-flow.workflow.json +0 -459
- package/docs/diagrams/forgeloop-verification-trust-flow.workflow.json +0 -398
- package/docs/diagrams/manifest.json +0 -84
- package/docs/diagrams/reviews/forgeloop-code-attestation-flow.review.json +0 -20
- package/docs/diagrams/reviews/forgeloop-engineering-flow.review.json +0 -20
- package/docs/diagrams/reviews/forgeloop-verification-trust-flow.review.json +0 -20
package/src/cli.js
CHANGED
|
@@ -318,6 +318,11 @@ export const COMMAND_HANDLERS = Object.freeze({
|
|
|
318
318
|
renderJsonOr(options, result, (await import("./commands/semantic-plan.js")).formatSemanticPlanResult);
|
|
319
319
|
return 0;
|
|
320
320
|
},
|
|
321
|
+
assess: async ({ target, options }) => {
|
|
322
|
+
const { result } = await COMMAND_EXECUTORS.assess({ target, options });
|
|
323
|
+
renderJsonOr(options, result, (await import("./commands/assess.js")).formatAssessResult);
|
|
324
|
+
return 0;
|
|
325
|
+
},
|
|
321
326
|
"test-inventory": async ({ target, options }) => {
|
|
322
327
|
const { result } = await COMMAND_EXECUTORS["test-inventory"]({ target, options });
|
|
323
328
|
renderJsonOr(options, result, (await import("./commands/test-inventory.js")).formatTestInventoryResult);
|
|
@@ -368,6 +373,16 @@ export const COMMAND_HANDLERS = Object.freeze({
|
|
|
368
373
|
renderJsonOr(options, result, value => `storage backup: ${value.path}\nattachments included: ${value.attachmentsIncluded}`);
|
|
369
374
|
return exitCode;
|
|
370
375
|
},
|
|
376
|
+
"sync-push": async ({ target, packageRoot, options }) => {
|
|
377
|
+
const { result, exitCode } = await COMMAND_EXECUTORS["sync-push"]({ target, packageRoot, options });
|
|
378
|
+
renderJsonOr(options, result, (await import("./commands/sync-push.js")).formatSyncPushResult);
|
|
379
|
+
return exitCode;
|
|
380
|
+
},
|
|
381
|
+
"sync-pull": async ({ target, packageRoot, options }) => {
|
|
382
|
+
const { result, exitCode } = await COMMAND_EXECUTORS["sync-pull"]({ target, packageRoot, options });
|
|
383
|
+
renderJsonOr(options, result, (await import("./commands/sync-pull.js")).formatSyncPullResult);
|
|
384
|
+
return exitCode;
|
|
385
|
+
},
|
|
371
386
|
"storage-restore": async ({ target, packageRoot, options }) => {
|
|
372
387
|
const { result, exitCode } = await COMMAND_EXECUTORS["storage-restore"]({ target, packageRoot, options });
|
|
373
388
|
renderJsonOr(options, result, value => `storage restore: ${value.path}\nactive: ${value.active}\nretained snapshot: ${value.retainedSnapshot}`);
|
|
@@ -558,6 +573,22 @@ export const COMMAND_HANDLERS = Object.freeze({
|
|
|
558
573
|
renderJsonOr(options, result, (await import("./commands/attestation-status.js")).formatAttestationStatusResult);
|
|
559
574
|
return exitCode;
|
|
560
575
|
},
|
|
576
|
+
"evidence-export": async ({ target, packageRoot, options }) => {
|
|
577
|
+
const { result } = await COMMAND_EXECUTORS["evidence-export"]({ target, packageRoot, options });
|
|
578
|
+
renderJsonOr(options, result, (await import("./commands/evidence-export.js")).formatEvidenceExportResult);
|
|
579
|
+
return 0;
|
|
580
|
+
},
|
|
581
|
+
"evidence-publish": async ({ target, packageRoot, options }) => {
|
|
582
|
+
const { result, exitCode } = await COMMAND_EXECUTORS["evidence-publish"]({ target, packageRoot, options });
|
|
583
|
+
renderJsonOr(options, result, (await import("./commands/evidence-publish.js")).formatEvidencePublishResult);
|
|
584
|
+
return exitCode;
|
|
585
|
+
},
|
|
586
|
+
"evidence-verify": async ({ target, packageRoot, options }) => {
|
|
587
|
+
const { result, exitCode } = await COMMAND_EXECUTORS["evidence-verify"]({ target, packageRoot, options });
|
|
588
|
+
const { formatEvidenceVerifyResult } = await import("./commands/evidence-verify.js");
|
|
589
|
+
renderJsonOr(options, result, (value) => formatEvidenceVerifyResult(value, options));
|
|
590
|
+
return exitCode;
|
|
591
|
+
},
|
|
561
592
|
"attestation-verify-range": async ({ target, packageRoot, options }) => {
|
|
562
593
|
const { result, exitCode } = await COMMAND_EXECUTORS["attestation-verify-range"]({ target, packageRoot, options });
|
|
563
594
|
renderJsonOr(options, result, (await import("./commands/attestation-verify-range.js")).formatAttestationVerifyRangeResult);
|
|
@@ -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
|
+
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import { buildAttestationStatement, writeAttestationStatement } from "../core/attestation.js";
|
|
1
|
+
import { buildAttestationStatement, readAttestationStatement, writeAttestationStatement } from "../core/attestation.js";
|
|
2
|
+
import { readCodeManifest } from "../core/code-manifest.js";
|
|
3
|
+
import { taskAttestationStatementPath } from "../core/task-paths.js";
|
|
2
4
|
import { withTaskTransaction } from "../core/transaction.js";
|
|
3
5
|
import { assertTaskMutationAllowed } from "../core/task-claim-state.js";
|
|
4
6
|
import { readWorkState } from "../core/work-state.js";
|
|
@@ -19,6 +21,24 @@ export async function runAttestationCreate({ target, packageRoot, taskId } = {})
|
|
|
19
21
|
if (error.code !== "E_TASK_COMPLETE") throw error;
|
|
20
22
|
});
|
|
21
23
|
await assertWorkspaceBinding(target, { taskId, packageRoot, operation: "attestation-create" });
|
|
24
|
+
// complete may already have attested this cycle (automatic evidence
|
|
25
|
+
// export), and the exported bundle then sits in the worktree. The
|
|
26
|
+
// statement is immutable within a cycle, so return it unchanged while it
|
|
27
|
+
// still binds the current manifest instead of rebuilding.
|
|
28
|
+
const existing = await readAttestationStatement({ target, packageRoot, taskId }).catch(() => null);
|
|
29
|
+
if (existing) {
|
|
30
|
+
const manifest = await readCodeManifest({ target, packageRoot, taskId }).catch(() => null);
|
|
31
|
+
if (manifest && existing.value.predicate.content.manifestFingerprint === manifest.fingerprint) {
|
|
32
|
+
return {
|
|
33
|
+
path: taskAttestationStatementPath(taskId),
|
|
34
|
+
fingerprint: existing.fingerprint,
|
|
35
|
+
statement: existing.value,
|
|
36
|
+
statementFingerprint: existing.fingerprint,
|
|
37
|
+
manifestFingerprint: manifest.fingerprint,
|
|
38
|
+
reused: true,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
}
|
|
22
42
|
const built = await buildAttestationStatement({ target, packageRoot, taskId });
|
|
23
43
|
const written = await writeAttestationStatement({ target, packageRoot, taskId, statement: built.statement });
|
|
24
44
|
return { ...written, statementFingerprint: built.fingerprint, manifestFingerprint: built.manifest.fingerprint };
|
package/src/commands/complete.js
CHANGED
|
@@ -34,6 +34,9 @@ export function formatCompleteResult(result) {
|
|
|
34
34
|
lines.push(`PUBLICATION: ${result.publicationStatus}`);
|
|
35
35
|
lines.push(`PRODUCTION_READINESS: ${result.productionReadiness}`);
|
|
36
36
|
}
|
|
37
|
+
const evidence = result.evidence;
|
|
38
|
+
if (evidence?.status === "EXPORTED") lines.push(`EVIDENCE: exported ${evidence.path} (commit it with the change)`);
|
|
39
|
+
else if (evidence?.status === "FAILED") lines.push(`EVIDENCE: export failed (${evidence.code}): ${evidence.message}`, `NEXT: ${evidence.next}`);
|
|
37
40
|
for (const error of result.errors) {
|
|
38
41
|
lines.push(`${error.code}: ${error.message}`);
|
|
39
42
|
if (error.next) lines.push(`NEXT: ${error.next}`);
|
|
@@ -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,22 @@
|
|
|
1
|
+
import { publishEvidence } from "../core/evidence/publish.js";
|
|
2
|
+
|
|
3
|
+
export async function runEvidencePublish({ target, taskId, all, evidenceDirectory, remote, repository, env, fetchImpl } = {}) {
|
|
4
|
+
return publishEvidence({
|
|
5
|
+
target,
|
|
6
|
+
taskIds: taskId ? [taskId] : [],
|
|
7
|
+
all: all === true,
|
|
8
|
+
...(evidenceDirectory ? { directory: evidenceDirectory } : {}),
|
|
9
|
+
remote,
|
|
10
|
+
repository,
|
|
11
|
+
...(env ? { env } : {}),
|
|
12
|
+
...(fetchImpl ? { fetchImpl } : {}),
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function formatEvidencePublishResult(result) {
|
|
17
|
+
const lines = [`FORGELOOP EVIDENCE PUBLISH: ${result.status}`, `REMOTE: ${result.remote}`, `REPOSITORY: ${result.repository}`];
|
|
18
|
+
for (const item of result.results) lines.push(`${item.status} ${item.taskId}${item.message ? ` (${item.message})` : ""}`);
|
|
19
|
+
if (result.queued > 0) lines.push(`QUEUED: ${result.queued} bundle(s) stay queued; run forgeloop evidence-publish again to retry.`);
|
|
20
|
+
lines.push("");
|
|
21
|
+
return lines.join("\n");
|
|
22
|
+
}
|
|
@@ -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,111 @@
|
|
|
1
|
+
import { cp, mkdtemp, rm } from "node:fs/promises";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
import { readSyncCredentials, readSyncState, 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 { buildMergedBackup, classifyTasks, readDatabaseDigests } from "../core/sync/merge.js";
|
|
8
|
+
import { runStorageRestore } from "./storage-restore.js";
|
|
9
|
+
|
|
10
|
+
// Downloads, decrypts and restores the repository's snapshot. Remote state is
|
|
11
|
+
// untrusted: it must decrypt and authenticate under FORGELOOP_SYNC_KEY, every
|
|
12
|
+
// file digest must match, and activation goes through the verified
|
|
13
|
+
// storage-restore path (a fresh project, or explicit --replace-active).
|
|
14
|
+
// --merge keeps local work: whole tasks are combined three-way against the
|
|
15
|
+
// per-task digests recorded at the last push or pull, and the merged state is
|
|
16
|
+
// activated through the same replace-active restore.
|
|
17
|
+
function assertPullOptions({ writersQuiesced, replaceActive, merge, dryRun }) {
|
|
18
|
+
if (writersQuiesced !== true && !(merge && dryRun)) throw syncError("E_STORAGE_MIGRATION_QUIESCENCE_REQUIRED", "Stop every ForgeLoop writer for this project, then pass --writers-quiesced");
|
|
19
|
+
if (dryRun && !merge) throw syncError("E_SYNC_CONFIG", "--dry-run applies to --merge");
|
|
20
|
+
if (merge && replaceActive) throw syncError("E_SYNC_CONFIG", "Use either --merge or --replace-active");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async function fetchSnapshot({ target, remote, repository, env, fetchImpl }) {
|
|
24
|
+
const { token, passphrase } = readSyncCredentials(env);
|
|
25
|
+
const resolvedRemote = resolveRemote(remote);
|
|
26
|
+
const resolvedRepository = await resolveRepository(target, repository);
|
|
27
|
+
const response = await syncRequest({ remote: resolvedRemote, repository: resolvedRepository, token, method: "GET", fetchImpl });
|
|
28
|
+
if (response.status === 404) throw syncError("E_SYNC_REMOTE", `No snapshot has been pushed for ${resolvedRepository}`);
|
|
29
|
+
if (!response.ok) throw await remoteError(response);
|
|
30
|
+
const etag = strongEtag(response.headers.get("etag"));
|
|
31
|
+
const body = Buffer.from(await response.arrayBuffer());
|
|
32
|
+
if (body.length > MAX_SNAPSHOT_BYTES) throw syncError("E_SYNC_TOO_LARGE", "Remote snapshot exceeds the size limit");
|
|
33
|
+
const { envelope, payload } = openSnapshot(body, { passphrase, repository: resolvedRepository });
|
|
34
|
+
return { remote: resolvedRemote, repository: resolvedRepository, etag, envelope, payload };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function mergeSnapshot({ target, packageRoot, staging, source, remoteTasks, summary, snapshot, dryRun, writersQuiesced, env, recordPull }) {
|
|
38
|
+
const local = path.join(staging, "local");
|
|
39
|
+
await backupLocalState(target, local);
|
|
40
|
+
const previous = await readSyncState(target, { remote: snapshot.remote, repository: snapshot.repository, env });
|
|
41
|
+
const base = previous?.tasks && typeof previous.tasks === "object" ? previous.tasks : null;
|
|
42
|
+
const plan = classifyTasks({ local: readDatabaseDigests(path.join(local, "state.sqlite")), remote: remoteTasks, base });
|
|
43
|
+
const report = { ...summary, base: base ? "recorded" : "none", take: plan.take, keep: plan.keep, same: plan.same.length, conflicts: plan.conflicts };
|
|
44
|
+
if (dryRun) return { status: plan.conflicts.length > 0 ? "CONFLICT" : "PLANNED", ...report };
|
|
45
|
+
if (plan.conflicts.length > 0) {
|
|
46
|
+
throw Object.assign(syncError("E_SYNC_MERGE_CONFLICT", `Tasks changed on both machines cannot be merged: ${plan.conflicts.map((item) => item.taskId).join(", ")}`), { report });
|
|
47
|
+
}
|
|
48
|
+
if (plan.take.length === 0) {
|
|
49
|
+
await recordPull();
|
|
50
|
+
return { status: "UP_TO_DATE", ...report };
|
|
51
|
+
}
|
|
52
|
+
const workingCopy = path.join(staging, "working");
|
|
53
|
+
await cp(local, workingCopy, { recursive: true });
|
|
54
|
+
const merged = path.join(staging, "merged");
|
|
55
|
+
await buildMergedBackup({ localBackup: workingCopy, remoteBackup: source, take: plan.take.map((item) => item.taskId), destination: merged });
|
|
56
|
+
const restore = await runStorageRestore({ target, source: merged, writersQuiesced, replaceActive: true, packageRoot });
|
|
57
|
+
await recordPull();
|
|
58
|
+
return { status: "MERGED", ...report, restore };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function runSyncPull({ target, packageRoot, remote, repository, writersQuiesced = false, replaceActive = false, merge = false, dryRun = false, env = process.env, fetchImpl = fetch } = {}) {
|
|
62
|
+
assertPullOptions({ writersQuiesced, replaceActive, merge, dryRun });
|
|
63
|
+
const snapshot = await fetchSnapshot({ target, remote, repository, env, fetchImpl });
|
|
64
|
+
const staging = await mkdtemp(path.join(os.tmpdir(), "forgeloop-sync-"));
|
|
65
|
+
try {
|
|
66
|
+
const source = path.join(staging, "backup");
|
|
67
|
+
const files = await unpackDirectory(snapshot.payload, source);
|
|
68
|
+
const remoteTasks = readDatabaseDigests(path.join(source, "state.sqlite"));
|
|
69
|
+
const recordPull = () => (snapshot.etag
|
|
70
|
+
? writeSyncState(target, { remote: snapshot.remote, repository: snapshot.repository, etag: snapshot.etag, direction: "pull", at: new Date().toISOString(), tasks: remoteTasks }, { env })
|
|
71
|
+
: null);
|
|
72
|
+
const summary = { repository: snapshot.repository, remote: snapshot.remote, etag: snapshot.etag, files: files.length, snapshotCreatedAt: snapshot.envelope.createdAt ?? null };
|
|
73
|
+
if (merge) return await mergeSnapshot({ target, packageRoot, staging, source, remoteTasks, summary, snapshot, dryRun, writersQuiesced, env, recordPull });
|
|
74
|
+
const restore = await runStorageRestore({ target, source, writersQuiesced, replaceActive, packageRoot });
|
|
75
|
+
await recordPull();
|
|
76
|
+
return { status: "PULLED", ...summary, replaceActive, restore };
|
|
77
|
+
} finally {
|
|
78
|
+
await rm(staging, { recursive: true, force: true });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function backupLocalState(target, destination) {
|
|
83
|
+
const { withProjectStorage } = await import("../storage/project-boundary.js");
|
|
84
|
+
const { getOperationalStore } = await import("../storage/operational-context.js");
|
|
85
|
+
const { backupProjectStorage } = await import("../storage/project-backup.js");
|
|
86
|
+
await withProjectStorage(target, () => {
|
|
87
|
+
const store = getOperationalStore(target);
|
|
88
|
+
if (!store) throw syncError("E_SYNC_CONFIG", "sync-pull --merge requires an existing SQLite project");
|
|
89
|
+
return backupProjectStorage(store.db, target, destination);
|
|
90
|
+
}, { readOnly: true, existingOnly: true });
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function formatSyncPullResult(result) {
|
|
94
|
+
if (result.take !== undefined) {
|
|
95
|
+
const lines = [`FORGELOOP SYNC MERGE: ${result.status} (${result.repository})`, `BASE: ${result.base}`];
|
|
96
|
+
for (const item of result.take) lines.push(`TAKE ${item.taskId} (${item.reason})`);
|
|
97
|
+
for (const item of result.keep) lines.push(`KEEP ${item.taskId} (${item.reason})`);
|
|
98
|
+
for (const item of result.conflicts) lines.push(`CONFLICT ${item.taskId} (${item.reason})`);
|
|
99
|
+
lines.push(`SAME: ${result.same} task(s)`);
|
|
100
|
+
if (result.status === "MERGED") lines.push("The merged state is active (the outgoing state is retained). Run forgeloop sync-push to publish it.");
|
|
101
|
+
lines.push("");
|
|
102
|
+
return lines.join("\n");
|
|
103
|
+
}
|
|
104
|
+
return [
|
|
105
|
+
`FORGELOOP SYNC PULLED: ${result.repository}`,
|
|
106
|
+
`SNAPSHOT: ${result.snapshotCreatedAt ?? "unknown time"} (${result.files} files, ETag ${result.etag ?? "unknown"})`,
|
|
107
|
+
`RESTORED: ${result.replaceActive ? "replaced the active state (outgoing state retained)" : "into a fresh project"}`,
|
|
108
|
+
"Run forgeloop task-list to resume. This machine is now the one allowed to push.",
|
|
109
|
+
"",
|
|
110
|
+
].join("\n");
|
|
111
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
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 { readDatabaseDigests } from "../core/sync/merge.js";
|
|
8
|
+
import { runStorageBackup } from "./storage-backup.js";
|
|
9
|
+
|
|
10
|
+
// Uploads an encrypted, attachment-inclusive backup of this project's ForgeLoop
|
|
11
|
+
// state. The write is conditional: the first push only creates, later pushes
|
|
12
|
+
// must match the ETag this machine last pushed or pulled.
|
|
13
|
+
export async function runSyncPush({ target, packageRoot, remote, repository, env = process.env, fetchImpl = fetch } = {}) {
|
|
14
|
+
const { token, passphrase } = readSyncCredentials(env);
|
|
15
|
+
const resolvedRemote = resolveRemote(remote);
|
|
16
|
+
const resolvedRepository = await resolveRepository(target, repository);
|
|
17
|
+
const staging = path.join(".forgeloop", `sync-staging-${randomUUID()}`);
|
|
18
|
+
let body;
|
|
19
|
+
let files;
|
|
20
|
+
let tasks;
|
|
21
|
+
try {
|
|
22
|
+
await runStorageBackup({ target, destination: staging, includeAttachments: true });
|
|
23
|
+
tasks = readDatabaseDigests(path.join(target, staging, "state.sqlite"));
|
|
24
|
+
const payload = await packDirectory(path.join(target, staging));
|
|
25
|
+
files = payload.files.length;
|
|
26
|
+
const version = packageRoot ? JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8")).version ?? null : null;
|
|
27
|
+
body = sealSnapshot(payload, { passphrase, repository: resolvedRepository, forgeloopVersion: version });
|
|
28
|
+
} finally {
|
|
29
|
+
await rm(path.join(target, staging), { recursive: true, force: true });
|
|
30
|
+
}
|
|
31
|
+
const previous = await readSyncState(target, { remote: resolvedRemote, repository: resolvedRepository, env });
|
|
32
|
+
const response = await syncRequest({
|
|
33
|
+
remote: resolvedRemote, repository: resolvedRepository, token, method: "PUT", body, fetchImpl,
|
|
34
|
+
headers: previous ? { "if-match": strongEtag(previous.etag) } : { "if-none-match": "*" },
|
|
35
|
+
});
|
|
36
|
+
if (!response.ok) throw await remoteError(response);
|
|
37
|
+
const result = await response.json().catch(() => ({}));
|
|
38
|
+
const etag = strongEtag(typeof result.etag === "string" ? result.etag : response.headers.get("etag"));
|
|
39
|
+
if (etag) await writeSyncState(target, { remote: resolvedRemote, repository: resolvedRepository, etag, direction: "push", at: new Date().toISOString(), tasks }, { env });
|
|
40
|
+
return { status: "PUSHED", repository: resolvedRepository, remote: resolvedRemote, etag, files, bytes: body.length, firstPush: previous === null };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function formatSyncPushResult(result) {
|
|
44
|
+
return [
|
|
45
|
+
`FORGELOOP SYNC PUSHED: ${result.repository}`,
|
|
46
|
+
`REMOTE: ${result.remote}`,
|
|
47
|
+
`FILES: ${result.files} (${result.bytes} encrypted bytes)`,
|
|
48
|
+
`ETAG: ${result.etag ?? "unknown"}`,
|
|
49
|
+
"Another machine can now run forgeloop sync-pull. Pushes from machines that have not pulled this version are refused.",
|
|
50
|
+
"",
|
|
51
|
+
].join("\n");
|
|
52
|
+
}
|
|
@@ -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
|
+
}
|