minimal-forge-work-pack-sync 0.1.18 → 0.1.20

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 (2) hide show
  1. package/dist/index.js +278 -177
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -7367,77 +7367,6 @@ var require_dist = __commonJS({
7367
7367
  }
7368
7368
  });
7369
7369
 
7370
- // packages/cli/src/workPackSyncPlugin.ts
7371
- import { createHash as createHash5 } from "node:crypto";
7372
- import { pathToFileURL } from "node:url";
7373
-
7374
- // packages/cli/src/skillUsageReporter.ts
7375
- function skillUsageReporter(origin, credentialId, send) {
7376
- const symbol2 = /* @__PURE__ */ Symbol.for("minimal-forge.skill-usage.v1");
7377
- const shared = globalThis;
7378
- const origins = shared[symbol2] ??= /* @__PURE__ */ new Map();
7379
- let owner = origins.get(origin);
7380
- if (!owner) {
7381
- owner = { seen: /* @__PURE__ */ new Map(), reporters: /* @__PURE__ */ new Map() };
7382
- origins.set(origin, owner);
7383
- }
7384
- const seen = owner.seen;
7385
- let state = owner.reporters.get(credentialId);
7386
- if (!state) {
7387
- state = { pending: [], sending: false, nextSend: 0 };
7388
- owner.reporters.set(credentialId, state);
7389
- }
7390
- const reporter = state;
7391
- function schedule() {
7392
- if (reporter.timer || reporter.sending || !reporter.pending.length) return;
7393
- reporter.timer = setTimeout(() => {
7394
- reporter.timer = void 0;
7395
- void flush();
7396
- }, Math.max(1e3, reporter.nextSend - Date.now()));
7397
- reporter.timer.unref?.();
7398
- }
7399
- async function flush() {
7400
- if (reporter.sending || !reporter.pending.length) return;
7401
- reporter.sending = true;
7402
- reporter.nextSend = Date.now() + 12e4;
7403
- const batch = reporter.pending.splice(0, 100);
7404
- try {
7405
- const response = await send(batch);
7406
- if (response.status === 429) {
7407
- reporter.pending.unshift(...batch);
7408
- if (reporter.pending.length > 1e3) {
7409
- reporter.pending.length = 1e3;
7410
- console.error("[Forge evidence] Local usage buffer full after rate rejection");
7411
- }
7412
- const retry = Number(response.headers.get("retry-after"));
7413
- reporter.nextSend = Date.now() + Math.max(12e4, Number.isFinite(retry) ? retry * 1e3 : 0);
7414
- } else if (!response.ok) console.error(`[Forge evidence] Upload rejected (HTTP ${response.status})`);
7415
- } catch {
7416
- console.error("[Forge evidence] Upload unconfirmed; batch not retried");
7417
- } finally {
7418
- reporter.sending = false;
7419
- schedule();
7420
- }
7421
- }
7422
- return (sessionID, callID, slug) => {
7423
- if (!sessionID || !callID) return;
7424
- const now = Date.now();
7425
- for (const [key2, at2] of seen) if (now - at2 > 24 * 60 * 6e4) seen.delete(key2);
7426
- const key = JSON.stringify([sessionID, callID]);
7427
- if (seen.has(key)) return;
7428
- if (seen.size >= 2e4 || reporter.pending.length >= 1e3) {
7429
- console.error("[Forge evidence] Local usage buffer full");
7430
- return;
7431
- }
7432
- seen.set(key, now);
7433
- const day = new Date(now).toISOString().slice(0, 10);
7434
- const existing = reporter.pending.find((event) => event.slug === slug && event.day === day && event.count < 100);
7435
- if (existing) existing.count++;
7436
- else reporter.pending.push({ kind: "work_pack_invocation", slug, day, count: 1 });
7437
- schedule();
7438
- };
7439
- }
7440
-
7441
7370
  // packages/shared/src/contracts/models.ts
7442
7371
  var BUILT_IN_OPENROUTER_MODELS = [
7443
7372
  {
@@ -7594,6 +7523,11 @@ function openRouterReasoningVariants(efforts) {
7594
7523
  return Object.fromEntries(efforts.map((effort) => [effort, { reasoning: { effort } }]));
7595
7524
  }
7596
7525
 
7526
+ // packages/shared/src/runtimeObservation.ts
7527
+ function runtimeVersion(value) {
7528
+ return typeof value === "string" && /^[0-9][A-Za-z0-9.+_-]{0,63}$/.test(value) ? value : void 0;
7529
+ }
7530
+
7597
7531
  // packages/shared/src/contracts/debugTrace.ts
7598
7532
  var DEFAULT_DEBUG_TRACE_LIMITS = {
7599
7533
  eventEnvelopeBytes: 256 * 1024,
@@ -7614,7 +7548,7 @@ var DEFAULT_DEBUG_TRACE_LIMITS = {
7614
7548
  };
7615
7549
 
7616
7550
  // packages/shared/src/contracts/settings.ts
7617
- var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.18";
7551
+ var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.20";
7618
7552
  var WORK_PACK_SYNC_PLUGIN_PACKAGE = `minimal-forge-work-pack-sync@${WORK_PACK_SYNC_PLUGIN_VERSION}`;
7619
7553
  var WORK_PACK_SYNC_PLUGIN_FILENAME = `minimal-forge-work-pack-sync-${WORK_PACK_SYNC_PLUGIN_VERSION}.tgz`;
7620
7554
  var FIRECRAWL_KEYLESS_MCP_NAME = "firecrawl";
@@ -7690,6 +7624,113 @@ function integrityKind(summary) {
7690
7624
  return "match";
7691
7625
  }
7692
7626
 
7627
+ // packages/cli/src/runtimeObservation.ts
7628
+ var UNKNOWN_RUNTIME = {
7629
+ opencode: { status: "unknown" },
7630
+ openwork: { status: "unknown" }
7631
+ };
7632
+ async function observeRuntime(input) {
7633
+ let timer;
7634
+ const controller = new AbortController();
7635
+ try {
7636
+ const url2 = input?.serverUrl;
7637
+ if (!(url2 instanceof URL) || !["http:", "https:"].includes(url2.protocol) || !["localhost", "127.0.0.1", "[::1]"].includes(url2.hostname) || url2.username || url2.password) return structuredClone(UNKNOWN_RUNTIME);
7638
+ const endpoint = new URL("/global/health", url2);
7639
+ const headers = {};
7640
+ if (process.env.OPENCODE_SERVER_PASSWORD) {
7641
+ headers.authorization = `Basic ${Buffer.from(`${process.env.OPENCODE_SERVER_USERNAME || "opencode"}:${process.env.OPENCODE_SERVER_PASSWORD}`).toString("base64")}`;
7642
+ }
7643
+ const probe = async () => {
7644
+ const response = await fetch(endpoint, { headers, signal: controller.signal, redirect: "error" });
7645
+ if (!response.ok) return structuredClone(UNKNOWN_RUNTIME);
7646
+ const body = await response.json();
7647
+ const version2 = runtimeVersion(body.version);
7648
+ return { openwork: { status: "unknown" }, opencode: body.healthy === true && version2 ? { status: "known", version: version2, source: "engine-health" } : { status: "unknown" } };
7649
+ };
7650
+ return await Promise.race([probe(), new Promise((resolve) => {
7651
+ timer = setTimeout(() => {
7652
+ controller.abort();
7653
+ resolve(structuredClone(UNKNOWN_RUNTIME));
7654
+ }, 500);
7655
+ })]);
7656
+ } catch {
7657
+ return structuredClone(UNKNOWN_RUNTIME);
7658
+ } finally {
7659
+ if (timer) clearTimeout(timer);
7660
+ }
7661
+ }
7662
+
7663
+ // packages/cli/src/workPackSyncPlugin.ts
7664
+ import { createHash as createHash5 } from "node:crypto";
7665
+ import { pathToFileURL } from "node:url";
7666
+
7667
+ // packages/cli/src/skillUsageReporter.ts
7668
+ function skillUsageReporter(origin, credentialId, send) {
7669
+ const symbol2 = /* @__PURE__ */ Symbol.for("minimal-forge.skill-usage.v1");
7670
+ const shared = globalThis;
7671
+ const origins = shared[symbol2] ??= /* @__PURE__ */ new Map();
7672
+ let owner = origins.get(origin);
7673
+ if (!owner) {
7674
+ owner = { seen: /* @__PURE__ */ new Map(), reporters: /* @__PURE__ */ new Map() };
7675
+ origins.set(origin, owner);
7676
+ }
7677
+ const seen = owner.seen;
7678
+ let state = owner.reporters.get(credentialId);
7679
+ if (!state) {
7680
+ state = { pending: [], sending: false, nextSend: 0 };
7681
+ owner.reporters.set(credentialId, state);
7682
+ }
7683
+ const reporter = state;
7684
+ function schedule() {
7685
+ if (reporter.timer || reporter.sending || !reporter.pending.length) return;
7686
+ reporter.timer = setTimeout(() => {
7687
+ reporter.timer = void 0;
7688
+ void flush();
7689
+ }, Math.max(1e3, reporter.nextSend - Date.now()));
7690
+ reporter.timer.unref?.();
7691
+ }
7692
+ async function flush() {
7693
+ if (reporter.sending || !reporter.pending.length) return;
7694
+ reporter.sending = true;
7695
+ reporter.nextSend = Date.now() + 12e4;
7696
+ const batch = reporter.pending.splice(0, 100);
7697
+ try {
7698
+ const response = await send(batch);
7699
+ if (response.status === 429) {
7700
+ reporter.pending.unshift(...batch);
7701
+ if (reporter.pending.length > 1e3) {
7702
+ reporter.pending.length = 1e3;
7703
+ console.error("[Forge evidence] Local usage buffer full after rate rejection");
7704
+ }
7705
+ const retry = Number(response.headers.get("retry-after"));
7706
+ reporter.nextSend = Date.now() + Math.max(12e4, Number.isFinite(retry) ? retry * 1e3 : 0);
7707
+ } else if (!response.ok) console.error(`[Forge evidence] Upload rejected (HTTP ${response.status})`);
7708
+ } catch {
7709
+ console.error("[Forge evidence] Upload unconfirmed; batch not retried");
7710
+ } finally {
7711
+ reporter.sending = false;
7712
+ schedule();
7713
+ }
7714
+ }
7715
+ return (sessionID, callID, slug) => {
7716
+ if (!sessionID || !callID) return;
7717
+ const now = Date.now();
7718
+ for (const [key2, at2] of seen) if (now - at2 > 24 * 60 * 6e4) seen.delete(key2);
7719
+ const key = JSON.stringify([sessionID, callID]);
7720
+ if (seen.has(key)) return;
7721
+ if (seen.size >= 2e4 || reporter.pending.length >= 1e3) {
7722
+ console.error("[Forge evidence] Local usage buffer full");
7723
+ return;
7724
+ }
7725
+ seen.set(key, now);
7726
+ const day = new Date(now).toISOString().slice(0, 10);
7727
+ const existing = reporter.pending.find((event) => event.slug === slug && event.day === day && event.count < 100);
7728
+ if (existing) existing.count++;
7729
+ else reporter.pending.push({ kind: "work_pack_invocation", slug, day, count: 1 });
7730
+ schedule();
7731
+ };
7732
+ }
7733
+
7693
7734
  // packages/cli/src/pluginWriter.ts
7694
7735
  var FORGE_PLUGIN_HEADER = "// Managed by Forge sync. Do not edit.";
7695
7736
  var FORGE_EVIDENCE_PLUGIN_FILENAME = "forge-evidence.js";
@@ -20330,7 +20371,7 @@ function resolveOpenCodeDir(home, platform, env, exists, pathApi) {
20330
20371
  // packages/cli/src/report.ts
20331
20372
  import os2 from "node:os";
20332
20373
  var AGENT_VERSION = "0.1.0";
20333
- async function reportFailure(credentials, kind, error45) {
20374
+ async function reportFailure(credentials, kind, error45, runtime = UNKNOWN_RUNTIME) {
20334
20375
  try {
20335
20376
  const message = error45 instanceof Error ? error45.message : String(error45);
20336
20377
  await fetch(`${credentials.forgeBaseUrl.replace(/\/$/, "")}/sync/report`, {
@@ -20344,6 +20385,7 @@ async function reportFailure(credentials, kind, error45) {
20344
20385
  body: JSON.stringify({
20345
20386
  kind,
20346
20387
  ok: false,
20388
+ ...runtime ? { runtime } : {},
20347
20389
  message
20348
20390
  }),
20349
20391
  signal: AbortSignal.timeout(3e3)
@@ -20352,7 +20394,7 @@ async function reportFailure(credentials, kind, error45) {
20352
20394
  console.error("[Forge] Failed to report failure to Forge server:", error46 instanceof Error ? error46.message : String(error46));
20353
20395
  }
20354
20396
  }
20355
- async function reportWorkPackObservations(credentials, kind, workPacks) {
20397
+ async function reportWorkPackObservations(credentials, kind, workPacks, runtime = UNKNOWN_RUNTIME) {
20356
20398
  try {
20357
20399
  await fetch(`${credentials.forgeBaseUrl.replace(/\/$/, "")}/sync/report`, {
20358
20400
  method: "POST",
@@ -20362,7 +20404,7 @@ async function reportWorkPackObservations(credentials, kind, workPacks) {
20362
20404
  "x-forge-hostname": os2.hostname(),
20363
20405
  "x-forge-agent-version": AGENT_VERSION
20364
20406
  },
20365
- body: JSON.stringify({ kind, ok: true, workPacks }),
20407
+ body: JSON.stringify({ kind, ok: true, workPacks, ...runtime ? { runtime } : {} }),
20366
20408
  signal: AbortSignal.timeout(3e3)
20367
20409
  });
20368
20410
  } catch (error45) {
@@ -20398,11 +20440,11 @@ async function checkWorkPackInstalledState(input) {
20398
20440
  if (!state) return "missing";
20399
20441
  return await matchesInstalledState(input, state) ? "match" : "changed";
20400
20442
  }
20401
- async function checkWorkPackTreeState(packDir) {
20443
+ async function checkWorkPackTreeState(packDir, allowAdditional = false) {
20402
20444
  const state = await readInstalledState(packDir);
20403
20445
  if (!state) return "missing";
20404
20446
  const tree = await digestPackTree(packDir).catch(() => void 0);
20405
- return tree && sameTree(tree, state) ? "match" : "changed";
20447
+ return tree && (allowAdditional ? containsOriginalTree(tree, state) : sameTree(tree, state)) ? "match" : "changed";
20406
20448
  }
20407
20449
  async function adoptWorkPackInstalledState(input) {
20408
20450
  const state = await readInstalledState(input.expectedPackDir);
@@ -20410,34 +20452,6 @@ async function adoptWorkPackInstalledState(input) {
20410
20452
  await writeJsonAtomic(path3.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
20411
20453
  return checkWorkPackInstalledState(input).then((result) => result === "match");
20412
20454
  }
20413
- async function adoptVerifiedWorkPackState(input) {
20414
- const tree = await digestPackTree(input.packDir);
20415
- if (!tree) return false;
20416
- const projections = async (kind, directory) => {
20417
- const prefix = `${kind}/`;
20418
- const expected = tree.files.filter((file2) => file2.path.startsWith(prefix) && !file2.path.slice(prefix.length).includes("/") && file2.path.endsWith(".md") && !file2.path.slice(prefix.length).startsWith("._"));
20419
- const result = [];
20420
- for (const file2 of expected) {
20421
- const filename = file2.path.slice(prefix.length);
20422
- const absolute = path3.join(directory, filename);
20423
- const info = await lstat2(absolute);
20424
- if (!info.isFile() || info.isSymbolicLink()) throw new Error("Unsafe projection");
20425
- result.push({ filename, sha256: digest(await readFile2(absolute)) });
20426
- }
20427
- return result.sort((a, b2) => a.filename.localeCompare(b2.filename));
20428
- };
20429
- const state = {
20430
- schemaVersion: 1,
20431
- version: input.version,
20432
- ...tree,
20433
- agents: await projections("agents", input.agentsDir),
20434
- commands: await projections("commands", input.commandsDir)
20435
- };
20436
- if (digest(Buffer.from(canonicalWorkPackState(state))) !== input.fingerprint) return false;
20437
- if (!await matchesInstalledState(input, state)) return false;
20438
- await writeJsonAtomic(path3.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
20439
- return await checkWorkPackInstalledState(input) === "match";
20440
- }
20441
20455
  async function readInstalledState(packDir) {
20442
20456
  const info = await lstat2(path3.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME)).catch(() => void 0);
20443
20457
  if (!info?.isFile() || info.isSymbolicLink() || info.size > 1024 * 1024) return void 0;
@@ -20458,6 +20472,8 @@ async function digestPackTree(root) {
20458
20472
  if (!prefix && entry.name === WORK_PACK_LOCAL_STATE_FILENAME) continue;
20459
20473
  const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
20460
20474
  const absolute = path3.join(directory, entry.name);
20475
+ const info = await lstat2(absolute);
20476
+ if (info.isSymbolicLink() || info.isFile() && info.nlink > 1) return false;
20461
20477
  if (entry.isDirectory()) {
20462
20478
  directories.push(relative);
20463
20479
  if (!await visit(absolute, relative)) return false;
@@ -20485,7 +20501,7 @@ async function projectionsMatch(directory, expected) {
20485
20501
  }
20486
20502
  async function matchesInstalledState(input, state) {
20487
20503
  const tree = await digestPackTree(input.packDir).catch(() => void 0);
20488
- if (!tree || !sameTree(tree, state)) return false;
20504
+ if (!tree || !(input.allowAdditional ? containsOriginalTree(tree, state) : sameTree(tree, state))) return false;
20489
20505
  if (!await projectionsMatch(input.agentsDir, state.agents)) return false;
20490
20506
  return projectionsMatch(input.commandsDir, state.commands);
20491
20507
  }
@@ -20507,6 +20523,24 @@ async function writeJsonAtomic(filePath, value) {
20507
20523
  `);
20508
20524
  await rename2(tempPath, filePath);
20509
20525
  }
20526
+ async function adoptWorkPackFileManifest(input) {
20527
+ if (!await matchesInstalledState({ ...input, allowAdditional: true }, input.expected)) return false;
20528
+ await writeJsonAtomic(path3.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), input.expected);
20529
+ return true;
20530
+ }
20531
+ function containsOriginalTree(actual, expected) {
20532
+ const files = new Map(actual.files.map((file2) => [file2.path, file2.sha256]));
20533
+ const directories = new Set(actual.directories);
20534
+ return expected.files.every((file2) => files.get(file2.path) === file2.sha256) && expected.directories.every((directory) => directories.has(directory));
20535
+ }
20536
+ async function workPackExtrasTree(packDir) {
20537
+ const state = await readInstalledState(packDir);
20538
+ const tree = await digestPackTree(packDir);
20539
+ if (!state || !tree) return void 0;
20540
+ const files = new Set(state.files.map((file2) => file2.path));
20541
+ const directories = new Set(state.directories);
20542
+ return { files: tree.files.filter((file2) => !files.has(file2.path)), directories: tree.directories.filter((dir) => !directories.has(dir)) };
20543
+ }
20510
20544
 
20511
20545
  // packages/cli/src/workPackIntegrity.ts
20512
20546
  var MAX_ENTRIES = 1e4;
@@ -20683,6 +20717,41 @@ async function regularFileDigest(filePath, budget) {
20683
20717
  return void 0;
20684
20718
  }
20685
20719
  }
20720
+ async function fetchWorkPackFileManifest(credentials, slug, version2) {
20721
+ assertSlug(slug);
20722
+ const origin = new URL(credentials.forgeBaseUrl);
20723
+ if (origin.username || origin.password || origin.protocol !== "https:" && !(origin.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(origin.hostname))) return void 0;
20724
+ if (!version2 || Buffer.byteLength(version2) > 4096) return void 0;
20725
+ const url2 = new URL(`/sync/skills/${encodeURIComponent(slug)}/baseline/${encodeURIComponent(version2)}?details=1`, origin);
20726
+ try {
20727
+ const response = await fetch(url2, { headers: { authorization: `Bearer ${credentials.forgeApiKey}` }, redirect: "manual", signal: AbortSignal.timeout(1e4) });
20728
+ if (!response.ok || response.redirected || response.url && new URL(response.url).origin !== origin.origin) return void 0;
20729
+ const reader = response.body?.getReader();
20730
+ if (!reader) return void 0;
20731
+ const chunks = [];
20732
+ let size = 0;
20733
+ try {
20734
+ while (true) {
20735
+ const { done, value } = await reader.read();
20736
+ if (done) break;
20737
+ size += value.byteLength;
20738
+ if (size > 1024 * 1024) {
20739
+ await reader.cancel();
20740
+ return void 0;
20741
+ }
20742
+ chunks.push(value);
20743
+ }
20744
+ } finally {
20745
+ reader.releaseLock();
20746
+ }
20747
+ const payload = JSON.parse(Buffer.concat(chunks).toString("utf8"));
20748
+ const manifest = parseWorkPackFileManifest(payload.manifest);
20749
+ if (!manifest || manifest.version !== version2 || typeof payload.fingerprint !== "string" || createHash2("sha256").update(canonicalWorkPackState(manifest)).digest("hex") !== payload.fingerprint) return void 0;
20750
+ return manifest;
20751
+ } catch {
20752
+ return void 0;
20753
+ }
20754
+ }
20686
20755
  function assertSlug(slug) {
20687
20756
  if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug) || slug.length > 64) throw new Error("Identificador de skill inv\xE1lido");
20688
20757
  }
@@ -23807,7 +23876,7 @@ async function runOperation(operation, operate) {
23807
23876
  code: stableCode(result.code),
23808
23877
  ...result.integrity ? { integrity: result.integrity } : {},
23809
23878
  ...result.projectionConflict ? { projectionConflict: result.projectionConflict } : {},
23810
- message: `O pacote "${operation.pack.slug}" falhou, mas o estado anterior foi restaurado exatamente. Corrija a causa indicada e volte a sincronizar.`
23879
+ message: result.message ?? `O pacote "${operation.pack.slug}" falhou, mas o estado anterior foi restaurado exatamente. Corrija a causa indicada e volte a sincronizar.`
23811
23880
  };
23812
23881
  }
23813
23882
  if (!validSuccessFor(operation.action, result.status)) return uncertainOutcome(operation, "invalid-callback-result");
@@ -23954,7 +24023,7 @@ async function collectWorkPackObservations(paths, reconciliation) {
23954
24023
  return [...observations.values()].sort((a, b2) => a.slug.localeCompare(b2.slug));
23955
24024
  }
23956
24025
  async function enrichIntegrityFailure(paths, operation, result) {
23957
- if (result.status !== "failed" || !["local-edits-preserved", "local-baseline-missing"].includes(result.code)) return result;
24026
+ if (result.status !== "failed" || result.integrity || !["local-edits-preserved", "local-baseline-missing"].includes(result.code)) return result;
23958
24027
  try {
23959
24028
  const { summary } = await inspectWorkPackIntegrity({ paths, slug: operation.pack.slug });
23960
24029
  if (summary.kind === "match") return result;
@@ -24006,24 +24075,39 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
24006
24075
  try {
24007
24076
  const currentVersion = await readFile3(path5.join(target, ".forge-version"), "utf8").catch(() => "");
24008
24077
  const sameVersion = currentVersion.trim() === skill.version;
24009
- if (sameVersion) {
24078
+ if (ownership === "managed") {
24010
24079
  let localState = await checkWorkPackInstalledState({
24011
24080
  packDir: target,
24012
24081
  agentsDir: paths.agentsDir,
24013
- commandsDir: paths.commandsDir
24082
+ commandsDir: paths.commandsDir,
24083
+ allowAdditional: true
24014
24084
  });
24015
24085
  if (localState === "missing") {
24016
- const candidateArchive = await downloadSkill(credentials, skill.url);
24017
- const candidateSha256 = createHash3("sha256").update(candidateArchive).digest("hex");
24018
- if (candidateSha256 !== skill.sha256) {
24019
- return { status: "failed", restoration: "exact", code: "local-baseline-missing" };
24020
- }
24021
- localState = await adoptLegacyWorkPackState(paths, skill.slug, skill.version, candidateArchive, approvedModelIds) ? "match" : "changed";
24022
- }
24023
- if (localState !== "match") {
24024
- return { status: "failed", restoration: "exact", code: "local-edits-preserved" };
24025
- }
24026
- if (!await workPackNeedsModelNormalization(target, approvedModelIds, skill.slug)) {
24086
+ const expected = await fetchWorkPackFileManifest(credentials, skill.slug, currentVersion.trim());
24087
+ if (expected) {
24088
+ const diagnosis = await inspectWorkPackIntegrity({ paths, slug: skill.slug, expected });
24089
+ if (diagnosis.summary.modified || diagnosis.summary.missing || diagnosis.summary.unsafe || diagnosis.summary.unreadable || diagnosis.summary.truncated) {
24090
+ return { status: "failed", restoration: "exact", code: "local-edits-preserved", integrity: diagnosis.summary };
24091
+ }
24092
+ localState = await adoptWorkPackFileManifest({
24093
+ packDir: target,
24094
+ agentsDir: paths.agentsDir,
24095
+ commandsDir: paths.commandsDir,
24096
+ expected
24097
+ }) ? "match" : "changed";
24098
+ } else if (sameVersion) {
24099
+ const candidateArchive = await downloadSkill(credentials, skill.url);
24100
+ if (createHash3("sha256").update(candidateArchive).digest("hex") !== skill.sha256)
24101
+ return { status: "failed", restoration: "exact", code: "local-baseline-missing" };
24102
+ localState = await adoptLegacyWorkPackState(paths, skill.slug, skill.version, candidateArchive, approvedModelIds) ? "match" : "changed";
24103
+ }
24104
+ }
24105
+ if (localState !== "match") return {
24106
+ status: "failed",
24107
+ restoration: "exact",
24108
+ code: localState === "missing" ? "local-baseline-missing" : "local-edits-preserved"
24109
+ };
24110
+ if (sameVersion && !await workPackNeedsModelNormalization(target, approvedModelIds, skill.slug)) {
24027
24111
  return cleanupPendingSlugs.has(skill.slug) ? {
24028
24112
  status: "unchanged",
24029
24113
  warningCode: "cleanup-pending",
@@ -24031,36 +24115,6 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
24031
24115
  } : { status: "unchanged" };
24032
24116
  }
24033
24117
  }
24034
- if (ownership === "managed" && !sameVersion) {
24035
- let localState = await checkWorkPackInstalledState({
24036
- packDir: target,
24037
- agentsDir: paths.agentsDir,
24038
- commandsDir: paths.commandsDir
24039
- });
24040
- if (localState === "missing") {
24041
- try {
24042
- const baselineUrl = `/sync/skills/${encodeURIComponent(skill.slug)}/baseline/${encodeURIComponent(currentVersion.trim())}`;
24043
- const baseline = JSON.parse(new TextDecoder().decode(await downloadSkill(credentials, baselineUrl)));
24044
- if (typeof baseline.fingerprint === "string" && /^[a-f0-9]{64}$/.test(baseline.fingerprint)) {
24045
- localState = await adoptVerifiedWorkPackState({
24046
- packDir: target,
24047
- agentsDir: paths.agentsDir,
24048
- commandsDir: paths.commandsDir,
24049
- version: currentVersion.trim(),
24050
- fingerprint: baseline.fingerprint
24051
- }) ? "match" : "missing";
24052
- }
24053
- } catch {
24054
- }
24055
- }
24056
- if (localState !== "match") {
24057
- return {
24058
- status: "failed",
24059
- restoration: "exact",
24060
- code: localState === "missing" ? "local-baseline-missing" : "local-edits-preserved"
24061
- };
24062
- }
24063
- }
24064
24118
  previousManagedPaths = await managedWorkPackPaths(paths, target);
24065
24119
  archive = await downloadSkill(credentials, skill.url);
24066
24120
  const sha256 = createHash3("sha256").update(archive).digest("hex");
@@ -24101,7 +24155,7 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
24101
24155
  }
24102
24156
  function exactPackFailure(error45) {
24103
24157
  if (error45 instanceof WorkPackLocalEditsError) {
24104
- return { status: "failed", restoration: "exact", code: error45.code };
24158
+ return { status: "failed", restoration: "exact", code: error45.code, message: error45.message };
24105
24159
  }
24106
24160
  if (error45 instanceof WorkPackProjectionConflictError) {
24107
24161
  return {
@@ -24174,21 +24228,24 @@ var WorkPackLocalEditsError = class extends Error {
24174
24228
  }
24175
24229
  code;
24176
24230
  };
24177
- async function assertWorkPackUnchangedAtBoundary(paths, target) {
24231
+ async function assertWorkPackUnchangedAtBoundary(paths, target, snapshot) {
24178
24232
  const ownership = await workPackOwnership(target);
24179
24233
  if (ownership === "absent") return;
24180
24234
  if (ownership === "foreign") throw foreignWorkPackError(path5.basename(target));
24181
24235
  const localState = await checkWorkPackInstalledState({
24182
24236
  packDir: target,
24183
24237
  agentsDir: paths.agentsDir,
24184
- commandsDir: paths.commandsDir
24238
+ commandsDir: paths.commandsDir,
24239
+ allowAdditional: snapshot !== void 0
24185
24240
  });
24186
24241
  if (localState !== "match") {
24187
24242
  throw new WorkPackLocalEditsError(localState === "missing" ? "local-baseline-missing" : "local-edits-preserved");
24188
24243
  }
24244
+ if (snapshot) await assertWorkPackTreeUnchangedAtBoundary(target, snapshot);
24189
24245
  }
24190
- async function assertWorkPackTreeUnchangedAtBoundary(target) {
24191
- const localState = await checkWorkPackTreeState(target);
24246
+ async function assertWorkPackTreeUnchangedAtBoundary(target, snapshot) {
24247
+ const actual = snapshot ? await digestPackTree(target) : void 0;
24248
+ const localState = snapshot ? actual && sameTree(actual, snapshot) ? "match" : "changed" : await checkWorkPackTreeState(target);
24192
24249
  if (localState !== "match") {
24193
24250
  throw new WorkPackLocalEditsError(localState === "missing" ? "local-baseline-missing" : "local-edits-preserved");
24194
24251
  }
@@ -24200,6 +24257,31 @@ function skillSlugFromUrl(value) {
24200
24257
  return value;
24201
24258
  }
24202
24259
  }
24260
+ async function preserveWorkPackExtras(target, nextPath, actual) {
24261
+ const expected = await readInstalledState(target);
24262
+ if (!expected) throw new WorkPackLocalEditsError("local-baseline-missing");
24263
+ const ownedFiles = new Set(expected.files.map((file2) => file2.path));
24264
+ const ownedDirectories = new Set(expected.directories);
24265
+ const next = await digestPackTree(nextPath);
24266
+ if (!next) throw new WorkPackLocalEditsError("local-edits-preserved");
24267
+ const newPaths = /* @__PURE__ */ new Set([...next.files.map((file2) => file2.path), ...next.directories]);
24268
+ const extras = actual.files.filter((file2) => !ownedFiles.has(file2.path));
24269
+ const directories = actual.directories.filter((directory) => !ownedDirectories.has(directory));
24270
+ for (const name of [...extras.map((file2) => file2.path), ...directories]) {
24271
+ if (newPaths.has(name)) throw new WorkPackLocalEditsError(
24272
+ "local-addition-collision",
24273
+ `A nova vers\xE3o usa o caminho adicional "${name}". O pacote anterior e os ficheiros locais foram preservados.`
24274
+ );
24275
+ }
24276
+ for (const directory of directories) await mkdir2(path5.join(nextPath, directory), { recursive: true });
24277
+ for (const file2 of extras) {
24278
+ const destination = path5.join(nextPath, file2.path);
24279
+ await mkdir2(path5.dirname(destination), { recursive: true });
24280
+ await cp(path5.join(target, file2.path), destination, { errorOnExist: true, force: false });
24281
+ if (createHash3("sha256").update(await readFile3(destination)).digest("hex") !== file2.sha256)
24282
+ throw new WorkPackLocalEditsError("local-edits-preserved");
24283
+ }
24284
+ }
24203
24285
  async function installSkillArchive(paths, slug, version2, archive, options = {}) {
24204
24286
  const tempRoot = await mkdtemp(path5.join(os4.tmpdir(), `forge-${slug}-`));
24205
24287
  const archivePath = path5.join(tempRoot, `${slug}.tar`);
@@ -24271,9 +24353,18 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
24271
24353
  ])
24272
24354
  );
24273
24355
  const previousManagedPaths = await managedWorkPackPaths(paths, target);
24356
+ let originalTree;
24357
+ let installedTree;
24274
24358
  try {
24359
+ if (await workPackOwnership(target) === "managed") {
24360
+ originalTree = await digestPackTree(target);
24361
+ if (!originalTree) throw new WorkPackLocalEditsError("local-edits-preserved");
24362
+ await preserveWorkPackExtras(target, nextPath, originalTree);
24363
+ }
24364
+ installedTree = await digestPackTree(nextPath);
24365
+ if (!installedTree) throw new WorkPackLocalEditsError("local-edits-preserved");
24275
24366
  if (previousManagedPaths.length > 0) await options.beforeManagedPathsRemoved?.(previousManagedPaths);
24276
- await assertWorkPackUnchangedAtBoundary(paths, target);
24367
+ await assertWorkPackUnchangedAtBoundary(paths, target, originalTree);
24277
24368
  } catch (error45) {
24278
24369
  await rm(tempRoot, { recursive: true, force: true });
24279
24370
  throw error45;
@@ -24297,7 +24388,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
24297
24388
  }
24298
24389
  if (targetBackedUp) {
24299
24390
  await options.installWorkPackBoundary?.("after-backup");
24300
- await assertWorkPackUnchangedAtBoundary(paths, backup);
24391
+ await assertWorkPackUnchangedAtBoundary(paths, backup, originalTree);
24301
24392
  }
24302
24393
  await rename3(nextPath, target);
24303
24394
  targetInstalled = true;
@@ -24331,12 +24422,13 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
24331
24422
  await writeProjection(filePath, command.content);
24332
24423
  }
24333
24424
  }
24334
- if (targetBackedUp) await assertWorkPackTreeUnchangedAtBoundary(backup);
24425
+ if (targetBackedUp) await assertWorkPackTreeUnchangedAtBoundary(backup, originalTree);
24335
24426
  if (targetBackedUp) await options.installWorkPackBoundary?.("before-commit");
24427
+ await assertWorkPackTreeUnchangedAtBoundary(target, installedTree);
24336
24428
  if (targetBackedUp) {
24337
24429
  await rename3(backup, claimedBackup);
24338
24430
  backupClaimed = true;
24339
- await assertWorkPackTreeUnchangedAtBoundary(claimedBackup);
24431
+ await assertWorkPackTreeUnchangedAtBoundary(claimedBackup, originalTree);
24340
24432
  await writeFile3(path5.join(claimedBackup, WORK_PACK_COMMITTED_MARKER), `${version2}
24341
24433
  `);
24342
24434
  await writeTextAtomic(transactionPath, "committed\n");
@@ -24344,6 +24436,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
24344
24436
  } catch (error45) {
24345
24437
  try {
24346
24438
  if (targetInstalled) {
24439
+ await assertWorkPackTreeUnchangedAtBoundary(target, installedTree);
24347
24440
  await restoreProjectionState(agentSnapshot, agentTransactionState);
24348
24441
  await restoreProjectionState(commandSnapshot, commandTransactionState);
24349
24442
  }
@@ -24399,7 +24492,8 @@ async function adoptLegacyWorkPackState(paths, slug, version2, archive, approved
24399
24492
  expectedPackDir: path5.join(comparisonPaths.skillsDir, slug),
24400
24493
  packDir: path5.join(paths.skillsDir, slug),
24401
24494
  agentsDir: paths.agentsDir,
24402
- commandsDir: paths.commandsDir
24495
+ commandsDir: paths.commandsDir,
24496
+ allowAdditional: true
24403
24497
  });
24404
24498
  } finally {
24405
24499
  await rm(comparisonRoot, { recursive: true, force: true }).catch(() => void 0);
@@ -24465,17 +24559,23 @@ async function recoverInterruptedWorkPackInstall(paths, target, cleanupWorkPackB
24465
24559
  }
24466
24560
  const targetOwnership = await workPackOwnership(target);
24467
24561
  if (targetOwnership === "managed") {
24468
- const localState = await checkWorkPackTreeState(target);
24562
+ const localState = await checkWorkPackTreeState(target, true);
24469
24563
  if (localState !== "match") {
24470
24564
  return localState === "missing" ? "local-baseline-missing" : "local-edits-preserved";
24471
24565
  }
24566
+ const currentExtras = await workPackExtrasTree(target);
24567
+ if (!currentExtras) return "local-edits-preserved";
24568
+ if (currentExtras.files.length || currentExtras.directories.length) {
24569
+ const backupExtras = await workPackExtrasTree(backup);
24570
+ if (!backupExtras || !sameTree(currentExtras, backupExtras)) return "local-edits-preserved";
24571
+ }
24472
24572
  }
24473
24573
  const currentAgents = await readAgentRecord(target);
24474
24574
  const currentCommands = await readCommandRecord(target);
24475
- const currentAgentFiles = await readPackAgentFiles(target);
24476
- const currentCommandFiles = await readPackCommandFiles(target);
24477
- const previousAgents = await readPackAgentFiles(backup);
24478
- const previousCommands = await readPackCommandFiles(backup);
24575
+ const currentAgentFiles = await readPackAgentFiles(target, new Set(currentAgents));
24576
+ const currentCommandFiles = await readPackCommandFiles(target, new Set(currentCommands));
24577
+ const previousAgents = await readPackAgentFiles(backup, new Set(await readAgentRecord(backup)));
24578
+ const previousCommands = await readPackCommandFiles(backup, new Set(await readCommandRecord(backup)));
24479
24579
  const removedProjections = transactionState === "remove" ? await readWorkPackRemovedProjections(backup) : { agents: /* @__PURE__ */ new Set(), commands: /* @__PURE__ */ new Set() };
24480
24580
  const missingPreviousAgentPolicy = targetOwnership === "absent" ? transactionState === "remove" ? removedProjections.agents : true : false;
24481
24581
  const missingPreviousCommandPolicy = targetOwnership === "absent" ? transactionState === "remove" ? removedProjections.commands : true : false;
@@ -24668,7 +24768,7 @@ async function restoreProjectionState(snapshot, transactionState) {
24668
24768
  else await writeTextAtomic(filePath, content);
24669
24769
  }
24670
24770
  }
24671
- async function readPackAgentFiles(skillFolder) {
24771
+ async function readPackAgentFiles(skillFolder, managedNames) {
24672
24772
  const agentsFolder = path5.join(skillFolder, "agents");
24673
24773
  const entries = await readdir3(agentsFolder, { withFileTypes: true }).catch((error45) => {
24674
24774
  if (error45.code === "ENOENT") return [];
@@ -24676,7 +24776,7 @@ async function readPackAgentFiles(skillFolder) {
24676
24776
  });
24677
24777
  const files = [];
24678
24778
  for (const entry of entries) {
24679
- if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
24779
+ if (!entry.isFile() || !entry.name.endsWith(".md") || managedNames && !managedNames.has(entry.name)) continue;
24680
24780
  if (entry.name.startsWith("._")) continue;
24681
24781
  const content = await readFile3(path5.join(agentsFolder, entry.name), "utf8");
24682
24782
  validateAgentFile(entry.name, content);
@@ -24697,18 +24797,18 @@ async function normalizePackAgentModels(skillFolder, agentFiles, approvedModelId
24697
24797
  }
24698
24798
  async function workPackNeedsModelNormalization(target, approvedModelIds, slug) {
24699
24799
  const approved = new Set(approvedModelIds);
24700
- const agentsNeedNormalization = (await readPackAgentFiles(target)).some(
24800
+ const agentsNeedNormalization = (await readPackAgentFiles(target, new Set(await readAgentRecord(target)))).some(
24701
24801
  (agent) => normalizePackExtensionModel(`agents/${agent.filename}`, agent.content, approved, slug) !== agent.content
24702
24802
  );
24703
24803
  if (agentsNeedNormalization) return true;
24704
- return (await readPackCommandFiles(target)).some(
24804
+ return (await readPackCommandFiles(target, new Set(await readCommandRecord(target)))).some(
24705
24805
  (command) => normalizePackExtensionModel(`commands/${command.filename}`, command.content, approved, slug) !== command.content
24706
24806
  );
24707
24807
  }
24708
24808
  function normalizePackAgentModel(filename, content, approvedModelIds, slug) {
24709
24809
  return normalizePackExtensionModel(`agents/${filename}`, content, approvedModelIds, slug);
24710
24810
  }
24711
- async function readPackCommandFiles(skillFolder) {
24811
+ async function readPackCommandFiles(skillFolder, managedNames) {
24712
24812
  const commandsFolder = path5.join(skillFolder, "commands");
24713
24813
  const entries = await readdir3(commandsFolder, { withFileTypes: true }).catch((error45) => {
24714
24814
  if (error45.code === "ENOENT") return [];
@@ -24716,7 +24816,7 @@ async function readPackCommandFiles(skillFolder) {
24716
24816
  });
24717
24817
  const files = [];
24718
24818
  for (const entry of entries) {
24719
- if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
24819
+ if (!entry.isFile() || !entry.name.endsWith(".md") || managedNames && !managedNames.has(entry.name)) continue;
24720
24820
  if (entry.name.startsWith("._")) continue;
24721
24821
  const content = await readFile3(path5.join(commandsFolder, entry.name), "utf8");
24722
24822
  validateCommandFile(entry.name, content);
@@ -25041,14 +25141,14 @@ function isRecord(value) {
25041
25141
  }
25042
25142
 
25043
25143
  // packages/cli/src/workPackSyncPlugin.ts
25044
- var PLUGIN_VERSION = "0.1.18";
25144
+ var PLUGIN_VERSION = "0.1.20";
25045
25145
  var STATUS_FILENAME = "work-pack-startup-status.json";
25046
25146
  var activeSync = /* @__PURE__ */ new Map();
25047
25147
  var ForgeWorkPackSyncServer = async (_input, options) => {
25048
25148
  const forgeBaseUrl = parseForgeBaseUrl(options);
25049
25149
  let sync = activeSync.get(forgeBaseUrl);
25050
25150
  if (!sync) {
25051
- sync = synchronizeAtStartup(forgeBaseUrl);
25151
+ sync = synchronizeAtStartup(forgeBaseUrl, _input);
25052
25152
  activeSync.set(forgeBaseUrl, sync);
25053
25153
  }
25054
25154
  const state = await sync;
@@ -25130,18 +25230,19 @@ function createForgeFeedbackTool(forgeBaseUrl, paths) {
25130
25230
  }
25131
25231
  });
25132
25232
  }
25133
- async function synchronizeAtStartup(forgeBaseUrl) {
25233
+ async function synchronizeAtStartup(forgeBaseUrl, input) {
25134
25234
  const paths = resolveStartupPaths();
25135
25235
  const before = await managedProjectionNames(paths);
25136
25236
  let credentials;
25137
25237
  let forgeConfigVerified = false;
25238
+ const runtime = await observeRuntime(input);
25138
25239
  try {
25139
25240
  await retireDebugCapture(paths);
25140
25241
  credentials = await readWellKnownForgeCredentials(paths.opencodeAuthPath, forgeBaseUrl);
25141
25242
  const manifest = await fetchManifest(credentials);
25142
25243
  forgeConfigVerified = true;
25143
25244
  const result = await applyWorkPackManifest(paths, credentials, manifest, {});
25144
- await reportWorkPackObservations(credentials, "sync", result.workPackObservations);
25245
+ await reportWorkPackObservations(credentials, "sync", result.workPackObservations, runtime);
25145
25246
  const failures = result.workPacks.outcomes.filter(
25146
25247
  (outcome) => outcome.status === "failed" || outcome.status === "recovery-uncertain"
25147
25248
  );
@@ -25169,7 +25270,7 @@ async function synchronizeAtStartup(forgeBaseUrl) {
25169
25270
  attemptedAt: (/* @__PURE__ */ new Date()).toISOString(),
25170
25271
  message
25171
25272
  }).catch(() => void 0);
25172
- if (credentials) await reportFailure(credentials, "sync", new Error(message));
25273
+ if (credentials) await reportFailure(credentials, "sync", new Error(message), runtime);
25173
25274
  const after = await managedProjectionNames(paths).catch(() => before);
25174
25275
  return { paths, before, after, forgeConfigVerified };
25175
25276
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "minimal-forge-work-pack-sync",
3
- "version": "0.1.18",
3
+ "version": "0.1.20",
4
4
  "description": "Minimal Forge Work Pack startup synchronization for OpenCode and OpenWork.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {