minimal-forge-work-pack-sync 0.1.43 → 0.1.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -7607,7 +7607,7 @@ var DEFAULT_DEBUG_TRACE_LIMITS = {
7607
7607
  // packages/shared/src/contracts/settings.ts
7608
7608
  var DOCUMENT_READER_AGENT = "document-reader";
7609
7609
  var OPENROUTER_ALIAS_PROVIDER_NAME = "OpenRouter (via Forge)";
7610
- var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.43";
7610
+ var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.44";
7611
7611
  var WORK_PACK_SYNC_PLUGIN_PACKAGE = `minimal-forge-work-pack-sync@${WORK_PACK_SYNC_PLUGIN_VERSION}`;
7612
7612
  var WORK_PACK_SYNC_PLUGIN_FILENAME = `minimal-forge-work-pack-sync-${WORK_PACK_SYNC_PLUGIN_VERSION}.tgz`;
7613
7613
  var FIRECRAWL_KEYLESS_MCP_NAME = "firecrawl";
@@ -7866,6 +7866,90 @@ async function probeHealth(url2, route, headers, healthyField, source) {
7866
7866
  }
7867
7867
  }
7868
7868
 
7869
+ // packages/cli/src/ownerOnlyFile.ts
7870
+ import { spawnSync as nodeSpawnSync } from "node:child_process";
7871
+ import { randomUUID } from "node:crypto";
7872
+ import { chmod, mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
7873
+ import path from "node:path";
7874
+ async function protectOwnerOnlyPath(filePath, kind, options = {}) {
7875
+ const platform = options.platform ?? process.platform;
7876
+ if (platform !== "win32") {
7877
+ await chmod(filePath, kind === "directory" ? 448 : 384);
7878
+ return;
7879
+ }
7880
+ const spawn = options.spawnSync ?? nodeSpawnSync;
7881
+ const command = kind === "directory" ? "$ErrorActionPreference = 'Stop'; $path = [Console]::In.ReadToEnd(); $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.DirectorySecurity]::new(); $acl.SetAccessRuleProtection($true, $false); $inheritance = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit; $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity, [System.Security.AccessControl.FileSystemRights]::FullControl, $inheritance, [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow); [void]$acl.AddAccessRule($rule); [System.IO.Directory]::SetAccessControl($path, $acl)" : "$ErrorActionPreference = 'Stop'; $path = [Console]::In.ReadToEnd(); $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.FileSecurity]::new(); $acl.SetAccessRuleProtection($true, $false); $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity, [System.Security.AccessControl.FileSystemRights]::FullControl, [System.Security.AccessControl.AccessControlType]::Allow); [void]$acl.AddAccessRule($rule); [System.IO.File]::SetAccessControl($path, $acl)";
7882
+ const result = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
7883
+ encoding: "utf8",
7884
+ input: filePath
7885
+ });
7886
+ if (result.status !== 0) {
7887
+ const detail = typeof result.stderr === "string" ? result.stderr.trim().replace(/\s+/g, " ").slice(0, 500) : "";
7888
+ const context = options.failureContext ?? (kind === "directory" ? "o diret\xF3rio" : "o ficheiro");
7889
+ throw new Error(`N\xE3o foi poss\xEDvel proteger ${context} em ${filePath}${detail ? `: ${detail}` : ""}`);
7890
+ }
7891
+ }
7892
+ async function assertExistingDirectoryIsSafe(directory, options) {
7893
+ const platform = options.platform ?? process.platform;
7894
+ if (platform !== "win32") {
7895
+ const info = await stat(directory);
7896
+ const currentUid = process.getuid?.();
7897
+ if (currentUid !== void 0 && info.uid !== currentUid || (info.mode & 18) !== 0) {
7898
+ const mode = (info.mode & 511).toString(8).padStart(3, "0");
7899
+ throw new Error(`O diret\xF3rio existente ${directory} n\xE3o \xE9 controlado apenas pelo utilizador atual (modo ${mode})`);
7900
+ }
7901
+ return;
7902
+ }
7903
+ const spawn = options.spawnSync ?? nodeSpawnSync;
7904
+ const command = "$ErrorActionPreference = 'Stop'; $path = [Console]::In.ReadToEnd(); $current = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; $trusted = @($current, 'S-1-5-18', 'S-1-5-32-544'); $dangerous = [System.Security.AccessControl.FileSystemRights]::Write -bor [System.Security.AccessControl.FileSystemRights]::Delete -bor [System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor [System.Security.AccessControl.FileSystemRights]::ChangePermissions -bor [System.Security.AccessControl.FileSystemRights]::TakeOwnership; $acl = [System.IO.Directory]::GetAccessControl($path); $rules = $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier]); foreach ($rule in $rules) { if ($rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and $rule.PropagationFlags -ne [System.Security.AccessControl.PropagationFlags]::InheritOnly -and ($rule.FileSystemRights -band $dangerous) -ne 0 -and $trusted -notcontains $rule.IdentityReference.Value) { throw ('O diret\xF3rio permite escrita por ' + $rule.IdentityReference.Value) } }";
7905
+ const result = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
7906
+ encoding: "utf8",
7907
+ input: directory
7908
+ });
7909
+ if (result.status !== 0) {
7910
+ const detail = typeof result.stderr === "string" ? result.stderr.trim().replace(/\s+/g, " ").slice(0, 500) : "";
7911
+ throw new Error(`O diret\xF3rio existente ${directory} n\xE3o \xE9 controlado apenas pelo utilizador atual${detail ? `: ${detail}` : ""}`);
7912
+ }
7913
+ }
7914
+ async function prepareOwnerOnlyFileDestination(filePath, options = {}) {
7915
+ const directory = path.dirname(filePath);
7916
+ let existing;
7917
+ try {
7918
+ existing = await stat(directory);
7919
+ } catch (error45) {
7920
+ if (error45.code !== "ENOENT") throw error45;
7921
+ }
7922
+ if (existing) {
7923
+ if (!existing.isDirectory()) throw new Error(`O destino ${directory} existe, mas n\xE3o \xE9 um diret\xF3rio`);
7924
+ await assertExistingDirectoryIsSafe(directory, options);
7925
+ return;
7926
+ }
7927
+ let createdDirectory;
7928
+ try {
7929
+ createdDirectory = await mkdir(directory, { recursive: true, mode: 448 });
7930
+ } catch (error45) {
7931
+ if (error45.code !== "EEXIST" || !(await stat(directory)).isDirectory()) throw error45;
7932
+ await assertExistingDirectoryIsSafe(directory, options);
7933
+ return;
7934
+ }
7935
+ if (createdDirectory !== void 0) await protectOwnerOnlyPath(directory, "directory", options);
7936
+ else await assertExistingDirectoryIsSafe(directory, options);
7937
+ }
7938
+ async function writeOwnerOnlyTextAtomic(filePath, content, options = {}) {
7939
+ const directory = path.dirname(filePath);
7940
+ await prepareOwnerOnlyFileDestination(filePath, options);
7941
+ const temporary = path.join(directory, `.${path.basename(filePath)}.${randomUUID()}.tmp`);
7942
+ try {
7943
+ await writeFile(temporary, content, { flag: "wx", mode: 384 });
7944
+ await protectOwnerOnlyPath(temporary, "file", options);
7945
+ await rename(temporary, filePath);
7946
+ await protectOwnerOnlyPath(filePath, "file", options);
7947
+ } catch (error45) {
7948
+ await rm(temporary, { force: true }).catch(() => void 0);
7949
+ throw error45;
7950
+ }
7951
+ }
7952
+
7869
7953
  // packages/cli/src/workPackSyncPlugin.ts
7870
7954
  import { createHash as createHash7, randomUUID as randomUUID4 } from "node:crypto";
7871
7955
  import { pathToFileURL } from "node:url";
@@ -8127,16 +8211,16 @@ async function readForgeCredentials() {
8127
8211
  }
8128
8212
 
8129
8213
  // packages/cli/src/retireDebugCapture.ts
8130
- import { lstat, readFile, rename, writeFile } from "node:fs/promises";
8131
- import { randomUUID } from "node:crypto";
8132
- import path from "node:path";
8214
+ import { lstat, readFile, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
8215
+ import { randomUUID as randomUUID2 } from "node:crypto";
8216
+ import path2 from "node:path";
8133
8217
  var MANAGED_HEADER = "// Managed by Forge sync. Do not edit.";
8134
8218
  var RETIRED_DEBUG_PLUGIN = `${MANAGED_HEADER}
8135
8219
  // Detailed capture retired. Keep this module loadable for old OpenCode configs.
8136
8220
  export const ForgeDebugTrace = async () => ({})
8137
8221
  `;
8138
8222
  async function retireDebugCapture(paths) {
8139
- const configPath = path.join(paths.forgeDir, "debug-trace.json");
8223
+ const configPath = path2.join(paths.forgeDir, "debug-trace.json");
8140
8224
  const raw = await readRegularFile(configPath);
8141
8225
  if (raw !== void 0) {
8142
8226
  const config2 = JSON.parse(raw);
@@ -8145,7 +8229,7 @@ async function retireDebugCapture(paths) {
8145
8229
  `);
8146
8230
  }
8147
8231
  }
8148
- const pluginPath = path.join(paths.pluginDir, "forge-debug-trace.js");
8232
+ const pluginPath = path2.join(paths.pluginDir, "forge-debug-trace.js");
8149
8233
  const plugin = await readRegularFile(pluginPath);
8150
8234
  if (plugin?.startsWith(MANAGED_HEADER) && plugin !== RETIRED_DEBUG_PLUGIN) {
8151
8235
  await replaceFile(pluginPath, RETIRED_DEBUG_PLUGIN);
@@ -8153,7 +8237,7 @@ async function retireDebugCapture(paths) {
8153
8237
  }
8154
8238
  async function readRegularFile(filename) {
8155
8239
  try {
8156
- const directory = await lstat(path.dirname(filename));
8240
+ const directory = await lstat(path2.dirname(filename));
8157
8241
  const info = await lstat(filename);
8158
8242
  if (!directory.isDirectory() || !info.isFile() || info.isSymbolicLink()) {
8159
8243
  throw new Error("Legacy debug capture path must be a regular file in a real directory");
@@ -8165,9 +8249,9 @@ async function readRegularFile(filename) {
8165
8249
  }
8166
8250
  }
8167
8251
  async function replaceFile(filename, contents) {
8168
- const temporary = `${filename}.retired-${randomUUID()}`;
8169
- await writeFile(temporary, contents, { flag: "wx", mode: 384 });
8170
- await rename(temporary, filename);
8252
+ const temporary = `${filename}.retired-${randomUUID2()}`;
8253
+ await writeFile2(temporary, contents, { flag: "wx", mode: 384 });
8254
+ await rename2(temporary, filename);
8171
8255
  }
8172
8256
 
8173
8257
  // packages/cli/src/reasoningLoopGuard.ts
@@ -8380,6 +8464,7 @@ function createReasoningLoopGuard(client, log = console.error, report = () => vo
8380
8464
  // packages/cli/src/workPackSyncPlugin.ts
8381
8465
  var import_yaml = __toESM(require_dist(), 1);
8382
8466
  import { link, mkdir as mkdir7, mkdtemp as mkdtemp2, readdir as readdir5, readFile as readFile11, realpath, rename as rename8, rm as rm6, rmdir, stat as stat3, unlink, writeFile as writeFile8 } from "node:fs/promises";
8467
+ import os5 from "node:os";
8383
8468
  import path12 from "node:path";
8384
8469
 
8385
8470
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/classic/external.js
@@ -20805,7 +20890,7 @@ function tool(input) {
20805
20890
  tool.schema = external_exports;
20806
20891
 
20807
20892
  // packages/cli/src/credentials.ts
20808
- import { chmod, mkdir, readFile as readFile2, rename as rename2, rm, writeFile as writeFile2 } from "node:fs/promises";
20893
+ import { chmod as chmod2, mkdir as mkdir2, readFile as readFile2, rename as rename3, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
20809
20894
  async function readCredentials(paths) {
20810
20895
  const raw = await readFile2(paths.credentialsPath, "utf8");
20811
20896
  const parsed = JSON.parse(raw);
@@ -20817,10 +20902,10 @@ async function readCredentials(paths) {
20817
20902
 
20818
20903
  // packages/cli/src/paths.ts
20819
20904
  import os from "node:os";
20820
- import path2 from "node:path";
20905
+ import path3 from "node:path";
20821
20906
  import { existsSync } from "node:fs";
20822
20907
  function resolvePaths(home = os.homedir(), platform = process.platform, env = process.env, exists2 = existsSync) {
20823
- const pathApi = platform === "win32" ? path2.win32 : path2.posix;
20908
+ const pathApi = platform === "win32" ? path3.win32 : path3.posix;
20824
20909
  const userHome = platform === "win32" ? env.USERPROFILE ?? home : home;
20825
20910
  const forgeConfigRoot = env.XDG_CONFIG_HOME ?? pathApi.join(userHome, ".config");
20826
20911
  const forgeDir = pathApi.join(forgeConfigRoot, "forge");
@@ -20908,12 +20993,12 @@ async function reportWorkPackObservations(credentials, kind, workPacks, runtime
20908
20993
  import { createHash as createHash2 } from "node:crypto";
20909
20994
  import { constants } from "node:fs";
20910
20995
  import { lstat as lstat3, open, readdir as readdir2 } from "node:fs/promises";
20911
- import path4 from "node:path";
20996
+ import path5 from "node:path";
20912
20997
 
20913
20998
  // packages/cli/src/workPackLocalState.ts
20914
20999
  import { createHash } from "node:crypto";
20915
- import { lstat as lstat2, mkdir as mkdir2, readFile as readFile3, readdir, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
20916
- import path3 from "node:path";
21000
+ import { lstat as lstat2, mkdir as mkdir3, readFile as readFile3, readdir, rename as rename4, writeFile as writeFile4 } from "node:fs/promises";
21001
+ import path4 from "node:path";
20917
21002
  var WORK_PACK_LOCAL_STATE_FILENAME = ".forge-installed-state.json";
20918
21003
  async function writeWorkPackInstalledState(input) {
20919
21004
  const tree = await digestPackTree(input.packDir);
@@ -20925,7 +21010,7 @@ async function writeWorkPackInstalledState(input) {
20925
21010
  agents: digestProjectionContents(input.agents),
20926
21011
  commands: digestProjectionContents(input.commands)
20927
21012
  };
20928
- await writeJsonAtomic(path3.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
21013
+ await writeJsonAtomic(path4.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
20929
21014
  }
20930
21015
  async function checkWorkPackInstalledState(input) {
20931
21016
  const state = await readInstalledState(input.packDir);
@@ -20941,13 +21026,13 @@ async function checkWorkPackTreeState(packDir, allowAdditional = false) {
20941
21026
  async function adoptWorkPackInstalledState(input) {
20942
21027
  const state = await readInstalledState(input.expectedPackDir);
20943
21028
  if (!state || !await matchesInstalledState(input, state)) return false;
20944
- await writeJsonAtomic(path3.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
21029
+ await writeJsonAtomic(path4.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
20945
21030
  return checkWorkPackInstalledState(input).then((result) => result === "match");
20946
21031
  }
20947
21032
  async function readInstalledState(packDir) {
20948
- const info = await lstat2(path3.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME)).catch(() => void 0);
21033
+ const info = await lstat2(path4.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME)).catch(() => void 0);
20949
21034
  if (!info?.isFile() || info.isSymbolicLink() || info.size > 1024 * 1024) return void 0;
20950
- const raw = await readFile3(path3.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME), "utf8").catch(() => void 0);
21035
+ const raw = await readFile3(path4.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME), "utf8").catch(() => void 0);
20951
21036
  if (!raw) return void 0;
20952
21037
  try {
20953
21038
  return parseWorkPackFileManifest(JSON.parse(raw));
@@ -20963,7 +21048,7 @@ async function digestPackTree(root) {
20963
21048
  for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
20964
21049
  if (!prefix && entry.name === WORK_PACK_LOCAL_STATE_FILENAME) continue;
20965
21050
  const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
20966
- const absolute = path3.join(directory, entry.name);
21051
+ const absolute = path4.join(directory, entry.name);
20967
21052
  const info = await lstat2(absolute);
20968
21053
  if (info.isSymbolicLink() || info.isFile() && info.nlink > 1) return false;
20969
21054
  if (entry.isDirectory()) {
@@ -20983,7 +21068,7 @@ function digestProjectionContents(files) {
20983
21068
  }
20984
21069
  async function projectionsMatch(directory, expected) {
20985
21070
  for (const projection of expected) {
20986
- const absolute = path3.join(directory, projection.filename);
21071
+ const absolute = path4.join(directory, projection.filename);
20987
21072
  const info = await lstat2(absolute).catch(() => void 0);
20988
21073
  if (!info?.isFile() || info.isSymbolicLink()) return false;
20989
21074
  const bytes = await readFile3(absolute).catch(() => void 0);
@@ -21009,15 +21094,15 @@ function digest(bytes) {
21009
21094
  return createHash("sha256").update(bytes).digest("hex");
21010
21095
  }
21011
21096
  async function writeJsonAtomic(filePath, value) {
21012
- await mkdir2(path3.dirname(filePath), { recursive: true });
21013
- const tempPath = path3.join(path3.dirname(filePath), `.${path3.basename(filePath)}.${process.pid}.tmp`);
21014
- await writeFile3(tempPath, `${JSON.stringify(value, null, 2)}
21097
+ await mkdir3(path4.dirname(filePath), { recursive: true });
21098
+ const tempPath = path4.join(path4.dirname(filePath), `.${path4.basename(filePath)}.${process.pid}.tmp`);
21099
+ await writeFile4(tempPath, `${JSON.stringify(value, null, 2)}
21015
21100
  `);
21016
- await rename3(tempPath, filePath);
21101
+ await rename4(tempPath, filePath);
21017
21102
  }
21018
21103
  async function adoptWorkPackFileManifest(input) {
21019
21104
  if (!await matchesInstalledState({ ...input, allowAdditional: true }, input.expected)) return false;
21020
- await writeJsonAtomic(path3.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), input.expected);
21105
+ await writeJsonAtomic(path4.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), input.expected);
21021
21106
  return true;
21022
21107
  }
21023
21108
  function containsOriginalTree(actual, expected) {
@@ -21053,7 +21138,7 @@ function emptySummary() {
21053
21138
  }
21054
21139
  async function inspectWorkPackIntegrity(input) {
21055
21140
  assertSlug(input.slug);
21056
- const packDir = path4.join(input.paths.skillsDir, input.slug);
21141
+ const packDir = path5.join(input.paths.skillsDir, input.slug);
21057
21142
  const result = { slug: input.slug, summary: emptySummary(), differences: [], differencesTruncated: false };
21058
21143
  const add = (kind, area, name) => {
21059
21144
  if (result.summary[kind] === MAX_ENTRIES) result.summary.truncated = true;
@@ -21093,7 +21178,7 @@ async function inspectWorkPackIntegrity(input) {
21093
21178
  return;
21094
21179
  }
21095
21180
  const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
21096
- const absolute = path4.join(directory, entry.name);
21181
+ const absolute = path5.join(directory, entry.name);
21097
21182
  const info = await lstat3(absolute).catch(() => void 0);
21098
21183
  if (!info) {
21099
21184
  add("unreadable", "pack", relative);
@@ -21143,7 +21228,7 @@ async function inspectWorkPackIntegrity(input) {
21143
21228
  const source = match ? `${match[1] ?? ""}${match[2]}.py` : void 0;
21144
21229
  if (source && unchanged.has(source)) {
21145
21230
  add("runtimeArtifacts", "pack", name);
21146
- cacheDirectories.add(path4.posix.dirname(name));
21231
+ cacheDirectories.add(path5.posix.dirname(name));
21147
21232
  } else add("additional", "pack", name);
21148
21233
  }
21149
21234
  for (const name of extraDirectories) if (!cacheDirectories.has(name)) add("additional", "pack", name);
@@ -21157,7 +21242,7 @@ async function inspectWorkPackIntegrity(input) {
21157
21242
  continue;
21158
21243
  }
21159
21244
  for (const item of items) {
21160
- const absolute = path4.join(directory, item.filename);
21245
+ const absolute = path5.join(directory, item.filename);
21161
21246
  try {
21162
21247
  const info = await lstat3(absolute);
21163
21248
  if (!info.isFile() || info.isSymbolicLink() || info.nlink > 1) add("unsafe", area, item.filename);
@@ -24236,74 +24321,6 @@ function renderTuiConfig(manifest) {
24236
24321
  import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
24237
24322
  import { chmod as chmod3, lstat as lstat4, mkdir as mkdir4, readFile as readFile4, rename as rename5, rm as rm3, writeFile as writeFile5 } from "node:fs/promises";
24238
24323
  import path6 from "node:path";
24239
-
24240
- // packages/cli/src/ownerOnlyFile.ts
24241
- import { spawnSync as nodeSpawnSync } from "node:child_process";
24242
- import { randomUUID as randomUUID2 } from "node:crypto";
24243
- import { chmod as chmod2, mkdir as mkdir3, rename as rename4, rm as rm2, stat, writeFile as writeFile4 } from "node:fs/promises";
24244
- import path5 from "node:path";
24245
- async function protectOwnerOnlyPath(filePath, kind, options = {}) {
24246
- const platform = options.platform ?? process.platform;
24247
- if (platform !== "win32") {
24248
- await chmod2(filePath, kind === "directory" ? 448 : 384);
24249
- return;
24250
- }
24251
- const spawn = options.spawnSync ?? nodeSpawnSync;
24252
- const command = kind === "directory" ? "$ErrorActionPreference = 'Stop'; $path = [Console]::In.ReadToEnd(); $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.DirectorySecurity]::new(); $acl.SetAccessRuleProtection($true, $false); $inheritance = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit; $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity, [System.Security.AccessControl.FileSystemRights]::FullControl, $inheritance, [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow); [void]$acl.AddAccessRule($rule); [System.IO.Directory]::SetAccessControl($path, $acl)" : "$ErrorActionPreference = 'Stop'; $path = [Console]::In.ReadToEnd(); $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.FileSecurity]::new(); $acl.SetAccessRuleProtection($true, $false); $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity, [System.Security.AccessControl.FileSystemRights]::FullControl, [System.Security.AccessControl.AccessControlType]::Allow); [void]$acl.AddAccessRule($rule); [System.IO.File]::SetAccessControl($path, $acl)";
24253
- const result = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
24254
- encoding: "utf8",
24255
- input: filePath
24256
- });
24257
- if (result.status !== 0) {
24258
- const detail = typeof result.stderr === "string" ? result.stderr.trim().replace(/\s+/g, " ").slice(0, 500) : "";
24259
- const context = options.failureContext ?? (kind === "directory" ? "o diret\xF3rio" : "o ficheiro");
24260
- throw new Error(`N\xE3o foi poss\xEDvel proteger ${context} em ${filePath}${detail ? `: ${detail}` : ""}`);
24261
- }
24262
- }
24263
- async function assertExistingDirectoryIsSafe(directory, options) {
24264
- const platform = options.platform ?? process.platform;
24265
- if (platform !== "win32") {
24266
- const info = await stat(directory);
24267
- const currentUid = process.getuid?.();
24268
- if (currentUid !== void 0 && info.uid !== currentUid || (info.mode & 18) !== 0) {
24269
- const mode = (info.mode & 511).toString(8).padStart(3, "0");
24270
- throw new Error(`O diret\xF3rio existente ${directory} n\xE3o \xE9 controlado apenas pelo utilizador atual (modo ${mode})`);
24271
- }
24272
- return;
24273
- }
24274
- const spawn = options.spawnSync ?? nodeSpawnSync;
24275
- const command = "$ErrorActionPreference = 'Stop'; $path = [Console]::In.ReadToEnd(); $current = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; $trusted = @($current, 'S-1-5-18', 'S-1-5-32-544'); $dangerous = [System.Security.AccessControl.FileSystemRights]::Write -bor [System.Security.AccessControl.FileSystemRights]::Delete -bor [System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor [System.Security.AccessControl.FileSystemRights]::ChangePermissions -bor [System.Security.AccessControl.FileSystemRights]::TakeOwnership; $acl = [System.IO.Directory]::GetAccessControl($path); $rules = $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier]); foreach ($rule in $rules) { if ($rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and $rule.PropagationFlags -ne [System.Security.AccessControl.PropagationFlags]::InheritOnly -and ($rule.FileSystemRights -band $dangerous) -ne 0 -and $trusted -notcontains $rule.IdentityReference.Value) { throw ('O diret\xF3rio permite escrita por ' + $rule.IdentityReference.Value) } }";
24276
- const result = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
24277
- encoding: "utf8",
24278
- input: directory
24279
- });
24280
- if (result.status !== 0) {
24281
- const detail = typeof result.stderr === "string" ? result.stderr.trim().replace(/\s+/g, " ").slice(0, 500) : "";
24282
- throw new Error(`O diret\xF3rio existente ${directory} n\xE3o \xE9 controlado apenas pelo utilizador atual${detail ? `: ${detail}` : ""}`);
24283
- }
24284
- }
24285
- async function prepareOwnerOnlyFileDestination(filePath, options = {}) {
24286
- const directory = path5.dirname(filePath);
24287
- const createdDirectory = await mkdir3(directory, { recursive: true, mode: 448 });
24288
- if (createdDirectory !== void 0) await protectOwnerOnlyPath(directory, "directory", options);
24289
- else await assertExistingDirectoryIsSafe(directory, options);
24290
- }
24291
- async function writeOwnerOnlyTextAtomic(filePath, content, options = {}) {
24292
- const directory = path5.dirname(filePath);
24293
- await prepareOwnerOnlyFileDestination(filePath, options);
24294
- const temporary = path5.join(directory, `.${path5.basename(filePath)}.${randomUUID2()}.tmp`);
24295
- try {
24296
- await writeFile4(temporary, content, { flag: "wx", mode: 384 });
24297
- await protectOwnerOnlyPath(temporary, "file", options);
24298
- await rename4(temporary, filePath);
24299
- await protectOwnerOnlyPath(filePath, "file", options);
24300
- } catch (error45) {
24301
- await rm2(temporary, { force: true }).catch(() => void 0);
24302
- throw error45;
24303
- }
24304
- }
24305
-
24306
- // packages/cli/src/coreSyncTransaction.ts
24307
24324
  var CORE_RUNTIME_MANIFEST_VERSION = 1;
24308
24325
  var CoreSyncUncertainError = class extends Error {
24309
24326
  constructor(message, paths) {
@@ -26452,7 +26469,7 @@ async function syncLocalWorker(paths, credentials, manifest) {
26452
26469
  }
26453
26470
 
26454
26471
  // packages/cli/src/workPackSyncPlugin.ts
26455
- var PLUGIN_VERSION = "0.1.43";
26472
+ var PLUGIN_VERSION = "0.1.44";
26456
26473
  var FORGE_DECISION_TIMEOUT_MS = 11e4;
26457
26474
  var STATUS_FILENAME = "work-pack-startup-status.json";
26458
26475
  var activeSync = /* @__PURE__ */ new Map();
@@ -26587,7 +26604,7 @@ function createForgeImageTool(forgeBaseUrl, gatewayBaseUrl, paths) {
26587
26604
  }
26588
26605
  });
26589
26606
  }
26590
- function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseDirectory) {
26607
+ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseDirectory, beforeCall) {
26591
26608
  const question = tool.schema.discriminatedUnion("type", [
26592
26609
  tool.schema.object({
26593
26610
  type: tool.schema.literal("noul"),
@@ -26624,6 +26641,21 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
26624
26641
  let requestBody;
26625
26642
  if (fromFile) {
26626
26643
  const file2 = await fileInsideWorkspace(context.directory, args.request_file);
26644
+ const planFile = path12.join(path12.dirname(path12.dirname(file2)), "plan.json");
26645
+ if (!responseDirectory && path12.basename(path12.dirname(file2)) === "requests" && await fileExists(planFile)) {
26646
+ const plan = JSON.parse(await readFile11(planFile, "utf8"));
26647
+ if (plan?.engine === "jev-batch" && plan.model === "typesafe/jev-1.13" && Array.isArray(plan.batches)) {
26648
+ let batch;
26649
+ for (const candidate of plan.batches) {
26650
+ if (await fileInsideWorkspace(context.directory, candidate.request_file) === file2) {
26651
+ batch = candidate;
26652
+ break;
26653
+ }
26654
+ }
26655
+ if (!batch) throw new Error("O pedido n\xE3o pertence ao plano Jev guardado.");
26656
+ return createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths).execute({ plan_file: planFile, batch_id: batch.batch_id }, context);
26657
+ }
26658
+ }
26627
26659
  const raw = await readFile11(file2, "utf8");
26628
26660
  if (Buffer.byteLength(raw) > 512 * 1024) throw new Error("O ficheiro de pedido excede 512 KiB.");
26629
26661
  let parsed;
@@ -26647,6 +26679,11 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
26647
26679
  const responseFile = path12.join(responseDir, "response.json");
26648
26680
  try {
26649
26681
  const credentials = await readForgeCredentials(paths, forgeBaseUrl);
26682
+ const probeFile = path12.join(responseDir, ".write-test");
26683
+ await writeFile8(probeFile, "", { flag: "wx", mode: 384 });
26684
+ await unlink(probeFile);
26685
+ context.abort.throwIfAborted();
26686
+ await beforeCall?.(responseFile);
26650
26687
  const response = await fetch(`${decisionBaseUrl}/v1/decisions`, {
26651
26688
  method: "POST",
26652
26689
  redirect: "error",
@@ -26667,11 +26704,13 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
26667
26704
  try {
26668
26705
  await writeFile8(responseFile, raw, { flag: "wx", mode: 384 });
26669
26706
  return JSON.stringify({ ...body, response_file: responseFile }, null, 2);
26670
- } catch {
26707
+ } catch (error45) {
26671
26708
  return JSON.stringify({
26672
26709
  ...body,
26673
26710
  response_file: null,
26674
- persistence_error: "A decis\xE3o foi conclu\xEDda, mas n\xE3o foi poss\xEDvel guardar o ficheiro. Recuperar esta resposta do hist\xF3rico da ferramenta; n\xE3o repetir a chamada ao Jev."
26711
+ persistence_code: error45.code,
26712
+ recovery_file: responseFile,
26713
+ persistence_error: "A decis\xE3o foi conclu\xEDda, mas n\xE3o foi poss\xEDvel guardar o ficheiro. Recuperar esta resposta do hist\xF3rico da ferramenta; resolver a grava\xE7\xE3o antes de retomar o lote pelo runner."
26675
26714
  }, null, 2);
26676
26715
  }
26677
26716
  }
@@ -26704,6 +26743,20 @@ async function fileExists(candidate) {
26704
26743
  throw error45;
26705
26744
  }
26706
26745
  }
26746
+ async function ensureJevDirectory(directory, filesystem = { stat: stat3, mkdir: mkdir7 }) {
26747
+ try {
26748
+ if ((await filesystem.stat(directory)).isDirectory()) return;
26749
+ throw new Error(`O destino ${path12.basename(directory)} existe, mas n\xE3o \xE9 uma pasta. Preservar o conte\xFAdo e verificar o caminho.`);
26750
+ } catch (error45) {
26751
+ if (error45.code !== "ENOENT") throw error45;
26752
+ }
26753
+ try {
26754
+ await filesystem.mkdir(directory, { recursive: true });
26755
+ } catch (error45) {
26756
+ if (error45.code === "EEXIST" && (await filesystem.stat(directory)).isDirectory()) return;
26757
+ throw error45;
26758
+ }
26759
+ }
26707
26760
  function canonicalJson(value) {
26708
26761
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
26709
26762
  if (value && typeof value === "object") {
@@ -26712,34 +26765,84 @@ function canonicalJson(value) {
26712
26765
  }
26713
26766
  return JSON.stringify(value);
26714
26767
  }
26768
+ async function validateSavedDecision(file2, request) {
26769
+ const body = JSON.parse(await readFile11(file2, "utf8"));
26770
+ const answers = body.answers;
26771
+ const questions = request.questions;
26772
+ const usage = body.usage;
26773
+ if (typeof body.model !== "string" || !/^typesafe\/jev-1\.13(?:-|$)/.test(body.model) || !answers || Array.isArray(answers) || !usage || !Number.isInteger(usage.input_tokens) || !Number.isInteger(usage.output_tokens) || Object.keys(answers).sort().join("\n") !== Object.keys(questions).sort().join("\n") || Object.entries(questions).some(([id, question]) => !answers[id] || answers[id].type !== question.type || question.type === "noul" && (typeof answers[id].noul !== "number" || !Number.isFinite(answers[id].noul)))) {
26774
+ throw new Error("Resposta Jev guardada inv\xE1lida; preservar o ficheiro e verificar antes de continuar.");
26775
+ }
26776
+ return body;
26777
+ }
26778
+ async function acquireJevRunLock(lockDir) {
26779
+ try {
26780
+ await mkdir7(lockDir);
26781
+ return {};
26782
+ } catch (error45) {
26783
+ if (error45.code !== "EEXIST") throw error45;
26784
+ }
26785
+ let owner;
26786
+ let ownerRaw;
26787
+ try {
26788
+ ownerRaw = await readFile11(path12.join(lockDir, "owner.json"), "utf8");
26789
+ owner = JSON.parse(ownerRaw);
26790
+ } catch {
26791
+ throw new Error("Chamada interrompida com lock sem identifica\xE7\xE3o; n\xE3o \xE9 poss\xEDvel confirmar que terminou. Preservar o lock e verificar a execu\xE7\xE3o.");
26792
+ }
26793
+ if (!Number.isInteger(owner.pid) || owner.pid <= 0 || owner.hostname && owner.hostname !== os5.hostname()) {
26794
+ throw new Error("N\xE3o \xE9 poss\xEDvel confirmar que a execu\xE7\xE3o do lock terminou nesta m\xE1quina. Preservar o lock.");
26795
+ }
26796
+ try {
26797
+ process.kill(owner.pid, 0);
26798
+ } catch (error45) {
26799
+ if (error45.code === "ESRCH") {
26800
+ const archived = `${lockDir}.interrupted-${createHash7("sha256").update(ownerRaw).digest("hex")}`;
26801
+ await rename8(lockDir, archived);
26802
+ try {
26803
+ await mkdir7(lockDir);
26804
+ } catch {
26805
+ throw new Error("Este plano j\xE1 est\xE1 em execu\xE7\xE3o; a recupera\xE7\xE3o ficou preservada.");
26806
+ }
26807
+ return owner;
26808
+ }
26809
+ throw new Error("N\xE3o \xE9 poss\xEDvel verificar o processo do lock. Preservar o lock.");
26810
+ }
26811
+ throw new Error("Este plano j\xE1 est\xE1 em execu\xE7\xE3o. Aguardar o fim da chamada antes de retomar.");
26812
+ }
26715
26813
  function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
26716
26814
  return tool({
26717
- description: "Executa em c\xF3digo os lotes Jev pendentes de um plano preparado. Guarda cada resposta crua e nunca repete lotes com resposta ou aceita\xE7\xE3o j\xE1 guardada. Requer a aprova\xE7\xE3o habitual para as chamadas pagas antes de usar.",
26718
- args: { plan_file: tool.schema.string().describe("Caminho de jev/plan.json dentro do workspace") },
26815
+ description: "Executa os lotes Jev pendentes, recupera respostas v\xE1lidas e permite no m\xE1ximo uma repeti\xE7\xE3o por lote com resultado perdido. Requer a aprova\xE7\xE3o habitual para as chamadas pagas antes de usar.",
26816
+ args: {
26817
+ plan_file: tool.schema.string().describe("Caminho de jev/plan.json dentro do workspace"),
26818
+ batch_id: tool.schema.string().optional().describe("Executar apenas este lote, com o mesmo limite de recupera\xE7\xE3o")
26819
+ },
26719
26820
  async execute(args, context) {
26720
26821
  const planFile = await fileInsideWorkspace(context.directory, args.plan_file);
26721
26822
  if (path12.basename(planFile) !== "plan.json" || path12.basename(path12.dirname(planFile)) !== "jev") throw new Error("Indica o ficheiro jev/plan.json.");
26722
26823
  const runDir = path12.dirname(path12.dirname(planFile));
26723
26824
  const plan = JSON.parse(await readFile11(planFile, "utf8"));
26724
26825
  if (plan.engine !== "jev-batch" || plan.model !== "typesafe/jev-1.13" || !Array.isArray(plan.batches)) throw new Error("O plano Jev \xE9 inv\xE1lido.");
26725
- const batches = plan.batches;
26826
+ const allBatches = plan.batches;
26827
+ const batches = args.batch_id ? allBatches.filter((batch) => batch.batch_id === args.batch_id) : allBatches;
26828
+ if (args.batch_id && batches.length !== 1) throw new Error("O lote indicado n\xE3o pertence ao plano Jev.");
26726
26829
  const responsePath = path12.join(runDir, "jev", "responses");
26727
- await mkdir7(responsePath, { recursive: true });
26830
+ await ensureJevDirectory(responsePath);
26728
26831
  const responseDir = await fileInsideWorkspace(context.directory, responsePath);
26729
26832
  if (path12.dirname(responseDir) !== path12.join(runDir, "jev")) throw new Error("A pasta de respostas tem de pertencer ao run Jev.");
26730
- const decide = createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseDir);
26731
26833
  const lockDir = path12.join(runDir, "jev", ".decide-run.lock");
26732
- try {
26733
- await mkdir7(lockDir);
26734
- } catch (error45) {
26735
- if (error45.code !== "EEXIST") throw error45;
26736
- throw new Error("Este plano j\xE1 est\xE1 em execu\xE7\xE3o ou tem uma chamada interrompida. Verificar as respostas e recuperar o lote antes de remover jev/.decide-run.lock; n\xE3o repetir chamadas incertas.");
26737
- }
26738
- let releaseLock = true;
26834
+ const interrupted = await acquireJevRunLock(lockDir);
26739
26835
  let saved = 0;
26740
26836
  let skipped = 0;
26837
+ let recovered = 0;
26838
+ const repeated = [];
26741
26839
  try {
26742
- await writeFile8(path12.join(lockDir, "owner.json"), JSON.stringify({ pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
26840
+ const ownerFile = path12.join(lockDir, "owner.json");
26841
+ await writeOwnerOnlyTextAtomic(ownerFile, JSON.stringify({ ...interrupted, pid: process.pid, hostname: os5.hostname(), started_at: (/* @__PURE__ */ new Date()).toISOString() }));
26842
+ const attemptsPath = path12.join(runDir, "jev", "attempts");
26843
+ await ensureJevDirectory(attemptsPath);
26844
+ const attemptsDir = await fileInsideWorkspace(context.directory, attemptsPath);
26845
+ if (path12.dirname(attemptsDir) !== path12.join(runDir, "jev")) throw new Error("A pasta de tentativas tem de pertencer ao run Jev.");
26743
26846
  for (const batch of batches) {
26744
26847
  context.abort.throwIfAborted();
26745
26848
  const batchId = batch.batch_id;
@@ -26753,49 +26856,120 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
26753
26856
  const request = JSON.parse(await readFile11(requestFile, "utf8"));
26754
26857
  const fingerprint = createHash7("sha256").update(canonicalJson(request)).digest("hex");
26755
26858
  if (fingerprint !== batch.request_fingerprint) throw new Error(`${batchId}: fingerprint do pedido n\xE3o corresponde ao plano.`);
26756
- if (await fileExists(acceptedFile) || await fileExists(responseFile)) {
26859
+ if (await fileExists(acceptedFile)) {
26757
26860
  skipped++;
26758
26861
  continue;
26759
26862
  }
26760
- let result;
26761
- await writeFile8(path12.join(lockDir, "owner.json"), JSON.stringify({ pid: process.pid, batch_id: batchId, request_fingerprint: fingerprint, started_at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
26762
- try {
26763
- const output = await decide.execute({ request_file: requestFile }, context);
26764
- result = JSON.parse(typeof output === "string" ? output : output.output);
26765
- } catch (error45) {
26766
- releaseLock = error45 instanceof ForgeDecisionRejectedError;
26767
- return JSON.stringify({ verified: false, saved, skipped, stopped_at: batchId, recovery_lock: releaseLock ? void 0 : lockDir, error: error45 instanceof Error ? error45.message : "Falha na chamada Jev." });
26863
+ if (await fileExists(responseFile)) {
26864
+ const body = await validateSavedDecision(await fileInsideWorkspace(context.directory, responseFile), request);
26865
+ if (args.batch_id) return JSON.stringify({ ...body, response_file: responseFile });
26866
+ skipped++;
26867
+ continue;
26768
26868
  }
26769
- if (typeof result.response_file !== "string") {
26770
- releaseLock = false;
26771
- return JSON.stringify({ verified: false, saved, skipped, stopped_at: batchId, recovery_response: result, error: result.persistence_error ?? "Resposta Jev sem ficheiro guardado; recuperar do hist\xF3rico, sem repetir." });
26869
+ const attemptsFile = path12.join(attemptsDir, `${batchId}.json`);
26870
+ let attempts = { request_fingerprint: fingerprint, attempts: 0, response_files: [] };
26871
+ if (await fileExists(attemptsFile)) attempts = JSON.parse(await readFile11(attemptsFile, "utf8"));
26872
+ else if (interrupted.batch_id === batchId) {
26873
+ if (interrupted.request_fingerprint !== fingerprint) throw new Error(`${batchId}: fingerprint da chamada interrompida n\xE3o corresponde ao plano.`);
26874
+ attempts.attempts = 1;
26772
26875
  }
26773
- try {
26774
- await link(result.response_file, responseFile);
26775
- } catch {
26776
- releaseLock = false;
26777
- return JSON.stringify({
26778
- verified: false,
26779
- saved,
26780
- skipped,
26781
- stopped_at: batchId,
26782
- recovery_file: result.response_file,
26783
- error: "Resposta conclu\xEDda mas n\xE3o copiada para o run; recuperar o ficheiro indicado, sem repetir a chamada."
26876
+ if (attempts.request_fingerprint !== fingerprint || !Number.isInteger(attempts.attempts) || attempts.attempts < 0 || attempts.attempts > 2 || !Array.isArray(attempts.response_files)) {
26877
+ throw new Error(`${batchId}: registo de tentativas inv\xE1lido; preservar e verificar antes de continuar.`);
26878
+ }
26879
+ if (attempts.repeated_at) repeated.push(batchId);
26880
+ const persistAttempts = () => writeOwnerOnlyTextAtomic(attemptsFile, JSON.stringify(attempts));
26881
+ if (!await fileExists(attemptsFile) && attempts.attempts > 0) await persistAttempts();
26882
+ const stop = (error45, detail = {}) => JSON.stringify({ verified: false, saved, skipped, recovered, repeated, stopped_at: batchId, ...detail, error: error45 });
26883
+ const recoverResponse = async () => {
26884
+ const legacyAllocations = interrupted.batch_id === batchId && interrupted.request_fingerprint === fingerprint ? (await readdir5(responseDir)).filter((name) => name.startsWith(".forge-decision-")).map((name) => path12.join(responseDir, name, "response.json")) : [];
26885
+ const candidates = [...attempts.response_files, ...legacyAllocations];
26886
+ for (const candidate of new Set(candidates)) {
26887
+ if (typeof candidate !== "string") throw new Error("Registo de recupera\xE7\xE3o inv\xE1lido.");
26888
+ if (!await fileExists(candidate)) continue;
26889
+ const file2 = await fileInsideWorkspace(context.directory, candidate);
26890
+ if (path12.dirname(path12.dirname(file2)) !== responseDir) throw new Error("Resposta recuper\xE1vel fora da pasta do lote.");
26891
+ try {
26892
+ await validateSavedDecision(file2, request);
26893
+ } catch {
26894
+ continue;
26895
+ }
26896
+ if (!attempts.response_files.includes(file2)) {
26897
+ attempts.response_files.push(file2);
26898
+ await persistAttempts();
26899
+ }
26900
+ return file2;
26901
+ }
26902
+ return void 0;
26903
+ };
26904
+ let source = await recoverResponse();
26905
+ if (source) recovered++;
26906
+ while (!source) {
26907
+ context.abort.throwIfAborted();
26908
+ if (attempts.attempts >= 2) return stop("A \xFAnica repeti\xE7\xE3o deste lote j\xE1 foi usada. Preservar o progresso e recuperar a resposta do hist\xF3rico acess\xEDvel.");
26909
+ const previousAttempts = attempts.attempts;
26910
+ const decide = createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseDir, async (allocated) => {
26911
+ await writeOwnerOnlyTextAtomic(ownerFile, JSON.stringify({ pid: process.pid, hostname: os5.hostname(), batch_id: batchId, request_fingerprint: fingerprint, started_at: (/* @__PURE__ */ new Date()).toISOString() }));
26912
+ const next = { ...attempts, attempts: attempts.attempts + 1, response_files: [...attempts.response_files, allocated] };
26913
+ if (next.attempts === 2) next.repeated_at = (/* @__PURE__ */ new Date()).toISOString();
26914
+ await writeOwnerOnlyTextAtomic(attemptsFile, JSON.stringify(next));
26915
+ attempts = next;
26784
26916
  });
26917
+ let result;
26918
+ try {
26919
+ result = JSON.parse(await decide.execute({ request_file: requestFile }, context));
26920
+ } catch (error45) {
26921
+ if (error45 instanceof ForgeDecisionRejectedError) {
26922
+ attempts.attempts = previousAttempts;
26923
+ if (previousAttempts < 2) delete attempts.repeated_at;
26924
+ await persistAttempts();
26925
+ return stop(error45.message);
26926
+ }
26927
+ if (attempts.attempts === previousAttempts) return stop(error45 instanceof Error ? error45.message : "Falha local antes da chamada Jev.");
26928
+ if (attempts.attempts === 2 && !repeated.includes(batchId)) repeated.push(batchId);
26929
+ if (context.abort.aborted) return stop("Execu\xE7\xE3o interrompida; preservar o progresso e retomar quando poss\xEDvel.");
26930
+ source = await recoverResponse();
26931
+ if (source) recovered++;
26932
+ continue;
26933
+ }
26934
+ if (attempts.attempts === 2 && !repeated.includes(batchId)) repeated.push(batchId);
26935
+ if (typeof result.response_file !== "string") return stop(String(result.persistence_error), { recovery_response: result, persistence_code: result.persistence_code });
26936
+ source = result.response_file;
26937
+ try {
26938
+ await validateSavedDecision(source, request);
26939
+ } catch (error45) {
26940
+ return stop(error45 instanceof Error ? error45.message : "Resposta inv\xE1lida.", { recovery_file: source });
26941
+ }
26942
+ }
26943
+ try {
26944
+ await link(source, responseFile);
26945
+ } catch (error45) {
26946
+ let identical = false;
26947
+ if (error45.code === "EEXIST") {
26948
+ try {
26949
+ identical = await readFile11(source, "utf8") === await readFile11(responseFile, "utf8");
26950
+ } catch {
26951
+ }
26952
+ }
26953
+ if (!identical) {
26954
+ return stop("Resposta conclu\xEDda mas n\xE3o guardada no destino do lote; resolver a grava\xE7\xE3o e retomar sem nova chamada.", { recovery_file: source, persistence_code: error45.code });
26955
+ }
26785
26956
  }
26786
- await unlink(result.response_file).then(() => rmdir(path12.dirname(result.response_file))).catch(() => void 0);
26957
+ await unlink(source).then(() => rmdir(path12.dirname(source))).catch(() => void 0);
26787
26958
  saved++;
26959
+ if (args.batch_id) return JSON.stringify({ ...await validateSavedDecision(responseFile, request), response_file: responseFile, repeated });
26788
26960
  }
26789
26961
  return JSON.stringify({
26790
26962
  verified: true,
26791
26963
  batch_count: batches.length,
26792
26964
  saved,
26793
26965
  skipped,
26966
+ recovered,
26967
+ repeated,
26794
26968
  response_dir: responseDir,
26795
26969
  next_step: "Executar jev-accept sobre as respostas guardadas ainda n\xE3o aceites; depois jev-validate e jev-merge."
26796
26970
  });
26797
26971
  } finally {
26798
- if (releaseLock) await rm6(lockDir, { recursive: true });
26972
+ await rm6(lockDir, { recursive: true });
26799
26973
  }
26800
26974
  }
26801
26975
  });
@@ -27053,5 +27227,6 @@ export {
27053
27227
  FORGE_DECISION_TIMEOUT_MS,
27054
27228
  ForgeWorkPackSyncServer,
27055
27229
  workPackSyncPlugin_default as default,
27230
+ ensureJevDirectory,
27056
27231
  resolveDecisionBaseUrl
27057
27232
  };
package/dist/repair.js CHANGED
@@ -161,7 +161,25 @@ async function assertExistingDirectoryIsSafe(directory, options) {
161
161
  }
162
162
  async function prepareOwnerOnlyFileDestination(filePath, options = {}) {
163
163
  const directory = path.dirname(filePath);
164
- const createdDirectory = await mkdir2(directory, { recursive: true, mode: 448 });
164
+ let existing;
165
+ try {
166
+ existing = await stat(directory);
167
+ } catch (error) {
168
+ if (error.code !== "ENOENT") throw error;
169
+ }
170
+ if (existing) {
171
+ if (!existing.isDirectory()) throw new Error(`O destino ${directory} existe, mas n\xE3o \xE9 um diret\xF3rio`);
172
+ await assertExistingDirectoryIsSafe(directory, options);
173
+ return;
174
+ }
175
+ let createdDirectory;
176
+ try {
177
+ createdDirectory = await mkdir2(directory, { recursive: true, mode: 448 });
178
+ } catch (error) {
179
+ if (error.code !== "EEXIST" || !(await stat(directory)).isDirectory()) throw error;
180
+ await assertExistingDirectoryIsSafe(directory, options);
181
+ return;
182
+ }
165
183
  if (createdDirectory !== void 0) await protectOwnerOnlyPath(directory, "directory", options);
166
184
  else await assertExistingDirectoryIsSafe(directory, options);
167
185
  }
@@ -401,7 +419,7 @@ var DEVICE_ENROLLMENT_PROTOCOL_VERSION = 1;
401
419
  // packages/shared/src/contracts/settings.ts
402
420
  var DOCUMENT_READER_AGENT = "document-reader";
403
421
  var OPENROUTER_ALIAS_PROVIDER_NAME = "OpenRouter (via Forge)";
404
- var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.43";
422
+ var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.44";
405
423
  var WORK_PACK_SYNC_PLUGIN_PACKAGE = `minimal-forge-work-pack-sync@${WORK_PACK_SYNC_PLUGIN_VERSION}`;
406
424
  var WORK_PACK_SYNC_PLUGIN_FILENAME = `minimal-forge-work-pack-sync-${WORK_PACK_SYNC_PLUGIN_VERSION}.tgz`;
407
425
  var FIRECRAWL_KEYLESS_MCP_NAME = "firecrawl";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "minimal-forge-work-pack-sync",
3
- "version": "0.1.43",
3
+ "version": "0.1.44",
4
4
  "description": "Minimal Forge Work Pack startup synchronization for OpenCode and OpenWork.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {