minimal-forge-work-pack-sync 0.1.53 → 0.1.54

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
@@ -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, path15) {
121
- const ctrl = callVisitor(key, node, visitor, path15);
120
+ function visit_(key, node, visitor, path16) {
121
+ const ctrl = callVisitor(key, node, visitor, path16);
122
122
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
123
- replaceNode(key, path15, ctrl);
124
- return visit_(key, ctrl, visitor, path15);
123
+ replaceNode(key, path16, ctrl);
124
+ return visit_(key, ctrl, visitor, path16);
125
125
  }
126
126
  if (typeof ctrl !== "symbol") {
127
127
  if (identity.isCollection(node)) {
128
- path15 = Object.freeze(path15.concat(node));
128
+ path16 = Object.freeze(path16.concat(node));
129
129
  for (let i = 0; i < node.items.length; ++i) {
130
- const ci2 = visit_(i, node.items[i], visitor, path15);
130
+ const ci2 = visit_(i, node.items[i], visitor, path16);
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
- path15 = Object.freeze(path15.concat(node));
142
- const ck = visit_("key", node.key, visitor, path15);
141
+ path16 = Object.freeze(path16.concat(node));
142
+ const ck = visit_("key", node.key, visitor, path16);
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, path15);
147
+ const cv = visit_("value", node.value, visitor, path16);
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, path15) {
169
- const ctrl = await callVisitor(key, node, visitor, path15);
168
+ async function visitAsync_(key, node, visitor, path16) {
169
+ const ctrl = await callVisitor(key, node, visitor, path16);
170
170
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
171
- replaceNode(key, path15, ctrl);
172
- return visitAsync_(key, ctrl, visitor, path15);
171
+ replaceNode(key, path16, ctrl);
172
+ return visitAsync_(key, ctrl, visitor, path16);
173
173
  }
174
174
  if (typeof ctrl !== "symbol") {
175
175
  if (identity.isCollection(node)) {
176
- path15 = Object.freeze(path15.concat(node));
176
+ path16 = Object.freeze(path16.concat(node));
177
177
  for (let i = 0; i < node.items.length; ++i) {
178
- const ci2 = await visitAsync_(i, node.items[i], visitor, path15);
178
+ const ci2 = await visitAsync_(i, node.items[i], visitor, path16);
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
- path15 = Object.freeze(path15.concat(node));
190
- const ck = await visitAsync_("key", node.key, visitor, path15);
189
+ path16 = Object.freeze(path16.concat(node));
190
+ const ck = await visitAsync_("key", node.key, visitor, path16);
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, path15);
195
+ const cv = await visitAsync_("value", node.value, visitor, path16);
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, path15) {
222
+ function callVisitor(key, node, visitor, path16) {
223
223
  if (typeof visitor === "function")
224
- return visitor(key, node, path15);
224
+ return visitor(key, node, path16);
225
225
  if (identity.isMap(node))
226
- return visitor.Map?.(key, node, path15);
226
+ return visitor.Map?.(key, node, path16);
227
227
  if (identity.isSeq(node))
228
- return visitor.Seq?.(key, node, path15);
228
+ return visitor.Seq?.(key, node, path16);
229
229
  if (identity.isPair(node))
230
- return visitor.Pair?.(key, node, path15);
230
+ return visitor.Pair?.(key, node, path16);
231
231
  if (identity.isScalar(node))
232
- return visitor.Scalar?.(key, node, path15);
232
+ return visitor.Scalar?.(key, node, path16);
233
233
  if (identity.isAlias(node))
234
- return visitor.Alias?.(key, node, path15);
234
+ return visitor.Alias?.(key, node, path16);
235
235
  return void 0;
236
236
  }
237
- function replaceNode(key, path15, node) {
238
- const parent = path15[path15.length - 1];
237
+ function replaceNode(key, path16, node) {
238
+ const parent = path16[path16.length - 1];
239
239
  if (identity.isCollection(parent)) {
240
240
  parent.items[key] = node;
241
241
  } else if (identity.isPair(parent)) {
@@ -847,10 +847,10 @@ var require_Collection = __commonJS({
847
847
  var createNode = require_createNode();
848
848
  var identity = require_identity();
849
849
  var Node = require_Node();
850
- function collectionFromPath(schema, path15, value) {
850
+ function collectionFromPath(schema, path16, value) {
851
851
  let v2 = value;
852
- for (let i = path15.length - 1; i >= 0; --i) {
853
- const k2 = path15[i];
852
+ for (let i = path16.length - 1; i >= 0; --i) {
853
+ const k2 = path16[i];
854
854
  if (typeof k2 === "number" && Number.isInteger(k2) && k2 >= 0) {
855
855
  const a = [];
856
856
  a[k2] = v2;
@@ -869,7 +869,7 @@ var require_Collection = __commonJS({
869
869
  sourceObjects: /* @__PURE__ */ new Map()
870
870
  });
871
871
  }
872
- var isEmptyPath = (path15) => path15 == null || typeof path15 === "object" && !!path15[Symbol.iterator]().next().done;
872
+ var isEmptyPath = (path16) => path16 == null || typeof path16 === "object" && !!path16[Symbol.iterator]().next().done;
873
873
  var Collection = class extends Node.NodeBase {
874
874
  constructor(type, schema) {
875
875
  super(type);
@@ -899,11 +899,11 @@ var require_Collection = __commonJS({
899
899
  * be a Pair instance or a `{ key, value }` object, which may not have a key
900
900
  * that already exists in the map.
901
901
  */
902
- addIn(path15, value) {
903
- if (isEmptyPath(path15))
902
+ addIn(path16, value) {
903
+ if (isEmptyPath(path16))
904
904
  this.add(value);
905
905
  else {
906
- const [key, ...rest] = path15;
906
+ const [key, ...rest] = path16;
907
907
  const node = this.get(key, true);
908
908
  if (identity.isCollection(node))
909
909
  node.addIn(rest, value);
@@ -917,8 +917,8 @@ var require_Collection = __commonJS({
917
917
  * Removes a value from the collection.
918
918
  * @returns `true` if the item was found and removed.
919
919
  */
920
- deleteIn(path15) {
921
- const [key, ...rest] = path15;
920
+ deleteIn(path16) {
921
+ const [key, ...rest] = path16;
922
922
  if (rest.length === 0)
923
923
  return this.delete(key);
924
924
  const node = this.get(key, true);
@@ -932,8 +932,8 @@ var require_Collection = __commonJS({
932
932
  * scalar values from their surrounding node; to disable set `keepScalar` to
933
933
  * `true` (collections are always returned intact).
934
934
  */
935
- getIn(path15, keepScalar) {
936
- const [key, ...rest] = path15;
935
+ getIn(path16, keepScalar) {
936
+ const [key, ...rest] = path16;
937
937
  const node = this.get(key, true);
938
938
  if (rest.length === 0)
939
939
  return !keepScalar && identity.isScalar(node) ? node.value : node;
@@ -951,8 +951,8 @@ var require_Collection = __commonJS({
951
951
  /**
952
952
  * Checks if the collection includes a value with the key `key`.
953
953
  */
954
- hasIn(path15) {
955
- const [key, ...rest] = path15;
954
+ hasIn(path16) {
955
+ const [key, ...rest] = path16;
956
956
  if (rest.length === 0)
957
957
  return this.has(key);
958
958
  const node = this.get(key, true);
@@ -962,8 +962,8 @@ var require_Collection = __commonJS({
962
962
  * Sets a value in this collection. For `!!set`, `value` needs to be a
963
963
  * boolean to add/remove the item from the set.
964
964
  */
965
- setIn(path15, value) {
966
- const [key, ...rest] = path15;
965
+ setIn(path16, value) {
966
+ const [key, ...rest] = path16;
967
967
  if (rest.length === 0) {
968
968
  this.set(key, value);
969
969
  } else {
@@ -3478,9 +3478,9 @@ var require_Document = __commonJS({
3478
3478
  this.contents.add(value);
3479
3479
  }
3480
3480
  /** Adds a value to the document. */
3481
- addIn(path15, value) {
3481
+ addIn(path16, value) {
3482
3482
  if (assertCollection(this.contents))
3483
- this.contents.addIn(path15, value);
3483
+ this.contents.addIn(path16, value);
3484
3484
  }
3485
3485
  /**
3486
3486
  * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
@@ -3555,14 +3555,14 @@ var require_Document = __commonJS({
3555
3555
  * Removes a value from the document.
3556
3556
  * @returns `true` if the item was found and removed.
3557
3557
  */
3558
- deleteIn(path15) {
3559
- if (Collection.isEmptyPath(path15)) {
3558
+ deleteIn(path16) {
3559
+ if (Collection.isEmptyPath(path16)) {
3560
3560
  if (this.contents == null)
3561
3561
  return false;
3562
3562
  this.contents = null;
3563
3563
  return true;
3564
3564
  }
3565
- return assertCollection(this.contents) ? this.contents.deleteIn(path15) : false;
3565
+ return assertCollection(this.contents) ? this.contents.deleteIn(path16) : false;
3566
3566
  }
3567
3567
  /**
3568
3568
  * Returns item at `key`, or `undefined` if not found. By default unwraps
@@ -3577,10 +3577,10 @@ var require_Document = __commonJS({
3577
3577
  * scalar values from their surrounding node; to disable set `keepScalar` to
3578
3578
  * `true` (collections are always returned intact).
3579
3579
  */
3580
- getIn(path15, keepScalar) {
3581
- if (Collection.isEmptyPath(path15))
3580
+ getIn(path16, keepScalar) {
3581
+ if (Collection.isEmptyPath(path16))
3582
3582
  return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
3583
- return identity.isCollection(this.contents) ? this.contents.getIn(path15, keepScalar) : void 0;
3583
+ return identity.isCollection(this.contents) ? this.contents.getIn(path16, keepScalar) : void 0;
3584
3584
  }
3585
3585
  /**
3586
3586
  * Checks if the document includes a value with the key `key`.
@@ -3591,10 +3591,10 @@ var require_Document = __commonJS({
3591
3591
  /**
3592
3592
  * Checks if the document includes a value at `path`.
3593
3593
  */
3594
- hasIn(path15) {
3595
- if (Collection.isEmptyPath(path15))
3594
+ hasIn(path16) {
3595
+ if (Collection.isEmptyPath(path16))
3596
3596
  return this.contents !== void 0;
3597
- return identity.isCollection(this.contents) ? this.contents.hasIn(path15) : false;
3597
+ return identity.isCollection(this.contents) ? this.contents.hasIn(path16) : false;
3598
3598
  }
3599
3599
  /**
3600
3600
  * Sets a value in this document. For `!!set`, `value` needs to be a
@@ -3611,13 +3611,13 @@ var require_Document = __commonJS({
3611
3611
  * Sets a value in this document. For `!!set`, `value` needs to be a
3612
3612
  * boolean to add/remove the item from the set.
3613
3613
  */
3614
- setIn(path15, value) {
3615
- if (Collection.isEmptyPath(path15)) {
3614
+ setIn(path16, value) {
3615
+ if (Collection.isEmptyPath(path16)) {
3616
3616
  this.contents = value;
3617
3617
  } else if (this.contents == null) {
3618
- this.contents = Collection.collectionFromPath(this.schema, Array.from(path15), value);
3618
+ this.contents = Collection.collectionFromPath(this.schema, Array.from(path16), value);
3619
3619
  } else if (assertCollection(this.contents)) {
3620
- this.contents.setIn(path15, value);
3620
+ this.contents.setIn(path16, value);
3621
3621
  }
3622
3622
  }
3623
3623
  /**
@@ -5578,9 +5578,9 @@ var require_cst_visit = __commonJS({
5578
5578
  visit.BREAK = BREAK;
5579
5579
  visit.SKIP = SKIP;
5580
5580
  visit.REMOVE = REMOVE;
5581
- visit.itemAtPath = (cst, path15) => {
5581
+ visit.itemAtPath = (cst, path16) => {
5582
5582
  let item = cst;
5583
- for (const [field, index] of path15) {
5583
+ for (const [field, index] of path16) {
5584
5584
  const tok = item?.[field];
5585
5585
  if (tok && "items" in tok) {
5586
5586
  item = tok.items[index];
@@ -5589,23 +5589,23 @@ var require_cst_visit = __commonJS({
5589
5589
  }
5590
5590
  return item;
5591
5591
  };
5592
- visit.parentCollection = (cst, path15) => {
5593
- const parent = visit.itemAtPath(cst, path15.slice(0, -1));
5594
- const field = path15[path15.length - 1][0];
5592
+ visit.parentCollection = (cst, path16) => {
5593
+ const parent = visit.itemAtPath(cst, path16.slice(0, -1));
5594
+ const field = path16[path16.length - 1][0];
5595
5595
  const coll = parent?.[field];
5596
5596
  if (coll && "items" in coll)
5597
5597
  return coll;
5598
5598
  throw new Error("Parent collection not found");
5599
5599
  };
5600
- function _visit(path15, item, visitor) {
5601
- let ctrl = visitor(item, path15);
5600
+ function _visit(path16, item, visitor) {
5601
+ let ctrl = visitor(item, path16);
5602
5602
  if (typeof ctrl === "symbol")
5603
5603
  return ctrl;
5604
5604
  for (const field of ["key", "value"]) {
5605
5605
  const token = item[field];
5606
5606
  if (token && "items" in token) {
5607
5607
  for (let i = 0; i < token.items.length; ++i) {
5608
- const ci2 = _visit(Object.freeze(path15.concat([[field, i]])), token.items[i], visitor);
5608
+ const ci2 = _visit(Object.freeze(path16.concat([[field, i]])), token.items[i], visitor);
5609
5609
  if (typeof ci2 === "number")
5610
5610
  i = ci2 - 1;
5611
5611
  else if (ci2 === BREAK)
@@ -5616,10 +5616,10 @@ var require_cst_visit = __commonJS({
5616
5616
  }
5617
5617
  }
5618
5618
  if (typeof ctrl === "function" && field === "key")
5619
- ctrl = ctrl(item, path15);
5619
+ ctrl = ctrl(item, path16);
5620
5620
  }
5621
5621
  }
5622
- return typeof ctrl === "function" ? ctrl(item, path15) : ctrl;
5622
+ return typeof ctrl === "function" ? ctrl(item, path16) : ctrl;
5623
5623
  }
5624
5624
  exports.visit = visit;
5625
5625
  }
@@ -7615,7 +7615,7 @@ var WORKER_FEEDBACK_MAX_MESSAGE_LENGTH = 24e3;
7615
7615
  // packages/shared/src/contracts/settings.ts
7616
7616
  var DOCUMENT_READER_AGENT = "document-reader";
7617
7617
  var OPENROUTER_ALIAS_PROVIDER_NAME = "OpenRouter (via Forge)";
7618
- var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.53";
7618
+ var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.54";
7619
7619
  var WORK_PACK_SYNC_PLUGIN_PACKAGE = `minimal-forge-work-pack-sync@${WORK_PACK_SYNC_PLUGIN_VERSION}`;
7620
7620
  var WORK_PACK_SYNC_PLUGIN_FILENAME = `minimal-forge-work-pack-sync-${WORK_PACK_SYNC_PLUGIN_VERSION}.tgz`;
7621
7621
  var FIRECRAWL_KEYLESS_MCP_NAME = "firecrawl";
@@ -8069,7 +8069,7 @@ async function writeOwnerOnlyTextAtomic(filePath, content, options = {}) {
8069
8069
  }
8070
8070
 
8071
8071
  // packages/cli/src/workPackSyncPlugin.ts
8072
- import { createHash as createHash7, randomUUID as randomUUID5 } from "node:crypto";
8072
+ import { createHash as createHash8, randomUUID as randomUUID5 } from "node:crypto";
8073
8073
  import { pathToFileURL } from "node:url";
8074
8074
 
8075
8075
  // packages/cli/src/skillUsageReporter.ts
@@ -9310,10 +9310,10 @@ function mergeDefs(...defs) {
9310
9310
  function cloneDef(schema) {
9311
9311
  return mergeDefs(schema._zod.def);
9312
9312
  }
9313
- function getElementAtPath(obj, path15) {
9314
- if (!path15)
9313
+ function getElementAtPath(obj, path16) {
9314
+ if (!path16)
9315
9315
  return obj;
9316
- return path15.reduce((acc, key) => acc?.[key], obj);
9316
+ return path16.reduce((acc, key) => acc?.[key], obj);
9317
9317
  }
9318
9318
  function promiseAllObject(promisesObj) {
9319
9319
  const keys = Object.keys(promisesObj);
@@ -9674,11 +9674,11 @@ function aborted(x, startIndex = 0) {
9674
9674
  }
9675
9675
  return false;
9676
9676
  }
9677
- function prefixIssues(path15, issues) {
9677
+ function prefixIssues(path16, issues) {
9678
9678
  return issues.map((iss) => {
9679
9679
  var _a;
9680
9680
  (_a = iss).path ?? (_a.path = []);
9681
- iss.path.unshift(path15);
9681
+ iss.path.unshift(path16);
9682
9682
  return iss;
9683
9683
  });
9684
9684
  }
@@ -9846,7 +9846,7 @@ function treeifyError(error45, _mapper) {
9846
9846
  return issue2.message;
9847
9847
  };
9848
9848
  const result = { errors: [] };
9849
- const processError = (error46, path15 = []) => {
9849
+ const processError = (error46, path16 = []) => {
9850
9850
  var _a, _b;
9851
9851
  for (const issue2 of error46.issues) {
9852
9852
  if (issue2.code === "invalid_union" && issue2.errors.length) {
@@ -9856,7 +9856,7 @@ function treeifyError(error45, _mapper) {
9856
9856
  } else if (issue2.code === "invalid_element") {
9857
9857
  processError({ issues: issue2.issues }, issue2.path);
9858
9858
  } else {
9859
- const fullpath = [...path15, ...issue2.path];
9859
+ const fullpath = [...path16, ...issue2.path];
9860
9860
  if (fullpath.length === 0) {
9861
9861
  result.errors.push(mapper(issue2));
9862
9862
  continue;
@@ -9888,8 +9888,8 @@ function treeifyError(error45, _mapper) {
9888
9888
  }
9889
9889
  function toDotPath(_path) {
9890
9890
  const segs = [];
9891
- const path15 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
9892
- for (const seg of path15) {
9891
+ const path16 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
9892
+ for (const seg of path16) {
9893
9893
  if (typeof seg === "number")
9894
9894
  segs.push(`[${seg}]`);
9895
9895
  else if (typeof seg === "symbol")
@@ -21049,7 +21049,7 @@ function openCode2Result(result) {
21049
21049
  };
21050
21050
  }
21051
21051
  function completedSkillCall(event) {
21052
- if (event.tool !== "skill" || event.status !== "completed") return void 0;
21052
+ if (!event || event.tool !== "skill" || event.status !== "completed") return void 0;
21053
21053
  const name = isRecord2(event.input) ? event.input.id : void 0;
21054
21054
  return { sessionID: event.sessionID, callID: event.id, name };
21055
21055
  }
@@ -21087,9 +21087,9 @@ function guardEventsFor(event) {
21087
21087
  function openCode2GuardClient(ctx) {
21088
21088
  return {
21089
21089
  session: {
21090
- abort: ({ path: path15 }) => ctx.session.interrupt({ sessionID: path15.id }),
21090
+ abort: ({ path: path16 }) => ctx.session.interrupt({ sessionID: path16.id }),
21091
21091
  // The resume prompt runs with the session's current agent and model, so `body.agent` and `body.model` are not sent.
21092
- promptAsync: ({ path: path15, body }) => ctx.session.prompt({ sessionID: path15.id, text: body.parts.map((part) => part.text).join("\n\n") })
21092
+ promptAsync: ({ path: path16, body }) => ctx.session.prompt({ sessionID: path16.id, text: body.parts.map((part) => part.text).join("\n\n") })
21093
21093
  }
21094
21094
  };
21095
21095
  }
@@ -21140,9 +21140,9 @@ function isRecord2(value) {
21140
21140
  }
21141
21141
 
21142
21142
  // packages/cli/src/workPackSyncPlugin.ts
21143
- import { link, mkdir as mkdir8, mkdtemp as mkdtemp2, readdir as readdir7, readFile as readFile14, realpath as realpath2, rename as rename9, rm as rm6, rmdir as rmdir2, stat as stat3, unlink as unlink2, writeFile as writeFile9 } from "node:fs/promises";
21143
+ import { link, mkdir as mkdir8, mkdtemp as mkdtemp2, readdir as readdir8, readFile as readFile15, realpath as realpath3, rename as rename9, rm as rm6, rmdir as rmdir2, stat as stat3, unlink as unlink2, writeFile as writeFile9 } from "node:fs/promises";
21144
21144
  import os5 from "node:os";
21145
- import path14 from "node:path";
21145
+ import path15 from "node:path";
21146
21146
 
21147
21147
  // packages/cli/src/credentials.ts
21148
21148
  import { chmod as chmod2, mkdir as mkdir2, readFile as readFile3, rename as rename3, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
@@ -21295,13 +21295,13 @@ async function readInstalledState(packDir) {
21295
21295
  return void 0;
21296
21296
  }
21297
21297
  }
21298
- async function digestPackTree(root) {
21298
+ async function digestPackTree(root, includeReceipt = false) {
21299
21299
  const files = [];
21300
21300
  const directories = [];
21301
21301
  const visit = async (directory, prefix) => {
21302
21302
  const entries = await readdir2(directory, { withFileTypes: true });
21303
21303
  for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
21304
- if (!prefix && entry.name === WORK_PACK_LOCAL_STATE_FILENAME) continue;
21304
+ if (!includeReceipt && !prefix && entry.name === WORK_PACK_LOCAL_STATE_FILENAME) continue;
21305
21305
  const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
21306
21306
  const absolute = path5.join(directory, entry.name);
21307
21307
  const info = await lstat2(absolute);
@@ -25498,11 +25498,12 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
25498
25498
  enabled: skill.enabled
25499
25499
  }));
25500
25500
  const skillBySlug = new Map(manifest.skills.map((skill) => [skill.slug, skill]));
25501
+ const authoritative = manifest.workPacksComplete === true;
25501
25502
  const approvedModelIds = manifest.config.models.map((model) => typeof model === "string" ? model : model.id);
25502
25503
  const workPacks = await reconcileWorkPacks({
25503
25504
  desired,
25504
25505
  managed,
25505
- desiredIsComplete: manifest.workPacksComplete === true,
25506
+ desiredIsComplete: authoritative,
25506
25507
  operate: async (operation) => enrichIntegrityFailure(paths, operation, await operateWorkPack(
25507
25508
  paths,
25508
25509
  credentials,
@@ -25511,6 +25512,7 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
25511
25512
  recovery.cleanupPendingSlugs,
25512
25513
  recovery.failures,
25513
25514
  operation,
25515
+ authoritative,
25514
25516
  options
25515
25517
  )),
25516
25518
  recoveryFailures: recovery.failures,
@@ -25532,6 +25534,10 @@ async function collectWorkPackObservations(paths, reconciliation) {
25532
25534
  [...installedVersions].map(([slug, version2]) => [slug, { slug, state: "installed", version: version2 }])
25533
25535
  );
25534
25536
  for (const outcome of reconciliation.outcomes) {
25537
+ const installed = observations.get(outcome.slug);
25538
+ if (outcome.warningCode === "local-copy-archived" && installed?.state === "installed") {
25539
+ installed.warningCode = "local-copy-archived";
25540
+ }
25535
25541
  if (outcome.status !== "failed" && outcome.status !== "recovery-uncertain") continue;
25536
25542
  observations.set(outcome.slug, {
25537
25543
  slug: outcome.slug,
@@ -25555,7 +25561,7 @@ async function enrichIntegrityFailure(paths, operation, result) {
25555
25561
  return result;
25556
25562
  }
25557
25563
  }
25558
- async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds, cleanupPendingSlugs, recoveryFailures, operation, options) {
25564
+ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds, cleanupPendingSlugs, recoveryFailures, operation, authoritative, options) {
25559
25565
  const target = path10.join(paths.skillsDir, operation.pack.slug);
25560
25566
  const recoveryFailure = recoveryFailures.get(operation.pack.slug);
25561
25567
  if (recoveryFailure) return { status: "failed", restoration: "exact", code: recoveryFailure };
@@ -25574,14 +25580,14 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
25574
25580
  agentsDir: paths.agentsDir,
25575
25581
  commandsDir: paths.commandsDir
25576
25582
  });
25577
- if (localState !== "match") {
25583
+ if (localState !== "match" && !authoritative) {
25578
25584
  return {
25579
25585
  status: "failed",
25580
25586
  restoration: "exact",
25581
25587
  code: localState === "missing" ? "local-baseline-missing" : "local-edits-preserved"
25582
25588
  };
25583
25589
  }
25584
- const removedManagedPaths = await removeManagedWorkPackTransaction(paths, target, options);
25590
+ const removedManagedPaths = await removeManagedWorkPackTransaction(paths, target, options, localState !== "match");
25585
25591
  return { status: "removed", removedManagedPaths };
25586
25592
  } catch (error45) {
25587
25593
  if (error45 instanceof WorkPackRecoveryUncertainError) {
@@ -25594,6 +25600,8 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
25594
25600
  if (!skill) return { status: "recovery-uncertain", code: "missing-desired-pack" };
25595
25601
  let previousManagedPaths;
25596
25602
  let archive;
25603
+ let retainLocalCopy = false;
25604
+ let legacyReference;
25597
25605
  try {
25598
25606
  const currentVersion = await readFile9(path10.join(target, ".forge-version"), "utf8").catch(() => "");
25599
25607
  const sameVersion = currentVersion.trim() === skill.version;
@@ -25602,34 +25610,39 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
25602
25610
  packDir: target,
25603
25611
  agentsDir: paths.agentsDir,
25604
25612
  commandsDir: paths.commandsDir,
25605
- allowAdditional: true
25613
+ allowAdditional: !authoritative
25606
25614
  });
25607
25615
  if (localState === "missing") {
25608
25616
  const expected = await fetchWorkPackFileManifest(credentials, skill.slug, currentVersion.trim());
25617
+ legacyReference = expected;
25609
25618
  if (expected) {
25610
25619
  const diagnosis = await inspectWorkPackIntegrity({ paths, slug: skill.slug, expected });
25611
25620
  if (diagnosis.summary.modified || diagnosis.summary.missing || diagnosis.summary.unsafe || diagnosis.summary.unreadable || diagnosis.summary.truncated) {
25612
- return { status: "failed", restoration: "exact", code: "local-edits-preserved", integrity: diagnosis.summary };
25621
+ if (!authoritative) return { status: "failed", restoration: "exact", code: "local-edits-preserved", integrity: diagnosis.summary };
25622
+ localState = "changed";
25623
+ } else {
25624
+ localState = await adoptWorkPackFileManifest({
25625
+ packDir: target,
25626
+ agentsDir: paths.agentsDir,
25627
+ commandsDir: paths.commandsDir,
25628
+ expected
25629
+ }) ? "match" : "changed";
25613
25630
  }
25614
- localState = await adoptWorkPackFileManifest({
25615
- packDir: target,
25616
- agentsDir: paths.agentsDir,
25617
- commandsDir: paths.commandsDir,
25618
- expected
25619
- }) ? "match" : "changed";
25620
25631
  } else if (sameVersion) {
25621
- const candidateArchive = await downloadSkill(credentials, skill.url);
25622
- if (createHash4("sha256").update(candidateArchive).digest("hex") !== skill.sha256)
25623
- return { status: "failed", restoration: "exact", code: "local-baseline-missing" };
25624
- localState = await adoptLegacyWorkPackState(paths, skill.slug, skill.version, candidateArchive, approvedModelIds) ? "match" : "changed";
25632
+ archive = await downloadSkill(credentials, skill.url);
25633
+ if (createHash4("sha256").update(archive).digest("hex") !== skill.sha256)
25634
+ return { status: "failed", restoration: "exact", code: authoritative ? "checksum-mismatch" : "local-baseline-missing" };
25635
+ localState = await adoptLegacyWorkPackState(paths, skill.slug, skill.version, archive, approvedModelIds) ? "match" : "changed";
25625
25636
  }
25637
+ if (authoritative && localState === "match") localState = await checkWorkPackTreeState(target);
25626
25638
  }
25627
- if (localState !== "match") return {
25639
+ if (localState !== "match" && !authoritative) return {
25628
25640
  status: "failed",
25629
25641
  restoration: "exact",
25630
25642
  code: localState === "missing" ? "local-baseline-missing" : "local-edits-preserved"
25631
25643
  };
25632
- if (sameVersion && !await workPackNeedsModelNormalization(target, approvedModelIds, skill.slug)) {
25644
+ retainLocalCopy = localState !== "match";
25645
+ if (!retainLocalCopy && sameVersion && !await workPackNeedsModelNormalization(target, approvedModelIds, skill.slug)) {
25633
25646
  return cleanupPendingSlugs.has(skill.slug) ? {
25634
25647
  status: "unchanged",
25635
25648
  warningCode: "cleanup-pending",
@@ -25638,7 +25651,7 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
25638
25651
  }
25639
25652
  }
25640
25653
  previousManagedPaths = await managedWorkPackPaths(paths, target);
25641
- archive = await downloadSkill(credentials, skill.url);
25654
+ archive ??= await downloadSkill(credentials, skill.url);
25642
25655
  const sha2563 = createHash4("sha256").update(archive).digest("hex");
25643
25656
  if (sha2563 !== skill.sha256) return { status: "failed", restoration: "exact", code: "checksum-mismatch" };
25644
25657
  } catch (error45) {
@@ -25652,6 +25665,8 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
25652
25665
  installWorkPackBoundary: options.installWorkPackBoundary,
25653
25666
  workPackProjectionBoundary: options.workPackProjectionBoundary,
25654
25667
  cleanupWorkPackBackup: options.cleanupWorkPackBackup,
25668
+ retainLocalCopy,
25669
+ legacyReference,
25655
25670
  approvedModelIds
25656
25671
  });
25657
25672
  cleanupPending = install.cleanup === "pending";
@@ -25669,6 +25684,9 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
25669
25684
  ...cleanupPending ? {
25670
25685
  warningCode: "cleanup-pending",
25671
25686
  message: `O pacote "${skill.slug}" foi instalado, mas o backup anterior continua bloqueado. Feche o OpenWork e volte a sincronizar para concluir a limpeza.`
25687
+ } : retainLocalCopy ? {
25688
+ warningCode: "local-copy-archived",
25689
+ message: "A vers\xE3o oficial foi instalada. As altera\xE7\xF5es anteriores ficaram numa c\xF3pia local fora do OpenWork."
25672
25690
  } : {}
25673
25691
  };
25674
25692
  } catch {
@@ -25796,8 +25814,12 @@ var WorkPackLocalEditsError = class extends Error {
25796
25814
  }
25797
25815
  code;
25798
25816
  };
25799
- async function assertWorkPackUnchangedAtBoundary(paths, target, snapshot) {
25817
+ async function assertWorkPackUnchangedAtBoundary(paths, target, snapshot, retained = false) {
25800
25818
  const ownership = await workPackOwnership(target);
25819
+ if (retained) {
25820
+ if (ownership !== "managed" || !snapshot) throw new WorkPackLocalEditsError("local-edits-preserved");
25821
+ return assertWorkPackTreeUnchangedAtBoundary(target, snapshot, true);
25822
+ }
25801
25823
  if (ownership === "absent") return;
25802
25824
  if (ownership === "foreign") throw foreignWorkPackError(path10.basename(target));
25803
25825
  const localState = await checkWorkPackInstalledState({
@@ -25811,8 +25833,8 @@ async function assertWorkPackUnchangedAtBoundary(paths, target, snapshot) {
25811
25833
  }
25812
25834
  if (snapshot) await assertWorkPackTreeUnchangedAtBoundary(target, snapshot);
25813
25835
  }
25814
- async function assertWorkPackTreeUnchangedAtBoundary(target, snapshot) {
25815
- const actual = snapshot ? await digestPackTree(target) : void 0;
25836
+ async function assertWorkPackTreeUnchangedAtBoundary(target, snapshot, includeReceipt = false) {
25837
+ const actual = snapshot ? await digestPackTree(target, includeReceipt) : void 0;
25816
25838
  const localState = snapshot ? actual && sameTree(actual, snapshot) ? "match" : "changed" : await checkWorkPackTreeState(target);
25817
25839
  if (localState !== "match") {
25818
25840
  throw new WorkPackLocalEditsError(localState === "missing" ? "local-baseline-missing" : "local-edits-preserved");
@@ -25923,16 +25945,22 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25923
25945
  const previousManagedPaths = await managedWorkPackPaths(paths, target);
25924
25946
  let originalTree;
25925
25947
  let installedTree;
25948
+ let retainedProjections = [];
25926
25949
  try {
25927
25950
  if (await workPackOwnership(target) === "managed") {
25928
- originalTree = await digestPackTree(target);
25951
+ originalTree = await digestPackTree(target, options.retainLocalCopy);
25929
25952
  if (!originalTree) throw new WorkPackLocalEditsError("local-edits-preserved");
25930
- await preserveWorkPackExtras(target, nextPath, originalTree);
25953
+ if (options.retainLocalCopy) {
25954
+ if (await pathExists(backup)) throw new WorkPackLocalEditsError("local-edits-preserved");
25955
+ retainedProjections = await retainLocalWorkPack(paths, target, originalTree, previousAgents, previousCommands, options.legacyReference);
25956
+ } else {
25957
+ await preserveWorkPackExtras(target, nextPath, originalTree);
25958
+ }
25931
25959
  }
25932
25960
  installedTree = await digestPackTree(nextPath);
25933
25961
  if (!installedTree) throw new WorkPackLocalEditsError("local-edits-preserved");
25934
25962
  if (previousManagedPaths.length > 0) await options.beforeManagedPathsRemoved?.(previousManagedPaths);
25935
- await assertWorkPackUnchangedAtBoundary(paths, target, originalTree);
25963
+ await assertWorkPackUnchangedAtBoundary(paths, target, originalTree, options.retainLocalCopy);
25936
25964
  } catch (error45) {
25937
25965
  await rm4(tempRoot, { recursive: true, force: true });
25938
25966
  throw error45;
@@ -25956,13 +25984,14 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25956
25984
  }
25957
25985
  if (targetBackedUp) {
25958
25986
  await options.installWorkPackBoundary?.("after-backup");
25959
- await assertWorkPackUnchangedAtBoundary(paths, backup, originalTree);
25987
+ await assertWorkPackUnchangedAtBoundary(paths, backup, originalTree, options.retainLocalCopy);
25960
25988
  }
25961
25989
  await rename7(nextPath, target);
25962
25990
  targetInstalled = true;
25963
25991
  for (const filename of previousAgents.filter((name) => !nextAgentNames.has(name))) {
25964
25992
  const filePath = path10.join(paths.agentsDir, filename);
25965
25993
  await options.workPackProjectionBoundary?.("install", filePath);
25994
+ await assertRetainedProjectionState(retainedProjections, filePath);
25966
25995
  await assertProjectionState(filePath, agentSnapshot.get(filePath));
25967
25996
  await rm4(filePath, { force: true });
25968
25997
  }
@@ -25971,6 +26000,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25971
26000
  for (const agent of agentFiles) {
25972
26001
  const filePath = path10.join(paths.agentsDir, agent.filename);
25973
26002
  await options.workPackProjectionBoundary?.("install", filePath);
26003
+ await assertRetainedProjectionState(retainedProjections, filePath);
25974
26004
  await assertProjectionState(filePath, agentSnapshot.get(filePath));
25975
26005
  await writeProjection(filePath, agent.content);
25976
26006
  }
@@ -25978,6 +26008,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25978
26008
  for (const filename of previousCommands.filter((name) => !nextCommandNames.has(name))) {
25979
26009
  const filePath = path10.join(paths.commandsDir, filename);
25980
26010
  await options.workPackProjectionBoundary?.("install", filePath);
26011
+ await assertRetainedProjectionState(retainedProjections, filePath);
25981
26012
  await assertProjectionState(filePath, commandSnapshot.get(filePath));
25982
26013
  await rm4(filePath, { force: true });
25983
26014
  }
@@ -25986,17 +26017,18 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25986
26017
  for (const command of commandFiles) {
25987
26018
  const filePath = path10.join(paths.commandsDir, command.filename);
25988
26019
  await options.workPackProjectionBoundary?.("install", filePath);
26020
+ await assertRetainedProjectionState(retainedProjections, filePath);
25989
26021
  await assertProjectionState(filePath, commandSnapshot.get(filePath));
25990
26022
  await writeProjection(filePath, command.content);
25991
26023
  }
25992
26024
  }
25993
- if (targetBackedUp) await assertWorkPackTreeUnchangedAtBoundary(backup, originalTree);
26025
+ if (targetBackedUp) await assertWorkPackTreeUnchangedAtBoundary(backup, originalTree, options.retainLocalCopy);
25994
26026
  if (targetBackedUp) await options.installWorkPackBoundary?.("before-commit");
25995
26027
  await assertWorkPackTreeUnchangedAtBoundary(target, installedTree);
25996
26028
  if (targetBackedUp) {
25997
26029
  await rename7(backup, claimedBackup);
25998
26030
  backupClaimed = true;
25999
- await assertWorkPackTreeUnchangedAtBoundary(claimedBackup, originalTree);
26031
+ await assertWorkPackTreeUnchangedAtBoundary(claimedBackup, originalTree, options.retainLocalCopy);
26000
26032
  await writeFile7(path10.join(claimedBackup, WORK_PACK_COMMITTED_MARKER), `${version2}
26001
26033
  `);
26002
26034
  await writeTextAtomic(transactionPath, "committed\n");
@@ -26005,8 +26037,8 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
26005
26037
  try {
26006
26038
  if (targetInstalled) {
26007
26039
  await assertWorkPackTreeUnchangedAtBoundary(target, installedTree);
26008
- await restoreProjectionState(agentSnapshot, agentTransactionState);
26009
- await restoreProjectionState(commandSnapshot, commandTransactionState);
26040
+ await restoreProjectionState(agentSnapshot, agentTransactionState, retainedProjections);
26041
+ await restoreProjectionState(commandSnapshot, commandTransactionState, retainedProjections);
26010
26042
  }
26011
26043
  if (targetBackedUp) {
26012
26044
  const restoredTarget = path10.join(tempRoot, `${slug}-restore`);
@@ -26323,7 +26355,7 @@ async function captureProjectionState(directory, filenames) {
26323
26355
  }
26324
26356
  return snapshot;
26325
26357
  }
26326
- async function restoreProjectionState(snapshot, transactionState) {
26358
+ async function restoreProjectionState(snapshot, transactionState, retainedProjections = []) {
26327
26359
  for (const [filePath, content] of snapshot) {
26328
26360
  if (transactionState) {
26329
26361
  const current = await readFile9(filePath, "utf8").catch((error45) => {
@@ -26332,7 +26364,11 @@ async function restoreProjectionState(snapshot, transactionState) {
26332
26364
  });
26333
26365
  if (current !== transactionState.get(filePath)) continue;
26334
26366
  }
26335
- if (content === void 0) await rm4(filePath, { force: true });
26367
+ const original = retainedProjections.find((entry) => entry.path === filePath);
26368
+ if (original?.exists) {
26369
+ await writeFile7(filePath, original.bytes);
26370
+ await chmod4(filePath, original.mode);
26371
+ } else if (content === void 0) await rm4(filePath, { force: true });
26336
26372
  else await writeTextAtomic(filePath, content);
26337
26373
  }
26338
26374
  }
@@ -26467,17 +26503,56 @@ async function managedWorkPackSlugs(skillsDir) {
26467
26503
  }
26468
26504
  return slugs.sort((left, right) => left.localeCompare(right));
26469
26505
  }
26470
- async function removeManagedWorkPackTransaction(paths, target, options) {
26506
+ async function retainLocalWorkPack(paths, target, original, agents, commands, legacyReference) {
26507
+ const reference = await readInstalledState(target) ?? legacyReference;
26508
+ const matches = (actual, expected) => actual.length === expected.length && new Set(actual).size === actual.length && actual.every((name) => expected.includes(name));
26509
+ if (!matches(agents, reference?.agents.map(({ filename }) => filename) ?? []) || !matches(commands, reference?.commands.map(({ filename }) => filename) ?? [])) {
26510
+ throw new WorkPackLocalEditsError("local-baseline-missing");
26511
+ }
26512
+ const snapshots = await Promise.all([
26513
+ ...agents.map((filename) => ({ kind: "agents", file: path10.join(paths.agentsDir, filename) })),
26514
+ ...commands.map((filename) => ({ kind: "commands", file: path10.join(paths.commandsDir, filename) }))
26515
+ ].map(async ({ kind, file: file2 }) => ({ kind, ...await captureExactFile(file2) })));
26516
+ const directory = path10.join(paths.forgeDir, "work-pack-recovery");
26517
+ await mkdir6(directory, { recursive: true, mode: 448 });
26518
+ if (!(await lstat5(directory)).isDirectory()) throw new Error("Pasta de recupera\xE7\xE3o local inv\xE1lida");
26519
+ const recovery = await mkdtemp(path10.join(directory, path10.basename(target) + "-"));
26520
+ try {
26521
+ const pack = path10.join(recovery, "pack");
26522
+ await cp(target, pack, { recursive: true, force: false, errorOnExist: true });
26523
+ await assertWorkPackTreeUnchangedAtBoundary(pack, original, true);
26524
+ for (const snapshot of snapshots) {
26525
+ if (!snapshot.exists) continue;
26526
+ const copy = path10.join(recovery, snapshot.kind, path10.basename(snapshot.path));
26527
+ await mkdir6(path10.dirname(copy), { recursive: true });
26528
+ await writeFile7(copy, snapshot.bytes, { mode: snapshot.mode });
26529
+ if (!(await readFile9(copy)).equals(snapshot.bytes)) throw new Error("C\xF3pia de recupera\xE7\xE3o local incompleta");
26530
+ }
26531
+ await assertWorkPackTreeUnchangedAtBoundary(target, original, true);
26532
+ for (const snapshot of snapshots) await assertExactFileState(snapshots, snapshot.path);
26533
+ return snapshots;
26534
+ } catch (error45) {
26535
+ await rm4(recovery, { recursive: true, force: true }).catch(() => void 0);
26536
+ throw error45;
26537
+ }
26538
+ }
26539
+ async function assertRetainedProjectionState(snapshots, filePath) {
26540
+ if (snapshots.some((snapshot) => snapshot.path === filePath)) await assertExactFileState(snapshots, filePath);
26541
+ }
26542
+ async function removeManagedWorkPackTransaction(paths, target, options, retainLocalCopy) {
26471
26543
  const pathsToRemove = await managedWorkPackPaths(paths, target);
26472
26544
  if (pathsToRemove.length > 0) await options.beforeManagedPathsRemoved?.(pathsToRemove);
26473
26545
  const agents = await readAgentRecord(target);
26474
26546
  const commands = await readCommandRecord(target);
26475
- const snapshots = await Promise.all([
26547
+ const backup = `${target}.previous`;
26548
+ if (retainLocalCopy && await pathExists(backup)) throw new WorkPackLocalEditsError("local-edits-preserved");
26549
+ const original = retainLocalCopy ? await digestPackTree(target, true) : void 0;
26550
+ if (retainLocalCopy && !original) throw new WorkPackLocalEditsError("local-edits-preserved");
26551
+ const snapshots = original ? await retainLocalWorkPack(paths, target, original, agents, commands) : await Promise.all([
26476
26552
  ...agents.map((filename) => captureExactFile(path10.join(paths.agentsDir, filename))),
26477
26553
  ...commands.map((filename) => captureExactFile(path10.join(paths.commandsDir, filename)))
26478
26554
  ]);
26479
- await assertWorkPackUnchangedAtBoundary(paths, target);
26480
- const backup = `${target}.previous`;
26555
+ await assertWorkPackUnchangedAtBoundary(paths, target, original, retainLocalCopy);
26481
26556
  const transactionPath = `${backup}${WORK_PACK_TRANSACTION_SUFFIX}`;
26482
26557
  const transactionRoot = await mkdtemp(path10.join(os4.tmpdir(), "forge-remove-"));
26483
26558
  const claimedBackup = path10.join(transactionRoot, path10.basename(target));
@@ -26495,7 +26570,7 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
26495
26570
  }
26496
26571
  try {
26497
26572
  await options.removeWorkPackBoundary?.("after-backup");
26498
- await assertWorkPackUnchangedAtBoundary(paths, backup);
26573
+ await assertWorkPackUnchangedAtBoundary(paths, backup, original, retainLocalCopy);
26499
26574
  projectionsRemoved = agents.length > 0;
26500
26575
  for (const filename of agents) {
26501
26576
  const filePath = path10.join(paths.agentsDir, filename);
@@ -26514,11 +26589,11 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
26514
26589
  await rm4(filePath, { force: true });
26515
26590
  }
26516
26591
  await options.removeWorkPackBoundary?.("after-commands");
26517
- await assertWorkPackTreeUnchangedAtBoundary(backup);
26592
+ await assertWorkPackTreeUnchangedAtBoundary(backup, original, retainLocalCopy);
26518
26593
  await options.removeWorkPackBoundary?.("before-commit");
26519
26594
  await rename7(backup, claimedBackup);
26520
26595
  backupClaimed = true;
26521
- await assertWorkPackTreeUnchangedAtBoundary(claimedBackup);
26596
+ await assertWorkPackTreeUnchangedAtBoundary(claimedBackup, original, retainLocalCopy);
26522
26597
  await writeTextAtomic(transactionPath, "committed\n");
26523
26598
  await rm4(claimedBackup, { recursive: true, force: true });
26524
26599
  await rm4(transactionPath, { force: true });
@@ -26720,9 +26795,15 @@ antes de executar trabalho que delas dependa. Segue os processos indicados pelo
26720
26795
  utilizador quando aplic\xE1veis. N\xE3o declares que uma ferramenta ou fonte foi
26721
26796
  aprovada pela organiza\xE7\xE3o apenas por estar dispon\xEDvel.
26722
26797
 
26723
- Quando o trabalho se repete, prop\xF5e uma skill reutiliz\xE1vel. Cria ou atualiza-a
26724
- quando autorizado, sem dados privados de clientes. Publicar e distribuir a
26725
- skill s\xE3o a\xE7\xF5es separadas, com os respetivos controlos do Forge.
26798
+ Nas skills distribu\xEDdas pelo Forge, aplica adapta\xE7\xF5es pontuais apenas na conversa.
26799
+ Para corrigir ou guardar uma mudan\xE7a para pr\xF3ximas tarefas, prepara uma sugest\xE3o
26800
+ com /feedback. Mostra o texto e pede confirma\xE7\xE3o antes de enviar, mantendo a
26801
+ aprova\xE7\xE3o da ferramenta. Preserva a instala\xE7\xE3o gerida e encaminha a atualiza\xE7\xE3o
26802
+ permanente para o respons\xE1vel pelo Forge.
26803
+
26804
+ Quando o trabalho se repete e ainda n\xE3o existe uma skill para essa tarefa, prop\xF5e
26805
+ uma nova skill reutiliz\xE1vel. Cria-a quando autorizado, sem dados privados de
26806
+ clientes. Publicar e distribuir s\xE3o a\xE7\xF5es separadas, com os controlos do Forge.
26726
26807
 
26727
26808
  ## Entregas e comunica\xE7\xE3o
26728
26809
 
@@ -26930,8 +27011,127 @@ async function writeOpenworkEngineConfig(directory, config2) {
26930
27011
  return { changed: true };
26931
27012
  }
26932
27013
 
27014
+ // packages/cli/src/managedSkillSession.ts
27015
+ import { createHash as createHash7 } from "node:crypto";
27016
+ import { lstat as lstat7, readFile as readFile14, readdir as readdir7, realpath as realpath2 } from "node:fs/promises";
27017
+ import path14 from "node:path";
27018
+ var SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
27019
+ var MANAGED_SKILL_INSTRUCTION = `As skills distribu\xEDdas s\xE3o geridas pelo Forge. Usa a ferramenta skill para carregar as instru\xE7\xF5es oficiais.
27020
+ Quando a pessoa pedir uma adapta\xE7\xE3o para uma tarefa, aplica-a s\xF3 nesta conversa.
27021
+ Se pedir para corrigir, atualizar ou guardar uma mudan\xE7a para as pr\xF3ximas tarefas, explica que a altera\xE7\xE3o permanente passa pelo /feedback. Prepara uma sugest\xE3o com o nome da skill, a vers\xE3o se confirmada, o resultado esperado e um exemplo do que aconteceu. Segue a skill feedback-forge quando estiver dispon\xEDvel.
27022
+ Mant\xE9m a instala\xE7\xE3o gerida intacta. N\xE3o cries uma c\xF3pia para substituir a skill nem uses o terminal ou outra ferramenta para contornar uma edi\xE7\xE3o recusada.
27023
+ Mostra o texto proposto e pede confirma\xE7\xE3o antes de usar forge_feedback, mantendo a aprova\xE7\xE3o vis\xEDvel da ferramenta. Se o envio n\xE3o estiver dispon\xEDvel ou n\xE3o for confirmado, deixa a sugest\xE3o em formato copi\xE1vel e indica que o envio est\xE1 por verificar.`;
27024
+ var WRITE_DENIED = "Esta skill \xE9 gerida pelo Forge. Podes adaptar o trabalho nesta conversa ou sugerir uma altera\xE7\xE3o com /feedback.";
27025
+ async function managedSkillSession(paths, manifest) {
27026
+ const versions = /* @__PURE__ */ new Map();
27027
+ const entries = await readdir7(paths.skillsDir, { withFileTypes: true }).catch(() => []);
27028
+ for (const entry of entries) {
27029
+ if (!entry.isDirectory() || !SLUG.test(entry.name)) continue;
27030
+ const version2 = await managedVersion(path14.join(paths.skillsDir, entry.name));
27031
+ if (version2) versions.set(entry.name, manifest?.workPacksComplete === true ? null : version2);
27032
+ }
27033
+ for (const skill of manifest?.skills ?? []) {
27034
+ if (SLUG.test(skill.slug)) versions.set(skill.slug, skill.enabled ? skill.version : null);
27035
+ }
27036
+ const canonicalRoot = await realpath2(paths.skillsDir).catch(() => paths.skillsDir);
27037
+ return {
27038
+ active: versions.size > 0,
27039
+ async assertWritable(tool2, args, directory) {
27040
+ if (!versions.size) return;
27041
+ for (const file2 of toolWritePaths(tool2, args)) {
27042
+ const absolute = path14.resolve(directory, file2);
27043
+ if (protectedPath(paths.skillsDir, absolute, versions) || protectedPath(canonicalRoot, await resolveWritePath(absolute), versions)) {
27044
+ throw new Error(WRITE_DENIED);
27045
+ }
27046
+ }
27047
+ },
27048
+ async load(name) {
27049
+ const slug = typeof name === "string" ? name.trim().toLowerCase() : "";
27050
+ if (!versions.has(slug)) return void 0;
27051
+ const unavailable = {
27052
+ title: "Skill Forge indispon\xEDvel",
27053
+ output: "N\xE3o foi poss\xEDvel confirmar a vers\xE3o oficial desta skill. Fecha e volta a abrir o OpenWork para sincronizar. Se continuar, usa /feedback.",
27054
+ metadata: { name: slug },
27055
+ loaded: false
27056
+ };
27057
+ const version2 = versions.get(slug);
27058
+ if (!version2) return {
27059
+ ...unavailable,
27060
+ output: "Esta skill j\xE1 n\xE3o est\xE1 atribu\xEDda neste Forge. Usa /feedback se precisares de acesso."
27061
+ };
27062
+ const dir = path14.join(paths.skillsDir, slug);
27063
+ try {
27064
+ if (await managedVersion(dir) !== version2) return unavailable;
27065
+ const expected = await readInstalledState(dir);
27066
+ if (expected?.version !== version2 || await checkWorkPackTreeState(dir, true) !== "match") return unavailable;
27067
+ const bytes = await readFile14(path14.join(dir, "SKILL.md"));
27068
+ const hash2 = createHash7("sha256").update(bytes).digest("hex");
27069
+ if (!expected.files.some((file2) => file2.path === "SKILL.md" && file2.sha256 === hash2)) return unavailable;
27070
+ const body = bytes.toString("utf8").replace(/^\uFEFF?---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, "").trim();
27071
+ const files = expected.files.filter((file2) => file2.path !== "SKILL.md" && !file2.path.startsWith(".forge-")).slice(0, 10).map((file2) => "<file>" + path14.join(dir, file2.path) + "</file>");
27072
+ return {
27073
+ title: "Loaded skill: " + slug,
27074
+ output: [
27075
+ '<skill_content name="' + slug + '">',
27076
+ "# Skill: " + slug,
27077
+ "",
27078
+ body,
27079
+ "",
27080
+ "Base directory for this skill: " + dir,
27081
+ "Relative paths in this skill are relative to this base directory.",
27082
+ "<skill_files>",
27083
+ ...files,
27084
+ "</skill_files>",
27085
+ "</skill_content>"
27086
+ ].join("\n"),
27087
+ metadata: { name: slug, dir, forgeVersion: version2 },
27088
+ loaded: true
27089
+ };
27090
+ } catch {
27091
+ return unavailable;
27092
+ }
27093
+ }
27094
+ };
27095
+ }
27096
+ async function managedVersion(dir) {
27097
+ const marker = path14.join(dir, ".forge-version");
27098
+ try {
27099
+ if (!(await lstat7(dir)).isDirectory() || !(await lstat7(marker)).isFile()) return void 0;
27100
+ return (await readFile14(marker, "utf8")).trim() || void 0;
27101
+ } catch {
27102
+ return void 0;
27103
+ }
27104
+ }
27105
+ function toolWritePaths(tool2, value) {
27106
+ if (!value || typeof value !== "object") return [];
27107
+ const args = value;
27108
+ if (tool2 === "edit" || tool2 === "write") {
27109
+ const file2 = args.filePath ?? args.path;
27110
+ return typeof file2 === "string" ? [file2] : [];
27111
+ }
27112
+ if (tool2 !== "apply_patch" && tool2 !== "patch") return [];
27113
+ const patch = args.patchText ?? args.patch;
27114
+ if (typeof patch !== "string") return [];
27115
+ return [...patch.matchAll(/^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/gm)].map((match) => match[1].trim());
27116
+ }
27117
+ function protectedPath(root, file2, versions) {
27118
+ const slug = path14.relative(root, file2).split(path14.sep)[0]?.toLowerCase();
27119
+ if (slug && versions.has(slug)) return true;
27120
+ const parts = file2.toLowerCase().split(path14.sep);
27121
+ return parts.some((part, i) => [".opencode", ".agents", ".claude"].includes(part) && ["skill", "skills"].includes(parts[i + 1] ?? "") && versions.has(parts[i + 2] ?? ""));
27122
+ }
27123
+ async function resolveWritePath(file2) {
27124
+ try {
27125
+ return await realpath2(file2);
27126
+ } catch (error45) {
27127
+ const parent = path14.dirname(file2);
27128
+ if (parent === file2 || error45.code !== "ENOENT") return file2;
27129
+ return path14.join(await resolveWritePath(parent), path14.basename(file2));
27130
+ }
27131
+ }
27132
+
26933
27133
  // packages/cli/src/workPackSyncPlugin.ts
26934
- var PLUGIN_VERSION = "0.1.53";
27134
+ var PLUGIN_VERSION = "0.1.54";
26935
27135
  var FORGE_DECISION_TIMEOUT_MS = 11e4;
26936
27136
  var STATUS_FILENAME = "work-pack-startup-status.json";
26937
27137
  var activeSync = /* @__PURE__ */ new Map();
@@ -26959,7 +27159,7 @@ function createForgeTools(forgeBaseUrl, state) {
26959
27159
  function createEvidenceReporters(forgeBaseUrl, state) {
26960
27160
  const reportEvidence = async (sessionID, callID, slug, kind) => {
26961
27161
  const { forgeApiKey } = await readForgeCredentials(state.paths, forgeBaseUrl);
26962
- const credentialId = createHash7("sha256").update(forgeApiKey).digest("hex");
27162
+ const credentialId = createHash8("sha256").update(forgeApiKey).digest("hex");
26963
27163
  const report = skillUsageReporter(forgeBaseUrl, credentialId, (events) => fetch(`${forgeBaseUrl}/sync/evidence`, {
26964
27164
  method: "POST",
26965
27165
  redirect: "error",
@@ -26978,7 +27178,7 @@ function createEvidenceReporters(forgeBaseUrl, state) {
26978
27178
  const slug = typeof name === "string" ? name.trim().toLowerCase() : "";
26979
27179
  if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) return;
26980
27180
  try {
26981
- await readFile14(path14.join(state.paths.skillsDir, slug, ".forge-version"), "utf8");
27181
+ await readFile15(path15.join(state.paths.skillsDir, slug, ".forge-version"), "utf8");
26982
27182
  } catch {
26983
27183
  return;
26984
27184
  }
@@ -26993,17 +27193,30 @@ function createEvidenceReporters(forgeBaseUrl, state) {
26993
27193
  var ForgeWorkPackSyncServer = async (_input, options) => {
26994
27194
  const forgeBaseUrl = parseForgeBaseUrl(options);
26995
27195
  const state = await startupSync(forgeBaseUrl, isLocalConfig(options), () => observeRuntime(_input), _input);
26996
- const legacyPath = path14.join(state.paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
27196
+ const legacyPath = path15.join(state.paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
26997
27197
  const ownershipSymbol = /* @__PURE__ */ Symbol.for("minimal-forge.legacy-evidence-owners.v1");
26998
27198
  const shared = globalThis;
26999
27199
  const legacyOwners = shared[ownershipSymbol] ??= /* @__PURE__ */ new Set();
27000
27200
  const legacyOwnerKey = JSON.stringify([forgeBaseUrl, legacyPath]);
27001
27201
  const client = reasoningLoopGuardClient(_input);
27002
27202
  const { reportReasoningLoop, reportSkillInvocation } = createEvidenceReporters(forgeBaseUrl, state);
27203
+ const skills = await managedSkillSession(state.paths, state.manifest ?? state.failedManifest);
27204
+ const directory = _input?.directory ?? process.cwd();
27003
27205
  return {
27004
27206
  ...client ? { event: createReasoningLoopGuard(client, console.error, reportReasoningLoop) } : {},
27005
- "tool.execute.after": async (input) => {
27006
- if (input.tool !== "skill" || legacyOwners.has(legacyOwnerKey)) return;
27207
+ "experimental.chat.system.transform": async (_input2, output) => {
27208
+ if (skills.active) output.system.push(MANAGED_SKILL_INSTRUCTION);
27209
+ },
27210
+ "tool.execute.before": async (input, output) => skills.assertWritable(input.tool, output.args, directory),
27211
+ "tool.execute.after": async (input, output) => {
27212
+ if (input.tool !== "skill") return;
27213
+ const official = await skills.load(input.args?.name);
27214
+ if (official) {
27215
+ output.title = official.title;
27216
+ output.output = official.output;
27217
+ output.metadata = official.metadata;
27218
+ }
27219
+ if (official?.loaded === false || legacyOwners.has(legacyOwnerKey)) return;
27007
27220
  await reportSkillInvocation(input.sessionID, input.callID, input.args?.name);
27008
27221
  },
27009
27222
  config: async (config2) => {
@@ -27012,7 +27225,7 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
27012
27225
  const name = Array.isArray(entry) ? entry[0] : entry;
27013
27226
  return name === legacyPath || name === pathToFileURL(legacyPath).href;
27014
27227
  });
27015
- const legacy = registered ? await readFile14(legacyPath, "utf8").catch(() => "") : "";
27228
+ const legacy = registered ? await readFile15(legacyPath, "utf8").catch(() => "") : "";
27016
27229
  const oldLegacyRegistered = registered && legacy.startsWith(FORGE_PLUGIN_HEADER) && legacy.includes("work_pack_invocation") && !legacy.includes("minimal-forge.skill-usage.v1");
27017
27230
  if (oldLegacyRegistered) legacyOwners.add(legacyOwnerKey);
27018
27231
  if (oldLegacyRegistered) await writeFile9(legacyPath, renderEvidencePlugin()).catch(() => {
@@ -27033,11 +27246,11 @@ async function ForgeWorkPackSyncSetup(ctx) {
27033
27246
  const directory = ctx.options.openworkEngineConfigDir;
27034
27247
  if (typeof directory === "string" && state.manifest) {
27035
27248
  const active = process.env.OPENCODE_CONFIG_DIR;
27036
- if (!active || await realpath2(active) !== await realpath2(directory)) {
27249
+ if (!active || await realpath3(active) !== await realpath3(directory)) {
27037
27250
  throw new Error("A pasta do motor ativo mudou. Confirme a liga\xE7\xE3o Forge neste perfil do OpenWork.");
27038
27251
  }
27039
27252
  const credentials = await readForgeCredentials(state.paths, forgeBaseUrl);
27040
- const canonical = objectRecord2(parseJsonc(await readFile14(state.paths.opencodeConfigPath, "utf8")));
27253
+ const canonical = objectRecord2(parseJsonc(await readFile15(state.paths.opencodeConfigPath, "utf8")));
27041
27254
  const config2 = renderOpenworkEngineConfig(state.manifest, credentials, state.paths, directory, canonical);
27042
27255
  if (state.partialWorkPackSync) {
27043
27256
  const companion = await inspectOpenworkEngineConfig(directory);
@@ -27053,6 +27266,10 @@ async function ForgeWorkPackSyncSetup(ctx) {
27053
27266
  });
27054
27267
  syncedTools.catch(() => void 0);
27055
27268
  const { reportReasoningLoop, reportSkillInvocation } = createEvidenceReporters(forgeBaseUrl, { paths });
27269
+ const managedSkills = sync.then(
27270
+ (state) => managedSkillSession(paths, state.manifest ?? state.failedManifest),
27271
+ () => managedSkillSession(paths)
27272
+ );
27056
27273
  const directoryOf = sessionDirectoryResolver(ctx);
27057
27274
  const registrations = Object.entries(createForgeTools(forgeBaseUrl, { paths, decisionBaseUrl: forgeBaseUrl })).filter(([name]) => name !== "forge_feedback").map(([name, shape]) => openCode2Tool(name, {
27058
27275
  description: shape.description,
@@ -27066,10 +27283,18 @@ async function ForgeWorkPackSyncSetup(ctx) {
27066
27283
  await ctx.tool.transform((editor) => {
27067
27284
  for (const registration of registrations) editor.add(registration);
27068
27285
  });
27286
+ await ctx.tool.hook("execute.before", async (event) => {
27287
+ if (!["edit", "write", "patch", "apply_patch"].includes(event.tool)) return;
27288
+ await (await managedSkills).assertWritable(event.tool, event.input, ctx.location.directory);
27289
+ });
27069
27290
  await ctx.tool.hook("execute.after", async (event) => {
27291
+ const call = completedSkillCall(event);
27292
+ if (!call || event.status !== "completed") return;
27293
+ const official = await (await managedSkills).load(call.name);
27294
+ if (official) event.result = { content: official.output, metadata: official.metadata };
27295
+ if (official?.loaded === false) return;
27070
27296
  try {
27071
- const call = completedSkillCall(event);
27072
- if (call) await reportSkillInvocation(call.sessionID, call.callID, call.name);
27297
+ await reportSkillInvocation(call.sessionID, call.callID, call.name);
27073
27298
  } catch {
27074
27299
  console.error("[Forge evidence] Invocation could not be reported");
27075
27300
  }
@@ -27095,7 +27320,7 @@ function createForgeImageTool(forgeBaseUrl, gatewayBaseUrl, paths) {
27095
27320
  const requestId = randomUUID5();
27096
27321
  let referenceDataUrl;
27097
27322
  if (args.referencePath) {
27098
- const bytes = await readFile14(args.referencePath);
27323
+ const bytes = await readFile15(args.referencePath);
27099
27324
  if (bytes.byteLength > 25e5) throw new Error("A imagem de refer\xEAncia \xE9 demasiado grande. Reduza-a antes de tentar novamente.");
27100
27325
  const mime = bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) ? "image/png" : bytes.subarray(0, 3).equals(Buffer.from([255, 216, 255])) ? "image/jpeg" : bytes.subarray(0, 4).toString() === "RIFF" && bytes.subarray(8, 12).toString() === "WEBP" ? "image/webp" : void 0;
27101
27326
  if (!mime) throw new Error("A refer\xEAncia tem de ser PNG, JPEG ou WebP.");
@@ -27121,14 +27346,14 @@ function createForgeImageTool(forgeBaseUrl, gatewayBaseUrl, paths) {
27121
27346
  if (image.byteLength > 8 * 1024 * 1024 || !image.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
27122
27347
  throw new Error(`O PNG recebido \xE9 inv\xE1lido. Refer\xEAncia: ${requestId}`);
27123
27348
  }
27124
- const destination = path14.join(context.directory, `forge-image-${requestId}.png`);
27349
+ const destination = path15.join(context.directory, `forge-image-${requestId}.png`);
27125
27350
  await writeFile9(destination, image, { flag: "wx" });
27126
27351
  const reset = body.quota && new Intl.DateTimeFormat("pt-PT", { dateStyle: "long", timeZone: "Europe/Lisbon" }).format(new Date(body.quota.resetsAt));
27127
27352
  const remaining = body.quota ? ` Restam ${body.quota.remaining} imagens at\xE9 ${reset}.` : "";
27128
27353
  return {
27129
27354
  title: "Imagem criada",
27130
27355
  output: `Imagem guardada em ${destination}.${remaining} A pessoa j\xE1 v\xEA a imagem na conversa. Se n\xE3o a conseguires ver, isso n\xE3o \xE9 um erro: n\xE3o o reportes.`,
27131
- attachments: [{ type: "file", mime: "image/png", url: `data:image/png;base64,${body.b64_json}`, filename: path14.basename(destination) }]
27356
+ attachments: [{ type: "file", mime: "image/png", url: `data:image/png;base64,${body.b64_json}`, filename: path15.basename(destination) }]
27132
27357
  };
27133
27358
  }
27134
27359
  });
@@ -27170,9 +27395,9 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
27170
27395
  let requestBody;
27171
27396
  if (fromFile) {
27172
27397
  const file2 = await fileInsideWorkspace(context.directory, args.request_file);
27173
- const planFile = path14.join(path14.dirname(path14.dirname(file2)), "plan.json");
27174
- if (!responseDirectory && path14.basename(path14.dirname(file2)) === "requests" && await fileExists(planFile)) {
27175
- const plan = JSON.parse(await readFile14(planFile, "utf8"));
27398
+ const planFile = path15.join(path15.dirname(path15.dirname(file2)), "plan.json");
27399
+ if (!responseDirectory && path15.basename(path15.dirname(file2)) === "requests" && await fileExists(planFile)) {
27400
+ const plan = JSON.parse(await readFile15(planFile, "utf8"));
27176
27401
  if (plan?.engine === "jev-batch" && plan.model === "typesafe/jev-1.13" && Array.isArray(plan.batches)) {
27177
27402
  let batch;
27178
27403
  for (const candidate of plan.batches) {
@@ -27185,7 +27410,7 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
27185
27410
  return createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths).execute({ plan_file: planFile, batch_id: batch.batch_id }, context);
27186
27411
  }
27187
27412
  }
27188
- const raw = await readFile14(file2, "utf8");
27413
+ const raw = await readFile15(file2, "utf8");
27189
27414
  if (Buffer.byteLength(raw) > 512 * 1024) throw new Error("O ficheiro de pedido excede 512 KiB.");
27190
27415
  let parsed;
27191
27416
  try {
@@ -27204,11 +27429,11 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
27204
27429
  if (args.state === void 0 || !args.questions || Object.keys(args.questions).length === 0) throw new Error("Indica state e questions.");
27205
27430
  requestBody = { state: args.state, questions: args.questions };
27206
27431
  }
27207
- const responseDir = await mkdtemp2(path14.join(responseDirectory ?? context.directory, ".forge-decision-"));
27208
- const responseFile = path14.join(responseDir, "response.json");
27432
+ const responseDir = await mkdtemp2(path15.join(responseDirectory ?? context.directory, ".forge-decision-"));
27433
+ const responseFile = path15.join(responseDir, "response.json");
27209
27434
  try {
27210
27435
  const credentials = await readForgeCredentials(paths, forgeBaseUrl);
27211
- const probeFile = path14.join(responseDir, ".write-test");
27436
+ const probeFile = path15.join(responseDir, ".write-test");
27212
27437
  await writeFile9(probeFile, "", { flag: "wx", mode: 384 });
27213
27438
  await unlink2(probeFile);
27214
27439
  context.abort.throwIfAborted();
@@ -27257,10 +27482,10 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
27257
27482
  });
27258
27483
  }
27259
27484
  async function fileInsideWorkspace(directory, candidate) {
27260
- const workspace = await realpath2(directory);
27261
- const file2 = await realpath2(path14.resolve(workspace, candidate));
27262
- const relative = path14.relative(workspace, file2);
27263
- if (!relative || (relative === ".." || relative.startsWith(`..${path14.sep}`)) || path14.isAbsolute(relative)) throw new Error("O ficheiro tem de estar dentro do workspace.");
27485
+ const workspace = await realpath3(directory);
27486
+ const file2 = await realpath3(path15.resolve(workspace, candidate));
27487
+ const relative = path15.relative(workspace, file2);
27488
+ if (!relative || (relative === ".." || relative.startsWith(`..${path15.sep}`)) || path15.isAbsolute(relative)) throw new Error("O ficheiro tem de estar dentro do workspace.");
27264
27489
  return file2;
27265
27490
  }
27266
27491
  async function fileExists(candidate) {
@@ -27275,7 +27500,7 @@ async function fileExists(candidate) {
27275
27500
  async function ensureJevDirectory(directory, filesystem = { stat: stat3, mkdir: mkdir8 }) {
27276
27501
  try {
27277
27502
  if ((await filesystem.stat(directory)).isDirectory()) return;
27278
- throw new Error(`O destino ${path14.basename(directory)} existe, mas n\xE3o \xE9 uma pasta. Preservar o conte\xFAdo e verificar o caminho.`);
27503
+ throw new Error(`O destino ${path15.basename(directory)} existe, mas n\xE3o \xE9 uma pasta. Preservar o conte\xFAdo e verificar o caminho.`);
27279
27504
  } catch (error45) {
27280
27505
  if (error45.code !== "ENOENT") throw error45;
27281
27506
  }
@@ -27294,12 +27519,29 @@ function canonicalJson(value) {
27294
27519
  }
27295
27520
  return JSON.stringify(value);
27296
27521
  }
27297
- async function validateSavedDecision(file2, request) {
27298
- const body = JSON.parse(await readFile14(file2, "utf8"));
27522
+ function decisionProbability(value) {
27523
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
27524
+ }
27525
+ function validSmallDecision(answer, question) {
27526
+ if (question.type === "noul") return decisionProbability(answer.noul);
27527
+ const criteria = objectRecord2(question.criteria);
27528
+ if (question.type !== "choice" || typeof answer.choice !== "string" || !Object.hasOwn(criteria, answer.choice)) return false;
27529
+ if (answer.confidence !== void 0 && !decisionProbability(answer.confidence)) return false;
27530
+ if (answer.probabilities === void 0) return true;
27531
+ const probabilities = objectRecord2(answer.probabilities);
27532
+ return Object.keys(criteria).length === Object.keys(probabilities).length && Object.keys(criteria).every((key) => decisionProbability(probabilities[key]));
27533
+ }
27534
+ async function validateSavedDecision(file2, request, smallPlan) {
27535
+ const body = JSON.parse(await readFile15(file2, "utf8"));
27299
27536
  const answers = body.answers;
27300
27537
  const questions = request.questions;
27301
27538
  const usage = body.usage;
27302
- 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)))) {
27539
+ 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") || smallPlan && (Number(usage.input_tokens) < 0 || Number(usage.output_tokens) < 0) || Object.entries(questions).some(([id, question]) => {
27540
+ const answer = answers[id];
27541
+ if (!answer || answer.type !== question.type) return true;
27542
+ if (smallPlan) return !validSmallDecision(answer, question);
27543
+ return question.type === "noul" && (typeof answer.noul !== "number" || !Number.isFinite(answer.noul));
27544
+ })) {
27303
27545
  throw new Error("Resposta Jev guardada inv\xE1lida; preservar o ficheiro e verificar antes de continuar.");
27304
27546
  }
27305
27547
  return body;
@@ -27314,7 +27556,7 @@ async function acquireJevRunLock(lockDir) {
27314
27556
  let owner;
27315
27557
  let ownerRaw;
27316
27558
  try {
27317
- ownerRaw = await readFile14(path14.join(lockDir, "owner.json"), "utf8");
27559
+ ownerRaw = await readFile15(path15.join(lockDir, "owner.json"), "utf8");
27318
27560
  owner = JSON.parse(ownerRaw);
27319
27561
  } catch {
27320
27562
  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.");
@@ -27326,7 +27568,7 @@ async function acquireJevRunLock(lockDir) {
27326
27568
  process.kill(owner.pid, 0);
27327
27569
  } catch (error45) {
27328
27570
  if (error45.code === "ESRCH") {
27329
- const archived = `${lockDir}.interrupted-${createHash7("sha256").update(ownerRaw).digest("hex")}`;
27571
+ const archived = `${lockDir}.interrupted-${createHash8("sha256").update(ownerRaw).digest("hex")}`;
27330
27572
  await rename9(lockDir, archived);
27331
27573
  try {
27332
27574
  await mkdir8(lockDir);
@@ -27348,56 +27590,79 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27348
27590
  },
27349
27591
  async execute(args, context) {
27350
27592
  const planFile = await fileInsideWorkspace(context.directory, args.plan_file);
27351
- if (path14.basename(planFile) !== "plan.json" || path14.basename(path14.dirname(planFile)) !== "jev") throw new Error("Indica o ficheiro jev/plan.json.");
27352
- const runDir = path14.dirname(path14.dirname(planFile));
27353
- const plan = JSON.parse(await readFile14(planFile, "utf8"));
27354
- if (plan.engine !== "jev-batch" || plan.model !== "typesafe/jev-1.13" || !Array.isArray(plan.batches)) throw new Error("O plano Jev \xE9 inv\xE1lido.");
27355
- const allBatches = plan.batches;
27593
+ if (path15.basename(planFile) !== "plan.json" || path15.basename(path15.dirname(planFile)) !== "jev") throw new Error("Indica o ficheiro jev/plan.json.");
27594
+ const runDir = path15.dirname(path15.dirname(planFile));
27595
+ const plan = objectRecord2(JSON.parse(await readFile15(planFile, "utf8")));
27596
+ const smallPlan = plan.schema_version === 2 && Array.isArray(plan.requests) && plan.batches === void 0;
27597
+ if (plan.engine !== "jev-batch" || plan.model !== "typesafe/jev-1.13" || !smallPlan && (!Array.isArray(plan.batches) || plan.requests !== void 0)) throw new Error("O plano Jev \xE9 inv\xE1lido.");
27598
+ const allBatches = smallPlan ? plan.requests.map((request, index) => {
27599
+ const id = String(index).padStart(4, "0");
27600
+ return {
27601
+ batch_id: id,
27602
+ request_file: path15.join(runDir, "jev", "requests", `${id}.json`),
27603
+ request_fingerprint: createHash8("sha256").update(canonicalJson(request)).digest("hex")
27604
+ };
27605
+ }) : plan.batches.map(objectRecord2);
27356
27606
  const batches = args.batch_id ? allBatches.filter((batch) => batch.batch_id === args.batch_id) : allBatches;
27357
27607
  if (args.batch_id && batches.length !== 1) throw new Error("O lote indicado n\xE3o pertence ao plano Jev.");
27358
- const responsePath = path14.join(runDir, "jev", "responses");
27608
+ const responsePath = path15.join(runDir, "jev", "responses");
27359
27609
  await ensureJevDirectory(responsePath);
27360
27610
  const responseDir = await fileInsideWorkspace(context.directory, responsePath);
27361
- if (path14.dirname(responseDir) !== path14.join(runDir, "jev")) throw new Error("A pasta de respostas tem de pertencer ao run Jev.");
27362
- const lockDir = path14.join(runDir, "jev", ".decide-run.lock");
27611
+ if (path15.dirname(responseDir) !== path15.join(runDir, "jev")) throw new Error("A pasta de respostas tem de pertencer ao run Jev.");
27612
+ const lockDir = path15.join(runDir, "jev", ".decide-run.lock");
27363
27613
  const interrupted = await acquireJevRunLock(lockDir);
27364
27614
  let saved = 0;
27365
27615
  let skipped = 0;
27366
27616
  let recovered = 0;
27367
27617
  const repeated = [];
27368
27618
  try {
27369
- const ownerFile = path14.join(lockDir, "owner.json");
27619
+ const ownerFile = path15.join(lockDir, "owner.json");
27370
27620
  await writeOwnerOnlyTextAtomic(ownerFile, JSON.stringify({ ...interrupted, pid: process.pid, hostname: os5.hostname(), started_at: (/* @__PURE__ */ new Date()).toISOString() }));
27371
- const attemptsPath = path14.join(runDir, "jev", "attempts");
27621
+ const attemptsPath = path15.join(runDir, "jev", "attempts");
27372
27622
  await ensureJevDirectory(attemptsPath);
27373
27623
  const attemptsDir = await fileInsideWorkspace(context.directory, attemptsPath);
27374
- if (path14.dirname(attemptsDir) !== path14.join(runDir, "jev")) throw new Error("A pasta de tentativas tem de pertencer ao run Jev.");
27624
+ if (path15.dirname(attemptsDir) !== path15.join(runDir, "jev")) throw new Error("A pasta de tentativas tem de pertencer ao run Jev.");
27375
27625
  for (const batch of batches) {
27376
27626
  context.abort.throwIfAborted();
27377
27627
  const batchId = batch.batch_id;
27378
- if (typeof batchId !== "string" || !/^batch-[0-9]{4}-[A-Za-z0-9._-]+$/.test(batchId) || typeof batch.request_file !== "string" || typeof batch.request_fingerprint !== "string") {
27628
+ const validBatchId = smallPlan ? /^\d{4,}$/ : /^batch-[0-9]{4}-[A-Za-z0-9._-]+$/;
27629
+ if (typeof batchId !== "string" || !validBatchId.test(batchId) || typeof batch.request_file !== "string" || typeof batch.request_fingerprint !== "string") {
27379
27630
  throw new Error("O plano Jev cont\xE9m um lote inv\xE1lido.");
27380
27631
  }
27381
- const acceptedFile = path14.join(runDir, "jev", "accepted", `${batchId}.json`);
27382
- const responseFile = path14.join(responseDir, `${batchId}.response.json`);
27632
+ const acceptedFile = path15.join(runDir, "jev", "accepted", `${batchId}.json`);
27633
+ const responseFile = path15.join(responseDir, smallPlan ? `${batchId}.json` : `${batchId}.response.json`);
27383
27634
  const requestFile = await fileInsideWorkspace(context.directory, batch.request_file);
27384
- if (path14.dirname(requestFile) !== path14.join(runDir, "jev", "requests")) throw new Error(`${batchId}: pedido fora do run.`);
27385
- const request = JSON.parse(await readFile14(requestFile, "utf8"));
27386
- const fingerprint = createHash7("sha256").update(canonicalJson(request)).digest("hex");
27635
+ if (path15.dirname(requestFile) !== path15.join(runDir, "jev", "requests")) throw new Error(`${batchId}: pedido fora do run.`);
27636
+ const rawRequest = await readFile15(requestFile, "utf8");
27637
+ if (Buffer.byteLength(rawRequest) > 512 * 1024) throw new Error("O ficheiro de pedido excede 512 KiB.");
27638
+ const request = objectRecord2(JSON.parse(rawRequest));
27639
+ const questions = objectRecord2(request.questions);
27640
+ if (request.state === void 0 || !Object.keys(questions).length) throw new Error("O pedido deve conter state e questions.");
27641
+ if (request.model !== void 0 && request.model !== plan.model) throw new Error("O modelo do pedido n\xE3o corresponde ao Jev configurado.");
27642
+ const fingerprint = createHash8("sha256").update(canonicalJson(request)).digest("hex");
27387
27643
  if (fingerprint !== batch.request_fingerprint) throw new Error(`${batchId}: fingerprint do pedido n\xE3o corresponde ao plano.`);
27388
27644
  if (await fileExists(acceptedFile)) {
27645
+ if (smallPlan) {
27646
+ const file2 = await fileInsideWorkspace(context.directory, acceptedFile);
27647
+ if (file2 !== acceptedFile) throw new Error(`${batchId}: resposta aceite fora do destino previsto.`);
27648
+ const body = await validateSavedDecision(file2, request, true);
27649
+ if (await fileExists(responseFile) && canonicalJson(await validateSavedDecision(await fileInsideWorkspace(context.directory, responseFile), request, true)) !== canonicalJson(body)) {
27650
+ throw new Error(`${batchId}: resposta diverge do lote aceite; preservar e investigar.`);
27651
+ }
27652
+ if (args.batch_id) return JSON.stringify({ ...body, response_file: file2 });
27653
+ }
27389
27654
  skipped++;
27390
27655
  continue;
27391
27656
  }
27392
27657
  if (await fileExists(responseFile)) {
27393
- const body = await validateSavedDecision(await fileInsideWorkspace(context.directory, responseFile), request);
27658
+ const body = await validateSavedDecision(await fileInsideWorkspace(context.directory, responseFile), request, smallPlan);
27394
27659
  if (args.batch_id) return JSON.stringify({ ...body, response_file: responseFile });
27395
27660
  skipped++;
27396
27661
  continue;
27397
27662
  }
27398
- const attemptsFile = path14.join(attemptsDir, `${batchId}.json`);
27663
+ const attemptsFile = path15.join(attemptsDir, `${batchId}.json`);
27399
27664
  let attempts = { request_fingerprint: fingerprint, attempts: 0, response_files: [] };
27400
- if (await fileExists(attemptsFile)) attempts = JSON.parse(await readFile14(attemptsFile, "utf8"));
27665
+ if (await fileExists(attemptsFile)) attempts = JSON.parse(await readFile15(attemptsFile, "utf8"));
27401
27666
  else if (interrupted.batch_id === batchId) {
27402
27667
  if (interrupted.request_fingerprint !== fingerprint) throw new Error(`${batchId}: fingerprint da chamada interrompida n\xE3o corresponde ao plano.`);
27403
27668
  attempts.attempts = 1;
@@ -27410,15 +27675,15 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27410
27675
  if (!await fileExists(attemptsFile) && attempts.attempts > 0) await persistAttempts();
27411
27676
  const stop = (error45, detail = {}) => JSON.stringify({ verified: false, saved, skipped, recovered, repeated, stopped_at: batchId, ...detail, error: error45 });
27412
27677
  const recoverResponse = async () => {
27413
- const legacyAllocations = interrupted.batch_id === batchId && interrupted.request_fingerprint === fingerprint ? (await readdir7(responseDir)).filter((name) => name.startsWith(".forge-decision-")).map((name) => path14.join(responseDir, name, "response.json")) : [];
27678
+ const legacyAllocations = interrupted.batch_id === batchId && interrupted.request_fingerprint === fingerprint ? (await readdir8(responseDir)).filter((name) => name.startsWith(".forge-decision-")).map((name) => path15.join(responseDir, name, "response.json")) : [];
27414
27679
  const candidates = [...attempts.response_files, ...legacyAllocations];
27415
27680
  for (const candidate of new Set(candidates)) {
27416
27681
  if (typeof candidate !== "string") throw new Error("Registo de recupera\xE7\xE3o inv\xE1lido.");
27417
27682
  if (!await fileExists(candidate)) continue;
27418
27683
  const file2 = await fileInsideWorkspace(context.directory, candidate);
27419
- if (path14.dirname(path14.dirname(file2)) !== responseDir) throw new Error("Resposta recuper\xE1vel fora da pasta do lote.");
27684
+ if (path15.dirname(path15.dirname(file2)) !== responseDir) throw new Error("Resposta recuper\xE1vel fora da pasta do lote.");
27420
27685
  try {
27421
- await validateSavedDecision(file2, request);
27686
+ await validateSavedDecision(file2, request, smallPlan);
27422
27687
  } catch {
27423
27688
  continue;
27424
27689
  }
@@ -27445,7 +27710,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27445
27710
  });
27446
27711
  let result;
27447
27712
  try {
27448
- result = JSON.parse(await decide.execute({ request_file: requestFile }, context));
27713
+ result = JSON.parse(await decide.execute({ state: request.state, questions }, context));
27449
27714
  } catch (error45) {
27450
27715
  if (error45 instanceof ForgeDecisionRejectedError) {
27451
27716
  attempts.attempts = previousAttempts;
@@ -27464,7 +27729,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27464
27729
  if (typeof result.response_file !== "string") return stop(String(result.persistence_error), { recovery_response: result, persistence_code: result.persistence_code });
27465
27730
  source = result.response_file;
27466
27731
  try {
27467
- await validateSavedDecision(source, request);
27732
+ await validateSavedDecision(source, request, smallPlan);
27468
27733
  } catch (error45) {
27469
27734
  return stop(error45 instanceof Error ? error45.message : "Resposta inv\xE1lida.", { recovery_file: source });
27470
27735
  }
@@ -27475,7 +27740,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27475
27740
  let identical = false;
27476
27741
  if (error45.code === "EEXIST") {
27477
27742
  try {
27478
- identical = await readFile14(source, "utf8") === await readFile14(responseFile, "utf8");
27743
+ identical = await readFile15(source, "utf8") === await readFile15(responseFile, "utf8");
27479
27744
  } catch {
27480
27745
  }
27481
27746
  }
@@ -27483,9 +27748,9 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27483
27748
  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 });
27484
27749
  }
27485
27750
  }
27486
- await unlink2(source).then(() => rmdir2(path14.dirname(source))).catch(() => void 0);
27751
+ await unlink2(source).then(() => rmdir2(path15.dirname(source))).catch(() => void 0);
27487
27752
  saved++;
27488
- if (args.batch_id) return JSON.stringify({ ...await validateSavedDecision(responseFile, request), response_file: responseFile, repeated });
27753
+ if (args.batch_id) return JSON.stringify({ ...await validateSavedDecision(responseFile, request, smallPlan), response_file: responseFile, repeated });
27489
27754
  }
27490
27755
  return JSON.stringify({
27491
27756
  verified: true,
@@ -27495,7 +27760,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27495
27760
  recovered,
27496
27761
  repeated,
27497
27762
  response_dir: responseDir,
27498
- next_step: "Executar jev-accept sobre as respostas guardadas ainda n\xE3o aceites; depois jev-validate e jev-merge."
27763
+ next_step: smallPlan ? "Executar python3 scripts/classify_jev.py collect <run_dir>." : "Executar jev-accept sobre as respostas guardadas ainda n\xE3o aceites; depois jev-validate e jev-merge."
27499
27764
  });
27500
27765
  } finally {
27501
27766
  await rm6(lockDir, { recursive: true });
@@ -27541,6 +27806,8 @@ function createForgeFeedbackTool(forgeBaseUrl, paths) {
27541
27806
  message: tool.schema.string().trim().min(1).max(WORKER_FEEDBACK_MAX_MESSAGE_LENGTH).describe("Texto completo e exato aprovado pela pessoa, at\xE9 24.000 caracteres; n\xE3o enviar conversa nem logs em bruto")
27542
27807
  },
27543
27808
  async execute(args, context) {
27809
+ await context.ask({ permission: "forge_feedback", patterns: [args.kind], always: [], metadata: {} });
27810
+ context.abort.throwIfAborted();
27544
27811
  const credentials = await readForgeCredentials(paths, forgeBaseUrl);
27545
27812
  const response = await fetch(`${forgeBaseUrl}/sync/feedback`, {
27546
27813
  method: "POST",
@@ -27569,17 +27836,18 @@ async function synchronizeAtStartup(forgeBaseUrl, observe, localConfig, input) {
27569
27836
  let appliedLocalSync;
27570
27837
  let pluginUpdate;
27571
27838
  let decisionBaseUrl = forgeBaseUrl;
27839
+ let manifest;
27572
27840
  const runtime = await observe();
27573
27841
  try {
27574
27842
  await retireDebugCapture(paths);
27575
27843
  credentials = await readForgeCredentials(paths, forgeBaseUrl);
27576
- const manifest = await fetchManifest(credentials, PLUGIN_VERSION);
27844
+ manifest = await fetchManifest(credentials, PLUGIN_VERSION);
27577
27845
  decisionBaseUrl = resolveDecisionBaseUrl(manifest.gatewayBaseUrl, forgeBaseUrl);
27578
27846
  forgeConfigVerified = true;
27579
27847
  const result = localConfig ? await syncLocalWorker(paths, credentials, manifest) : await applyWorkPackManifest(paths, credentials, manifest, {});
27580
27848
  if (localConfig) {
27581
27849
  appliedLocalSync = { manifest, partialWorkPackSync: result };
27582
- const config2 = objectRecord2(parseJsonc(await readFile14(paths.opencodeConfigPath, "utf8")));
27850
+ const config2 = objectRecord2(parseJsonc(await readFile15(paths.opencodeConfigPath, "utf8")));
27583
27851
  const targetVersion = configuredWorkPackSyncPluginVersion(config2);
27584
27852
  if (targetVersion) pluginUpdate = { targetVersion, restartRequired: targetVersion !== PLUGIN_VERSION };
27585
27853
  if (pluginUpdate?.restartRequired) {
@@ -27626,12 +27894,12 @@ async function synchronizeAtStartup(forgeBaseUrl, observe, localConfig, input) {
27626
27894
  decisionBaseUrl = await savedGatewayBaseUrl(paths, credentials, forgeBaseUrl) ?? decisionBaseUrl;
27627
27895
  }
27628
27896
  const after = await managedProjectionNames(paths).catch(() => before);
27629
- return { paths, before, after, forgeConfigVerified, decisionBaseUrl, ...appliedLocalSync };
27897
+ return { paths, before, after, forgeConfigVerified, decisionBaseUrl, failedManifest: manifest, ...appliedLocalSync };
27630
27898
  }
27631
27899
  }
27632
27900
  async function savedGatewayBaseUrl(paths, credentials, forgeBaseUrl) {
27633
27901
  try {
27634
- const config2 = objectRecord2(parseJsonc(await readFile14(paths.opencodeConfigPath, "utf8")));
27902
+ const config2 = objectRecord2(parseJsonc(await readFile15(paths.opencodeConfigPath, "utf8")));
27635
27903
  const options = objectRecord2(objectRecord2(objectRecord2(config2.provider).forge).options);
27636
27904
  if (options.apiKey !== credentials.forgeApiKey || typeof options.baseURL !== "string" || !options.baseURL.endsWith("/v1")) return void 0;
27637
27905
  const origin = options.baseURL.slice(0, -"/v1".length);
@@ -27656,7 +27924,7 @@ function resolveStartupPaths() {
27656
27924
  return resolvePaths(void 0, void 0, env);
27657
27925
  }
27658
27926
  async function readForgeCredentials(paths, forgeBaseUrl) {
27659
- const raw = await readFile14(paths.opencodeAuthPath, "utf8").catch((error45) => {
27927
+ const raw = await readFile15(paths.opencodeAuthPath, "utf8").catch((error45) => {
27660
27928
  if (error45.code === "ENOENT") return void 0;
27661
27929
  throw error45;
27662
27930
  });
@@ -27701,8 +27969,8 @@ function objectRecord2(value) {
27701
27969
  }
27702
27970
  async function writeStatus(paths, value) {
27703
27971
  await mkdir8(paths.forgeDir, { recursive: true });
27704
- const target = path14.join(paths.forgeDir, STATUS_FILENAME);
27705
- const temporary = path14.join(paths.forgeDir, `.${STATUS_FILENAME}.${process.pid}.tmp`);
27972
+ const target = path15.join(paths.forgeDir, STATUS_FILENAME);
27973
+ const temporary = path15.join(paths.forgeDir, `.${STATUS_FILENAME}.${process.pid}.tmp`);
27706
27974
  await writeFile9(temporary, `${JSON.stringify(value, null, 2)}
27707
27975
  `, { mode: 384 });
27708
27976
  await rename9(temporary, target);