@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.
Files changed (67) hide show
  1. package/CONTRIBUTING.md +22 -2
  2. package/DOCS_INDEX.md +4 -13
  3. package/ENG/sec-code-eng.md +1 -1
  4. package/ENG/test-code-eng.md +32 -1
  5. package/LOOP_SYSTEM_DESIGN.md +2 -3
  6. package/QUALITY_SCORECARD.md +0 -1
  7. package/README.md +19 -48
  8. package/THIRD_PARTY_NOTICES.md +0 -15
  9. package/completions/_forgeloop +7 -1
  10. package/completions/forgeloop.bash +13 -1
  11. package/completions/forgeloop.fish +51 -1
  12. package/docs/AGENT_PROTOCOL_SUMMARY.md +7 -1
  13. package/docs/ARTIFACT_REFERENCE.md +1 -0
  14. package/docs/CLI_REFERENCE.md +111 -3
  15. package/docs/CODE_ATTESTATION.md +16 -7
  16. package/docs/DOCUMENTATION_GUIDE.md +10 -28
  17. package/docs/PACKAGE_CONTENTS.md +0 -3
  18. package/docs/RELEASE_CHECKLIST.md +81 -15
  19. package/docs/REVISION_PROVIDERS.md +3 -6
  20. package/docs/TROUBLESHOOTING.md +11 -0
  21. package/docs/documentation-manifest.json +0 -13
  22. package/package.json +2 -6
  23. package/schemas/config.schema.json +1 -0
  24. package/scripts/CI_VALIDATORS.md +2 -2
  25. package/src/cli.js +31 -0
  26. package/src/commands/assess.js +36 -0
  27. package/src/commands/attestation-create.js +21 -1
  28. package/src/commands/complete.js +3 -0
  29. package/src/commands/evidence-export.js +17 -0
  30. package/src/commands/evidence-publish.js +22 -0
  31. package/src/commands/evidence-verify.js +36 -0
  32. package/src/commands/sync-pull.js +111 -0
  33. package/src/commands/sync-push.js +52 -0
  34. package/src/core/assessment/facts.js +146 -0
  35. package/src/core/assessment/plan.js +133 -0
  36. package/src/core/audit.js +7 -0
  37. package/src/core/cli-command-definitions.js +88 -0
  38. package/src/core/command-executors.js +42 -5
  39. package/src/core/config.js +44 -37
  40. package/src/core/error-codes.js +70 -0
  41. package/src/core/evidence/auto-export.js +61 -0
  42. package/src/core/evidence/bundle-format.js +74 -0
  43. package/src/core/evidence/export.js +184 -0
  44. package/src/core/evidence/markdown.js +40 -0
  45. package/src/core/evidence/publish.js +187 -0
  46. package/src/core/evidence/verify.js +179 -0
  47. package/src/core/integration-invocation-policy.js +5 -2
  48. package/src/core/sync/merge.js +135 -0
  49. package/src/core/sync/remote.js +124 -0
  50. package/src/core/sync/snapshot.js +129 -0
  51. package/docs/assets/diagrams/forgeloop-code-attestation-flow.html +0 -13852
  52. package/docs/assets/diagrams/forgeloop-code-attestation-flow.receipt.json +0 -37
  53. package/docs/assets/diagrams/forgeloop-code-attestation-flow.svg +0 -5055
  54. package/docs/assets/diagrams/forgeloop-engineering-flow.html +0 -13837
  55. package/docs/assets/diagrams/forgeloop-engineering-flow.receipt.json +0 -37
  56. package/docs/assets/diagrams/forgeloop-engineering-flow.svg +0 -5011
  57. package/docs/assets/diagrams/forgeloop-verification-trust-flow.html +0 -13795
  58. package/docs/assets/diagrams/forgeloop-verification-trust-flow.receipt.json +0 -37
  59. package/docs/assets/diagrams/forgeloop-verification-trust-flow.svg +0 -4997
  60. package/docs/diagrams/README.md +0 -103
  61. package/docs/diagrams/forgeloop-code-attestation-flow.workflow.json +0 -451
  62. package/docs/diagrams/forgeloop-engineering-flow.workflow.json +0 -459
  63. package/docs/diagrams/forgeloop-verification-trust-flow.workflow.json +0 -398
  64. package/docs/diagrams/manifest.json +0 -84
  65. package/docs/diagrams/reviews/forgeloop-code-attestation-flow.review.json +0 -20
  66. package/docs/diagrams/reviews/forgeloop-engineering-flow.review.json +0 -20
  67. package/docs/diagrams/reviews/forgeloop-verification-trust-flow.review.json +0 -20
package/src/core/audit.js CHANGED
@@ -13,6 +13,7 @@ import { readCodeManifest } from "./code-manifest.js";
13
13
  import { readAttestationStatement, validateAttestationStatement } from "./attestation.js";
14
14
  import { assertAttestationStatementBindings, verifyCodeManifestContent } from "./attestation-verifier.js";
15
15
  import { projectStructuralQualityStatus } from "./structural-quality/status.js";
16
+ import { DEFAULT_EVIDENCE_DIRECTORY } from "./evidence/bundle-format.js";
16
17
 
17
18
  function sortErrors(errors) {
18
19
  return [...errors].sort((left, right) => left.code.localeCompare(right.code)
@@ -48,6 +49,12 @@ async function compareChangedPaths(target, packageRoot, options = {}) {
48
49
  if (observed === null) {
49
50
  return { status: "NOT_VERIFIED", expected: receipt.changedPaths ?? [], observed: [], missing: [], unexpected: [] };
50
51
  }
52
+ // complete exports the task's own evidence bundle after the receipt is
53
+ // final; it is a protocol-owned derivative, not an unexpected change.
54
+ if (options.taskId) {
55
+ const ownBundle = `${DEFAULT_EVIDENCE_DIRECTORY}/${options.taskId}.json`;
56
+ observed = observed.filter((relativePath) => relativePath !== ownBundle);
57
+ }
51
58
  const expected = [...new Set(receipt.changedPaths ?? [])].sort();
52
59
  const missing = expected.filter((relativePath) => !observed.includes(relativePath));
53
60
  const unexpected = observed.filter((relativePath) => !expected.includes(relativePath));
@@ -156,6 +156,32 @@ 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
+ "--merge": Object.freeze({ targetKey: "syncMerge", parseType: "boolean", takesValue: false, description: "combine whole tasks three-way with local state instead of replacing it" }),
178
+ "--dry-run": Object.freeze({ targetKey: "dryRun", parseType: "boolean", takesValue: false, description: "with --merge, report the per-task plan without changing anything" }),
179
+ "--writers-quiesced": Object.freeze({ targetKey: "writersQuiesced", parseType: "boolean", takesValue: false, description: "assert that all writers have been externally stopped" }),
180
+ "--json": Object.freeze({ targetKey: "json", parseType: "boolean", takesValue: false, description: "emit the pull and restore result as JSON" }),
181
+ }),
182
+ 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,
183
+ description: "Downloads, decrypts and verifies the repository's sync snapshot, then activates it through storage-restore: into a fresh project, replacing local state with --replace-active, or merged task by task with local state with --merge.",
184
+ }),
159
185
  "protocol-info": Object.freeze({
160
186
  name: "protocol-info",
161
187
  category: "diagnostics",
@@ -256,6 +282,17 @@ export const CLI_COMMAND_DEFINITIONS = Object.freeze({
256
282
  writes: [], removes: [], mayExecuteExternalProcess: false,
257
283
  description: "Discovers tests deterministically and assigns stable semantic test IDs without pruning authority.",
258
284
  }),
285
+ assess: Object.freeze({
286
+ name: "assess",
287
+ category: "diagnostics",
288
+ mutation: "READ_ONLY",
289
+ options: Object.freeze({
290
+ ...CLI_COMMON_OPTIONS,
291
+ "--json": Object.freeze({ targetKey: "json", parseType: "boolean", takesValue: false, description: "emit the repository assessment plan as JSON" }),
292
+ }),
293
+ writes: [], removes: [], mayExecuteExternalProcess: false,
294
+ description: "Assesses an existing repository read-only: stack, areas, tests, candidate checks, observed gaps, and a guide-routed review plan without executing target code.",
295
+ }),
259
296
  "test-utility": Object.freeze({
260
297
  name: "test-utility",
261
298
  category: "diagnostics",
@@ -1733,6 +1770,57 @@ export const CLI_COMMAND_DEFINITIONS = Object.freeze({
1733
1770
  mayExecuteExternalProcess: true,
1734
1771
  description: "Reports local ForgeLoop attestation status and trust level without network access.",
1735
1772
  }),
1773
+ "evidence-export": Object.freeze({
1774
+ name: "evidence-export",
1775
+ category: "attestation",
1776
+ mutation: "MUTATING",
1777
+ options: Object.freeze({
1778
+ ...CLI_COMMON_OPTIONS,
1779
+ ...CLI_TASK_OPTION,
1780
+ "--dir": Object.freeze({ targetKey: "evidenceDirectory", parseType: "string", takesValue: true, valueName: "path", missingValueMessage: "--dir requires a path", description: "tracked evidence directory (default: .forgeloop-evidence)" }),
1781
+ "--json": Object.freeze({ targetKey: "json", parseType: "boolean", takesValue: false, description: "emit the export result as JSON" }),
1782
+ }),
1783
+ writes: [".forgeloop-evidence/<taskId>.json"], removes: [], mayExecuteExternalProcess: false,
1784
+ description: "Exports a completed task's attestation as a portable, redacted evidence bundle to commit with the change.",
1785
+ }),
1786
+ "evidence-publish": Object.freeze({
1787
+ name: "evidence-publish",
1788
+ category: "attestation",
1789
+ mutation: "MUTATING",
1790
+ options: Object.freeze({
1791
+ ...CLI_COMMON_OPTIONS,
1792
+ "--task": Object.freeze({ targetKey: "taskId", parseType: "string", takesValue: true, valueName: "id", missingValueMessage: "--task requires a task ID", description: "publish this task's exported bundle" }),
1793
+ "--all": Object.freeze({ targetKey: "all", parseType: "boolean", takesValue: false, description: "publish every bundle in the evidence directory" }),
1794
+ "--dir": Object.freeze({ targetKey: "evidenceDirectory", parseType: "string", takesValue: true, valueName: "path", missingValueMessage: "--dir requires a path", description: "tracked evidence directory (default: .forgeloop-evidence)" }),
1795
+ "--remote": Object.freeze({ targetKey: "evidenceRemote", parseType: "string", takesValue: true, valueName: "url", missingValueMessage: "--remote requires a URL", description: "evidence endpoint (default: https://forgeloop.monster/api/evidence)" }),
1796
+ "--repo": Object.freeze({ targetKey: "evidenceRepository", parseType: "string", takesValue: true, valueName: "owner/name", missingValueMessage: "--repo requires owner/name", description: "repository the bundles belong to (default: from the git origin)" }),
1797
+ "--json": Object.freeze({ targetKey: "json", parseType: "boolean", takesValue: false, description: "emit the publish result as JSON" }),
1798
+ }),
1799
+ writes: ["<user config>/forgeloop/evidence-queue/<project>.json"], removes: [], mayExecuteExternalProcess: true,
1800
+ description: "Opt-in: uploads redacted evidence bundles to the team dashboard, authenticated by FORGELOOP_SYNC_TOKEN. Bundles wait in an offline queue outside the repository until the remote accepts them.",
1801
+ }),
1802
+ "evidence-verify": Object.freeze({
1803
+ name: "evidence-verify",
1804
+ category: "attestation",
1805
+ mutation: "READ_ONLY",
1806
+ options: Object.freeze({
1807
+ ...CLI_COMMON_OPTIONS,
1808
+ "--revision-provider": Object.freeze({ targetKey: "revisionProvider", parseType: "string", takesValue: true, valueName: "provider", missingValueMessage: "--revision-provider requires a provider", description: "revision provider (default: git)" }),
1809
+ "--base": Object.freeze({ targetKey: "baseRevision", parseType: "string", takesValue: true, valueName: "revision", missingValueMessage: "--base requires a revision", description: "base revision of the verified range" }),
1810
+ "--head": Object.freeze({ targetKey: "headRevision", parseType: "string", takesValue: true, valueName: "revision", missingValueMessage: "--head requires a revision", description: "head revision of the verified range" }),
1811
+ "--dir": Object.freeze({ targetKey: "evidenceDirectory", parseType: "string", takesValue: true, valueName: "path", missingValueMessage: "--dir requires a path", description: "tracked evidence directory (default: .forgeloop-evidence)" }),
1812
+ "--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)" }),
1813
+ "--allow-partial-coverage": Object.freeze({ targetKey: "allowPartialCoverage", parseType: "boolean", takesValue: false, description: "report uncovered changed paths without failing" }),
1814
+ "--require-signature": Object.freeze({ targetKey: "requireSignature", parseType: "boolean", takesValue: false, description: "require a valid Sigstore signature for every bundle used" }),
1815
+ "--identity": Object.freeze({ targetKey: "attestationIdentity", parseType: "string", takesValue: true, valueName: "identity", missingValueMessage: "--identity requires an identity", description: "exact signer identity policy" }),
1816
+ "--issuer": Object.freeze({ targetKey: "attestationIssuer", parseType: "string", takesValue: true, valueName: "issuer", missingValueMessage: "--issuer requires an issuer", description: "exact signer issuer policy" }),
1817
+ "--trusted-root": Object.freeze({ targetKey: "trustedRoot", parseType: "string", takesValue: true, valueName: "path", missingValueMessage: "--trusted-root requires a path", description: "trusted signing root path" }),
1818
+ "--format": Object.freeze({ targetKey: "evidenceFormat", parseType: "string", takesValue: true, valueName: "text|markdown", missingValueMessage: "--format requires text or markdown", description: "human output format (default: text)" }),
1819
+ "--json": Object.freeze({ targetKey: "json", parseType: "boolean", takesValue: false, description: "emit the verification result as JSON" }),
1820
+ }),
1821
+ writes: [], removes: [], mayExecuteExternalProcess: true,
1822
+ description: "Verifies committed evidence bundles for a revision range without local ForgeLoop state; signatures raise the level from INTEGRITY_ONLY to ATTESTED.",
1823
+ }),
1736
1824
  "attestation-verify-range": Object.freeze({
1737
1825
  name: "attestation-verify-range",
1738
1826
  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);
@@ -118,14 +121,18 @@ const runSearch = async (...args) => (await import("../commands/repository-index
118
121
  * The CLI renders these results; MCP and other integrations consume them
119
122
  * directly. No ownership, recovery, or lifecycle logic may live here.
120
123
  */
124
+ // Commands that write outside the project store (a backup destination, a
125
+ // user-config file) and therefore open the store read-only.
126
+ const READ_ONLY_STORAGE_COMMANDS = new Set(["storage-backup", "sync-push", "evidence-publish"]);
127
+
121
128
  const RAW_COMMAND_EXECUTORS = {
122
129
  "storage-restore-resume": async ({ target, packageRoot, options }) => {
123
130
  const { runStorageRestoreResume } = await import("../commands/storage-restore-resume.js");
124
- return { result: await runStorageRestoreResume({ target, packageRoot, operationId: options.operationId, expectedOwnerId: options.expectedOwnerId, writersQuiesced: options.writersQuiesced, replaceActive: options.replaceActive }), exitCode: 0 };
131
+ return { result: await runStorageRestoreResume({ target, packageRoot, operationId: options.operationId, expectedOwnerId: options.expectedOwnerId, writersQuiesced: options.writersQuiesced, replaceActive: options.replaceActive, merge: options.syncMerge, dryRun: options.dryRun }), exitCode: 0 };
125
132
  },
126
133
  "storage-restore": async ({ target, packageRoot, options }) => {
127
134
  const { runStorageRestore } = await import("../commands/storage-restore.js");
128
- return { result: await runStorageRestore({ target, packageRoot, source: options.source, writersQuiesced: options.writersQuiesced, replaceActive: options.replaceActive }), exitCode: 0 };
135
+ return { result: await runStorageRestore({ target, packageRoot, source: options.source, writersQuiesced: options.writersQuiesced, replaceActive: options.replaceActive, merge: options.syncMerge, dryRun: options.dryRun }), exitCode: 0 };
129
136
  },
130
137
  "storage-migration-status": async ({ target }) => {
131
138
  const { runStorageMigrationStatus } = await import("../commands/storage-migration-status.js");
@@ -147,6 +154,14 @@ const RAW_COMMAND_EXECUTORS = {
147
154
  const { runStorageMigrate } = await import("../commands/storage-migrate.js");
148
155
  return { result: await runStorageMigrate({ target, packageRoot, destination: options.destination, writersQuiesced: options.writersQuiesced }), exitCode: 0 };
149
156
  },
157
+ "sync-push": async ({ target, packageRoot, options }) => {
158
+ const { runSyncPush } = await import("../commands/sync-push.js");
159
+ return { result: await runSyncPush({ target, packageRoot, remote: options.syncRemote, repository: options.syncRepository }), exitCode: 0 };
160
+ },
161
+ "sync-pull": async ({ target, packageRoot, options }) => {
162
+ const { runSyncPull } = await import("../commands/sync-pull.js");
163
+ return { result: await runSyncPull({ target, packageRoot, remote: options.syncRemote, repository: options.syncRepository, writersQuiesced: options.writersQuiesced, replaceActive: options.replaceActive, merge: options.syncMerge, dryRun: options.dryRun }), exitCode: 0 };
164
+ },
150
165
  "storage-backup": async ({ target, options }) => {
151
166
  const { runStorageBackup } = await import("../commands/storage-backup.js");
152
167
  return { result: await runStorageBackup({ target, destination: options.destination, includeAttachments: options.includeAttachments }), exitCode: 0 };
@@ -210,6 +225,10 @@ const RAW_COMMAND_EXECUTORS = {
210
225
  }),
211
226
  exitCode: 0,
212
227
  }),
228
+ assess: async ({ target }) => ({
229
+ result: await runAssess({ target }),
230
+ exitCode: 0,
231
+ }),
213
232
  "test-inventory": async ({ target }) => ({
214
233
  result: await runTestInventory({ target }),
215
234
  exitCode: 0,
@@ -412,6 +431,19 @@ const RAW_COMMAND_EXECUTORS = {
412
431
  const result = await runAttestationStatus({ target, packageRoot, taskId: options.taskId });
413
432
  return { result, exitCode: exitCodeForAttestationResult(result) };
414
433
  },
434
+ "evidence-export": async ({ target, packageRoot, options }) => ({
435
+ result: await runEvidenceExport({ target, packageRoot, taskId: options.taskId, evidenceDirectory: options.evidenceDirectory }),
436
+ exitCode: 0,
437
+ }),
438
+ "evidence-publish": async ({ target, options }) => {
439
+ const { runEvidencePublish } = await import("../commands/evidence-publish.js");
440
+ const result = await runEvidencePublish({ target, taskId: options.taskId, all: options.all, evidenceDirectory: options.evidenceDirectory, remote: options.evidenceRemote, repository: options.evidenceRepository });
441
+ return { result, exitCode: result.status === "PUBLISHED" ? 0 : 1 };
442
+ },
443
+ "evidence-verify": async ({ target, packageRoot, options }) => {
444
+ const result = await runEvidenceVerify({ target, packageRoot, ...options });
445
+ return { result, exitCode: exitCodeForAttestationResult(result) };
446
+ },
415
447
  "attestation-verify-range": async ({ target, packageRoot, options }) => {
416
448
  const result = await runAttestationVerifyRange({ target, packageRoot, ...options });
417
449
  return { result, exitCode: exitCodeForAttestationResult(result) };
@@ -613,6 +645,10 @@ const RAW_COMMAND_EXECUTORS = {
613
645
  authorityContext,
614
646
  runtimeContext,
615
647
  });
648
+ if (result.status === "VALID") {
649
+ const { autoExportEvidence } = await import("./evidence/auto-export.js");
650
+ result.evidence = await autoExportEvidence({ target, packageRoot, taskId: options.taskId ?? null });
651
+ }
616
652
  return { result, exitCode: result.status === "VALID" ? 0 : 1 };
617
653
  },
618
654
  audit: async ({ target, packageRoot, options, authorityContext, runtimeContext }) => {
@@ -864,12 +900,13 @@ export const COMMAND_EXECUTORS = Object.fromEntries(Object.entries(RAW_COMMAND_E
864
900
  const { assertCanonicalPersistence } = await import("../storage/operational-context.js");
865
901
  assertCanonicalPersistence(context.runtimeContext?.forgeloopPersistence);
866
902
  }
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);
903
+ 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
904
  const { withProjectStorage } = await import("../storage/project-boundary.js");
869
905
  const { CLI_COMMAND_DEFINITIONS } = await import("./cli-command-definitions.js");
870
- // Backup writes its destination, not the source store. Doctor repairs only
906
+ // Backup (and sync-push, which backs up) writes its destination, not the source store, and
907
+ // evidence-publish writes only its user-config queue. Doctor repairs only
871
908
  // when explicitly requested; inspecting either must not migrate the source.
872
909
  const readOnly = CLI_COMMAND_DEFINITIONS[name]?.mutation === "READ_ONLY"
873
- || context.options?.dryRun === true || name === "storage-backup" || (name === "doctor" && context.options?.fix !== true);
910
+ || context.options?.dryRun === true || READ_ONLY_STORAGE_COMMANDS.has(name) || (name === "doctor" && context.options?.fix !== true);
874
911
  return withProjectStorage(context.target, () => executor(context), { readOnly, runtimeContext: context.runtimeContext });
875
912
  }]));
@@ -25,48 +25,55 @@ function configurationError(message) {
25
25
  return error;
26
26
  }
27
27
 
28
+ function booleanOption(value, name) {
29
+ if (typeof value !== "boolean") throw configurationError(`${name} must be a boolean`);
30
+ return value;
31
+ }
32
+
33
+ function normalizeAttestationConfig(raw) {
34
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
35
+ throw configurationError("attestation must be an object");
36
+ }
37
+ const mode = raw.mode ?? "optional";
38
+ if (!ATTESTATION_MODES.includes(mode)) throw configurationError(`Unknown attestation mode: ${mode}`);
39
+ const revisionProvider = raw.revisionProvider ?? "git";
40
+ if (typeof revisionProvider !== "string" || !revisionProvider.trim()) throw configurationError("attestation.revisionProvider must be a non-empty string");
41
+ const signing = raw.signing ?? {};
42
+ if (!signing || typeof signing !== "object" || Array.isArray(signing)) {
43
+ throw configurationError("attestation.signing must be an object");
44
+ }
45
+ const provider = signing.provider ?? "none";
46
+ if (!["none", "sigstore"].includes(provider)) throw configurationError(`Unknown attestation signing provider: ${provider}`);
47
+ const policy = signing.policy ?? {};
48
+ if (!policy || typeof policy !== "object" || Array.isArray(policy)) {
49
+ throw configurationError("attestation.signing.policy must be an object");
50
+ }
51
+ if (policy.issuer !== undefined && typeof policy.issuer !== "string") throw configurationError("attestation.signing.policy.issuer must be a string");
52
+ if (policy.identities !== undefined) stringArray(policy.identities, "attestation.signing.policy.identities");
53
+ return {
54
+ mode,
55
+ revisionProvider,
56
+ requireCompleteCoverage: raw.requireCompleteCoverage === true,
57
+ ...(raw.autoExportEvidence !== undefined ? { autoExportEvidence: booleanOption(raw.autoExportEvidence, "attestation.autoExportEvidence") } : {}),
58
+ coverage: { exclude: stringArray(raw.coverage?.exclude ?? [], "attestation.coverage.exclude") },
59
+ signing: {
60
+ provider,
61
+ required: signing.required === true,
62
+ policy: {
63
+ ...(policy.issuer !== undefined ? { issuer: policy.issuer } : {}),
64
+ identities: [...(policy.identities ?? [])],
65
+ requireTransparencyLog: policy.requireTransparencyLog !== false,
66
+ },
67
+ },
68
+ };
69
+ }
70
+
28
71
  export function createConfig(input = {}) {
29
72
  const complianceMode = input.complianceMode ?? "standard";
30
73
  if (!COMPLIANCE_MODES.includes(complianceMode)) {
31
74
  throw configurationError(`Unknown compliance mode: ${complianceMode}`);
32
75
  }
33
- let attestation;
34
- if (input.attestation !== undefined) {
35
- if (!input.attestation || typeof input.attestation !== "object" || Array.isArray(input.attestation)) {
36
- throw configurationError("attestation must be an object");
37
- }
38
- const mode = input.attestation.mode ?? "optional";
39
- if (!ATTESTATION_MODES.includes(mode)) throw configurationError(`Unknown attestation mode: ${mode}`);
40
- const revisionProvider = input.attestation.revisionProvider ?? "git";
41
- if (typeof revisionProvider !== "string" || !revisionProvider.trim()) throw configurationError("attestation.revisionProvider must be a non-empty string");
42
- const signing = input.attestation.signing ?? {};
43
- if (!signing || typeof signing !== "object" || Array.isArray(signing)) {
44
- throw configurationError("attestation.signing must be an object");
45
- }
46
- const provider = signing.provider ?? "none";
47
- if (!["none", "sigstore"].includes(provider)) throw configurationError(`Unknown attestation signing provider: ${provider}`);
48
- const policy = signing.policy ?? {};
49
- if (!policy || typeof policy !== "object" || Array.isArray(policy)) {
50
- throw configurationError("attestation.signing.policy must be an object");
51
- }
52
- if (policy.issuer !== undefined && typeof policy.issuer !== "string") throw configurationError("attestation.signing.policy.issuer must be a string");
53
- if (policy.identities !== undefined) stringArray(policy.identities, "attestation.signing.policy.identities");
54
- attestation = {
55
- mode,
56
- revisionProvider,
57
- requireCompleteCoverage: input.attestation.requireCompleteCoverage === true,
58
- coverage: { exclude: stringArray(input.attestation.coverage?.exclude ?? [], "attestation.coverage.exclude") },
59
- signing: {
60
- provider,
61
- required: signing.required === true,
62
- policy: {
63
- ...(policy.issuer !== undefined ? { issuer: policy.issuer } : {}),
64
- identities: [...(policy.identities ?? [])],
65
- requireTransparencyLog: policy.requireTransparencyLog !== false,
66
- },
67
- },
68
- };
69
- }
76
+ const attestation = input.attestation === undefined ? undefined : normalizeAttestationConfig(input.attestation);
70
77
  let verification;
71
78
  if (input.verification !== undefined) {
72
79
  try {
@@ -11,6 +11,15 @@ import {
11
11
  E_VERIFICATION_ISOLATION_UNAVAILABLE,
12
12
  } from "./verification-execution.js";
13
13
 
14
+ export const E_SYNC_CONFIG = "E_SYNC_CONFIG";
15
+ export const E_SYNC_UNAUTHORIZED = "E_SYNC_UNAUTHORIZED";
16
+ export const E_SYNC_CONFLICT = "E_SYNC_CONFLICT";
17
+ export const E_SYNC_REMOTE = "E_SYNC_REMOTE";
18
+ export const E_SYNC_SNAPSHOT_INVALID = "E_SYNC_SNAPSHOT_INVALID";
19
+ export const E_SYNC_TOO_LARGE = "E_SYNC_TOO_LARGE";
20
+ export const E_SYNC_MERGE_CONFLICT = "E_SYNC_MERGE_CONFLICT";
21
+ export const E_EVIDENCE_PUBLISH_CONFIG = "E_EVIDENCE_PUBLISH_CONFIG";
22
+ export const E_EVIDENCE_PUBLISH_UNAUTHORIZED = "E_EVIDENCE_PUBLISH_UNAUTHORIZED";
14
23
  export const E_REPOSITORY_INDEX_PLATFORM_UNSUPPORTED = "E_REPOSITORY_INDEX_PLATFORM_UNSUPPORTED";
15
24
  export const E_REPOSITORY_INDEX_ENGINE_MISSING = "E_REPOSITORY_INDEX_ENGINE_MISSING";
16
25
  export const E_REPOSITORY_INDEX_ENGINE_DOWNLOAD_FAILED = "E_REPOSITORY_INDEX_ENGINE_DOWNLOAD_FAILED";
@@ -89,6 +98,8 @@ export const E_ATTESTATION_MANIFEST_STALE = "E_ATTESTATION_MANIFEST_STALE";
89
98
  export const E_ATTESTATION_CONTENT_MISMATCH = "E_ATTESTATION_CONTENT_MISMATCH";
90
99
  export const E_ATTESTATION_SCOPE_MISMATCH = "E_ATTESTATION_SCOPE_MISMATCH";
91
100
  export const E_ATTESTATION_COVERAGE_GAP = "E_ATTESTATION_COVERAGE_GAP";
101
+ export const E_EVIDENCE_BUNDLE_INVALID = "E_EVIDENCE_BUNDLE_INVALID";
102
+ export const E_EVIDENCE_EXPORT_UNAVAILABLE = "E_EVIDENCE_EXPORT_UNAVAILABLE";
92
103
  export const E_ATTESTATION_COVERAGE_CONFLICT = "E_ATTESTATION_COVERAGE_CONFLICT";
93
104
  export const E_ATTESTATION_STATEMENT_MISSING = "E_ATTESTATION_STATEMENT_MISSING";
94
105
  export const E_ATTESTATION_STATEMENT_INVALID = "E_ATTESTATION_STATEMENT_INVALID";
@@ -241,6 +252,8 @@ const EXTENSION_PUBLIC_ERROR_CODES = Object.freeze(Object.fromEntries([
241
252
  E_ATTESTATION_CONTENT_MISMATCH,
242
253
  E_ATTESTATION_SCOPE_MISMATCH,
243
254
  E_ATTESTATION_COVERAGE_GAP,
255
+ E_EVIDENCE_BUNDLE_INVALID,
256
+ E_EVIDENCE_EXPORT_UNAVAILABLE,
244
257
  E_ATTESTATION_COVERAGE_CONFLICT,
245
258
  E_ATTESTATION_STATEMENT_MISSING,
246
259
  E_ATTESTATION_STATEMENT_INVALID,
@@ -663,6 +676,51 @@ const REPOSITORY_INDEX_ERROR_METADATA = Object.freeze(Object.fromEntries([
663
676
  safeResolution,
664
677
  })])));
665
678
 
679
+ const CLOUD_SYNC_ERROR_METADATA = Object.freeze(Object.fromEntries([
680
+ [E_SYNC_CONFIG, [
681
+ "Cloud sync is missing FORGELOOP_SYNC_TOKEN or a FORGELOOP_SYNC_KEY of at least 16 characters, or --remote or --repo is invalid.",
682
+ "Set both environment variables and pass an https --remote and an owner/name --repo, or a GitHub git origin.",
683
+ ]],
684
+ [E_SYNC_UNAUTHORIZED, [
685
+ "The sync remote rejected FORGELOOP_SYNC_TOKEN, or the token is not allowed for this repository.",
686
+ "Use a token whose SHA-256 hash the remote owner configured for this repository.",
687
+ ]],
688
+ [E_SYNC_CONFLICT, [
689
+ "The remote snapshot changed since this machine last pushed or pulled, so the push was refused instead of overwriting it.",
690
+ "Run forgeloop sync-pull --writers-quiesced --replace-active to adopt the remote state, then continue and push again.",
691
+ ]],
692
+ [E_SYNC_REMOTE, [
693
+ "The sync remote is unreachable, has no snapshot for this repository, or refused the request.",
694
+ "Check --remote and network access, push a first snapshot, or retry later.",
695
+ ]],
696
+ [E_SYNC_SNAPSHOT_INVALID, [
697
+ "The remote snapshot could not be decrypted with FORGELOOP_SYNC_KEY, belongs to another repository, or its contents failed integrity checks.",
698
+ "Use the same FORGELOOP_SYNC_KEY as the pushing machine; never restore a snapshot that fails these checks.",
699
+ ]],
700
+ [E_SYNC_TOO_LARGE, [
701
+ "The encrypted snapshot exceeds the 4 MiB sync limit.",
702
+ "Sync a project with less retained state; cloud sync does not split snapshots.",
703
+ ]],
704
+ [E_SYNC_MERGE_CONFLICT, [
705
+ "sync-pull --merge found tasks changed on both machines, or merged tasks would hold overlapping active claims, so nothing was changed.",
706
+ "Finish or abandon the task on one machine and sync it first, or run sync-pull --replace-active to adopt the remote state.",
707
+ ]],
708
+ [E_EVIDENCE_PUBLISH_CONFIG, [
709
+ "evidence-publish is missing FORGELOOP_SYNC_TOKEN, has nothing to publish, or --remote, --repo or a task ID is invalid.",
710
+ "Set FORGELOOP_SYNC_TOKEN, pass --task <id> or --all with an https --remote and an owner/name --repo (or a GitHub git origin).",
711
+ ]],
712
+ [E_EVIDENCE_PUBLISH_UNAUTHORIZED, [
713
+ "The evidence remote rejected FORGELOOP_SYNC_TOKEN, or the token is not allowed for this repository. The bundles stay queued.",
714
+ "Use a token issued for this repository, then run evidence-publish again to retry the queue.",
715
+ ]],
716
+ ].map(([code, [meaning, safeResolution]]) => [code, Object.freeze({
717
+ code,
718
+ category: "cloud-sync",
719
+ classification: "PUBLIC_STABLE",
720
+ meaning,
721
+ safeResolution,
722
+ })])));
723
+
666
724
  const PERSISTENT_TRANSPORT_ERROR_METADATA = Object.freeze(Object.fromEntries([
667
725
  [E_PERSISTENT_TRANSPORT_FRAME_INVALID, [
668
726
  "The local persistent-search byte stream did not contain a complete valid JSON frame.",
@@ -720,6 +778,7 @@ export const PUBLIC_ERROR_CODES = Object.freeze({
720
778
  ...STRUCTURAL_QUALITY_ERROR_METADATA,
721
779
  ...ADVISORY_CONTEXT_AND_HANDOFF_ERROR_METADATA,
722
780
  ...REPOSITORY_INDEX_ERROR_METADATA,
781
+ ...CLOUD_SYNC_ERROR_METADATA,
723
782
  ...PERSISTENT_TRANSPORT_ERROR_METADATA,
724
783
  E_PREFLIGHT_NOT_READY: Object.freeze({
725
784
  code: "E_PREFLIGHT_NOT_READY",
@@ -1754,6 +1813,8 @@ export const ALL_KNOWN_ERROR_CODES = Object.freeze(new Set([
1754
1813
  E_ATTESTATION_CONTENT_MISMATCH,
1755
1814
  E_ATTESTATION_SCOPE_MISMATCH,
1756
1815
  E_ATTESTATION_COVERAGE_GAP,
1816
+ E_EVIDENCE_BUNDLE_INVALID,
1817
+ E_EVIDENCE_EXPORT_UNAVAILABLE,
1757
1818
  E_ATTESTATION_COVERAGE_CONFLICT,
1758
1819
  E_ATTESTATION_STATEMENT_MISSING,
1759
1820
  E_ATTESTATION_STATEMENT_INVALID,
@@ -1854,6 +1915,15 @@ export const ALL_KNOWN_ERROR_CODES = Object.freeze(new Set([
1854
1915
  E_BASELINE_RECORD_DURING_ACTIVE_TASK,
1855
1916
  E_POLICY_INITIALIZATION_FAILED,
1856
1917
  E_INIT_KIT_CONFLICT,
1918
+ E_SYNC_CONFIG,
1919
+ E_SYNC_UNAUTHORIZED,
1920
+ E_SYNC_CONFLICT,
1921
+ E_SYNC_REMOTE,
1922
+ E_SYNC_SNAPSHOT_INVALID,
1923
+ E_SYNC_TOO_LARGE,
1924
+ E_SYNC_MERGE_CONFLICT,
1925
+ E_EVIDENCE_PUBLISH_CONFIG,
1926
+ E_EVIDENCE_PUBLISH_UNAUTHORIZED,
1857
1927
  E_REPOSITORY_INDEX_PLATFORM_UNSUPPORTED,
1858
1928
  E_REPOSITORY_INDEX_ENGINE_MISSING,
1859
1929
  E_REPOSITORY_INDEX_ENGINE_DOWNLOAD_FAILED,
@@ -0,0 +1,61 @@
1
+ import { readConfig } from "../config.js";
2
+ import { resolveSigningProvider } from "../signing/provider.js";
3
+ import { SIGNING_PROVIDERS } from "../signing/registry.js";
4
+ import { taskAttestationBundlePath, taskAttestationStatementPath } from "../task-paths.js";
5
+ import { withTaskTransaction } from "../transaction.js";
6
+ import { assertEvidenceTaskId } from "./bundle-format.js";
7
+ import { exportEvidenceBundle, hasAttestationSignature } from "./export.js";
8
+
9
+ // Signs the statement only when Sigstore is the configured provider and no
10
+ // signature exists yet: keyless signing publishes the signer identity, so it
11
+ // must follow explicit configuration and never replace an earlier signature.
12
+ async function signStatement({ target, packageRoot, taskId, signing, signer }) {
13
+ if (signing?.provider !== "sigstore") return { status: "NOT_CONFIGURED" };
14
+ try {
15
+ if (await hasAttestationSignature(target, taskId)) return { status: "EXISTING" };
16
+ const provider = signer ?? await resolveSigningProvider({ providerName: "sigstore", registry: SIGNING_PROVIDERS });
17
+ const result = await withTaskTransaction({ target, taskId, packageRoot, operation: "attestation-sign" }, () => provider.sign({
18
+ target,
19
+ statementPath: taskAttestationStatementPath(taskId),
20
+ bundlePath: taskAttestationBundlePath(taskId),
21
+ }));
22
+ if (result?.status === "VALID") return { status: "SIGNED" };
23
+ return { status: "FAILED", code: result?.code ?? "E_ATTESTATION_SIGNATURE_INVALID", message: result?.message ?? "Sigstore signing failed" };
24
+ } catch (error) {
25
+ return { status: "FAILED", code: error.code ?? "E_ATTESTATION_SIGNATURE_INVALID", message: error.message };
26
+ }
27
+ }
28
+
29
+ // Runs after a VALID completion has committed. Export is a convenience on top
30
+ // of the terminal state: every failure is reported, never thrown, so a broken
31
+ // export or signature cannot turn a valid completion into an error.
32
+ export async function autoExportEvidence({ target, packageRoot, taskId, signer = null } = {}) {
33
+ let attestation;
34
+ try {
35
+ attestation = (await readConfig(target, packageRoot))?.attestation ?? null;
36
+ } catch {
37
+ attestation = null;
38
+ }
39
+ if (attestation?.mode !== "required") return { status: "SKIPPED", reason: "attestation mode is not required" };
40
+ if (attestation.autoExportEvidence === false) return { status: "SKIPPED", reason: "attestation.autoExportEvidence is false" };
41
+ if (!taskId) return { status: "SKIPPED", reason: "complete ran without --task" };
42
+ try {
43
+ assertEvidenceTaskId(taskId);
44
+ } catch {
45
+ return { status: "SKIPPED", reason: "task ID cannot name an evidence bundle" };
46
+ }
47
+ try {
48
+ const { runAttestationCreate } = await import("../../commands/attestation-create.js");
49
+ await runAttestationCreate({ target, packageRoot, taskId });
50
+ const signature = await signStatement({ target, packageRoot, taskId, signing: attestation.signing, signer });
51
+ const exported = await exportEvidenceBundle({ target, packageRoot, taskId });
52
+ return { status: "EXPORTED", path: exported.path, digest: exported.digest, coveredPaths: exported.coveredPaths, signed: exported.signed, signature };
53
+ } catch (error) {
54
+ return {
55
+ status: "FAILED",
56
+ code: error.code ?? "E_EVIDENCE_EXPORT_UNAVAILABLE",
57
+ message: error.message,
58
+ next: `forgeloop attestation-create --task ${taskId} && forgeloop evidence-export --task ${taskId}`,
59
+ };
60
+ }
61
+ }
@@ -0,0 +1,74 @@
1
+ import { createHash } from "node:crypto";
2
+ import { canonicalFingerprint } from "../artifacts.js";
3
+ import { E_EVIDENCE_BUNDLE_INVALID } from "../error-codes.js";
4
+
5
+ // Portable evidence bundle: what a completed task can prove to a verifier that
6
+ // has only the repository checkout. Signed content is the exact attestation
7
+ // statement text; everything else is either bound to it (the code manifest) or
8
+ // informational (the summary).
9
+
10
+ export const EVIDENCE_BUNDLE_SCHEMA_VERSION = 1;
11
+ export const EVIDENCE_BUNDLE_KIND = "forgeloop-evidence-bundle";
12
+ export const DEFAULT_EVIDENCE_DIRECTORY = ".forgeloop-evidence";
13
+
14
+ export const EVIDENCE_REDACTIONS = Object.freeze([
15
+ "absolute-paths",
16
+ "command-argv",
17
+ "command-output",
18
+ "environment",
19
+ "ledger-events",
20
+ ]);
21
+
22
+ // Task IDs may contain dots (release-2.2.0); a leading letter or digit and the
23
+ // absence of separators keep the bundle file name inside the evidence directory.
24
+ const TASK_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/u;
25
+
26
+ export function evidenceError(code, message, details = {}) {
27
+ return Object.assign(new Error(message), { code, ...details });
28
+ }
29
+
30
+ export function assertEvidenceTaskId(taskId) {
31
+ if (typeof taskId !== "string" || !TASK_ID_PATTERN.test(taskId)) {
32
+ throw evidenceError(E_EVIDENCE_BUNDLE_INVALID, `Invalid evidence task ID: ${taskId} (bundles need letters, digits, ".", "_" or "-", starting with a letter or digit)`);
33
+ }
34
+ return taskId;
35
+ }
36
+
37
+ export function evidenceBundlePath(directory, taskId) {
38
+ return `${directory.replace(/\/+$/u, "")}/${assertEvidenceTaskId(taskId)}.json`;
39
+ }
40
+
41
+ export function evidenceBundleDigest(bundle) {
42
+ const { digest: _digest, ...body } = bundle;
43
+ return createHash("sha256").update(JSON.stringify(body)).digest("hex");
44
+ }
45
+
46
+ export function sealEvidenceBundle(body) {
47
+ return { ...body, digest: evidenceBundleDigest(body) };
48
+ }
49
+
50
+ export function serializeEvidenceBundle(bundle) {
51
+ return `${JSON.stringify(bundle, null, 2)}\n`;
52
+ }
53
+
54
+ function requireField(condition, message) {
55
+ if (!condition) throw evidenceError(E_EVIDENCE_BUNDLE_INVALID, message);
56
+ }
57
+
58
+ export function parseEvidenceBundle(text, expectedTaskId = null) {
59
+ let bundle;
60
+ try { bundle = JSON.parse(text); } catch { throw evidenceError(E_EVIDENCE_BUNDLE_INVALID, "Evidence bundle is not valid JSON"); }
61
+ requireField(bundle && typeof bundle === "object" && !Array.isArray(bundle), "Evidence bundle must be an object");
62
+ requireField(bundle.schemaVersion === EVIDENCE_BUNDLE_SCHEMA_VERSION, `Unsupported evidence bundle schemaVersion: ${bundle.schemaVersion}`);
63
+ requireField(bundle.kind === EVIDENCE_BUNDLE_KIND, "Evidence bundle kind is not forgeloop-evidence-bundle");
64
+ assertEvidenceTaskId(bundle.taskId);
65
+ requireField(expectedTaskId === null || bundle.taskId === expectedTaskId, `Evidence bundle taskId ${bundle.taskId} does not match its file name`);
66
+ requireField(typeof bundle.statement?.text === "string", "Evidence bundle is missing the statement text");
67
+ requireField(bundle.manifest && typeof bundle.manifest === "object", "Evidence bundle is missing the code manifest");
68
+ requireField(bundle.manifestFingerprint === canonicalFingerprint(bundle.manifest), "Evidence bundle manifest fingerprint does not match its manifest");
69
+ requireField(bundle.signature === null || (typeof bundle.signature?.bundleText === "string" && typeof bundle.signature?.provider === "string"), "Evidence bundle signature is malformed");
70
+ requireField(typeof bundle.digest === "string" && bundle.digest === evidenceBundleDigest(bundle), "Evidence bundle digest does not match its content");
71
+ let statement;
72
+ try { statement = JSON.parse(bundle.statement.text); } catch { throw evidenceError(E_EVIDENCE_BUNDLE_INVALID, "Evidence bundle statement text is not valid JSON"); }
73
+ return { bundle, statement };
74
+ }