minimal-forge-work-pack-sync 0.1.11 → 0.1.12

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 +732 -259
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -117,17 +117,17 @@ var require_visit = __commonJS({
117
117
  visit.BREAK = BREAK;
118
118
  visit.SKIP = SKIP;
119
119
  visit.REMOVE = REMOVE;
120
- function visit_(key, node, visitor, path4) {
121
- const ctrl = callVisitor(key, node, visitor, path4);
120
+ function visit_(key, node, visitor, path5) {
121
+ const ctrl = callVisitor(key, node, visitor, path5);
122
122
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
123
- replaceNode(key, path4, ctrl);
124
- return visit_(key, ctrl, visitor, path4);
123
+ replaceNode(key, path5, ctrl);
124
+ return visit_(key, ctrl, visitor, path5);
125
125
  }
126
126
  if (typeof ctrl !== "symbol") {
127
127
  if (identity.isCollection(node)) {
128
- path4 = Object.freeze(path4.concat(node));
128
+ path5 = Object.freeze(path5.concat(node));
129
129
  for (let i = 0; i < node.items.length; ++i) {
130
- const ci2 = visit_(i, node.items[i], visitor, path4);
130
+ const ci2 = visit_(i, node.items[i], visitor, path5);
131
131
  if (typeof ci2 === "number")
132
132
  i = ci2 - 1;
133
133
  else if (ci2 === BREAK)
@@ -138,13 +138,13 @@ var require_visit = __commonJS({
138
138
  }
139
139
  }
140
140
  } else if (identity.isPair(node)) {
141
- path4 = Object.freeze(path4.concat(node));
142
- const ck = visit_("key", node.key, visitor, path4);
141
+ path5 = Object.freeze(path5.concat(node));
142
+ const ck = visit_("key", node.key, visitor, path5);
143
143
  if (ck === BREAK)
144
144
  return BREAK;
145
145
  else if (ck === REMOVE)
146
146
  node.key = null;
147
- const cv = visit_("value", node.value, visitor, path4);
147
+ const cv = visit_("value", node.value, visitor, path5);
148
148
  if (cv === BREAK)
149
149
  return BREAK;
150
150
  else if (cv === REMOVE)
@@ -165,17 +165,17 @@ var require_visit = __commonJS({
165
165
  visitAsync.BREAK = BREAK;
166
166
  visitAsync.SKIP = SKIP;
167
167
  visitAsync.REMOVE = REMOVE;
168
- async function visitAsync_(key, node, visitor, path4) {
169
- const ctrl = await callVisitor(key, node, visitor, path4);
168
+ async function visitAsync_(key, node, visitor, path5) {
169
+ const ctrl = await callVisitor(key, node, visitor, path5);
170
170
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
171
- replaceNode(key, path4, ctrl);
172
- return visitAsync_(key, ctrl, visitor, path4);
171
+ replaceNode(key, path5, ctrl);
172
+ return visitAsync_(key, ctrl, visitor, path5);
173
173
  }
174
174
  if (typeof ctrl !== "symbol") {
175
175
  if (identity.isCollection(node)) {
176
- path4 = Object.freeze(path4.concat(node));
176
+ path5 = Object.freeze(path5.concat(node));
177
177
  for (let i = 0; i < node.items.length; ++i) {
178
- const ci2 = await visitAsync_(i, node.items[i], visitor, path4);
178
+ const ci2 = await visitAsync_(i, node.items[i], visitor, path5);
179
179
  if (typeof ci2 === "number")
180
180
  i = ci2 - 1;
181
181
  else if (ci2 === BREAK)
@@ -186,13 +186,13 @@ var require_visit = __commonJS({
186
186
  }
187
187
  }
188
188
  } else if (identity.isPair(node)) {
189
- path4 = Object.freeze(path4.concat(node));
190
- const ck = await visitAsync_("key", node.key, visitor, path4);
189
+ path5 = Object.freeze(path5.concat(node));
190
+ const ck = await visitAsync_("key", node.key, visitor, path5);
191
191
  if (ck === BREAK)
192
192
  return BREAK;
193
193
  else if (ck === REMOVE)
194
194
  node.key = null;
195
- const cv = await visitAsync_("value", node.value, visitor, path4);
195
+ const cv = await visitAsync_("value", node.value, visitor, path5);
196
196
  if (cv === BREAK)
197
197
  return BREAK;
198
198
  else if (cv === REMOVE)
@@ -219,23 +219,23 @@ var require_visit = __commonJS({
219
219
  }
220
220
  return visitor;
221
221
  }
222
- function callVisitor(key, node, visitor, path4) {
222
+ function callVisitor(key, node, visitor, path5) {
223
223
  if (typeof visitor === "function")
224
- return visitor(key, node, path4);
224
+ return visitor(key, node, path5);
225
225
  if (identity.isMap(node))
226
- return visitor.Map?.(key, node, path4);
226
+ return visitor.Map?.(key, node, path5);
227
227
  if (identity.isSeq(node))
228
- return visitor.Seq?.(key, node, path4);
228
+ return visitor.Seq?.(key, node, path5);
229
229
  if (identity.isPair(node))
230
- return visitor.Pair?.(key, node, path4);
230
+ return visitor.Pair?.(key, node, path5);
231
231
  if (identity.isScalar(node))
232
- return visitor.Scalar?.(key, node, path4);
232
+ return visitor.Scalar?.(key, node, path5);
233
233
  if (identity.isAlias(node))
234
- return visitor.Alias?.(key, node, path4);
234
+ return visitor.Alias?.(key, node, path5);
235
235
  return void 0;
236
236
  }
237
- function replaceNode(key, path4, node) {
238
- const parent = path4[path4.length - 1];
237
+ function replaceNode(key, path5, node) {
238
+ const parent = path5[path5.length - 1];
239
239
  if (identity.isCollection(parent)) {
240
240
  parent.items[key] = node;
241
241
  } else if (identity.isPair(parent)) {
@@ -845,10 +845,10 @@ var require_Collection = __commonJS({
845
845
  var createNode = require_createNode();
846
846
  var identity = require_identity();
847
847
  var Node = require_Node();
848
- function collectionFromPath(schema, path4, value) {
848
+ function collectionFromPath(schema, path5, value) {
849
849
  let v2 = value;
850
- for (let i = path4.length - 1; i >= 0; --i) {
851
- const k2 = path4[i];
850
+ for (let i = path5.length - 1; i >= 0; --i) {
851
+ const k2 = path5[i];
852
852
  if (typeof k2 === "number" && Number.isInteger(k2) && k2 >= 0) {
853
853
  const a = [];
854
854
  a[k2] = v2;
@@ -867,7 +867,7 @@ var require_Collection = __commonJS({
867
867
  sourceObjects: /* @__PURE__ */ new Map()
868
868
  });
869
869
  }
870
- var isEmptyPath = (path4) => path4 == null || typeof path4 === "object" && !!path4[Symbol.iterator]().next().done;
870
+ var isEmptyPath = (path5) => path5 == null || typeof path5 === "object" && !!path5[Symbol.iterator]().next().done;
871
871
  var Collection = class extends Node.NodeBase {
872
872
  constructor(type, schema) {
873
873
  super(type);
@@ -897,11 +897,11 @@ var require_Collection = __commonJS({
897
897
  * be a Pair instance or a `{ key, value }` object, which may not have a key
898
898
  * that already exists in the map.
899
899
  */
900
- addIn(path4, value) {
901
- if (isEmptyPath(path4))
900
+ addIn(path5, value) {
901
+ if (isEmptyPath(path5))
902
902
  this.add(value);
903
903
  else {
904
- const [key, ...rest] = path4;
904
+ const [key, ...rest] = path5;
905
905
  const node = this.get(key, true);
906
906
  if (identity.isCollection(node))
907
907
  node.addIn(rest, value);
@@ -915,8 +915,8 @@ var require_Collection = __commonJS({
915
915
  * Removes a value from the collection.
916
916
  * @returns `true` if the item was found and removed.
917
917
  */
918
- deleteIn(path4) {
919
- const [key, ...rest] = path4;
918
+ deleteIn(path5) {
919
+ const [key, ...rest] = path5;
920
920
  if (rest.length === 0)
921
921
  return this.delete(key);
922
922
  const node = this.get(key, true);
@@ -930,8 +930,8 @@ var require_Collection = __commonJS({
930
930
  * scalar values from their surrounding node; to disable set `keepScalar` to
931
931
  * `true` (collections are always returned intact).
932
932
  */
933
- getIn(path4, keepScalar) {
934
- const [key, ...rest] = path4;
933
+ getIn(path5, keepScalar) {
934
+ const [key, ...rest] = path5;
935
935
  const node = this.get(key, true);
936
936
  if (rest.length === 0)
937
937
  return !keepScalar && identity.isScalar(node) ? node.value : node;
@@ -949,8 +949,8 @@ var require_Collection = __commonJS({
949
949
  /**
950
950
  * Checks if the collection includes a value with the key `key`.
951
951
  */
952
- hasIn(path4) {
953
- const [key, ...rest] = path4;
952
+ hasIn(path5) {
953
+ const [key, ...rest] = path5;
954
954
  if (rest.length === 0)
955
955
  return this.has(key);
956
956
  const node = this.get(key, true);
@@ -960,8 +960,8 @@ var require_Collection = __commonJS({
960
960
  * Sets a value in this collection. For `!!set`, `value` needs to be a
961
961
  * boolean to add/remove the item from the set.
962
962
  */
963
- setIn(path4, value) {
964
- const [key, ...rest] = path4;
963
+ setIn(path5, value) {
964
+ const [key, ...rest] = path5;
965
965
  if (rest.length === 0) {
966
966
  this.set(key, value);
967
967
  } else {
@@ -3476,9 +3476,9 @@ var require_Document = __commonJS({
3476
3476
  this.contents.add(value);
3477
3477
  }
3478
3478
  /** Adds a value to the document. */
3479
- addIn(path4, value) {
3479
+ addIn(path5, value) {
3480
3480
  if (assertCollection(this.contents))
3481
- this.contents.addIn(path4, value);
3481
+ this.contents.addIn(path5, value);
3482
3482
  }
3483
3483
  /**
3484
3484
  * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
@@ -3553,14 +3553,14 @@ var require_Document = __commonJS({
3553
3553
  * Removes a value from the document.
3554
3554
  * @returns `true` if the item was found and removed.
3555
3555
  */
3556
- deleteIn(path4) {
3557
- if (Collection.isEmptyPath(path4)) {
3556
+ deleteIn(path5) {
3557
+ if (Collection.isEmptyPath(path5)) {
3558
3558
  if (this.contents == null)
3559
3559
  return false;
3560
3560
  this.contents = null;
3561
3561
  return true;
3562
3562
  }
3563
- return assertCollection(this.contents) ? this.contents.deleteIn(path4) : false;
3563
+ return assertCollection(this.contents) ? this.contents.deleteIn(path5) : false;
3564
3564
  }
3565
3565
  /**
3566
3566
  * Returns item at `key`, or `undefined` if not found. By default unwraps
@@ -3575,10 +3575,10 @@ var require_Document = __commonJS({
3575
3575
  * scalar values from their surrounding node; to disable set `keepScalar` to
3576
3576
  * `true` (collections are always returned intact).
3577
3577
  */
3578
- getIn(path4, keepScalar) {
3579
- if (Collection.isEmptyPath(path4))
3578
+ getIn(path5, keepScalar) {
3579
+ if (Collection.isEmptyPath(path5))
3580
3580
  return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
3581
- return identity.isCollection(this.contents) ? this.contents.getIn(path4, keepScalar) : void 0;
3581
+ return identity.isCollection(this.contents) ? this.contents.getIn(path5, keepScalar) : void 0;
3582
3582
  }
3583
3583
  /**
3584
3584
  * Checks if the document includes a value with the key `key`.
@@ -3589,10 +3589,10 @@ var require_Document = __commonJS({
3589
3589
  /**
3590
3590
  * Checks if the document includes a value at `path`.
3591
3591
  */
3592
- hasIn(path4) {
3593
- if (Collection.isEmptyPath(path4))
3592
+ hasIn(path5) {
3593
+ if (Collection.isEmptyPath(path5))
3594
3594
  return this.contents !== void 0;
3595
- return identity.isCollection(this.contents) ? this.contents.hasIn(path4) : false;
3595
+ return identity.isCollection(this.contents) ? this.contents.hasIn(path5) : false;
3596
3596
  }
3597
3597
  /**
3598
3598
  * Sets a value in this document. For `!!set`, `value` needs to be a
@@ -3609,13 +3609,13 @@ var require_Document = __commonJS({
3609
3609
  * Sets a value in this document. For `!!set`, `value` needs to be a
3610
3610
  * boolean to add/remove the item from the set.
3611
3611
  */
3612
- setIn(path4, value) {
3613
- if (Collection.isEmptyPath(path4)) {
3612
+ setIn(path5, value) {
3613
+ if (Collection.isEmptyPath(path5)) {
3614
3614
  this.contents = value;
3615
3615
  } else if (this.contents == null) {
3616
- this.contents = Collection.collectionFromPath(this.schema, Array.from(path4), value);
3616
+ this.contents = Collection.collectionFromPath(this.schema, Array.from(path5), value);
3617
3617
  } else if (assertCollection(this.contents)) {
3618
- this.contents.setIn(path4, value);
3618
+ this.contents.setIn(path5, value);
3619
3619
  }
3620
3620
  }
3621
3621
  /**
@@ -5575,9 +5575,9 @@ var require_cst_visit = __commonJS({
5575
5575
  visit.BREAK = BREAK;
5576
5576
  visit.SKIP = SKIP;
5577
5577
  visit.REMOVE = REMOVE;
5578
- visit.itemAtPath = (cst, path4) => {
5578
+ visit.itemAtPath = (cst, path5) => {
5579
5579
  let item = cst;
5580
- for (const [field, index] of path4) {
5580
+ for (const [field, index] of path5) {
5581
5581
  const tok = item?.[field];
5582
5582
  if (tok && "items" in tok) {
5583
5583
  item = tok.items[index];
@@ -5586,23 +5586,23 @@ var require_cst_visit = __commonJS({
5586
5586
  }
5587
5587
  return item;
5588
5588
  };
5589
- visit.parentCollection = (cst, path4) => {
5590
- const parent = visit.itemAtPath(cst, path4.slice(0, -1));
5591
- const field = path4[path4.length - 1][0];
5589
+ visit.parentCollection = (cst, path5) => {
5590
+ const parent = visit.itemAtPath(cst, path5.slice(0, -1));
5591
+ const field = path5[path5.length - 1][0];
5592
5592
  const coll = parent?.[field];
5593
5593
  if (coll && "items" in coll)
5594
5594
  return coll;
5595
5595
  throw new Error("Parent collection not found");
5596
5596
  };
5597
- function _visit(path4, item, visitor) {
5598
- let ctrl = visitor(item, path4);
5597
+ function _visit(path5, item, visitor) {
5598
+ let ctrl = visitor(item, path5);
5599
5599
  if (typeof ctrl === "symbol")
5600
5600
  return ctrl;
5601
5601
  for (const field of ["key", "value"]) {
5602
5602
  const token = item[field];
5603
5603
  if (token && "items" in token) {
5604
5604
  for (let i = 0; i < token.items.length; ++i) {
5605
- const ci2 = _visit(Object.freeze(path4.concat([[field, i]])), token.items[i], visitor);
5605
+ const ci2 = _visit(Object.freeze(path5.concat([[field, i]])), token.items[i], visitor);
5606
5606
  if (typeof ci2 === "number")
5607
5607
  i = ci2 - 1;
5608
5608
  else if (ci2 === BREAK)
@@ -5613,10 +5613,10 @@ var require_cst_visit = __commonJS({
5613
5613
  }
5614
5614
  }
5615
5615
  if (typeof ctrl === "function" && field === "key")
5616
- ctrl = ctrl(item, path4);
5616
+ ctrl = ctrl(item, path5);
5617
5617
  }
5618
5618
  }
5619
- return typeof ctrl === "function" ? ctrl(item, path4) : ctrl;
5619
+ return typeof ctrl === "function" ? ctrl(item, path5) : ctrl;
5620
5620
  }
5621
5621
  exports.visit = visit;
5622
5622
  }
@@ -7369,8 +7369,8 @@ var require_dist = __commonJS({
7369
7369
 
7370
7370
  // packages/cli/src/workPackSyncPlugin.ts
7371
7371
  var import_yaml = __toESM(require_dist(), 1);
7372
- import { mkdir as mkdir2, readdir as readdir2, readFile as readFile2, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
7373
- import path3 from "node:path";
7372
+ import { mkdir as mkdir3, readdir as readdir3, readFile as readFile3, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
7373
+ import path4 from "node:path";
7374
7374
 
7375
7375
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/classic/external.js
7376
7376
  var external_exports = {};
@@ -8103,10 +8103,10 @@ function mergeDefs(...defs) {
8103
8103
  function cloneDef(schema) {
8104
8104
  return mergeDefs(schema._zod.def);
8105
8105
  }
8106
- function getElementAtPath(obj, path4) {
8107
- if (!path4)
8106
+ function getElementAtPath(obj, path5) {
8107
+ if (!path5)
8108
8108
  return obj;
8109
- return path4.reduce((acc, key) => acc?.[key], obj);
8109
+ return path5.reduce((acc, key) => acc?.[key], obj);
8110
8110
  }
8111
8111
  function promiseAllObject(promisesObj) {
8112
8112
  const keys = Object.keys(promisesObj);
@@ -8467,11 +8467,11 @@ function aborted(x, startIndex = 0) {
8467
8467
  }
8468
8468
  return false;
8469
8469
  }
8470
- function prefixIssues(path4, issues) {
8470
+ function prefixIssues(path5, issues) {
8471
8471
  return issues.map((iss) => {
8472
8472
  var _a;
8473
8473
  (_a = iss).path ?? (_a.path = []);
8474
- iss.path.unshift(path4);
8474
+ iss.path.unshift(path5);
8475
8475
  return iss;
8476
8476
  });
8477
8477
  }
@@ -8639,7 +8639,7 @@ function treeifyError(error45, _mapper) {
8639
8639
  return issue2.message;
8640
8640
  };
8641
8641
  const result = { errors: [] };
8642
- const processError = (error46, path4 = []) => {
8642
+ const processError = (error46, path5 = []) => {
8643
8643
  var _a, _b;
8644
8644
  for (const issue2 of error46.issues) {
8645
8645
  if (issue2.code === "invalid_union" && issue2.errors.length) {
@@ -8649,7 +8649,7 @@ function treeifyError(error45, _mapper) {
8649
8649
  } else if (issue2.code === "invalid_element") {
8650
8650
  processError({ issues: issue2.issues }, issue2.path);
8651
8651
  } else {
8652
- const fullpath = [...path4, ...issue2.path];
8652
+ const fullpath = [...path5, ...issue2.path];
8653
8653
  if (fullpath.length === 0) {
8654
8654
  result.errors.push(mapper(issue2));
8655
8655
  continue;
@@ -8681,8 +8681,8 @@ function treeifyError(error45, _mapper) {
8681
8681
  }
8682
8682
  function toDotPath(_path) {
8683
8683
  const segs = [];
8684
- const path4 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
8685
- for (const seg of path4) {
8684
+ const path5 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
8685
+ for (const seg of path5) {
8686
8686
  if (typeof seg === "number")
8687
8687
  segs.push(`[${seg}]`);
8688
8688
  else if (typeof seg === "symbol")
@@ -19883,10 +19883,10 @@ async function reportWorkPackObservations(credentials, kind, workPacks) {
19883
19883
  }
19884
19884
 
19885
19885
  // packages/cli/src/sync.ts
19886
- import { createHash } from "node:crypto";
19887
- import { chmod, cp, lstat, mkdtemp, mkdir, readdir, readFile, rm, rename, writeFile } from "node:fs/promises";
19886
+ import { createHash as createHash2 } from "node:crypto";
19887
+ import { chmod, cp, lstat as lstat2, mkdtemp, mkdir as mkdir2, readdir as readdir2, readFile as readFile2, rm, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
19888
19888
  import os4 from "node:os";
19889
- import path2 from "node:path";
19889
+ import path3 from "node:path";
19890
19890
 
19891
19891
  // node_modules/tar/dist/esm/index.min.js
19892
19892
  import Qr from "events";
@@ -23033,7 +23033,7 @@ var DEFAULT_DEBUG_TRACE_LIMITS = {
23033
23033
  };
23034
23034
 
23035
23035
  // packages/shared/src/contracts/settings.ts
23036
- var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.11";
23036
+ var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.12";
23037
23037
  var WORK_PACK_SYNC_PLUGIN_PACKAGE = `minimal-forge-work-pack-sync@${WORK_PACK_SYNC_PLUGIN_VERSION}`;
23038
23038
  var WORK_PACK_SYNC_PLUGIN_FILENAME = `minimal-forge-work-pack-sync-${WORK_PACK_SYNC_PLUGIN_VERSION}.tgz`;
23039
23039
  var FIRECRAWL_KEYLESS_MCP_NAME = "firecrawl";
@@ -23120,6 +23120,17 @@ async function reconcileWorkPacks(input) {
23120
23120
  }
23121
23121
  }
23122
23122
  }
23123
+ for (const [slug, code] of input.recoveryFailures ?? []) {
23124
+ if (outcomes.some((outcome) => outcome.slug === slug)) continue;
23125
+ outcomes.push({
23126
+ slug,
23127
+ action: "install",
23128
+ reason: "omitted",
23129
+ status: "failed",
23130
+ code: stableCode(code),
23131
+ message: `O pacote "${slug}" tem uma instala\xE7\xE3o interrompida que n\xE3o foi recuperada para preservar ficheiros locais. Corrija a causa indicada e volte a sincronizar.`
23132
+ });
23133
+ }
23123
23134
  const receiptValue = {
23124
23135
  schemaVersion: 1,
23125
23136
  completedAt: (input.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
@@ -23212,8 +23223,127 @@ function assertUniqueSlugs(packs, label) {
23212
23223
  }
23213
23224
  }
23214
23225
 
23226
+ // packages/cli/src/workPackLocalState.ts
23227
+ import { createHash } from "node:crypto";
23228
+ import { lstat, mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises";
23229
+ import path2 from "node:path";
23230
+ var WORK_PACK_LOCAL_STATE_FILENAME = ".forge-installed-state.json";
23231
+ async function writeWorkPackInstalledState(input) {
23232
+ const tree = await digestPackTree(input.packDir);
23233
+ if (!tree) throw new Error("O pacote de trabalho cont\xE9m uma entrada local n\xE3o regular");
23234
+ const state = {
23235
+ schemaVersion: 1,
23236
+ version: input.version,
23237
+ ...tree,
23238
+ agents: digestProjectionContents(input.agents),
23239
+ commands: digestProjectionContents(input.commands)
23240
+ };
23241
+ await writeJsonAtomic(path2.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
23242
+ }
23243
+ async function checkWorkPackInstalledState(input) {
23244
+ const state = await readInstalledState(input.packDir);
23245
+ if (!state) return "missing";
23246
+ return await matchesInstalledState(input, state) ? "match" : "changed";
23247
+ }
23248
+ async function checkWorkPackTreeState(packDir) {
23249
+ const state = await readInstalledState(packDir);
23250
+ if (!state) return "missing";
23251
+ const tree = await digestPackTree(packDir).catch(() => void 0);
23252
+ return tree && sameTree(tree, state) ? "match" : "changed";
23253
+ }
23254
+ async function adoptWorkPackInstalledState(input) {
23255
+ const state = await readInstalledState(input.expectedPackDir);
23256
+ if (!state || !await matchesInstalledState(input, state)) return false;
23257
+ await writeJsonAtomic(path2.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
23258
+ return checkWorkPackInstalledState(input).then((result) => result === "match");
23259
+ }
23260
+ async function readInstalledState(packDir) {
23261
+ const raw = await readFile(path2.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME), "utf8").catch(() => void 0);
23262
+ if (!raw) return void 0;
23263
+ try {
23264
+ const value = JSON.parse(raw);
23265
+ if (value.schemaVersion !== 1 || typeof value.version !== "string") return void 0;
23266
+ if (!validDigests(value.files, "path") || !validDigests(value.agents, "filename") || !validDigests(value.commands, "filename")) {
23267
+ return void 0;
23268
+ }
23269
+ if (!validDirectories(value.directories)) return void 0;
23270
+ return value;
23271
+ } catch {
23272
+ return void 0;
23273
+ }
23274
+ }
23275
+ async function digestPackTree(root) {
23276
+ const files = [];
23277
+ const directories = [];
23278
+ const visit = async (directory, prefix) => {
23279
+ const entries = await readdir(directory, { withFileTypes: true });
23280
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
23281
+ if (!prefix && entry.name === WORK_PACK_LOCAL_STATE_FILENAME) continue;
23282
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
23283
+ const absolute = path2.join(directory, entry.name);
23284
+ if (entry.isDirectory()) {
23285
+ directories.push(relative);
23286
+ if (!await visit(absolute, relative)) return false;
23287
+ continue;
23288
+ }
23289
+ if (!entry.isFile()) return false;
23290
+ files.push({ path: relative, sha256: digest(await readFile(absolute)) });
23291
+ }
23292
+ return true;
23293
+ };
23294
+ return await visit(root, "") ? { files, directories } : void 0;
23295
+ }
23296
+ function digestProjectionContents(files) {
23297
+ return files.map((file2) => ({ filename: file2.filename, sha256: digest(Buffer.from(file2.content)) })).sort((left, right) => left.filename.localeCompare(right.filename));
23298
+ }
23299
+ async function projectionsMatch(directory, expected) {
23300
+ for (const projection of expected) {
23301
+ const absolute = path2.join(directory, projection.filename);
23302
+ const info = await lstat(absolute).catch(() => void 0);
23303
+ if (!info?.isFile() || info.isSymbolicLink()) return false;
23304
+ const bytes = await readFile(absolute).catch(() => void 0);
23305
+ if (!bytes || digest(bytes) !== projection.sha256) return false;
23306
+ }
23307
+ return true;
23308
+ }
23309
+ function validDigests(value, pathKey) {
23310
+ return Array.isArray(value) && value.every((entry) => typeof entry === "object" && entry !== null && typeof entry[pathKey] === "string" && typeof entry.sha256 === "string" && /^[a-f0-9]{64}$/.test(entry.sha256) && validRelativePath(entry[pathKey], pathKey === "filename"));
23311
+ }
23312
+ function validDirectories(value) {
23313
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string" && validRelativePath(entry, false));
23314
+ }
23315
+ async function matchesInstalledState(input, state) {
23316
+ const tree = await digestPackTree(input.packDir).catch(() => void 0);
23317
+ if (!tree || !sameTree(tree, state)) return false;
23318
+ if (!await projectionsMatch(input.agentsDir, state.agents)) return false;
23319
+ return projectionsMatch(input.commandsDir, state.commands);
23320
+ }
23321
+ function validRelativePath(value, filenameOnly) {
23322
+ if (!value || path2.isAbsolute(value) || value.includes("\\")) return false;
23323
+ const parts = value.split("/");
23324
+ if (parts.some((part) => !part || part === "." || part === "..")) return false;
23325
+ return !filenameOnly || parts.length === 1;
23326
+ }
23327
+ function sameTree(left, right) {
23328
+ return sameDigests(left.files, right.files) && left.directories.length === right.directories.length && left.directories.every((entry, index) => entry === right.directories[index]);
23329
+ }
23330
+ function sameDigests(left, right) {
23331
+ return left.length === right.length && left.every((entry, index) => entry.path === right[index]?.path && entry.sha256 === right[index]?.sha256);
23332
+ }
23333
+ function digest(bytes) {
23334
+ return createHash("sha256").update(bytes).digest("hex");
23335
+ }
23336
+ async function writeJsonAtomic(filePath, value) {
23337
+ await mkdir(path2.dirname(filePath), { recursive: true });
23338
+ const tempPath = path2.join(path2.dirname(filePath), `.${path2.basename(filePath)}.${process.pid}.tmp`);
23339
+ await writeFile(tempPath, `${JSON.stringify(value, null, 2)}
23340
+ `);
23341
+ await rename(tempPath, filePath);
23342
+ }
23343
+
23215
23344
  // packages/cli/src/sync.ts
23216
23345
  var WORK_PACK_COMMITTED_MARKER = ".forge-replacement-committed";
23346
+ var WORK_PACK_TRANSACTION_SUFFIX = ".transaction";
23217
23347
  var MAX_SYNC_ERROR_BODY_BYTES = 1536;
23218
23348
  function extractErrorBody(response) {
23219
23349
  return response.text().then((text) => text.slice(0, MAX_SYNC_ERROR_BODY_BYTES)).catch(() => "");
@@ -23254,14 +23384,14 @@ async function fetchManifest(credentials) {
23254
23384
  return await response.json();
23255
23385
  }
23256
23386
  async function applyWorkPackManifest(paths, credentials, manifest, options) {
23257
- await mkdir(paths.skillsDir, { recursive: true });
23258
- await mkdir(paths.commandsDir, { recursive: true });
23259
- const cleanupPendingSlugs = await recoverInterruptedWorkPackInstalls(paths, options.cleanupWorkPackBackup);
23387
+ await mkdir2(paths.skillsDir, { recursive: true });
23388
+ await mkdir2(paths.commandsDir, { recursive: true });
23389
+ const recovery = await recoverInterruptedWorkPackInstalls(paths, options.cleanupWorkPackBackup, options.workPackProjectionBoundary);
23260
23390
  const managed = await Promise.all((await managedWorkPackSlugs(paths.skillsDir)).map(async (slug) => ({
23261
23391
  slug,
23262
- version: (await readFile(path2.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim(),
23263
- agents: await readAgentRecord(path2.join(paths.skillsDir, slug)),
23264
- commands: await readCommandRecord(path2.join(paths.skillsDir, slug))
23392
+ version: (await readFile2(path3.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim(),
23393
+ agents: await readAgentRecord(path3.join(paths.skillsDir, slug)),
23394
+ commands: await readCommandRecord(path3.join(paths.skillsDir, slug))
23265
23395
  })));
23266
23396
  const desired = manifest.skills.map((skill) => ({
23267
23397
  slug: skill.slug,
@@ -23274,8 +23404,18 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
23274
23404
  desired,
23275
23405
  managed,
23276
23406
  desiredIsComplete: manifest.workPacksComplete === true,
23277
- operate: (operation) => operateWorkPack(paths, credentials, skillBySlug, approvedModelIds, cleanupPendingSlugs, operation, options),
23278
- writeAtomicReceipt: (receipt) => writeJsonAtomic(path2.join(paths.forgeDir, "work-pack-sync-receipt.json"), receipt)
23407
+ operate: (operation) => operateWorkPack(
23408
+ paths,
23409
+ credentials,
23410
+ skillBySlug,
23411
+ approvedModelIds,
23412
+ recovery.cleanupPendingSlugs,
23413
+ recovery.failures,
23414
+ operation,
23415
+ options
23416
+ ),
23417
+ recoveryFailures: recovery.failures,
23418
+ writeAtomicReceipt: (receipt) => writeJsonAtomic2(path3.join(paths.forgeDir, "work-pack-sync-receipt.json"), receipt)
23279
23419
  });
23280
23420
  const installed = workPacks.outcomes.filter((outcome) => outcome.status === "installed").map((outcome) => `${outcome.slug}@${outcome.version}`);
23281
23421
  const removed = workPacks.outcomes.filter((outcome) => outcome.status === "removed").map((outcome) => outcome.slug);
@@ -23286,7 +23426,7 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
23286
23426
  async function collectWorkPackObservations(paths, reconciliation) {
23287
23427
  const installedVersions = /* @__PURE__ */ new Map();
23288
23428
  for (const slug of await managedWorkPackSlugs(paths.skillsDir)) {
23289
- const version2 = (await readFile(path2.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim();
23429
+ const version2 = (await readFile2(path3.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim();
23290
23430
  if (version2) installedVersions.set(slug, version2);
23291
23431
  }
23292
23432
  const observations = new Map(
@@ -23304,8 +23444,10 @@ async function collectWorkPackObservations(paths, reconciliation) {
23304
23444
  }
23305
23445
  return [...observations.values()].sort((a, b2) => a.slug.localeCompare(b2.slug));
23306
23446
  }
23307
- async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds, cleanupPendingSlugs, operation, options) {
23308
- const target = path2.join(paths.skillsDir, operation.pack.slug);
23447
+ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds, cleanupPendingSlugs, recoveryFailures, operation, options) {
23448
+ const target = path3.join(paths.skillsDir, operation.pack.slug);
23449
+ const recoveryFailure = recoveryFailures.get(operation.pack.slug);
23450
+ if (recoveryFailure) return { status: "failed", restoration: "exact", code: recoveryFailure };
23309
23451
  let ownership;
23310
23452
  try {
23311
23453
  ownership = await workPackOwnership(target);
@@ -23316,6 +23458,18 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
23316
23458
  if (operation.action === "remove") {
23317
23459
  if (ownership === "absent") return { status: "unchanged" };
23318
23460
  try {
23461
+ const localState = await checkWorkPackInstalledState({
23462
+ packDir: target,
23463
+ agentsDir: paths.agentsDir,
23464
+ commandsDir: paths.commandsDir
23465
+ });
23466
+ if (localState !== "match") {
23467
+ return {
23468
+ status: "failed",
23469
+ restoration: "exact",
23470
+ code: localState === "missing" ? "local-baseline-missing" : "local-edits-preserved"
23471
+ };
23472
+ }
23319
23473
  const removedManagedPaths = await removeManagedWorkPackTransaction(paths, target, options);
23320
23474
  return { status: "removed", removedManagedPaths };
23321
23475
  } catch (error45) {
@@ -23330,17 +23484,50 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
23330
23484
  let previousManagedPaths;
23331
23485
  let archive;
23332
23486
  try {
23333
- const currentVersion = await readFile(path2.join(target, ".forge-version"), "utf8").catch(() => "");
23334
- if (currentVersion.trim() === skill.version && !await workPackNeedsModelNormalization(target, approvedModelIds, skill.slug)) {
23335
- return cleanupPendingSlugs.has(skill.slug) ? {
23336
- status: "unchanged",
23337
- warningCode: "cleanup-pending",
23338
- message: `O pacote "${skill.slug}" est\xE1 instalado, mas o backup anterior continua bloqueado. Feche o OpenWork e volte a sincronizar para concluir a limpeza.`
23339
- } : { status: "unchanged" };
23487
+ const currentVersion = await readFile2(path3.join(target, ".forge-version"), "utf8").catch(() => "");
23488
+ const sameVersion = currentVersion.trim() === skill.version;
23489
+ if (sameVersion) {
23490
+ let localState = await checkWorkPackInstalledState({
23491
+ packDir: target,
23492
+ agentsDir: paths.agentsDir,
23493
+ commandsDir: paths.commandsDir
23494
+ });
23495
+ if (localState === "missing") {
23496
+ const candidateArchive = await downloadSkill(credentials, skill.url);
23497
+ const candidateSha256 = createHash2("sha256").update(candidateArchive).digest("hex");
23498
+ if (candidateSha256 !== skill.sha256) {
23499
+ return { status: "failed", restoration: "exact", code: "local-baseline-missing" };
23500
+ }
23501
+ localState = await adoptLegacyWorkPackState(paths, skill.slug, skill.version, candidateArchive, approvedModelIds) ? "match" : "changed";
23502
+ }
23503
+ if (localState !== "match") {
23504
+ return { status: "failed", restoration: "exact", code: "local-edits-preserved" };
23505
+ }
23506
+ if (!await workPackNeedsModelNormalization(target, approvedModelIds, skill.slug)) {
23507
+ return cleanupPendingSlugs.has(skill.slug) ? {
23508
+ status: "unchanged",
23509
+ warningCode: "cleanup-pending",
23510
+ message: `O pacote "${skill.slug}" est\xE1 instalado, mas o backup anterior continua bloqueado. Feche o OpenWork e volte a sincronizar para concluir a limpeza.`
23511
+ } : { status: "unchanged" };
23512
+ }
23513
+ }
23514
+ if (ownership === "managed" && !sameVersion) {
23515
+ const localState = await checkWorkPackInstalledState({
23516
+ packDir: target,
23517
+ agentsDir: paths.agentsDir,
23518
+ commandsDir: paths.commandsDir
23519
+ });
23520
+ if (localState !== "match") {
23521
+ return {
23522
+ status: "failed",
23523
+ restoration: "exact",
23524
+ code: localState === "missing" ? "local-baseline-missing" : "local-edits-preserved"
23525
+ };
23526
+ }
23340
23527
  }
23341
23528
  previousManagedPaths = await managedWorkPackPaths(paths, target);
23342
23529
  archive = await downloadSkill(credentials, skill.url);
23343
- const sha256 = createHash("sha256").update(archive).digest("hex");
23530
+ const sha256 = createHash2("sha256").update(archive).digest("hex");
23344
23531
  if (sha256 !== skill.sha256) return { status: "failed", restoration: "exact", code: "checksum-mismatch" };
23345
23532
  } catch (error45) {
23346
23533
  return exactPackFailure(error45);
@@ -23350,6 +23537,8 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
23350
23537
  const install = await installSkillArchive(paths, skill.slug, skill.version, archive, {
23351
23538
  beforeManagedPathsRemoved: options.beforeManagedPathsRemoved,
23352
23539
  writeWorkPackProjection: options.writeWorkPackProjection,
23540
+ installWorkPackBoundary: options.installWorkPackBoundary,
23541
+ workPackProjectionBoundary: options.workPackProjectionBoundary,
23353
23542
  cleanupWorkPackBackup: options.cleanupWorkPackBackup,
23354
23543
  approvedModelIds
23355
23544
  });
@@ -23375,6 +23564,9 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
23375
23564
  }
23376
23565
  }
23377
23566
  function exactPackFailure(error45) {
23567
+ if (error45 instanceof WorkPackLocalEditsError) {
23568
+ return { status: "failed", restoration: "exact", code: error45.code };
23569
+ }
23378
23570
  if (error45 instanceof WorkPackProjectionConflictError) {
23379
23571
  return {
23380
23572
  status: "failed",
@@ -23438,6 +23630,33 @@ async function downloadSkill(credentials, url2) {
23438
23630
  }
23439
23631
  var WorkPackRecoveryUncertainError = class extends Error {
23440
23632
  };
23633
+ var WorkPackLocalEditsError = class extends Error {
23634
+ constructor(code, message) {
23635
+ super(message ?? `O pacote de trabalho tem altera\xE7\xF5es locais e n\xE3o foi alterado (${code})`);
23636
+ this.code = code;
23637
+ this.name = "WorkPackLocalEditsError";
23638
+ }
23639
+ code;
23640
+ };
23641
+ async function assertWorkPackUnchangedAtBoundary(paths, target) {
23642
+ const ownership = await workPackOwnership(target);
23643
+ if (ownership === "absent") return;
23644
+ if (ownership === "foreign") throw foreignWorkPackError(path3.basename(target));
23645
+ const localState = await checkWorkPackInstalledState({
23646
+ packDir: target,
23647
+ agentsDir: paths.agentsDir,
23648
+ commandsDir: paths.commandsDir
23649
+ });
23650
+ if (localState !== "match") {
23651
+ throw new WorkPackLocalEditsError(localState === "missing" ? "local-baseline-missing" : "local-edits-preserved");
23652
+ }
23653
+ }
23654
+ async function assertWorkPackTreeUnchangedAtBoundary(target) {
23655
+ const localState = await checkWorkPackTreeState(target);
23656
+ if (localState !== "match") {
23657
+ throw new WorkPackLocalEditsError(localState === "missing" ? "local-baseline-missing" : "local-edits-preserved");
23658
+ }
23659
+ }
23441
23660
  function skillSlugFromUrl(value) {
23442
23661
  try {
23443
23662
  return new URL(value).pathname.split("/").slice(-2, -1)[0] ?? value;
@@ -23446,21 +23665,21 @@ function skillSlugFromUrl(value) {
23446
23665
  }
23447
23666
  }
23448
23667
  async function installSkillArchive(paths, slug, version2, archive, options = {}) {
23449
- const tempRoot = await mkdtemp(path2.join(os4.tmpdir(), `forge-${slug}-`));
23450
- const archivePath = path2.join(tempRoot, `${slug}.tar`);
23451
- const extractPath = path2.join(tempRoot, "extract");
23452
- const nextPath = path2.join(tempRoot, slug);
23453
- const target = path2.join(paths.skillsDir, slug);
23454
- const backup = path2.join(paths.skillsDir, `${slug}.previous`);
23668
+ const tempRoot = await mkdtemp(path3.join(os4.tmpdir(), `forge-${slug}-`));
23669
+ const archivePath = path3.join(tempRoot, `${slug}.tar`);
23670
+ const extractPath = path3.join(tempRoot, "extract");
23671
+ const nextPath = path3.join(tempRoot, slug);
23672
+ const target = path3.join(paths.skillsDir, slug);
23673
+ const backup = path3.join(paths.skillsDir, `${slug}.previous`);
23455
23674
  let agentFiles;
23456
23675
  let commandFiles;
23457
23676
  let previousAgents;
23458
23677
  let previousCommands;
23459
23678
  try {
23460
- await mkdir(extractPath, { recursive: true });
23461
- await writeFile(archivePath, archive);
23679
+ await mkdir2(extractPath, { recursive: true });
23680
+ await writeFile2(archivePath, archive);
23462
23681
  await So({ file: archivePath, cwd: extractPath, strict: true });
23463
- const extractedSkillPath = path2.join(extractPath, slug);
23682
+ const extractedSkillPath = path3.join(extractPath, slug);
23464
23683
  await assertNoReservedMarkerAliases(extractedSkillPath);
23465
23684
  await validateSkillFolder(extractedSkillPath, slug);
23466
23685
  agentFiles = await normalizePackAgentModels(
@@ -23487,78 +23706,123 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
23487
23706
  }
23488
23707
  throw error45;
23489
23708
  }
23490
- await rename(path2.join(extractPath, slug), nextPath);
23491
- await writeFile(path2.join(nextPath, ".forge-version"), `${version2}
23709
+ await rename2(path3.join(extractPath, slug), nextPath);
23710
+ await writeFile2(path3.join(nextPath, ".forge-version"), `${version2}
23492
23711
  `);
23493
23712
  if (agentFiles.length > 0) {
23494
- await writeFile(path2.join(nextPath, ".forge-agents"), `${agentFiles.map((agent) => agent.filename).join("\n")}
23713
+ await writeFile2(path3.join(nextPath, ".forge-agents"), `${agentFiles.map((agent) => agent.filename).join("\n")}
23495
23714
  `);
23496
23715
  }
23497
23716
  if (commandFiles.length > 0) {
23498
- await writeFile(path2.join(nextPath, ".forge-commands"), `${commandFiles.map((command) => command.filename).join("\n")}
23717
+ await writeFile2(path3.join(nextPath, ".forge-commands"), `${commandFiles.map((command) => command.filename).join("\n")}
23499
23718
  `);
23500
23719
  }
23720
+ await writeWorkPackInstalledState({ packDir: nextPath, version: version2, agents: agentFiles, commands: commandFiles });
23501
23721
  const nextAgentNames = new Set(agentFiles.map((agent) => agent.filename));
23502
23722
  const nextCommandNames = new Set(commandFiles.map((command) => command.filename));
23503
23723
  const agentSnapshot = await captureProjectionState(paths.agentsDir, [.../* @__PURE__ */ new Set([...previousAgents, ...nextAgentNames])]);
23504
23724
  const commandSnapshot = await captureProjectionState(paths.commandsDir, [.../* @__PURE__ */ new Set([...previousCommands, ...nextCommandNames])]);
23725
+ const agentTransactionState = new Map(
23726
+ [...agentSnapshot.keys()].map((filePath) => [
23727
+ filePath,
23728
+ agentFiles.find((agent) => agent.filename === path3.basename(filePath))?.content
23729
+ ])
23730
+ );
23731
+ const commandTransactionState = new Map(
23732
+ [...commandSnapshot.keys()].map((filePath) => [
23733
+ filePath,
23734
+ commandFiles.find((command) => command.filename === path3.basename(filePath))?.content
23735
+ ])
23736
+ );
23505
23737
  const previousManagedPaths = await managedWorkPackPaths(paths, target);
23506
- if (previousManagedPaths.length > 0) {
23507
- try {
23508
- await options.beforeManagedPathsRemoved?.(previousManagedPaths);
23509
- } catch (error45) {
23510
- await rm(tempRoot, { recursive: true, force: true });
23511
- throw error45;
23512
- }
23738
+ try {
23739
+ if (previousManagedPaths.length > 0) await options.beforeManagedPathsRemoved?.(previousManagedPaths);
23740
+ await assertWorkPackUnchangedAtBoundary(paths, target);
23741
+ } catch (error45) {
23742
+ await rm(tempRoot, { recursive: true, force: true });
23743
+ throw error45;
23513
23744
  }
23514
23745
  const writeProjection = options.writeWorkPackProjection ?? writeTextAtomic;
23746
+ const claimedBackup = path3.join(tempRoot, `${slug}-claimed-previous`);
23747
+ const transactionPath = `${backup}${WORK_PACK_TRANSACTION_SUFFIX}`;
23515
23748
  let targetBackedUp = false;
23516
23749
  let targetInstalled = false;
23750
+ let backupClaimed = false;
23517
23751
  try {
23518
23752
  await rm(backup, { recursive: true, force: true });
23753
+ await rm(transactionPath, { force: true });
23754
+ await writeTextAtomic(transactionPath, "install\n");
23519
23755
  try {
23520
- await rename(target, backup);
23756
+ await rename2(target, backup);
23521
23757
  targetBackedUp = true;
23522
23758
  } catch (error45) {
23523
23759
  if (error45.code !== "ENOENT") throw error45;
23760
+ await rm(transactionPath, { force: true });
23761
+ }
23762
+ if (targetBackedUp) {
23763
+ await options.installWorkPackBoundary?.("after-backup");
23764
+ await assertWorkPackUnchangedAtBoundary(paths, backup);
23524
23765
  }
23525
- await rename(nextPath, target);
23766
+ await rename2(nextPath, target);
23526
23767
  targetInstalled = true;
23527
- await removeRecordedAgents(
23528
- paths.agentsDir,
23529
- previousAgents.filter((filename) => !nextAgentNames.has(filename))
23530
- );
23768
+ for (const filename of previousAgents.filter((name) => !nextAgentNames.has(name))) {
23769
+ const filePath = path3.join(paths.agentsDir, filename);
23770
+ await options.workPackProjectionBoundary?.("install", filePath);
23771
+ await assertProjectionState(filePath, agentSnapshot.get(filePath));
23772
+ await rm(filePath, { force: true });
23773
+ }
23531
23774
  if (agentFiles.length > 0) {
23532
- await mkdir(paths.agentsDir, { recursive: true });
23775
+ await mkdir2(paths.agentsDir, { recursive: true });
23533
23776
  for (const agent of agentFiles) {
23534
- await writeProjection(path2.join(paths.agentsDir, agent.filename), agent.content);
23777
+ const filePath = path3.join(paths.agentsDir, agent.filename);
23778
+ await options.workPackProjectionBoundary?.("install", filePath);
23779
+ await assertProjectionState(filePath, agentSnapshot.get(filePath));
23780
+ await writeProjection(filePath, agent.content);
23535
23781
  }
23536
23782
  }
23537
- await removeRecordedCommands(
23538
- paths.commandsDir,
23539
- previousCommands.filter((filename) => !nextCommandNames.has(filename))
23540
- );
23783
+ for (const filename of previousCommands.filter((name) => !nextCommandNames.has(name))) {
23784
+ const filePath = path3.join(paths.commandsDir, filename);
23785
+ await options.workPackProjectionBoundary?.("install", filePath);
23786
+ await assertProjectionState(filePath, commandSnapshot.get(filePath));
23787
+ await rm(filePath, { force: true });
23788
+ }
23541
23789
  if (commandFiles.length > 0) {
23542
- await mkdir(paths.commandsDir, { recursive: true });
23790
+ await mkdir2(paths.commandsDir, { recursive: true });
23543
23791
  for (const command of commandFiles) {
23544
- await writeProjection(path2.join(paths.commandsDir, command.filename), command.content);
23545
- }
23546
- }
23547
- if (targetBackedUp) await writeFile(path2.join(backup, WORK_PACK_COMMITTED_MARKER), `${version2}
23792
+ const filePath = path3.join(paths.commandsDir, command.filename);
23793
+ await options.workPackProjectionBoundary?.("install", filePath);
23794
+ await assertProjectionState(filePath, commandSnapshot.get(filePath));
23795
+ await writeProjection(filePath, command.content);
23796
+ }
23797
+ }
23798
+ if (targetBackedUp) await assertWorkPackTreeUnchangedAtBoundary(backup);
23799
+ if (targetBackedUp) await options.installWorkPackBoundary?.("before-commit");
23800
+ if (targetBackedUp) {
23801
+ await rename2(backup, claimedBackup);
23802
+ backupClaimed = true;
23803
+ await assertWorkPackTreeUnchangedAtBoundary(claimedBackup);
23804
+ await writeFile2(path3.join(claimedBackup, WORK_PACK_COMMITTED_MARKER), `${version2}
23548
23805
  `);
23806
+ await writeTextAtomic(transactionPath, "committed\n");
23807
+ }
23549
23808
  } catch (error45) {
23550
23809
  try {
23551
- await restoreProjectionState(agentSnapshot);
23552
- await restoreProjectionState(commandSnapshot);
23810
+ if (targetInstalled) {
23811
+ await restoreProjectionState(agentSnapshot, agentTransactionState);
23812
+ await restoreProjectionState(commandSnapshot, commandTransactionState);
23813
+ }
23553
23814
  if (targetBackedUp) {
23554
- const restoredTarget = path2.join(tempRoot, `${slug}-restore`);
23555
- await cp(backup, restoredTarget, { recursive: true });
23815
+ const restoredTarget = path3.join(tempRoot, `${slug}-restore`);
23816
+ const rollbackSource = backupClaimed ? claimedBackup : backup;
23817
+ await cp(rollbackSource, restoredTarget, { recursive: true });
23556
23818
  if (targetInstalled) await rm(target, { recursive: true, force: true });
23557
- await rename(restoredTarget, target);
23558
- await rm(backup, { recursive: true, force: true });
23819
+ await rename2(restoredTarget, target);
23820
+ await rm(rollbackSource, { recursive: true, force: true });
23821
+ await rm(transactionPath, { force: true });
23559
23822
  } else if (targetInstalled) {
23560
23823
  await rm(target, { recursive: true, force: true });
23561
23824
  }
23825
+ await rm(transactionPath, { force: true });
23562
23826
  await rm(tempRoot, { recursive: true, force: true });
23563
23827
  } catch (restoreError) {
23564
23828
  throw new WorkPackRecoveryUncertainError(`Falha ao instalar e restaurar o pacote de trabalho ${slug}`, {
@@ -23568,37 +23832,90 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
23568
23832
  throw error45;
23569
23833
  }
23570
23834
  let cleanup = "complete";
23835
+ const cleanupTarget = backupClaimed ? claimedBackup : backup;
23571
23836
  try {
23572
- await (options.cleanupWorkPackBackup ?? removeWorkPackBackup)(backup);
23837
+ await (options.cleanupWorkPackBackup ?? removeWorkPackBackup)(cleanupTarget);
23838
+ await rm(transactionPath, { force: true });
23573
23839
  } catch {
23574
- cleanup = "pending";
23840
+ if (!await pathExists(cleanupTarget)) {
23841
+ cleanup = "complete";
23842
+ await rm(transactionPath, { force: true });
23843
+ } else {
23844
+ cleanup = "pending";
23845
+ if (backupClaimed) await rename2(claimedBackup, backup);
23846
+ }
23575
23847
  }
23576
23848
  await rm(tempRoot, { recursive: true, force: true }).catch(() => void 0);
23577
23849
  return { cleanup };
23578
23850
  }
23579
- async function recoverInterruptedWorkPackInstalls(paths, cleanupWorkPackBackup) {
23851
+ async function adoptLegacyWorkPackState(paths, slug, version2, archive, approvedModelIds) {
23852
+ const comparisonRoot = await mkdtemp(path3.join(os4.tmpdir(), `forge-${slug}-baseline-`));
23853
+ const comparisonPaths = {
23854
+ ...paths,
23855
+ skillsDir: path3.join(comparisonRoot, "skills"),
23856
+ agentsDir: path3.join(comparisonRoot, "agents"),
23857
+ commandsDir: path3.join(comparisonRoot, "commands")
23858
+ };
23859
+ try {
23860
+ await mkdir2(comparisonPaths.skillsDir, { recursive: true });
23861
+ await installSkillArchive(comparisonPaths, slug, version2, archive, { approvedModelIds });
23862
+ return adoptWorkPackInstalledState({
23863
+ expectedPackDir: path3.join(comparisonPaths.skillsDir, slug),
23864
+ packDir: path3.join(paths.skillsDir, slug),
23865
+ agentsDir: paths.agentsDir,
23866
+ commandsDir: paths.commandsDir
23867
+ });
23868
+ } finally {
23869
+ await rm(comparisonRoot, { recursive: true, force: true }).catch(() => void 0);
23870
+ }
23871
+ }
23872
+ async function recoverInterruptedWorkPackInstalls(paths, cleanupWorkPackBackup, workPackProjectionBoundary) {
23580
23873
  const cleanupPending = /* @__PURE__ */ new Set();
23581
- const entries = await readdir(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
23874
+ const failures = /* @__PURE__ */ new Map();
23875
+ const entries = await readdir2(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
23582
23876
  if (error45.code === "ENOENT") return [];
23583
23877
  throw error45;
23584
23878
  });
23585
23879
  for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
23586
- if (!entry.isDirectory() || !entry.name.endsWith(".previous")) continue;
23880
+ if (!entry.name.endsWith(".previous")) continue;
23587
23881
  const slug = entry.name.slice(0, -".previous".length);
23588
23882
  if (!slug) continue;
23589
- const target = path2.join(paths.skillsDir, slug);
23590
- if (await workPackOwnership(`${target}.previous`) !== "managed") continue;
23591
- if (await recoverInterruptedWorkPackInstall(paths, target, cleanupWorkPackBackup) === "cleanup-pending") cleanupPending.add(slug);
23883
+ const target = path3.join(paths.skillsDir, slug);
23884
+ const backup = `${target}.previous`;
23885
+ const transactionState = await readWorkPackTransactionState(backup);
23886
+ if (transactionState === "committed") {
23887
+ try {
23888
+ await (cleanupWorkPackBackup ?? removeWorkPackBackup)(backup);
23889
+ await rm(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, { force: true });
23890
+ } catch {
23891
+ if (await pathExists(backup)) cleanupPending.add(slug);
23892
+ else await rm(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, { force: true });
23893
+ }
23894
+ continue;
23895
+ }
23896
+ if (!entry.isDirectory() || await workPackOwnership(backup) !== "managed") continue;
23897
+ const recovery = await recoverInterruptedWorkPackInstall(
23898
+ paths,
23899
+ target,
23900
+ cleanupWorkPackBackup,
23901
+ workPackProjectionBoundary,
23902
+ transactionState
23903
+ ).catch((error45) => {
23904
+ if (error45 instanceof WorkPackLocalEditsError) return error45.code;
23905
+ throw error45;
23906
+ });
23907
+ if (recovery === "cleanup-pending") cleanupPending.add(slug);
23908
+ if (recovery === "local-edits-preserved" || recovery === "local-baseline-missing") failures.set(slug, recovery);
23592
23909
  }
23593
- return cleanupPending;
23910
+ return { cleanupPendingSlugs: cleanupPending, failures };
23594
23911
  }
23595
- async function recoverInterruptedWorkPackInstall(paths, target, cleanupWorkPackBackup) {
23912
+ async function recoverInterruptedWorkPackInstall(paths, target, cleanupWorkPackBackup, workPackProjectionBoundary, transactionState) {
23596
23913
  const backup = `${target}.previous`;
23597
23914
  const backupOwnership = await workPackOwnership(backup);
23598
23915
  if (backupOwnership === "absent") return "recovered";
23599
- if (backupOwnership === "foreign") throw foreignWorkPackError(path2.basename(target));
23600
- if (await workPackOwnership(target) === "foreign") throw foreignWorkPackError(path2.basename(target));
23601
- const committed = await readFile(path2.join(backup, WORK_PACK_COMMITTED_MARKER), "utf8").catch((error45) => {
23916
+ if (backupOwnership === "foreign") throw foreignWorkPackError(path3.basename(target));
23917
+ if (await workPackOwnership(target) === "foreign") throw foreignWorkPackError(path3.basename(target));
23918
+ const committed = await readFile2(path3.join(backup, WORK_PACK_COMMITTED_MARKER), "utf8").catch((error45) => {
23602
23919
  if (error45.code === "ENOENT") return void 0;
23603
23920
  throw error45;
23604
23921
  });
@@ -23610,29 +23927,70 @@ async function recoverInterruptedWorkPackInstall(paths, target, cleanupWorkPackB
23610
23927
  return "cleanup-pending";
23611
23928
  }
23612
23929
  }
23930
+ const targetOwnership = await workPackOwnership(target);
23931
+ if (targetOwnership === "managed") {
23932
+ const localState = await checkWorkPackTreeState(target);
23933
+ if (localState !== "match") {
23934
+ return localState === "missing" ? "local-baseline-missing" : "local-edits-preserved";
23935
+ }
23936
+ }
23613
23937
  const currentAgents = await readAgentRecord(target);
23614
23938
  const currentCommands = await readCommandRecord(target);
23615
23939
  const currentAgentFiles = await readPackAgentFiles(target);
23616
23940
  const currentCommandFiles = await readPackCommandFiles(target);
23617
23941
  const previousAgents = await readPackAgentFiles(backup);
23618
23942
  const previousCommands = await readPackCommandFiles(backup);
23619
- await assertProjectionRecoveryIsSafe(paths.agentsDir, currentAgentFiles, previousAgents);
23620
- await assertProjectionRecoveryIsSafe(paths.commandsDir, currentCommandFiles, previousCommands);
23943
+ const removedProjections = transactionState === "remove" ? await readWorkPackRemovedProjections(backup) : { agents: /* @__PURE__ */ new Set(), commands: /* @__PURE__ */ new Set() };
23944
+ const missingPreviousAgentPolicy = targetOwnership === "absent" ? transactionState === "remove" ? removedProjections.agents : true : false;
23945
+ const missingPreviousCommandPolicy = targetOwnership === "absent" ? transactionState === "remove" ? removedProjections.commands : true : false;
23946
+ const agentRecoveryState = await assertProjectionRecoveryIsSafe(
23947
+ paths.agentsDir,
23948
+ currentAgentFiles,
23949
+ previousAgents,
23950
+ missingPreviousAgentPolicy
23951
+ );
23952
+ const commandRecoveryState = await assertProjectionRecoveryIsSafe(
23953
+ paths.commandsDir,
23954
+ currentCommandFiles,
23955
+ previousCommands,
23956
+ missingPreviousCommandPolicy
23957
+ );
23621
23958
  const previousAgentNames = new Set(previousAgents.map((agent) => agent.filename));
23622
23959
  const previousCommandNames = new Set(previousCommands.map((command) => command.filename));
23623
- const recoveryRoot = await mkdtemp(path2.join(os4.tmpdir(), "forge-recover-"));
23624
- const recoveredTarget = path2.join(recoveryRoot, path2.basename(target));
23960
+ const recoveryRoot = await mkdtemp(path3.join(os4.tmpdir(), "forge-recover-"));
23961
+ const recoveredTarget = path3.join(recoveryRoot, path3.basename(target));
23625
23962
  await cp(backup, recoveredTarget, { recursive: true });
23626
23963
  try {
23627
- await removeRecordedAgents(paths.agentsDir, currentAgents.filter((filename) => !previousAgentNames.has(filename)));
23628
- await mkdir(paths.agentsDir, { recursive: true });
23629
- for (const agent of previousAgents) await writeTextAtomic(path2.join(paths.agentsDir, agent.filename), agent.content);
23630
- await removeRecordedCommands(paths.commandsDir, currentCommands.filter((filename) => !previousCommandNames.has(filename)));
23631
- await mkdir(paths.commandsDir, { recursive: true });
23632
- for (const command of previousCommands) await writeTextAtomic(path2.join(paths.commandsDir, command.filename), command.content);
23964
+ for (const filename of currentAgents.filter((name) => !previousAgentNames.has(name))) {
23965
+ const filePath = path3.join(paths.agentsDir, filename);
23966
+ await workPackProjectionBoundary?.("recover", filePath);
23967
+ await assertProjectionState(filePath, agentRecoveryState.get(filePath));
23968
+ await rm(filePath, { force: true });
23969
+ }
23970
+ await mkdir2(paths.agentsDir, { recursive: true });
23971
+ for (const agent of previousAgents) {
23972
+ const filePath = path3.join(paths.agentsDir, agent.filename);
23973
+ await workPackProjectionBoundary?.("recover", filePath);
23974
+ await assertProjectionState(filePath, agentRecoveryState.get(filePath));
23975
+ await writeTextAtomic(filePath, agent.content);
23976
+ }
23977
+ for (const filename of currentCommands.filter((name) => !previousCommandNames.has(name))) {
23978
+ const filePath = path3.join(paths.commandsDir, filename);
23979
+ await workPackProjectionBoundary?.("recover", filePath);
23980
+ await assertProjectionState(filePath, commandRecoveryState.get(filePath));
23981
+ await rm(filePath, { force: true });
23982
+ }
23983
+ await mkdir2(paths.commandsDir, { recursive: true });
23984
+ for (const command of previousCommands) {
23985
+ const filePath = path3.join(paths.commandsDir, command.filename);
23986
+ await workPackProjectionBoundary?.("recover", filePath);
23987
+ await assertProjectionState(filePath, commandRecoveryState.get(filePath));
23988
+ await writeTextAtomic(filePath, command.content);
23989
+ }
23633
23990
  await rm(target, { recursive: true, force: true });
23634
- await rename(recoveredTarget, target);
23991
+ await rename2(recoveredTarget, target);
23635
23992
  await rm(backup, { recursive: true, force: true });
23993
+ await rm(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, { force: true });
23636
23994
  } finally {
23637
23995
  await rm(recoveryRoot, { recursive: true, force: true }).catch(() => void 0);
23638
23996
  }
@@ -23641,14 +23999,59 @@ async function recoverInterruptedWorkPackInstall(paths, target, cleanupWorkPackB
23641
23999
  async function removeWorkPackBackup(backupPath) {
23642
24000
  await rm(backupPath, { recursive: true, force: true });
23643
24001
  }
24002
+ async function readWorkPackTransactionFile(backup) {
24003
+ return readFile2(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, "utf8").catch((error45) => {
24004
+ if (error45.code === "ENOENT") return void 0;
24005
+ throw error45;
24006
+ });
24007
+ }
24008
+ async function readWorkPackTransactionState(backup) {
24009
+ const value = await readWorkPackTransactionFile(backup);
24010
+ const state = value?.split("\n", 1)[0]?.trim();
24011
+ return state === "install" || state === "remove" || state === "committed" ? state : void 0;
24012
+ }
24013
+ function isManagedProjectionName(filename) {
24014
+ return filename.length > 0 && !filename.includes("/") && !filename.includes("\\") && filename !== "..";
24015
+ }
24016
+ async function recordRemovedProjection(transactionPath, kind, filename) {
24017
+ const current = await readFile2(transactionPath, "utf8");
24018
+ await writeTextAtomic(transactionPath, `${current.trimEnd()}
24019
+ ${kind}:${filename}
24020
+ `);
24021
+ }
24022
+ async function readWorkPackRemovedProjections(backup) {
24023
+ const agents = /* @__PURE__ */ new Set();
24024
+ const commands = /* @__PURE__ */ new Set();
24025
+ const value = await readWorkPackTransactionFile(backup);
24026
+ if (!value) return { agents, commands };
24027
+ const lines = value.split("\n");
24028
+ if (lines[0]?.trim() !== "remove") return { agents, commands };
24029
+ for (const line of lines.slice(1)) {
24030
+ const trimmed = line.trim();
24031
+ const separator = trimmed.indexOf(":");
24032
+ if (separator <= 0) continue;
24033
+ const kind = trimmed.slice(0, separator);
24034
+ const filename = trimmed.slice(separator + 1);
24035
+ if (!isManagedProjectionName(filename)) continue;
24036
+ if (kind === "agent") agents.add(filename);
24037
+ else if (kind === "command") commands.add(filename);
24038
+ }
24039
+ return { agents, commands };
24040
+ }
24041
+ async function pathExists(filePath) {
24042
+ return lstat2(filePath).then(() => true, (error45) => {
24043
+ if (error45.code === "ENOENT") return false;
24044
+ throw error45;
24045
+ });
24046
+ }
23644
24047
  async function workPackOwnership(target) {
23645
- const targetStat = await lstat(target).catch((error45) => {
24048
+ const targetStat = await lstat2(target).catch((error45) => {
23646
24049
  if (error45.code === "ENOENT") return void 0;
23647
24050
  throw error45;
23648
24051
  });
23649
24052
  if (!targetStat) return "absent";
23650
24053
  if (!targetStat.isDirectory()) return "foreign";
23651
- const marker = await readFile(path2.join(target, ".forge-version"), "utf8").catch((error45) => {
24054
+ const marker = await readFile2(path3.join(target, ".forge-version"), "utf8").catch((error45) => {
23652
24055
  if (error45.code === "ENOENT") return void 0;
23653
24056
  throw error45;
23654
24057
  });
@@ -23657,28 +24060,58 @@ async function workPackOwnership(target) {
23657
24060
  function foreignWorkPackError(slug) {
23658
24061
  return new Error(`O diret\xF3rio do pacote de trabalho ${slug} j\xE1 existe e n\xE3o \xE9 gerido pelo Forge; n\xE3o foi alterado`);
23659
24062
  }
23660
- async function assertProjectionRecoveryIsSafe(directory, currentFiles, previousFiles) {
24063
+ function missingPreviousProjectionIsLocalDeletion(filename, projected, previousNames, currentNames, missingPreviousPolicy) {
24064
+ if (projected !== void 0 || !previousNames.has(filename)) return false;
24065
+ if (missingPreviousPolicy === true) return true;
24066
+ if (missingPreviousPolicy instanceof Set) return !missingPreviousPolicy.has(filename);
24067
+ return currentNames.has(filename);
24068
+ }
24069
+ async function assertProjectionRecoveryIsSafe(directory, currentFiles, previousFiles, missingPreviousPolicy = false) {
23661
24070
  const expected = /* @__PURE__ */ new Map();
24071
+ const validated = /* @__PURE__ */ new Map();
24072
+ const currentNames = new Set(currentFiles.map((file2) => file2.filename));
24073
+ const previousNames = new Set(previousFiles.map((file2) => file2.filename));
23662
24074
  for (const file2 of [...currentFiles, ...previousFiles]) {
23663
24075
  const contents = expected.get(file2.filename) ?? /* @__PURE__ */ new Set();
23664
24076
  contents.add(file2.content);
23665
24077
  expected.set(file2.filename, contents);
23666
24078
  }
23667
24079
  for (const [filename, contents] of expected) {
23668
- const projected = await readFile(path2.join(directory, filename), "utf8").catch((error45) => {
24080
+ const projected = await readFile2(path3.join(directory, filename), "utf8").catch((error45) => {
23669
24081
  if (error45.code === "ENOENT") return void 0;
23670
24082
  throw error45;
23671
24083
  });
23672
- if (projected !== void 0 && !contents.has(projected)) {
23673
- throw new Error(`A proje\xE7\xE3o ${filename} foi alterada durante a recupera\xE7\xE3o do pacote de trabalho`);
24084
+ validated.set(path3.join(directory, filename), projected);
24085
+ const missingPreviousProjection = missingPreviousProjectionIsLocalDeletion(
24086
+ filename,
24087
+ projected,
24088
+ previousNames,
24089
+ currentNames,
24090
+ missingPreviousPolicy
24091
+ );
24092
+ if (missingPreviousProjection || projected !== void 0 && !contents.has(projected)) {
24093
+ throw new WorkPackLocalEditsError(
24094
+ "local-edits-preserved",
24095
+ `A proje\xE7\xE3o ${filename} foi alterada durante a recupera\xE7\xE3o do pacote de trabalho`
24096
+ );
23674
24097
  }
23675
24098
  }
24099
+ return validated;
24100
+ }
24101
+ async function assertProjectionState(filePath, expected) {
24102
+ const current = await readFile2(filePath, "utf8").catch((error45) => {
24103
+ if (error45.code === "ENOENT") return void 0;
24104
+ throw error45;
24105
+ });
24106
+ if (current !== expected) {
24107
+ throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path3.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
24108
+ }
23676
24109
  }
23677
24110
  async function captureProjectionState(directory, filenames) {
23678
24111
  const snapshot = /* @__PURE__ */ new Map();
23679
24112
  for (const filename of filenames) {
23680
- const filePath = path2.join(directory, filename);
23681
- const content = await readFile(filePath, "utf8").catch((error45) => {
24113
+ const filePath = path3.join(directory, filename);
24114
+ const content = await readFile2(filePath, "utf8").catch((error45) => {
23682
24115
  if (error45.code === "ENOENT") return void 0;
23683
24116
  throw error45;
23684
24117
  });
@@ -23686,15 +24119,22 @@ async function captureProjectionState(directory, filenames) {
23686
24119
  }
23687
24120
  return snapshot;
23688
24121
  }
23689
- async function restoreProjectionState(snapshot) {
24122
+ async function restoreProjectionState(snapshot, transactionState) {
23690
24123
  for (const [filePath, content] of snapshot) {
24124
+ if (transactionState) {
24125
+ const current = await readFile2(filePath, "utf8").catch((error45) => {
24126
+ if (error45.code === "ENOENT") return void 0;
24127
+ throw error45;
24128
+ });
24129
+ if (current !== transactionState.get(filePath)) continue;
24130
+ }
23691
24131
  if (content === void 0) await rm(filePath, { force: true });
23692
24132
  else await writeTextAtomic(filePath, content);
23693
24133
  }
23694
24134
  }
23695
24135
  async function readPackAgentFiles(skillFolder) {
23696
- const agentsFolder = path2.join(skillFolder, "agents");
23697
- const entries = await readdir(agentsFolder, { withFileTypes: true }).catch((error45) => {
24136
+ const agentsFolder = path3.join(skillFolder, "agents");
24137
+ const entries = await readdir2(agentsFolder, { withFileTypes: true }).catch((error45) => {
23698
24138
  if (error45.code === "ENOENT") return [];
23699
24139
  throw error45;
23700
24140
  });
@@ -23702,7 +24142,7 @@ async function readPackAgentFiles(skillFolder) {
23702
24142
  for (const entry of entries) {
23703
24143
  if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
23704
24144
  if (entry.name.startsWith("._")) continue;
23705
- const content = await readFile(path2.join(agentsFolder, entry.name), "utf8");
24145
+ const content = await readFile2(path3.join(agentsFolder, entry.name), "utf8");
23706
24146
  validateAgentFile(entry.name, content);
23707
24147
  files.push({ filename: entry.name, content });
23708
24148
  }
@@ -23713,7 +24153,7 @@ async function normalizePackAgentModels(skillFolder, agentFiles, approvedModelId
23713
24153
  for (const agent of agentFiles) {
23714
24154
  const content = normalizePackAgentModel(agent.filename, agent.content, approvedModelIds, slug);
23715
24155
  if (content !== agent.content) {
23716
- await writeFile(path2.join(skillFolder, "agents", agent.filename), content);
24156
+ await writeFile2(path3.join(skillFolder, "agents", agent.filename), content);
23717
24157
  }
23718
24158
  normalized.push({ ...agent, content });
23719
24159
  }
@@ -23757,8 +24197,8 @@ ${normalizedFrontmatter}
23757
24197
  ---${content.slice(match.index + match[0].length)}`;
23758
24198
  }
23759
24199
  async function readPackCommandFiles(skillFolder) {
23760
- const commandsFolder = path2.join(skillFolder, "commands");
23761
- const entries = await readdir(commandsFolder, { withFileTypes: true }).catch((error45) => {
24200
+ const commandsFolder = path3.join(skillFolder, "commands");
24201
+ const entries = await readdir2(commandsFolder, { withFileTypes: true }).catch((error45) => {
23762
24202
  if (error45.code === "ENOENT") return [];
23763
24203
  throw error45;
23764
24204
  });
@@ -23766,7 +24206,7 @@ async function readPackCommandFiles(skillFolder) {
23766
24206
  for (const entry of entries) {
23767
24207
  if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
23768
24208
  if (entry.name.startsWith("._")) continue;
23769
- const content = await readFile(path2.join(commandsFolder, entry.name), "utf8");
24209
+ const content = await readFile2(path3.join(commandsFolder, entry.name), "utf8");
23770
24210
  validateCommandFile(entry.name, content);
23771
24211
  files.push({ filename: entry.name, content });
23772
24212
  }
@@ -23777,7 +24217,7 @@ async function normalizePackCommandModels(skillFolder, commandFiles, approvedMod
23777
24217
  for (const command of commandFiles) {
23778
24218
  const content = normalizePackExtensionModel(`commands/${command.filename}`, command.content, approvedModelIds, slug);
23779
24219
  if (content !== command.content) {
23780
- await writeFile(path2.join(skillFolder, "commands", command.filename), content);
24220
+ await writeFile2(path3.join(skillFolder, "commands", command.filename), content);
23781
24221
  }
23782
24222
  normalized.push({ ...command, content });
23783
24223
  }
@@ -23799,7 +24239,7 @@ async function assertNoForeignAgentConflicts(agentsDir, agentFiles, ownedFilenam
23799
24239
  const owned = new Set(ownedFilenames);
23800
24240
  for (const agent of agentFiles) {
23801
24241
  if (owned.has(agent.filename)) continue;
23802
- const existing = await readFile(path2.join(agentsDir, agent.filename), "utf8").catch((error45) => {
24242
+ const existing = await readFile2(path3.join(agentsDir, agent.filename), "utf8").catch((error45) => {
23803
24243
  if (error45.code === "ENOENT") return void 0;
23804
24244
  throw error45;
23805
24245
  });
@@ -23812,7 +24252,7 @@ async function assertNoForeignCommandConflicts(commandsDir, commandFiles, ownedF
23812
24252
  const owned = new Set(ownedFilenames);
23813
24253
  for (const command of commandFiles) {
23814
24254
  if (owned.has(command.filename)) continue;
23815
- const existing = await readFile(path2.join(commandsDir, command.filename), "utf8").catch((error45) => {
24255
+ const existing = await readFile2(path3.join(commandsDir, command.filename), "utf8").catch((error45) => {
23816
24256
  if (error45.code === "ENOENT") return void 0;
23817
24257
  throw error45;
23818
24258
  });
@@ -23822,28 +24262,28 @@ async function assertNoForeignCommandConflicts(commandsDir, commandFiles, ownedF
23822
24262
  }
23823
24263
  }
23824
24264
  async function readAgentRecord(skillFolder) {
23825
- const raw = await readFile(path2.join(skillFolder, ".forge-agents"), "utf8").catch(() => "");
24265
+ const raw = await readFile2(path3.join(skillFolder, ".forge-agents"), "utf8").catch(() => "");
23826
24266
  return raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.includes("/") && !line.includes("\\") && line !== "..");
23827
24267
  }
23828
24268
  async function readCommandRecord(skillFolder) {
23829
- const raw = await readFile(path2.join(skillFolder, ".forge-commands"), "utf8").catch(() => "");
24269
+ const raw = await readFile2(path3.join(skillFolder, ".forge-commands"), "utf8").catch(() => "");
23830
24270
  return raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.includes("/") && !line.includes("\\") && line !== "..");
23831
24271
  }
23832
24272
  async function managedWorkPackPaths(paths, skillFolder) {
23833
24273
  const files = await listFilesRecursively(skillFolder);
23834
- const agents = (await readAgentRecord(skillFolder)).map((filename) => path2.join(paths.agentsDir, filename));
23835
- const commands = (await readCommandRecord(skillFolder)).map((filename) => path2.join(paths.commandsDir, filename));
24274
+ const agents = (await readAgentRecord(skillFolder)).map((filename) => path3.join(paths.agentsDir, filename));
24275
+ const commands = (await readCommandRecord(skillFolder)).map((filename) => path3.join(paths.commandsDir, filename));
23836
24276
  return [.../* @__PURE__ */ new Set([...files, ...agents, ...commands])];
23837
24277
  }
23838
24278
  async function managedWorkPackSlugs(skillsDir) {
23839
- const entries = await readdir(skillsDir, { withFileTypes: true }).catch((error45) => {
24279
+ const entries = await readdir2(skillsDir, { withFileTypes: true }).catch((error45) => {
23840
24280
  if (error45.code === "ENOENT") return [];
23841
24281
  throw error45;
23842
24282
  });
23843
24283
  const slugs = [];
23844
24284
  for (const entry of entries) {
23845
24285
  if (!entry.isDirectory() || entry.name.endsWith(".previous")) continue;
23846
- if (await workPackOwnership(path2.join(skillsDir, entry.name)) === "managed") slugs.push(entry.name);
24286
+ if (await workPackOwnership(path3.join(skillsDir, entry.name)) === "managed") slugs.push(entry.name);
23847
24287
  }
23848
24288
  return slugs.sort((left, right) => left.localeCompare(right));
23849
24289
  }
@@ -23853,28 +24293,67 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
23853
24293
  const agents = await readAgentRecord(target);
23854
24294
  const commands = await readCommandRecord(target);
23855
24295
  const snapshots = await Promise.all([
23856
- ...agents.map((filename) => captureExactFile(path2.join(paths.agentsDir, filename))),
23857
- ...commands.map((filename) => captureExactFile(path2.join(paths.commandsDir, filename)))
24296
+ ...agents.map((filename) => captureExactFile(path3.join(paths.agentsDir, filename))),
24297
+ ...commands.map((filename) => captureExactFile(path3.join(paths.commandsDir, filename)))
23858
24298
  ]);
24299
+ await assertWorkPackUnchangedAtBoundary(paths, target);
23859
24300
  const backup = `${target}.previous`;
23860
- await rm(backup, { recursive: true, force: true });
23861
- await rename(target, backup);
24301
+ const transactionPath = `${backup}${WORK_PACK_TRANSACTION_SUFFIX}`;
24302
+ const transactionRoot = await mkdtemp(path3.join(os4.tmpdir(), "forge-remove-"));
24303
+ const claimedBackup = path3.join(transactionRoot, path3.basename(target));
24304
+ let projectionsRemoved = false;
24305
+ let backupClaimed = false;
24306
+ try {
24307
+ await rm(backup, { recursive: true, force: true });
24308
+ await rm(transactionPath, { force: true });
24309
+ await writeTextAtomic(transactionPath, "remove\n");
24310
+ await rename2(target, backup);
24311
+ } catch (error45) {
24312
+ await rm(transactionPath, { force: true }).catch(() => void 0);
24313
+ await rm(transactionRoot, { recursive: true, force: true }).catch(() => void 0);
24314
+ throw error45;
24315
+ }
23862
24316
  try {
23863
24317
  await options.removeWorkPackBoundary?.("after-backup");
23864
- await removeRecordedAgents(paths.agentsDir, agents);
24318
+ await assertWorkPackUnchangedAtBoundary(paths, backup);
24319
+ projectionsRemoved = agents.length > 0;
24320
+ for (const filename of agents) {
24321
+ const filePath = path3.join(paths.agentsDir, filename);
24322
+ await options.workPackProjectionBoundary?.("remove", filePath);
24323
+ await assertExactFileState(snapshots, filePath);
24324
+ await recordRemovedProjection(transactionPath, "agent", filename);
24325
+ await rm(filePath, { force: true });
24326
+ }
23865
24327
  await options.removeWorkPackBoundary?.("after-agents");
23866
- await removeRecordedCommands(paths.commandsDir, commands);
24328
+ projectionsRemoved ||= commands.length > 0;
24329
+ for (const filename of commands) {
24330
+ const filePath = path3.join(paths.commandsDir, filename);
24331
+ await options.workPackProjectionBoundary?.("remove", filePath);
24332
+ await assertExactFileState(snapshots, filePath);
24333
+ await recordRemovedProjection(transactionPath, "command", filename);
24334
+ await rm(filePath, { force: true });
24335
+ }
23867
24336
  await options.removeWorkPackBoundary?.("after-commands");
23868
- await rm(backup, { recursive: true, force: true });
24337
+ await assertWorkPackTreeUnchangedAtBoundary(backup);
24338
+ await options.removeWorkPackBoundary?.("before-commit");
24339
+ await rename2(backup, claimedBackup);
24340
+ backupClaimed = true;
24341
+ await assertWorkPackTreeUnchangedAtBoundary(claimedBackup);
24342
+ await writeTextAtomic(transactionPath, "committed\n");
24343
+ await rm(claimedBackup, { recursive: true, force: true });
24344
+ await rm(transactionPath, { force: true });
24345
+ await rm(transactionRoot, { recursive: true, force: true }).catch(() => void 0);
23869
24346
  return pathsToRemove;
23870
24347
  } catch (error45) {
23871
24348
  try {
23872
- await restoreExactFiles(snapshots);
23873
- await rename(backup, target);
23874
- await verifyExactFiles(snapshots);
24349
+ if (projectionsRemoved) await restoreRemovedExactFiles(snapshots);
24350
+ await rename2(backupClaimed ? claimedBackup : backup, target);
24351
+ await rm(transactionPath, { force: true });
24352
+ if (projectionsRemoved) await verifyRestoredOrLocallyChangedFiles(snapshots);
23875
24353
  if (await workPackOwnership(target) !== "managed") throw new Error("restored Work Pack marker missing");
24354
+ await rm(transactionRoot, { recursive: true, force: true }).catch(() => void 0);
23876
24355
  } catch (restoreError) {
23877
- throw new WorkPackRecoveryUncertainError(`Falha ao remover e restaurar o pacote de trabalho ${path2.basename(target)}`, {
24356
+ throw new WorkPackRecoveryUncertainError(`Falha ao remover e restaurar o pacote de trabalho ${path3.basename(target)}`, {
23878
24357
  cause: new AggregateError([error45, restoreError])
23879
24358
  });
23880
24359
  }
@@ -23883,60 +24362,54 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
23883
24362
  }
23884
24363
  async function captureExactFile(filePath) {
23885
24364
  try {
23886
- const info = await lstat(filePath);
24365
+ const info = await lstat2(filePath);
23887
24366
  if (!info.isFile()) throw new Error(`A proje\xE7\xE3o gerida n\xE3o \xE9 um ficheiro regular: ${filePath}`);
23888
- return { path: filePath, exists: true, bytes: await readFile(filePath), mode: info.mode & 4095 };
24367
+ return { path: filePath, exists: true, bytes: await readFile2(filePath), mode: info.mode & 4095 };
23889
24368
  } catch (error45) {
23890
24369
  if (error45.code === "ENOENT") return { path: filePath, exists: false };
23891
24370
  throw error45;
23892
24371
  }
23893
24372
  }
23894
- async function restoreExactFiles(snapshots) {
24373
+ async function assertExactFileState(snapshots, filePath) {
24374
+ const expected = snapshots.find((snapshot) => snapshot.path === filePath);
24375
+ const current = await captureExactFile(filePath);
24376
+ if (!expected || current.exists !== expected.exists) {
24377
+ throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path3.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
24378
+ }
24379
+ if (current.exists && (!current.bytes?.equals(expected.bytes) || current.mode !== expected.mode)) {
24380
+ throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path3.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
24381
+ }
24382
+ }
24383
+ async function restoreRemovedExactFiles(snapshots) {
23895
24384
  for (const snapshot of snapshots) {
23896
- if (!snapshot.exists) {
23897
- await rm(snapshot.path, { force: true });
23898
- continue;
23899
- }
23900
- await mkdir(path2.dirname(snapshot.path), { recursive: true });
23901
- await writeFile(snapshot.path, snapshot.bytes);
24385
+ if ((await captureExactFile(snapshot.path)).exists) continue;
24386
+ if (!snapshot.exists) continue;
24387
+ await mkdir2(path3.dirname(snapshot.path), { recursive: true });
24388
+ await writeFile2(snapshot.path, snapshot.bytes);
23902
24389
  await chmod(snapshot.path, snapshot.mode);
23903
24390
  }
23904
24391
  }
23905
- async function verifyExactFiles(snapshots) {
24392
+ async function verifyRestoredOrLocallyChangedFiles(snapshots) {
23906
24393
  for (const snapshot of snapshots) {
23907
- const restored = await captureExactFile(snapshot.path);
23908
- if (restored.exists !== snapshot.exists) throw new Error(`N\xE3o foi poss\xEDvel verificar ${snapshot.path}`);
23909
- if (!snapshot.exists) continue;
23910
- if (!restored.bytes?.equals(snapshot.bytes) || restored.mode !== snapshot.mode) {
23911
- throw new Error(`O restauro exato de ${snapshot.path} n\xE3o foi confirmado`);
23912
- }
24394
+ const current = await captureExactFile(snapshot.path);
24395
+ if (snapshot.exists && !current.exists) throw new Error(`N\xE3o foi poss\xEDvel verificar ${snapshot.path}`);
23913
24396
  }
23914
24397
  }
23915
24398
  async function listFilesRecursively(root) {
23916
- const entries = await readdir(root, { withFileTypes: true }).catch((error45) => {
24399
+ const entries = await readdir2(root, { withFileTypes: true }).catch((error45) => {
23917
24400
  if (error45.code === "ENOENT") return [];
23918
24401
  throw error45;
23919
24402
  });
23920
24403
  const files = [];
23921
24404
  for (const entry of entries) {
23922
- const absolute = path2.join(root, entry.name);
24405
+ const absolute = path3.join(root, entry.name);
23923
24406
  if (entry.isDirectory()) files.push(...await listFilesRecursively(absolute));
23924
24407
  else if (entry.isFile()) files.push(absolute);
23925
24408
  }
23926
24409
  return files;
23927
24410
  }
23928
- async function removeRecordedAgents(agentsDir, filenames) {
23929
- for (const filename of filenames) {
23930
- await rm(path2.join(agentsDir, filename), { force: true });
23931
- }
23932
- }
23933
- async function removeRecordedCommands(commandsDir, filenames) {
23934
- for (const filename of filenames) {
23935
- await rm(path2.join(commandsDir, filename), { force: true });
23936
- }
23937
- }
23938
24411
  async function validateSkillFolder(folder, slug) {
23939
- const skillMd = await readFile(path2.join(folder, "SKILL.md"), "utf8");
24412
+ const skillMd = await readFile2(path3.join(folder, "SKILL.md"), "utf8");
23940
24413
  const frontmatter = /^---\n([\s\S]+?)\n---/.exec(skillMd)?.[1] ?? "";
23941
24414
  if (!frontmatter.includes(`name: ${slug}`) && !frontmatter.includes(`name: "${slug}"`)) {
23942
24415
  throw new Error(`O campo name no frontmatter de SKILL.md tem de corresponder a ${slug}`);
@@ -23946,26 +24419,26 @@ async function validateSkillFolder(folder, slug) {
23946
24419
  }
23947
24420
  }
23948
24421
  async function assertNoReservedMarkerAliases(skillFolder) {
23949
- const reserved = /* @__PURE__ */ new Set([".forge-version", ".forge-agents", ".forge-commands"]);
23950
- const entries = await readdir(skillFolder);
24422
+ const reserved = /* @__PURE__ */ new Set([".forge-version", ".forge-agents", ".forge-commands", WORK_PACK_LOCAL_STATE_FILENAME]);
24423
+ const entries = await readdir2(skillFolder);
23951
24424
  const marker = entries.find((entry) => reserved.has(entry.toLowerCase()));
23952
24425
  if (marker) throw new Error(`O pacote de trabalho cont\xE9m o marcador Forge reservado ${marker}`);
23953
24426
  }
23954
- async function writeJsonAtomic(filePath, value) {
24427
+ async function writeJsonAtomic2(filePath, value) {
23955
24428
  const content = `${JSON.stringify(value, null, 2)}
23956
24429
  `;
23957
24430
  await writeTextAtomic(filePath, content);
23958
24431
  }
23959
24432
  async function writeTextAtomic(filePath, content) {
23960
- const dir = path2.dirname(filePath);
23961
- await mkdir(dir, { recursive: true });
23962
- const tempPath = path2.join(dir, `.${path2.basename(filePath)}.${process.pid}.tmp`);
23963
- await writeFile(tempPath, content);
23964
- await rename(tempPath, filePath);
24433
+ const dir = path3.dirname(filePath);
24434
+ await mkdir2(dir, { recursive: true });
24435
+ const tempPath = path3.join(dir, `.${path3.basename(filePath)}.${process.pid}.tmp`);
24436
+ await writeFile2(tempPath, content);
24437
+ await rename2(tempPath, filePath);
23965
24438
  }
23966
24439
 
23967
24440
  // packages/cli/src/workPackSyncPlugin.ts
23968
- var PLUGIN_VERSION = "0.1.11";
24441
+ var PLUGIN_VERSION = "0.1.12";
23969
24442
  var STATUS_FILENAME = "work-pack-startup-status.json";
23970
24443
  var activeSync = /* @__PURE__ */ new Map();
23971
24444
  var ForgeWorkPackSyncServer = async (_input, options) => {
@@ -24061,7 +24534,7 @@ function resolveStartupPaths() {
24061
24534
  return resolvePaths(void 0, void 0, env);
24062
24535
  }
24063
24536
  async function readWellKnownForgeCredentials(authPath, forgeBaseUrl) {
24064
- const raw = await readFile2(authPath, "utf8");
24537
+ const raw = await readFile3(authPath, "utf8");
24065
24538
  const parsed = JSON.parse(raw.startsWith("\uFEFF") ? raw.slice(1) : raw);
24066
24539
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
24067
24540
  throw new Error("A autentica\xE7\xE3o do OpenCode n\xE3o \xE9 um objeto JSON v\xE1lido");
@@ -24092,22 +24565,22 @@ function parseForgeBaseUrl(options) {
24092
24565
  async function managedProjectionNames(paths) {
24093
24566
  const agents = /* @__PURE__ */ new Set();
24094
24567
  const commands = /* @__PURE__ */ new Set();
24095
- const entries = await readdir2(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
24568
+ const entries = await readdir3(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
24096
24569
  if (error45.code === "ENOENT") return [];
24097
24570
  throw error45;
24098
24571
  });
24099
24572
  for (const entry of entries) {
24100
24573
  if (!entry.isDirectory()) continue;
24101
- const folder = path3.join(paths.skillsDir, entry.name);
24102
- const marker = await readFile2(path3.join(folder, ".forge-version"), "utf8").catch(() => "");
24574
+ const folder = path4.join(paths.skillsDir, entry.name);
24575
+ const marker = await readFile3(path4.join(folder, ".forge-version"), "utf8").catch(() => "");
24103
24576
  if (!marker.trim()) continue;
24104
- for (const name of await readProjectionRecord(path3.join(folder, ".forge-agents"))) agents.add(stripMarkdownExtension(name));
24105
- for (const name of await readProjectionRecord(path3.join(folder, ".forge-commands"))) commands.add(stripMarkdownExtension(name));
24577
+ for (const name of await readProjectionRecord(path4.join(folder, ".forge-agents"))) agents.add(stripMarkdownExtension(name));
24578
+ for (const name of await readProjectionRecord(path4.join(folder, ".forge-commands"))) commands.add(stripMarkdownExtension(name));
24106
24579
  }
24107
24580
  return { agents, commands };
24108
24581
  }
24109
24582
  async function readProjectionRecord(filePath) {
24110
- const raw = await readFile2(filePath, "utf8").catch(() => "");
24583
+ const raw = await readFile3(filePath, "utf8").catch(() => "");
24111
24584
  return raw.split("\n").map((line) => line.trim()).filter(
24112
24585
  (line) => line.endsWith(".md") && !line.includes("/") && !line.includes("\\") && line !== ".."
24113
24586
  );
@@ -24118,21 +24591,21 @@ async function projectCurrentExtensions(config2, state) {
24118
24591
  for (const name of state.before.agents) if (!state.after.agents.has(name)) delete agents[name];
24119
24592
  for (const name of state.before.commands) if (!state.after.commands.has(name)) delete commands[name];
24120
24593
  for (const name of state.after.agents) {
24121
- agents[name] = await parseMarkdownConfig(path3.join(state.paths.agentsDir, `${name}.md`), "prompt");
24594
+ agents[name] = await parseMarkdownConfig(path4.join(state.paths.agentsDir, `${name}.md`), "prompt");
24122
24595
  }
24123
24596
  for (const name of state.after.commands) {
24124
- commands[name] = await parseMarkdownConfig(path3.join(state.paths.commandsDir, `${name}.md`), "template");
24597
+ commands[name] = await parseMarkdownConfig(path4.join(state.paths.commandsDir, `${name}.md`), "template");
24125
24598
  }
24126
24599
  config2.agent = agents;
24127
24600
  config2.command = commands;
24128
24601
  }
24129
24602
  async function parseMarkdownConfig(filePath, bodyField) {
24130
- const raw = await readFile2(filePath, "utf8");
24603
+ const raw = await readFile3(filePath, "utf8");
24131
24604
  const match = /^---\r?\n([\s\S]+?)\r?\n---\r?\n?([\s\S]*)$/.exec(raw);
24132
- if (!match) throw new Error(`A extens\xE3o Forge ${path3.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
24605
+ if (!match) throw new Error(`A extens\xE3o Forge ${path4.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
24133
24606
  const data = (0, import_yaml.parse)(match[1]);
24134
24607
  if (!data || typeof data !== "object" || Array.isArray(data)) {
24135
- throw new Error(`A extens\xE3o Forge ${path3.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
24608
+ throw new Error(`A extens\xE3o Forge ${path4.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
24136
24609
  }
24137
24610
  const config2 = { ...data, [bodyField]: match[2].trim() };
24138
24611
  if (bodyField === "prompt" && typeof config2.permission === "string" && ["allow", "ask", "deny"].includes(config2.permission)) {
@@ -24147,12 +24620,12 @@ function stripMarkdownExtension(filename) {
24147
24620
  return filename.slice(0, -3);
24148
24621
  }
24149
24622
  async function writeStatus(paths, value) {
24150
- await mkdir2(paths.forgeDir, { recursive: true });
24151
- const target = path3.join(paths.forgeDir, STATUS_FILENAME);
24152
- const temporary = path3.join(paths.forgeDir, `.${STATUS_FILENAME}.${process.pid}.tmp`);
24153
- await writeFile2(temporary, `${JSON.stringify(value, null, 2)}
24623
+ await mkdir3(paths.forgeDir, { recursive: true });
24624
+ const target = path4.join(paths.forgeDir, STATUS_FILENAME);
24625
+ const temporary = path4.join(paths.forgeDir, `.${STATUS_FILENAME}.${process.pid}.tmp`);
24626
+ await writeFile3(temporary, `${JSON.stringify(value, null, 2)}
24154
24627
  `, { mode: 384 });
24155
- await rename2(temporary, target);
24628
+ await rename3(temporary, target);
24156
24629
  }
24157
24630
  function safeErrorMessage(error45) {
24158
24631
  const message = error45 instanceof Error ? error45.message : "erro desconhecido";