@cassiomc1/forgeloop 2.0.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.
Files changed (49) hide show
  1. package/.cursor/rules/project-loop.mdc +1 -1
  2. package/.github/copilot-instructions.md +1 -1
  3. package/AGENTS.md +1 -1
  4. package/CLAUDE.md +1 -1
  5. package/ENG/design-code-eng.md +7 -5
  6. package/ENG/dotnet-aspnetcore-development-eng.md +8 -4
  7. package/ENG/nodejs-backend-development-eng.md +7 -4
  8. package/ENG/sql-development-eng.md +5 -4
  9. package/ENG/taste-frontend-eng.md +19 -5
  10. package/PROTOCOL_INTEGRATION.md +21 -0
  11. package/README.md +10 -7
  12. package/THIRD_PARTY_NOTICES.md +1 -0
  13. package/completions/_forgeloop +6 -1
  14. package/completions/forgeloop.bash +11 -1
  15. package/completions/forgeloop.fish +40 -1
  16. package/docs/AGENT_PROTOCOL_SUMMARY.md +6 -1
  17. package/docs/CLI_REFERENCE.md +88 -3
  18. package/docs/CODE_ATTESTATION.md +7 -0
  19. package/docs/FORGELOOP_AUDIT.md +1 -1
  20. package/docs/GETTING_STARTED.md +8 -1
  21. package/docs/PACKAGE_CONTENTS.md +4 -5
  22. package/docs/RELEASE_CHECKLIST.md +67 -13
  23. package/docs/STABLE_2_ACCEPTANCE.md +118 -71
  24. package/docs/TROUBLESHOOTING.md +167 -0
  25. package/package.json +1 -5
  26. package/src/cli.js +26 -0
  27. package/src/commands/assess.js +36 -0
  28. package/src/commands/evidence-export.js +17 -0
  29. package/src/commands/evidence-verify.js +36 -0
  30. package/src/commands/sync-pull.js +46 -0
  31. package/src/commands/sync-push.js +49 -0
  32. package/src/core/assessment/facts.js +146 -0
  33. package/src/core/assessment/plan.js +133 -0
  34. package/src/core/cli-command-definitions.js +70 -0
  35. package/src/core/command-executors.js +26 -3
  36. package/src/core/error-codes.js +232 -2
  37. package/src/core/evidence/bundle-format.js +72 -0
  38. package/src/core/evidence/export.js +179 -0
  39. package/src/core/evidence/markdown.js +40 -0
  40. package/src/core/evidence/verify.js +179 -0
  41. package/src/core/integration-invocation-policy.js +4 -2
  42. package/src/core/next-action-review-phase.js +14 -5
  43. package/src/core/parsers/dotnet-project.js +221 -0
  44. package/src/core/parsers/limits.js +9 -0
  45. package/src/core/parsers/pubspec.js +307 -0
  46. package/src/core/parsers/shared.js +4 -0
  47. package/src/core/project-detection.js +6 -527
  48. package/src/core/sync/remote.js +124 -0
  49. package/src/core/sync/snapshot.js +129 -0
@@ -32,6 +32,12 @@ import { inspectJavaProject } from "./java-project.js";
32
32
  import { inspectNativeProject, nativeFrameworkForSource } from "./c-cpp-project.js";
33
33
  import { inspectSwiftProject, swiftSourceLooksExecutable } from "./swift-project.js";
34
34
  import { looksLikeSql, parseSqlProject } from "./sql-project.js";
35
+ import { PROJECT_DETECTION_LIMITS } from "./parsers/limits.js";
36
+ import { DOTNET_SDKS, parseDotNetProject, parseXmlStructure } from "./parsers/dotnet-project.js";
37
+ import { parsePubspec, splitTopLevel } from "./parsers/pubspec.js";
38
+ import { uniqueSorted } from "./parsers/shared.js";
39
+
40
+ export { PROJECT_DETECTION_LIMITS, parseDotNetProject, parsePubspec };
35
41
 
36
42
  export const PROJECT_EVIDENCE_SCHEMA_VERSION = 1;
37
43
 
@@ -42,22 +48,11 @@ export const PROJECT_EVIDENCE_SCOPES = Object.freeze([
42
48
  "NONE",
43
49
  ]);
44
50
 
45
- export const PROJECT_DETECTION_LIMITS = Object.freeze({
46
- maxManifests: 256,
47
- maxSolutionFiles: 64,
48
- maxManifestBytes: 1024 * 1024,
49
- maxSourceFiles: 256,
50
- maxSourceBytes: 512 * 1024,
51
- maxVisitedDirectories: 4096,
52
- maxVisitedEntries: 20000,
53
- });
54
51
  const MAX_MANIFESTS = PROJECT_DETECTION_LIMITS.maxManifests;
55
52
  const MAX_SOLUTION_FILES = PROJECT_DETECTION_LIMITS.maxSolutionFiles;
56
53
  const MAX_MANIFEST_BYTES = PROJECT_DETECTION_LIMITS.maxManifestBytes;
57
54
  const MAX_SOURCE_FILES = PROJECT_DETECTION_LIMITS.maxSourceFiles;
58
55
  const MAX_SOURCE_BYTES = PROJECT_DETECTION_LIMITS.maxSourceBytes;
59
- const MAX_XML_TEXT_LENGTH = 4096;
60
- const UNSUPPORTED_YAML_VALUE = Symbol("unsupported-yaml-value");
61
56
  const IGNORED_DIRECTORIES = new Set([
62
57
  ".dart_tool",
63
58
  ".forgeloop",
@@ -84,20 +79,6 @@ const IGNORED_DIRECTORIES = new Set([
84
79
  "third_party",
85
80
  ]);
86
81
  const DOTNET_PROJECT_EXTENSIONS = new Set([".csproj", ".fsproj", ".vbproj"]);
87
- const DOTNET_SDKS = new Set([
88
- "Microsoft.NET.Sdk",
89
- "Microsoft.NET.Sdk.Web",
90
- "Microsoft.NET.Sdk.Worker",
91
- "Microsoft.NET.Sdk.Razor",
92
- "Microsoft.NET.Sdk.BlazorWebAssembly",
93
- "Aspire.AppHost.Sdk",
94
- "MSTest.Sdk",
95
- ]);
96
- const ASPNETCORE_SDKS = new Set([
97
- "Microsoft.NET.Sdk.Web",
98
- "Microsoft.NET.Sdk.Razor",
99
- "Microsoft.NET.Sdk.BlazorWebAssembly",
100
- ]);
101
82
  const SHARED_DOTNET_FILES = new Set([
102
83
  "directory.build.props",
103
84
  "directory.build.targets",
@@ -247,308 +228,6 @@ function portableRelative(root, absolutePath) {
247
228
  return relative === "" ? "." : relative;
248
229
  }
249
230
 
250
- function uniqueSorted(values) {
251
- return [...new Set(values.filter((value) => typeof value === "string" && value.length > 0))]
252
- .sort((left, right) => left.localeCompare(right));
253
- }
254
-
255
- function stripYamlComment(value) {
256
- let quote = null;
257
- let braceDepth = 0;
258
- let bracketDepth = 0;
259
- for (let index = 0; index < value.length; index += 1) {
260
- const character = value[index];
261
- if (quote === "\"") {
262
- if (character === "\\") index += 1;
263
- else if (character === "\"") quote = null;
264
- continue;
265
- }
266
- if (quote === "'") {
267
- if (character === "'" && value[index + 1] === "'") index += 1;
268
- else if (character === "'") quote = null;
269
- continue;
270
- }
271
- if (character === "\"" || character === "'") {
272
- quote = character;
273
- continue;
274
- }
275
- if (character === "{") braceDepth += 1;
276
- else if (character === "}") braceDepth = Math.max(0, braceDepth - 1);
277
- else if (character === "[") bracketDepth += 1;
278
- else if (character === "]") bracketDepth = Math.max(0, bracketDepth - 1);
279
- else if (character === "#" && braceDepth === 0 && bracketDepth === 0
280
- && (index === 0 || /\s/u.test(value[index - 1]))) {
281
- return value.slice(0, index).trimEnd();
282
- }
283
- }
284
- return value.trimEnd();
285
- }
286
-
287
- function findTopLevelColon(value) {
288
- let quote = null;
289
- let braceDepth = 0;
290
- let bracketDepth = 0;
291
- for (let index = 0; index < value.length; index += 1) {
292
- const character = value[index];
293
- if (quote === "\"") {
294
- if (character === "\\") index += 1;
295
- else if (character === "\"") quote = null;
296
- continue;
297
- }
298
- if (quote === "'") {
299
- if (character === "'" && value[index + 1] === "'") index += 1;
300
- else if (character === "'") quote = null;
301
- continue;
302
- }
303
- if (character === "\"" || character === "'") {
304
- quote = character;
305
- continue;
306
- }
307
- if (character === "{") braceDepth += 1;
308
- else if (character === "}") braceDepth = Math.max(0, braceDepth - 1);
309
- else if (character === "[") bracketDepth += 1;
310
- else if (character === "]") bracketDepth = Math.max(0, bracketDepth - 1);
311
- else if (character === ":" && braceDepth === 0 && bracketDepth === 0) return index;
312
- }
313
- return -1;
314
- }
315
-
316
- function unquoteYamlScalar(value) {
317
- const trimmed = value.trim();
318
- if (trimmed.length < 2) return trimmed;
319
- if (trimmed.startsWith("\"") && trimmed.endsWith("\"")) {
320
- try {
321
- return JSON.parse(trimmed);
322
- } catch {
323
- return null;
324
- }
325
- }
326
- if (trimmed.startsWith("'") && trimmed.endsWith("'")) {
327
- return trimmed.slice(1, -1).replaceAll("''", "'");
328
- }
329
- return trimmed;
330
- }
331
-
332
- function splitTopLevel(value, delimiter = ",") {
333
- const parts = [];
334
- let start = 0;
335
- let quote = null;
336
- let braceDepth = 0;
337
- let bracketDepth = 0;
338
- for (let index = 0; index < value.length; index += 1) {
339
- const character = value[index];
340
- if (quote === "\"") {
341
- if (character === "\\") index += 1;
342
- else if (character === "\"") quote = null;
343
- continue;
344
- }
345
- if (quote === "'") {
346
- if (character === "'" && value[index + 1] === "'") index += 1;
347
- else if (character === "'") quote = null;
348
- continue;
349
- }
350
- if (character === "\"" || character === "'") {
351
- quote = character;
352
- continue;
353
- }
354
- if (character === "{") braceDepth += 1;
355
- else if (character === "}") braceDepth = Math.max(0, braceDepth - 1);
356
- else if (character === "[") bracketDepth += 1;
357
- else if (character === "]") bracketDepth = Math.max(0, bracketDepth - 1);
358
- else if (character === delimiter && braceDepth === 0 && bracketDepth === 0) {
359
- parts.push(value.slice(start, index).trim());
360
- start = index + 1;
361
- }
362
- }
363
- parts.push(value.slice(start).trim());
364
- return parts.filter(Boolean);
365
- }
366
-
367
- function parseInlineMap(value) {
368
- const trimmed = value.trim();
369
- if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) return null;
370
- const body = trimmed.slice(1, -1).trim();
371
- if (body === "") return {};
372
- const result = {};
373
- for (const pair of splitTopLevel(body)) {
374
- const separator = findTopLevelColon(pair);
375
- if (separator <= 0) return null;
376
- const key = unquoteYamlScalar(pair.slice(0, separator));
377
- const rawValue = pair.slice(separator + 1).trim();
378
- if (!key || rawValue === "" || Object.prototype.hasOwnProperty.call(result, key)) return null;
379
- const parsedValue = parseYamlValue(rawValue);
380
- if (parsedValue === null) return null;
381
- result[key] = parsedValue;
382
- }
383
- return result;
384
- }
385
-
386
- function parseYamlValue(value) {
387
- const withoutComment = stripYamlComment(value).trim();
388
- if (withoutComment === "") return "";
389
- if (withoutComment.startsWith("{")) {
390
- return withoutComment.endsWith("}") ? parseInlineMap(withoutComment) : null;
391
- }
392
- if (withoutComment.startsWith("[")) return UNSUPPORTED_YAML_VALUE;
393
- return unquoteYamlScalar(withoutComment);
394
- }
395
-
396
- function containsUnsupportedYamlValue(value) {
397
- if (value === UNSUPPORTED_YAML_VALUE) return true;
398
- if (!value || typeof value !== "object") return false;
399
- return Object.values(value).some(containsUnsupportedYamlValue);
400
- }
401
-
402
- function parseYamlLine(line) {
403
- if (/^\t/u.test(line)) return { invalid: true };
404
- const indent = line.match(/^ */u)?.[0].length ?? 0;
405
- const content = stripYamlComment(line.slice(indent)).trim();
406
- if (content === "" || content === "---" || content === "..." || content.startsWith("#")) {
407
- return null;
408
- }
409
- if (content.startsWith("- ") || content === "-") return { indent, sequence: true };
410
- const separator = findTopLevelColon(content);
411
- if (separator <= 0) return null;
412
- const key = unquoteYamlScalar(content.slice(0, separator));
413
- if (!key) return null;
414
- const rawValue = content.slice(separator + 1).trim();
415
- const value = rawValue === "" ? "" : parseYamlValue(rawValue);
416
- if (value === null) return { invalid: true };
417
- return { indent, key, value };
418
- }
419
-
420
- function dependencySdkValue(entry) {
421
- if (!entry) return null;
422
- if (entry.value && typeof entry.value === "object" && !Array.isArray(entry.value)) {
423
- return entry.value.sdk === "flutter" ? "flutter" : null;
424
- }
425
- return entry.value === "" ? null : null;
426
- }
427
-
428
- function parseYamlLines(lines) {
429
- const parsedLines = [];
430
- let valid = true;
431
- for (const line of lines) {
432
- const parsed = parseYamlLine(line);
433
- if (parsed?.invalid) valid = false;
434
- parsedLines.push(parsed);
435
- }
436
- return { parsedLines, valid };
437
- }
438
-
439
- function findSectionIndexes(parsedLines, sectionName) {
440
- const sectionIndexes = [];
441
- for (let index = 0; index < parsedLines.length; index += 1) {
442
- const parsed = parsedLines[index];
443
- if (parsed?.indent === 0 && parsed.key === sectionName) sectionIndexes.push(index);
444
- }
445
- return sectionIndexes;
446
- }
447
-
448
- function dependencyEntriesFromInline(value) {
449
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
450
- return Object.fromEntries(Object.entries(value).map(([key, entryValue]) => [key, { value: entryValue }]));
451
- }
452
-
453
- function findSectionIndent(parsedLines, sectionIndex) {
454
- for (let index = sectionIndex + 1; index < parsedLines.length; index += 1) {
455
- const parsed = parsedLines[index];
456
- if (!parsed) continue;
457
- if (parsed.indent === 0) break;
458
- return parsed.indent;
459
- }
460
- return null;
461
- }
462
-
463
- function readNestedDependencyMap(parsedLines, entryIndex, parentIndent) {
464
- let nestedIndent = null;
465
- const nested = {};
466
- for (let index = entryIndex + 1; index < parsedLines.length; index += 1) {
467
- const parsed = parsedLines[index];
468
- if (!parsed) continue;
469
- if (parsed.invalid) return null;
470
- if (parsed.sequence) {
471
- if (parsed.indent > parentIndent) return null;
472
- break;
473
- }
474
- if (parsed.indent <= parentIndent) break;
475
- if (containsUnsupportedYamlValue(parsed.value)) return null;
476
- nestedIndent ??= parsed.indent;
477
- if (parsed.indent !== nestedIndent) continue;
478
- if (Object.prototype.hasOwnProperty.call(nested, parsed.key)) return null;
479
- nested[parsed.key] = parsed.value;
480
- }
481
- return nested;
482
- }
483
-
484
- function readBlockDependencyEntries(parsedLines, sectionIndex, sectionIndent) {
485
- const entries = {};
486
- for (let index = sectionIndex + 1; index < parsedLines.length; index += 1) {
487
- const parsed = parsedLines[index];
488
- if (!parsed) continue;
489
- if (parsed.invalid) return null;
490
- if (parsed.indent === 0) break;
491
- if (parsed.sequence || containsUnsupportedYamlValue(parsed.value)) return null;
492
- if (parsed.indent !== sectionIndent) continue;
493
- if (Object.prototype.hasOwnProperty.call(entries, parsed.key)) return null;
494
- const entry = { value: parsed.value };
495
- if (parsed.value === "") {
496
- const nested = readNestedDependencyMap(parsedLines, index, parsed.indent);
497
- if (nested === null) return null;
498
- entry.value = nested;
499
- }
500
- entries[parsed.key] = entry;
501
- }
502
- return entries;
503
- }
504
-
505
- function readDependencySection(lines, sectionName) {
506
- const { parsedLines, valid } = parseYamlLines(lines);
507
- const sectionIndexes = findSectionIndexes(parsedLines, sectionName);
508
- if (sectionIndexes.length > 1) return { present: true, valid: false, entries: {} };
509
- if (sectionIndexes.length === 0) return { present: false, valid, entries: {} };
510
-
511
- const sectionIndex = sectionIndexes[0];
512
- const section = parsedLines[sectionIndex];
513
- const entries = {};
514
- if (section.value !== "") {
515
- if (containsUnsupportedYamlValue(section.value)) {
516
- return { present: true, valid: false, entries: {} };
517
- }
518
- const inlineEntries = dependencyEntriesFromInline(section.value);
519
- if (inlineEntries === null) {
520
- return { present: true, valid: false, entries: {} };
521
- }
522
- return { present: true, valid, entries: inlineEntries };
523
- }
524
-
525
- const sectionIndent = findSectionIndent(parsedLines, sectionIndex);
526
- if (sectionIndent === null) return { present: true, valid, entries };
527
- const blockEntries = readBlockDependencyEntries(parsedLines, sectionIndex, sectionIndent);
528
- if (blockEntries === null) return { present: true, valid: false, entries: {} };
529
- return { present: true, valid, entries: blockEntries };
530
- }
531
-
532
- export function parsePubspec(text) {
533
- if (typeof text !== "string" || text.length > MAX_MANIFEST_BYTES || /\r(?!\n)/u.test(text)) {
534
- return { valid: false, primary: false, flutterTest: false, override: false };
535
- }
536
- const lines = text.replaceAll("\r\n", "\n").split("\n");
537
- const dependencies = readDependencySection(lines, "dependencies");
538
- const devDependencies = readDependencySection(lines, "dev_dependencies");
539
- const dependencyOverrides = readDependencySection(lines, "dependency_overrides");
540
- const valid = dependencies.valid && devDependencies.valid && dependencyOverrides.valid;
541
- const primary = valid && dependencySdkValue(dependencies.entries.flutter) === "flutter";
542
- const flutterTest = valid && dependencySdkValue(devDependencies.entries.flutter_test) === "flutter";
543
- const override = valid && dependencySdkValue(dependencyOverrides.entries.flutter) === "flutter";
544
- return {
545
- valid,
546
- primary,
547
- flutterTest,
548
- override,
549
- };
550
- }
551
-
552
231
  function invalidNodePackage() {
553
232
  return {
554
233
  valid: false,
@@ -790,206 +469,6 @@ export function parsePackageJson(text) {
790
469
  };
791
470
  }
792
471
 
793
- function invalidDotNetProject() {
794
- return {
795
- valid: false,
796
- sdkStyle: false,
797
- projectSdks: [],
798
- targetFrameworks: [],
799
- frameworkReferences: [],
800
- packageReferences: [],
801
- projectReferences: [],
802
- dotnet: false,
803
- aspnetcore: false,
804
- abp: false,
805
- };
806
- }
807
-
808
- function findXmlTagEnd(text, start) {
809
- let quote = null;
810
- for (let index = start; index < text.length; index += 1) {
811
- const character = text[index];
812
- if (quote) {
813
- if (character === quote) quote = null;
814
- } else if (character === "\"" || character === "'") {
815
- quote = character;
816
- } else if (character === ">") {
817
- return index;
818
- }
819
- }
820
- return -1;
821
- }
822
-
823
- function parseXmlAttributes(text) {
824
- const attributes = {};
825
- let index = 0;
826
- while (index < text.length) {
827
- while (index < text.length && /\s/u.test(text[index])) index += 1;
828
- if (index >= text.length) break;
829
- const name = text.slice(index).match(/^[A-Za-z_][A-Za-z0-9_.:-]*/u)?.[0];
830
- if (!name) return null;
831
- index += name.length;
832
- while (index < text.length && /\s/u.test(text[index])) index += 1;
833
- if (text[index] !== "=") return null;
834
- index += 1;
835
- while (index < text.length && /\s/u.test(text[index])) index += 1;
836
- const quote = text[index];
837
- if (quote !== "\"" && quote !== "'") return null;
838
- index += 1;
839
- const end = text.indexOf(quote, index);
840
- if (end < 0 || Object.prototype.hasOwnProperty.call(attributes, name)) return null;
841
- attributes[name] = text.slice(index, end);
842
- index = end + 1;
843
- }
844
- return attributes;
845
- }
846
-
847
- function appendXmlText(stack, value) {
848
- if (value === "") return true;
849
- const current = stack[stack.length - 1];
850
- if (!current) return value.trim() === "";
851
- current.textParts.push(value);
852
- return true;
853
- }
854
-
855
- function consumeXmlSpecialToken(text, tagStart, stack) {
856
- if (text.startsWith("<!--", tagStart)) {
857
- const end = text.indexOf("-->", tagStart + 4);
858
- return end < 0 ? { valid: false } : { valid: true, nextIndex: end + 3 };
859
- }
860
- if (text.startsWith("<![CDATA[", tagStart)) {
861
- const end = text.indexOf("]]>", tagStart + 9);
862
- if (end < 0 || stack.length === 0) return { valid: false };
863
- stack[stack.length - 1].textParts.push(text.slice(tagStart + 9, end));
864
- return { valid: true, nextIndex: end + 3 };
865
- }
866
- if (text.startsWith("<?", tagStart)) {
867
- const end = text.indexOf("?>", tagStart + 2);
868
- return end < 0 ? { valid: false } : { valid: true, nextIndex: end + 2 };
869
- }
870
- if (text.startsWith("<!", tagStart)) return { valid: false };
871
- return null;
872
- }
873
-
874
- function closeXmlNode(raw, state) {
875
- const closing = raw.slice(1).trim().match(/^([A-Za-z_][A-Za-z0-9_.:-]*)\s*$/u)?.[1];
876
- const open = state.stack.pop();
877
- if (!closing || !open || open.name !== closing) return false;
878
- open.text = open.textParts.join("");
879
- if (state.stack.length === 0) {
880
- if (state.rootClosed || open !== state.root) return false;
881
- state.rootClosed = true;
882
- }
883
- return true;
884
- }
885
-
886
- function openXmlNode(raw, state) {
887
- const selfClosing = /\/\s*$/u.test(raw);
888
- const body = selfClosing ? raw.replace(/\/\s*$/u, "").trimEnd() : raw;
889
- const name = body.match(/^([A-Za-z_][A-Za-z0-9_.:-]*)/u)?.[1];
890
- if (!name) return false;
891
- if (state.stack.length === 0 && (state.root || state.rootClosed)) return false;
892
- if (!state.root && state.expectedRoot && name !== state.expectedRoot) return false;
893
- const attributes = parseXmlAttributes(body.slice(name.length).trim());
894
- if (!attributes) return false;
895
- const node = { name, attributes, textParts: [], children: [], text: "" };
896
- state.nodes.push(node);
897
- if (state.stack.length > 0) state.stack[state.stack.length - 1].children.push(node);
898
- if (!state.root) state.root = node;
899
- if (!selfClosing) state.stack.push(node);
900
- else if (node === state.root) state.rootClosed = true;
901
- return true;
902
- }
903
-
904
- function consumeXmlTag(text, tagStart, state) {
905
- const tagEnd = findXmlTagEnd(text, tagStart + 1);
906
- if (tagEnd < 0) return null;
907
- const raw = text.slice(tagStart + 1, tagEnd).trim();
908
- if (raw === "") return null;
909
- const valid = raw.startsWith("/") ? closeXmlNode(raw, state) : openXmlNode(raw, state);
910
- return { valid, nextIndex: tagEnd + 1 };
911
- }
912
-
913
- function parseXmlStructure(text, expectedRoot = null) {
914
- if (typeof text !== "string" || text.length > MAX_MANIFEST_BYTES || /\r(?!\n)/u.test(text)) return null;
915
- const state = { nodes: [], stack: [], root: null, rootClosed: false, expectedRoot };
916
- let index = 0;
917
- while (index < text.length) {
918
- const tagStart = text.indexOf("<", index);
919
- if (tagStart < 0) break;
920
- if (!appendXmlText(state.stack, text.slice(index, tagStart))) return null;
921
- const special = consumeXmlSpecialToken(text, tagStart, state.stack);
922
- if (special) {
923
- if (!special.valid) return null;
924
- index = special.nextIndex;
925
- continue;
926
- }
927
- const tag = consumeXmlTag(text, tagStart, state);
928
- if (!tag?.valid) return null;
929
- index = tag.nextIndex;
930
- }
931
- if (!appendXmlText(state.stack, text.slice(index))) return null;
932
- if (!state.root || state.stack.length > 0 || !state.rootClosed) return null;
933
- return { root: state.root, nodes: state.nodes };
934
- }
935
-
936
- function normalizeSdkName(value) {
937
- return typeof value === "string" ? value.trim().split("/")[0] : "";
938
- }
939
-
940
- function xmlValues(nodes, name, attribute = "Include") {
941
- return uniqueSorted(nodes
942
- .filter((node) => node.name === name && typeof node.attributes?.[attribute] === "string")
943
- .map((node) => node.attributes[attribute].trim())
944
- .filter(Boolean));
945
- }
946
-
947
- function targetFrameworkValues(nodes) {
948
- return uniqueSorted(nodes
949
- .filter((node) => (node.name === "TargetFramework" || node.name === "TargetFrameworks")
950
- && node.children.length === 0
951
- && node.text.length <= MAX_XML_TEXT_LENGTH)
952
- .flatMap((node) => node.text.split(";"))
953
- .map((value) => value.trim())
954
- .filter(Boolean));
955
- }
956
-
957
- export function parseDotNetProject(text) {
958
- const invalid = invalidDotNetProject();
959
- if (typeof text !== "string" || text.length > MAX_MANIFEST_BYTES) return invalid;
960
- const document = parseXmlStructure(text, "Project");
961
- if (!document) return invalid;
962
-
963
- const sdkValues = [
964
- document.root.attributes.Sdk ?? "",
965
- ...document.nodes.filter((node) => node.name === "Sdk").map((node) => node.attributes.Name ?? ""),
966
- ];
967
- const projectSdks = uniqueSorted(sdkValues
968
- .flatMap((value) => value.split(";"))
969
- .map(normalizeSdkName)
970
- .filter(Boolean));
971
- const recognizedSdks = projectSdks.filter((sdk) => DOTNET_SDKS.has(sdk));
972
- const frameworkReferences = xmlValues(document.nodes, "FrameworkReference");
973
- const packageReferences = xmlValues(document.nodes, "PackageReference");
974
- const projectReferences = xmlValues(document.nodes, "ProjectReference");
975
- const dotnet = recognizedSdks.length > 0;
976
- const aspnetcore = dotnet && (recognizedSdks.some((sdk) => ASPNETCORE_SDKS.has(sdk))
977
- || frameworkReferences.some((reference) => reference.toLowerCase() === "microsoft.aspnetcore.app"));
978
- const abp = dotnet && packageReferences.some((reference) => reference.toLowerCase().startsWith("volo.abp."));
979
- return {
980
- valid: true,
981
- sdkStyle: dotnet,
982
- projectSdks,
983
- targetFrameworks: targetFrameworkValues(document.nodes),
984
- frameworkReferences,
985
- packageReferences,
986
- projectReferences,
987
- dotnet,
988
- aspnetcore,
989
- abp,
990
- };
991
- }
992
-
993
472
  function createTraversalBudget(limits = {}) {
994
473
  const positiveLimit = (value, fallback) => Number.isInteger(value) && value > 0 ? value : fallback;
995
474
  return {
@@ -0,0 +1,124 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { promisify } from "node:util";
7
+
8
+ import { syncError } from "./snapshot.js";
9
+
10
+ // Cloud-sync transport and local bookkeeping. The bearer token and passphrase
11
+ // come only from the environment and are never written anywhere. The last
12
+ // remote ETag is kept per project outside the repository, under the user's
13
+ // config directory, so sync never adds files to the working tree.
14
+
15
+ export const DEFAULT_SYNC_REMOTE = "https://forgeloop.monster/api/sync";
16
+ const OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/u;
17
+ const NAME = /^[A-Za-z0-9._-]{1,100}$/u;
18
+ const REQUEST_TIMEOUT_MS = 60_000;
19
+
20
+ // The hosting edge may weaken a validator (W/"x") for the same version the
21
+ // store reports as "x"; sync always stores and sends the strong form.
22
+ export function strongEtag(value) {
23
+ return typeof value === "string" && value ? value.replace(/^W\//u, "") : null;
24
+ }
25
+
26
+ export function normalizeRepository(value) {
27
+ const [owner, name, extra] = String(value ?? "").split("/");
28
+ if (extra !== undefined || !OWNER.test(owner ?? "") || !NAME.test(name ?? "") || name === "." || name === "..") return null;
29
+ return `${owner}/${name}`.toLowerCase();
30
+ }
31
+
32
+ export function repositoryFromRemoteUrl(url) {
33
+ const match = /github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/u.exec(String(url ?? "").trim());
34
+ return match ? normalizeRepository(`${match[1]}/${match[2]}`) : null;
35
+ }
36
+
37
+ export async function resolveRepository(target, explicit) {
38
+ if (explicit) {
39
+ const repository = normalizeRepository(explicit);
40
+ if (!repository) throw syncError("E_SYNC_CONFIG", "--repo must be owner/name");
41
+ return repository;
42
+ }
43
+ try {
44
+ const { stdout } = await promisify(execFile)("git", ["-C", target, "config", "--get", "remote.origin.url"], { timeout: 10_000 });
45
+ const repository = repositoryFromRemoteUrl(stdout);
46
+ if (repository) return repository;
47
+ } catch {
48
+ // Fall through to the explicit-repository error.
49
+ }
50
+ throw syncError("E_SYNC_CONFIG", "Could not derive owner/name from the git origin; pass --repo owner/name");
51
+ }
52
+
53
+ export function resolveRemote(value) {
54
+ let url;
55
+ try {
56
+ url = new URL(value || DEFAULT_SYNC_REMOTE);
57
+ } catch {
58
+ throw syncError("E_SYNC_CONFIG", "--remote must be a URL");
59
+ }
60
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
61
+ if (url.protocol !== "https:" && !(local && url.protocol === "http:")) throw syncError("E_SYNC_CONFIG", "--remote must use https (http is allowed only for localhost)");
62
+ if (url.username || url.password || url.search || url.hash) throw syncError("E_SYNC_CONFIG", "--remote must not contain credentials, a query or a fragment");
63
+ return url.toString();
64
+ }
65
+
66
+ export function readSyncCredentials(env = process.env) {
67
+ const bearer = env.FORGELOOP_SYNC_TOKEN ?? "";
68
+ if (!/^[A-Za-z0-9._~+/-]{32,512}$/u.test(bearer)) throw syncError("E_SYNC_CONFIG", "FORGELOOP_SYNC_TOKEN must be set to the sync token (32 or more URL-safe characters)");
69
+ return { token: bearer, passphrase: env.FORGELOOP_SYNC_KEY ?? "" };
70
+ }
71
+
72
+ export async function syncRequest({ remote, repository, token, method, body, headers = {}, fetchImpl = fetch }) {
73
+ const url = new URL(remote);
74
+ url.searchParams.set("repo", repository);
75
+ let response;
76
+ try {
77
+ response = await fetchImpl(url.toString(), {
78
+ method,
79
+ headers: { authorization: `Bearer ${token}`, accept: "application/json", ...headers, ...(body ? { "content-type": "application/json" } : {}) },
80
+ ...(body ? { body } : {}),
81
+ signal: globalThis.AbortSignal.timeout(REQUEST_TIMEOUT_MS),
82
+ });
83
+ } catch (error) {
84
+ throw syncError("E_SYNC_REMOTE", `Sync remote unreachable: ${error.message}`);
85
+ }
86
+ return response;
87
+ }
88
+
89
+ export async function remoteError(response) {
90
+ const detail = await response.json().catch(() => ({}));
91
+ const message = typeof detail?.error === "string" ? detail.error : `HTTP ${response.status}`;
92
+ if (response.status === 412) return syncError("E_SYNC_CONFLICT", `${message}. Run forgeloop sync-pull first.`);
93
+ if (response.status === 401 || response.status === 403) return syncError("E_SYNC_UNAUTHORIZED", message);
94
+ if (response.status === 413) return syncError("E_SYNC_TOO_LARGE", message);
95
+ return syncError("E_SYNC_REMOTE", `Sync remote refused the request: ${message}`);
96
+ }
97
+
98
+ function stateDirectory(env = process.env) {
99
+ const base = env.FORGELOOP_SYNC_STATE_DIR
100
+ || (env.XDG_CONFIG_HOME ? path.join(env.XDG_CONFIG_HOME, "forgeloop") : path.join(os.homedir(), ".config", "forgeloop"));
101
+ return path.join(base, "sync");
102
+ }
103
+
104
+ function stateFile(target, env) {
105
+ const key = createHash("sha256").update(path.resolve(target)).digest("hex").slice(0, 32);
106
+ return path.join(stateDirectory(env), `${key}.json`);
107
+ }
108
+
109
+ export async function readSyncState(target, { remote, repository, env = process.env } = {}) {
110
+ try {
111
+ const state = JSON.parse(await readFile(stateFile(target, env), "utf8"));
112
+ return state.remote === remote && state.repository === repository && typeof state.etag === "string" ? state : null;
113
+ } catch {
114
+ return null;
115
+ }
116
+ }
117
+
118
+ export async function writeSyncState(target, state, { env = process.env } = {}) {
119
+ const file = stateFile(target, env);
120
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
121
+ const temporary = `${file}.${process.pid}.tmp`;
122
+ await writeFile(temporary, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
123
+ await rename(temporary, file);
124
+ }