minimal-forge-work-pack-sync 0.1.51 → 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.
Files changed (3) hide show
  1. package/dist/index.js +854 -440
  2. package/dist/repair.js +223 -69
  3. 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, 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.51";
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 randomUUID4 } 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 mkdir7, mkdtemp as mkdtemp2, readdir as readdir6, readFile as readFile13, realpath as realpath2, rename as rename8, rm as rm6, rmdir, stat as stat3, unlink, writeFile as writeFile8 } 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);
@@ -21591,9 +21591,9 @@ function assertSlug(slug) {
21591
21591
  // packages/cli/src/sync.ts
21592
21592
  import { createHash as createHash4 } from "node:crypto";
21593
21593
  import { spawnSync } from "node:child_process";
21594
- import { chmod as chmod4, cp, lstat as lstat5, mkdtemp, mkdir as mkdir5, readdir as readdir4, readFile as readFile8, rm as rm4, rename as rename6, writeFile as writeFile6 } from "node:fs/promises";
21594
+ import { chmod as chmod4, cp, lstat as lstat5, mkdtemp, mkdir as mkdir6, readdir as readdir5, readFile as readFile9, rm as rm4, rename as rename7, writeFile as writeFile7 } from "node:fs/promises";
21595
21595
  import os4 from "node:os";
21596
- import path9 from "node:path";
21596
+ import path10 from "node:path";
21597
21597
 
21598
21598
  // node_modules/tar/dist/esm/index.min.js
21599
21599
  import Qr from "events";
@@ -24573,9 +24573,98 @@ function renderTuiConfig(manifest) {
24573
24573
  }
24574
24574
 
24575
24575
  // packages/cli/src/coreSyncTransaction.ts
24576
- import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
24577
- import { chmod as chmod3, lstat as lstat4, mkdir as mkdir4, readFile as readFile5, rename as rename5, rm as rm3, writeFile as writeFile5 } from "node:fs/promises";
24576
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
24577
+ import { chmod as chmod3, lstat as lstat4, mkdir as mkdir5, readFile as readFile6, rename as rename6, rm as rm3, writeFile as writeFile6 } from "node:fs/promises";
24578
+ import path8 from "node:path";
24579
+
24580
+ // packages/cli/src/coreSyncLock.ts
24581
+ import { randomUUID as randomUUID3 } from "node:crypto";
24582
+ import { mkdir as mkdir4, readdir as readdir4, readFile as readFile5, rename as rename5, rmdir, unlink, writeFile as writeFile5 } from "node:fs/promises";
24583
+ import { hostname as hostname3 } from "node:os";
24578
24584
  import path7 from "node:path";
24585
+ function hasCode(error45, ...codes) {
24586
+ return error45 instanceof Error && codes.includes(error45.code ?? "");
24587
+ }
24588
+ function busy() {
24589
+ return new Error("Outra sincroniza\xE7\xE3o Forge pode estar em curso. Aguarde que termine e volte a tentar.");
24590
+ }
24591
+ function unknownOwner() {
24592
+ return new Error("O propriet\xE1rio do bloqueio de sincroniza\xE7\xE3o Forge n\xE3o foi confirmado nesta m\xE1quina. Pe\xE7a ao operador para verificar o processo e a m\xE1quina de origem.");
24593
+ }
24594
+ async function removeEmpty(directory) {
24595
+ try {
24596
+ await rmdir(directory);
24597
+ } catch (error45) {
24598
+ if (!hasCode(error45, "ENOENT", "EEXIST", "ENOTEMPTY")) throw error45;
24599
+ }
24600
+ }
24601
+ async function reclaim(lockPath, renameError) {
24602
+ let entries;
24603
+ try {
24604
+ entries = await readdir4(lockPath);
24605
+ } catch (error45) {
24606
+ if (!hasCode(error45, "ENOENT")) throw error45;
24607
+ if (hasCode(renameError, "EACCES", "EPERM")) throw renameError;
24608
+ return;
24609
+ }
24610
+ if (entries.length) {
24611
+ const marker = entries[0];
24612
+ const match = /^owner-([1-9]\d*)-[0-9a-f-]{36}$/.exec(marker);
24613
+ if (entries.length !== 1 || !match) throw unknownOwner();
24614
+ const markerPath = path7.join(lockPath, marker);
24615
+ let host;
24616
+ try {
24617
+ host = await readFile5(markerPath, "utf8");
24618
+ } catch (error45) {
24619
+ if (hasCode(error45, "ENOENT")) return;
24620
+ throw error45;
24621
+ }
24622
+ if (host !== hostname3()) throw unknownOwner();
24623
+ try {
24624
+ process.kill(Number(match[1]), 0);
24625
+ } catch (error45) {
24626
+ if (!hasCode(error45, "ESRCH")) throw error45;
24627
+ await unlink(markerPath).catch((cause) => {
24628
+ if (!hasCode(cause, "ENOENT")) throw cause;
24629
+ });
24630
+ await removeEmpty(lockPath);
24631
+ return;
24632
+ }
24633
+ throw busy();
24634
+ }
24635
+ await removeEmpty(lockPath);
24636
+ }
24637
+ async function withCoreSyncLock(journalPath, operation) {
24638
+ const lockPath = journalPath + ".lock";
24639
+ const id = randomUUID3();
24640
+ const candidate = lockPath + "-" + id;
24641
+ const marker = `owner-${process.pid}-${id}`;
24642
+ await mkdir4(path7.dirname(lockPath), { recursive: true });
24643
+ await mkdir4(candidate, { mode: 448 });
24644
+ let directory = candidate;
24645
+ try {
24646
+ await writeFile5(path7.join(candidate, marker), hostname3(), { mode: 384, flag: "wx" });
24647
+ for (let attempt = 0; attempt < 3; attempt++) {
24648
+ try {
24649
+ await rename5(candidate, lockPath);
24650
+ } catch (error45) {
24651
+ if (!hasCode(error45, "EEXIST", "ENOTEMPTY", "EPERM", "EACCES")) throw error45;
24652
+ await reclaim(lockPath, error45);
24653
+ continue;
24654
+ }
24655
+ directory = lockPath;
24656
+ return await operation();
24657
+ }
24658
+ throw busy();
24659
+ } finally {
24660
+ await unlink(path7.join(directory, marker)).catch((error45) => {
24661
+ if (!hasCode(error45, "ENOENT")) throw error45;
24662
+ });
24663
+ await removeEmpty(directory);
24664
+ }
24665
+ }
24666
+
24667
+ // packages/cli/src/coreSyncTransaction.ts
24579
24668
  var CORE_RUNTIME_MANIFEST_VERSION = 1;
24580
24669
  var CoreSyncUncertainError = class extends Error {
24581
24670
  constructor(message, paths) {
@@ -24584,11 +24673,11 @@ var CoreSyncUncertainError = class extends Error {
24584
24673
  }
24585
24674
  paths;
24586
24675
  };
24587
- var defaultFs = { chmod: chmod3, lstat: lstat4, mkdir: mkdir4, readFile: readFile5, rename: rename5, rm: rm3, writeFile: writeFile5 };
24676
+ var defaultFs = { chmod: chmod3, lstat: lstat4, mkdir: mkdir5, readFile: readFile6, rename: rename6, rm: rm3, writeFile: writeFile6 };
24588
24677
  function coreRuntimeManifestDigest(files) {
24589
24678
  const canonical = [...files].sort((a, b2) => a.id.localeCompare(b2.id)).map((file2) => ({
24590
24679
  id: file2.id,
24591
- path: path7.resolve(file2.path),
24680
+ path: path8.resolve(file2.path),
24592
24681
  exists: file2.bytes !== null,
24593
24682
  digest: file2.bytes === null ? void 0 : sha256(file2.bytes),
24594
24683
  mode: file2.mode,
@@ -24605,8 +24694,8 @@ function validateCoreRuntimeManifest(manifest) {
24605
24694
  const targets = /* @__PURE__ */ new Set();
24606
24695
  for (const file2 of manifest.files) {
24607
24696
  if (!file2.id || ids.has(file2.id)) throw new Error(`Duplicate core runtime file id: ${file2.id}`);
24608
- const target = path7.resolve(file2.path);
24609
- if (!path7.isAbsolute(file2.path) || targets.has(target)) throw new Error(`Invalid or duplicate core runtime target: ${file2.path}`);
24697
+ const target = path8.resolve(file2.path);
24698
+ if (!path8.isAbsolute(file2.path) || targets.has(target)) throw new Error(`Invalid or duplicate core runtime target: ${file2.path}`);
24610
24699
  if (file2.mode !== void 0 && (!Number.isInteger(file2.mode) || file2.mode < 0 || file2.mode > 4095)) throw new Error(`Invalid mode for ${file2.id}`);
24611
24700
  if (file2.ownerOnly !== void 0 && typeof file2.ownerOnly !== "boolean") throw new Error(`Invalid owner-only flag for ${file2.id}`);
24612
24701
  ids.add(file2.id);
@@ -24614,19 +24703,28 @@ function validateCoreRuntimeManifest(manifest) {
24614
24703
  }
24615
24704
  if (coreRuntimeManifestDigest(manifest.files) !== manifest.digest) throw new Error("Core runtime manifest digest mismatch");
24616
24705
  }
24617
- async function applyCoreSyncTransaction(options) {
24618
- validateCoreRuntimeManifest(options.manifest);
24706
+ async function withRecoveredCoreSync(journalPath, operation, options = {}) {
24707
+ const fs2 = options.fs ?? defaultFs;
24708
+ return withCoreSyncLock(journalPath, async () => {
24709
+ const recovery = await recoverUnderLock(journalPath, fs2);
24710
+ await options.afterRecovery?.();
24711
+ if (recovery.status === "uncertain") throw new CoreSyncUncertainError(recovery.message, recovery.uncertainPaths);
24712
+ return operation((manifest, hooks) => {
24713
+ validateCoreRuntimeManifest(manifest);
24714
+ return commitCoreFiles({ manifest, journalPath, fs: fs2, hooks });
24715
+ });
24716
+ });
24717
+ }
24718
+ async function commitCoreFiles(options) {
24619
24719
  const fs2 = options.fs ?? defaultFs;
24620
24720
  const hooks = options.hooks;
24621
- const existingRecovery = await recoverCoreSyncTransaction({ journalPath: options.journalPath, fs: fs2 });
24622
- if (existingRecovery.status === "uncertain") throw new CoreSyncUncertainError(existingRecovery.message, existingRecovery.uncertainPaths);
24623
- const transactionId = randomUUID3();
24721
+ const transactionId = randomUUID4();
24624
24722
  const files = [];
24625
24723
  try {
24626
24724
  for (const desired of options.manifest.files) {
24627
- const target = path7.resolve(desired.path);
24725
+ const target = path8.resolve(desired.path);
24628
24726
  if (desired.ownerOnly && desired.bytes !== null && fs2 === defaultFs) await prepareOwnerOnlyFileDestination(target);
24629
- else await fs2.mkdir(path7.dirname(target), { recursive: true });
24727
+ else await fs2.mkdir(path8.dirname(target), { recursive: true });
24630
24728
  const original = await capture(target, fs2);
24631
24729
  const suffix = `.forge-core-${transactionId}`;
24632
24730
  const backup = original.exists ? `${target}${suffix}.backup` : void 0;
@@ -24655,58 +24753,93 @@ async function applyCoreSyncTransaction(options) {
24655
24753
  await hooks?.boundary?.("after-journal");
24656
24754
  for (const file2 of files) {
24657
24755
  await hooks?.boundary?.(`before-commit:${file2.id}`);
24658
- await fs2.rm(file2.target, { force: true });
24659
24756
  if (file2.stage) await fs2.rename(file2.stage, file2.target);
24757
+ else await fs2.rm(file2.target, { force: true });
24660
24758
  if (file2.stage && file2.ownerOnly && fs2 === defaultFs) await protectOwnerOnlyPath(file2.target, "file");
24661
24759
  await hooks?.boundary?.(`after-commit:${file2.id}`);
24662
24760
  }
24663
24761
  await hooks?.boundary?.("before-cleanup");
24664
- await cleanup(journal, options.journalPath, fs2);
24665
- await hooks?.boundary?.("after-cleanup");
24666
- return { status: "committed", manifestId: options.manifest.id, digest: options.manifest.digest };
24762
+ await fs2.rename(options.journalPath, cleanupPath(options.journalPath));
24667
24763
  } catch (error45) {
24668
24764
  if (!await exists(options.journalPath, fs2)) {
24669
24765
  await Promise.all(files.flatMap((file2) => [file2.stage, file2.backup].filter((item) => Boolean(item))).map((item) => fs2.rm(item, { force: true }).catch(() => void 0)));
24670
24766
  throw error45;
24671
24767
  }
24672
- const recovery = await recoverCoreSyncTransaction({ journalPath: options.journalPath, fs: fs2 });
24768
+ const recovery = await recoverUnderLock(options.journalPath, fs2);
24673
24769
  if (recovery.status === "uncertain") throw new CoreSyncUncertainError(recovery.message, recovery.uncertainPaths);
24674
24770
  throw error45;
24675
24771
  }
24676
- }
24677
- async function recoverCoreSyncTransaction(options) {
24678
- const fs2 = options.fs ?? defaultFs;
24679
- let journal;
24772
+ const committed = { status: "committed", manifestId: options.manifest.id, digest: options.manifest.digest };
24680
24773
  try {
24681
- journal = JSON.parse(await fs2.readFile(options.journalPath, "utf8"));
24682
- } catch (error45) {
24683
- if (isNotFound(error45)) return { status: "nothing-to-recover" };
24684
- return { status: "uncertain", uncertainPaths: [options.journalPath], message: "Core sync journal is unreadable; exact recovery is uncertain." };
24774
+ await cleanup(files, cleanupPath(options.journalPath), fs2);
24775
+ } catch {
24776
+ return committed;
24685
24777
  }
24686
- if (!validJournal(journal)) return { status: "uncertain", uncertainPaths: [options.journalPath], message: "Core sync journal is invalid; exact recovery is uncertain." };
24778
+ await hooks?.boundary?.("after-cleanup");
24779
+ return committed;
24780
+ }
24781
+ async function recoverUnderLock(activePath, fs2) {
24782
+ const retiredPath = cleanupPath(activePath);
24783
+ for (const journalPath of [retiredPath, activePath]) {
24784
+ let journal;
24785
+ try {
24786
+ journal = JSON.parse(await fs2.readFile(journalPath, "utf8"));
24787
+ if (!validJournal(journal)) throw new Error("Invalid journal");
24788
+ } catch (error45) {
24789
+ if (isNotFound(error45)) continue;
24790
+ return { status: "uncertain", uncertainPaths: [journalPath], message: "Core sync journal is unreadable or invalid; exact recovery is uncertain." };
24791
+ }
24792
+ if (journalPath === retiredPath) {
24793
+ await cleanup(journal.files, retiredPath, fs2);
24794
+ } else {
24795
+ return restoreJournal(journal, journalPath, fs2);
24796
+ }
24797
+ }
24798
+ return { status: "nothing-to-recover" };
24799
+ }
24800
+ async function restoreJournal(journal, journalPath, fs2) {
24687
24801
  const uncertain = [];
24802
+ const backups = /* @__PURE__ */ new Map();
24688
24803
  for (const file2 of journal.files) {
24804
+ if (!file2.original.exists) continue;
24689
24805
  try {
24690
- if (!file2.original.exists) await fs2.rm(file2.target, { force: true });
24691
- else {
24692
- if (!file2.backup || !await exists(file2.backup, fs2)) throw new Error("backup missing");
24693
- const bytes = await fs2.readFile(file2.backup);
24694
- if (sha256(bytes) !== file2.original.digest) throw new Error("backup digest mismatch");
24695
- await writeExact(`${file2.target}.forge-restore-${journal.transactionId}`, bytes, file2.original.mode, fs2, file2.ownerOnly === true);
24806
+ if (!file2.backup) throw new Error("backup missing");
24807
+ const bytes = await fs2.readFile(file2.backup);
24808
+ if (sha256(bytes) !== file2.original.digest) throw new Error("backup digest mismatch");
24809
+ backups.set(file2, bytes);
24810
+ } catch {
24811
+ uncertain.push(file2.target);
24812
+ }
24813
+ }
24814
+ if (uncertain.length) return uncertainRestore(journal, uncertain);
24815
+ for (const file2 of journal.files) {
24816
+ try {
24817
+ if (!file2.original.exists) {
24696
24818
  await fs2.rm(file2.target, { force: true });
24697
- await fs2.rename(`${file2.target}.forge-restore-${journal.transactionId}`, file2.target);
24698
- if (file2.ownerOnly && fs2 === defaultFs) await protectOwnerOnlyPath(file2.target, "file");
24699
- const restored = await capture(file2.target, fs2);
24700
- if (!restored.bytes || sha256(restored.bytes) !== file2.original.digest || restored.mode !== file2.original.mode) throw new Error("restore verification failed");
24819
+ continue;
24820
+ }
24821
+ const restorePath = `${file2.target}.forge-restore-${journal.transactionId}`;
24822
+ await fs2.rm(restorePath, { force: true });
24823
+ await writeExact(restorePath, backups.get(file2), file2.original.mode, fs2, file2.ownerOnly);
24824
+ await fs2.rename(restorePath, file2.target);
24825
+ if (file2.ownerOnly && fs2 === defaultFs) await protectOwnerOnlyPath(file2.target, "file");
24826
+ const restored = await capture(file2.target, fs2);
24827
+ if (!restored.bytes || sha256(restored.bytes) !== file2.original.digest || restored.mode !== effectiveMode(file2.original.mode, file2.ownerOnly)) {
24828
+ throw new Error("restore verification failed");
24701
24829
  }
24702
24830
  } catch {
24703
24831
  uncertain.push(file2.target);
24704
24832
  }
24705
24833
  }
24706
- if (uncertain.length > 0) return { status: "uncertain", manifestId: journal.manifest.id, uncertainPaths: uncertain, message: "Core sync could not prove an exact restore for every path." };
24707
- await cleanup(journal, options.journalPath, fs2);
24834
+ if (uncertain.length) return uncertainRestore(journal, uncertain);
24835
+ const retiredPath = cleanupPath(journalPath);
24836
+ await fs2.rename(journalPath, retiredPath);
24837
+ await cleanup(journal.files, retiredPath, fs2);
24708
24838
  return { status: "restored", manifestId: journal.manifest.id };
24709
24839
  }
24840
+ function uncertainRestore(journal, paths) {
24841
+ return { status: "uncertain", manifestId: journal.manifest.id, uncertainPaths: paths, message: "Core sync could not prove an exact restore for every path." };
24842
+ }
24710
24843
  async function capture(target, fs2) {
24711
24844
  try {
24712
24845
  const info = await fs2.lstat(target);
@@ -24717,13 +24850,17 @@ async function capture(target, fs2) {
24717
24850
  throw error45;
24718
24851
  }
24719
24852
  }
24853
+ function effectiveMode(mode, ownerOnly = false) {
24854
+ return ownerOnly && process.platform !== "win32" ? 384 : mode;
24855
+ }
24720
24856
  async function writeExact(target, bytes, mode, fs2, ownerOnly = false) {
24721
- await fs2.writeFile(target, bytes, { flag: "wx", mode });
24722
- await fs2.chmod(target, mode);
24857
+ const permissions = effectiveMode(mode, ownerOnly);
24858
+ await fs2.writeFile(target, bytes, { flag: "wx", mode: permissions });
24859
+ await fs2.chmod(target, permissions);
24723
24860
  if (ownerOnly && fs2 === defaultFs) await protectOwnerOnlyPath(target, "file");
24724
24861
  }
24725
24862
  async function writeJournal(target, journal, fs2) {
24726
- await fs2.mkdir(path7.dirname(target), { recursive: true });
24863
+ await fs2.mkdir(path8.dirname(target), { recursive: true });
24727
24864
  const temporary = `${target}.next`;
24728
24865
  await fs2.rm(temporary, { force: true });
24729
24866
  await fs2.writeFile(temporary, `${JSON.stringify(journal, null, 2)}
@@ -24731,8 +24868,14 @@ async function writeJournal(target, journal, fs2) {
24731
24868
  await fs2.chmod(temporary, 384);
24732
24869
  await fs2.rename(temporary, target);
24733
24870
  }
24734
- async function cleanup(journal, journalPath, fs2) {
24735
- await Promise.all(journal.files.flatMap((file2) => [file2.stage, file2.backup].filter((item) => Boolean(item))).map((item) => fs2.rm(item, { force: true })));
24871
+ function cleanupPath(journalPath) {
24872
+ return `${journalPath}.cleanup`;
24873
+ }
24874
+ async function cleanup(files, journalPath, fs2) {
24875
+ for (const file2 of files) {
24876
+ if (file2.stage) await fs2.rm(file2.stage, { force: true });
24877
+ if (file2.backup) await fs2.rm(file2.backup, { force: true });
24878
+ }
24736
24879
  await fs2.rm(journalPath, { force: true });
24737
24880
  }
24738
24881
  async function exists(target, fs2) {
@@ -24751,7 +24894,12 @@ function sha256(value) {
24751
24894
  return createHash3("sha256").update(value).digest("hex");
24752
24895
  }
24753
24896
  function validJournal(value) {
24754
- return value?.schemaVersion === 1 && typeof value.transactionId === "string" && value.manifest?.version === 1 && typeof value.manifest.id === "string" && Array.isArray(value.files) && value.files.every((file2) => typeof file2.id === "string" && path7.isAbsolute(file2.target) && typeof file2.original?.exists === "boolean" && typeof file2.desired?.exists === "boolean" && (file2.ownerOnly === void 0 || typeof file2.ownerOnly === "boolean"));
24897
+ if (value?.schemaVersion !== 1 || typeof value.transactionId !== "string" || !/^[a-zA-Z0-9_-]+$/.test(value.transactionId) || value.manifest?.version !== 1 || typeof value.manifest.id !== "string" || !Array.isArray(value.files)) return false;
24898
+ return value.files.every((file2) => {
24899
+ if (typeof file2?.id !== "string" || typeof file2.target !== "string" || !path8.isAbsolute(file2.target)) return false;
24900
+ const prefix = `${file2.target}.forge-core-${value.transactionId}`;
24901
+ return (file2.stage === void 0 || file2.stage === `${prefix}.stage`) && (file2.backup === void 0 || file2.backup === `${prefix}.backup`) && typeof file2.original?.exists === "boolean" && typeof file2.desired?.exists === "boolean" && (file2.ownerOnly === void 0 || typeof file2.ownerOnly === "boolean");
24902
+ });
24755
24903
  }
24756
24904
 
24757
24905
  // packages/cli/src/jsonc.ts
@@ -24830,7 +24978,7 @@ function stripTrailingCommas(input) {
24830
24978
  }
24831
24979
 
24832
24980
  // packages/cli/src/remoteConfig.ts
24833
- import { readFile as readFile6 } from "node:fs/promises";
24981
+ import { readFile as readFile7 } from "node:fs/promises";
24834
24982
  var WELLKNOWN_ENV_KEY = "FORGE_API_KEY";
24835
24983
  async function removeWellKnownAuth(paths, credentials, previous) {
24836
24984
  const content = await prepareWellKnownAuthRemoval(paths, credentials, previous);
@@ -24888,7 +25036,7 @@ function normalizeBaseUrl(value) {
24888
25036
  async function readAuthJson(paths) {
24889
25037
  let raw;
24890
25038
  try {
24891
- raw = await readFile6(paths.opencodeAuthPath, "utf8");
25039
+ raw = await readFile7(paths.opencodeAuthPath, "utf8");
24892
25040
  } catch (error45) {
24893
25041
  if (error45.code === "ENOENT") return {};
24894
25042
  throw error45;
@@ -24902,21 +25050,21 @@ function isRecord3(value) {
24902
25050
  }
24903
25051
 
24904
25052
  // packages/cli/src/localConfigRecovery.ts
24905
- import { readFile as readFile7 } from "node:fs/promises";
24906
- import path8 from "node:path";
25053
+ import { readFile as readFile8 } from "node:fs/promises";
25054
+ import path9 from "node:path";
24907
25055
  var LocalConfigRecoveryError = class extends Error {
24908
25056
  };
24909
25057
  var LAST_GOOD_FILENAME = "last-good-opencode.json";
24910
25058
  function lastGoodLocalConfigFile(paths, credentials, content) {
24911
25059
  assertForgeConfig(content, credentials);
24912
- return { id: "last-good-config", path: path8.join(paths.forgeDir, LAST_GOOD_FILENAME), bytes: Buffer.from(content), mode: 384, ownerOnly: true };
25060
+ return { id: "last-good-config", path: path9.join(paths.forgeDir, LAST_GOOD_FILENAME), bytes: Buffer.from(content), mode: 384, ownerOnly: true };
24913
25061
  }
24914
25062
  async function retiredLastGoodLocalConfigFile(paths) {
24915
- const filePath = path8.join(paths.forgeDir, LAST_GOOD_FILENAME);
25063
+ const filePath = path9.join(paths.forgeDir, LAST_GOOD_FILENAME);
24916
25064
  return await readOptional(filePath) === void 0 ? void 0 : { id: "last-good-config", path: filePath, bytes: null };
24917
25065
  }
24918
25066
  async function inspectLocalConfigRecovery(paths, credentials) {
24919
- const snapshot = await readOptional(path8.join(paths.forgeDir, LAST_GOOD_FILENAME));
25067
+ const snapshot = await readOptional(path9.join(paths.forgeDir, LAST_GOOD_FILENAME));
24920
25068
  const current = await readOptional(paths.opencodeConfigPath);
24921
25069
  return {
24922
25070
  snapshot: snapshot === void 0 ? "missing" : isForgeConfig(snapshot, credentials) ? "available" : "invalid",
@@ -24959,7 +25107,7 @@ function forgePluginEntries(config2) {
24959
25107
  }
24960
25108
  async function readOptional(filePath) {
24961
25109
  try {
24962
- return await readFile7(filePath, "utf8");
25110
+ return await readFile8(filePath, "utf8");
24963
25111
  } catch (error45) {
24964
25112
  if (error45.code === "ENOENT") return void 0;
24965
25113
  throw error45;
@@ -25235,24 +25383,24 @@ function validCoreManifest(value) {
25235
25383
  return modelIds.every((id) => typeof id === "string" && id.length > 0) && modelIds.includes(config2.model) && modelIds.includes(config2.small_model);
25236
25384
  }
25237
25385
  async function applyManifest(paths, credentials, manifest, options = {}) {
25238
- const journalPath = path9.join(paths.forgeDir, "core-sync-journal.json");
25239
- const recovery = await recoverCoreSyncTransaction({ journalPath });
25240
- await retireDebugCapture(paths);
25241
- if (recovery.status === "uncertain") {
25242
- throw new CoreSyncUncertainError(recovery.message, recovery.uncertainPaths);
25243
- }
25244
- await mkdir5(paths.opencodeDir, { recursive: true });
25386
+ const journalPath = path10.join(paths.forgeDir, "core-sync-journal.json");
25245
25387
  return reconcileSyncSnapshot({
25246
- applyCore: () => applyCoreManifest(paths, credentials, manifest, options),
25388
+ applyCore: () => withRecoveredCoreSync(
25389
+ journalPath,
25390
+ (apply) => applyCoreManifest(paths, credentials, manifest, options, apply),
25391
+ { afterRecovery: () => retireDebugCapture(paths) }
25392
+ ),
25247
25393
  applyWorkPacks: () => applyWorkPackManifest(paths, credentials, manifest, options)
25248
25394
  });
25249
25395
  }
25250
- async function applyCoreManifest(paths, credentials, manifest, options) {
25251
- const attachmentPluginPath = path9.join(paths.pluginDir, FORGE_PLUGIN_FILENAME);
25252
- const evidencePluginPath = path9.join(paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
25253
- const debugTracePluginPath = path9.join(paths.pluginDir, FORGE_DEBUG_TRACE_PLUGIN_FILENAME);
25254
- const legacyAttachmentPluginPath = path9.join(paths.opencodeDir, "plugin", FORGE_PLUGIN_FILENAME);
25255
- const debugTraceConfigPath = path9.join(paths.forgeDir, FORGE_DEBUG_TRACE_CONFIG_FILENAME);
25396
+ async function applyCoreManifest(paths, credentials, manifest, options, apply) {
25397
+ await options.beforeCore?.();
25398
+ await mkdir6(paths.opencodeDir, { recursive: true });
25399
+ const attachmentPluginPath = path10.join(paths.pluginDir, FORGE_PLUGIN_FILENAME);
25400
+ const evidencePluginPath = path10.join(paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
25401
+ const debugTracePluginPath = path10.join(paths.pluginDir, FORGE_DEBUG_TRACE_PLUGIN_FILENAME);
25402
+ const legacyAttachmentPluginPath = path10.join(paths.opencodeDir, "plugin", FORGE_PLUGIN_FILENAME);
25403
+ const debugTraceConfigPath = path10.join(paths.forgeDir, FORGE_DEBUG_TRACE_CONFIG_FILENAME);
25256
25404
  const rules = attachmentBridgeRules(manifest.config.models);
25257
25405
  let bridgeEnabled = Boolean(manifest.config.documentReaderModel) && Object.keys(rules).length > 0;
25258
25406
  const existingConfig = await readJsoncObject(paths.opencodeConfigPath);
@@ -25324,28 +25472,25 @@ async function applyCoreManifest(paths, credentials, manifest, options) {
25324
25472
  if (retired) files.push(retired);
25325
25473
  }
25326
25474
  const digest2 = coreRuntimeManifestDigest(files);
25327
- await applyCoreSyncTransaction({
25328
- manifest: {
25329
- version: 1,
25330
- id: `derived:${digest2.slice(0, 32)}`,
25331
- digest: digest2,
25332
- files
25333
- },
25334
- journalPath: path9.join(paths.forgeDir, "core-sync-journal.json"),
25335
- hooks: options.coreTransactionHooks
25336
- });
25475
+ await apply({
25476
+ version: 1,
25477
+ id: `derived:${digest2.slice(0, 32)}`,
25478
+ digest: digest2,
25479
+ files
25480
+ }, options.coreTransactionHooks);
25337
25481
  await removeLegacyDebugTraceRuntime(paths);
25482
+ await options.afterCore?.();
25338
25483
  return { configPath: paths.opencodeConfigPath, tuiPath: paths.tuiConfigPath };
25339
25484
  }
25340
25485
  async function applyWorkPackManifest(paths, credentials, manifest, options) {
25341
- await mkdir5(paths.skillsDir, { recursive: true });
25342
- await mkdir5(paths.commandsDir, { recursive: true });
25486
+ await mkdir6(paths.skillsDir, { recursive: true });
25487
+ await mkdir6(paths.commandsDir, { recursive: true });
25343
25488
  const recovery = await recoverInterruptedWorkPackInstalls(paths, options.cleanupWorkPackBackup, options.workPackProjectionBoundary);
25344
25489
  const managed = await Promise.all((await managedWorkPackSlugs(paths.skillsDir)).map(async (slug) => ({
25345
25490
  slug,
25346
- version: (await readFile8(path9.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim(),
25347
- agents: await readAgentRecord(path9.join(paths.skillsDir, slug)),
25348
- commands: await readCommandRecord(path9.join(paths.skillsDir, slug))
25491
+ version: (await readFile9(path10.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim(),
25492
+ agents: await readAgentRecord(path10.join(paths.skillsDir, slug)),
25493
+ commands: await readCommandRecord(path10.join(paths.skillsDir, slug))
25349
25494
  })));
25350
25495
  const desired = manifest.skills.map((skill) => ({
25351
25496
  slug: skill.slug,
@@ -25353,11 +25498,12 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
25353
25498
  enabled: skill.enabled
25354
25499
  }));
25355
25500
  const skillBySlug = new Map(manifest.skills.map((skill) => [skill.slug, skill]));
25501
+ const authoritative = manifest.workPacksComplete === true;
25356
25502
  const approvedModelIds = manifest.config.models.map((model) => typeof model === "string" ? model : model.id);
25357
25503
  const workPacks = await reconcileWorkPacks({
25358
25504
  desired,
25359
25505
  managed,
25360
- desiredIsComplete: manifest.workPacksComplete === true,
25506
+ desiredIsComplete: authoritative,
25361
25507
  operate: async (operation) => enrichIntegrityFailure(paths, operation, await operateWorkPack(
25362
25508
  paths,
25363
25509
  credentials,
@@ -25366,10 +25512,11 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
25366
25512
  recovery.cleanupPendingSlugs,
25367
25513
  recovery.failures,
25368
25514
  operation,
25515
+ authoritative,
25369
25516
  options
25370
25517
  )),
25371
25518
  recoveryFailures: recovery.failures,
25372
- writeAtomicReceipt: (receipt) => writeJsonAtomic2(path9.join(paths.forgeDir, "work-pack-sync-receipt.json"), receipt)
25519
+ writeAtomicReceipt: (receipt) => writeJsonAtomic2(path10.join(paths.forgeDir, "work-pack-sync-receipt.json"), receipt)
25373
25520
  });
25374
25521
  const installed = workPacks.outcomes.filter((outcome) => outcome.status === "installed").map((outcome) => `${outcome.slug}@${outcome.version}`);
25375
25522
  const removed = workPacks.outcomes.filter((outcome) => outcome.status === "removed").map((outcome) => outcome.slug);
@@ -25380,13 +25527,17 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
25380
25527
  async function collectWorkPackObservations(paths, reconciliation) {
25381
25528
  const installedVersions = /* @__PURE__ */ new Map();
25382
25529
  for (const slug of await managedWorkPackSlugs(paths.skillsDir)) {
25383
- const version2 = (await readFile8(path9.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim();
25530
+ const version2 = (await readFile9(path10.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim();
25384
25531
  if (version2) installedVersions.set(slug, version2);
25385
25532
  }
25386
25533
  const observations = new Map(
25387
25534
  [...installedVersions].map(([slug, version2]) => [slug, { slug, state: "installed", version: version2 }])
25388
25535
  );
25389
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
+ }
25390
25541
  if (outcome.status !== "failed" && outcome.status !== "recovery-uncertain") continue;
25391
25542
  observations.set(outcome.slug, {
25392
25543
  slug: outcome.slug,
@@ -25410,8 +25561,8 @@ async function enrichIntegrityFailure(paths, operation, result) {
25410
25561
  return result;
25411
25562
  }
25412
25563
  }
25413
- async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds, cleanupPendingSlugs, recoveryFailures, operation, options) {
25414
- const target = path9.join(paths.skillsDir, operation.pack.slug);
25564
+ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds, cleanupPendingSlugs, recoveryFailures, operation, authoritative, options) {
25565
+ const target = path10.join(paths.skillsDir, operation.pack.slug);
25415
25566
  const recoveryFailure = recoveryFailures.get(operation.pack.slug);
25416
25567
  if (recoveryFailure) return { status: "failed", restoration: "exact", code: recoveryFailure };
25417
25568
  let ownership;
@@ -25429,14 +25580,14 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
25429
25580
  agentsDir: paths.agentsDir,
25430
25581
  commandsDir: paths.commandsDir
25431
25582
  });
25432
- if (localState !== "match") {
25583
+ if (localState !== "match" && !authoritative) {
25433
25584
  return {
25434
25585
  status: "failed",
25435
25586
  restoration: "exact",
25436
25587
  code: localState === "missing" ? "local-baseline-missing" : "local-edits-preserved"
25437
25588
  };
25438
25589
  }
25439
- const removedManagedPaths = await removeManagedWorkPackTransaction(paths, target, options);
25590
+ const removedManagedPaths = await removeManagedWorkPackTransaction(paths, target, options, localState !== "match");
25440
25591
  return { status: "removed", removedManagedPaths };
25441
25592
  } catch (error45) {
25442
25593
  if (error45 instanceof WorkPackRecoveryUncertainError) {
@@ -25449,42 +25600,49 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
25449
25600
  if (!skill) return { status: "recovery-uncertain", code: "missing-desired-pack" };
25450
25601
  let previousManagedPaths;
25451
25602
  let archive;
25603
+ let retainLocalCopy = false;
25604
+ let legacyReference;
25452
25605
  try {
25453
- const currentVersion = await readFile8(path9.join(target, ".forge-version"), "utf8").catch(() => "");
25606
+ const currentVersion = await readFile9(path10.join(target, ".forge-version"), "utf8").catch(() => "");
25454
25607
  const sameVersion = currentVersion.trim() === skill.version;
25455
25608
  if (ownership === "managed") {
25456
25609
  let localState = await checkWorkPackInstalledState({
25457
25610
  packDir: target,
25458
25611
  agentsDir: paths.agentsDir,
25459
25612
  commandsDir: paths.commandsDir,
25460
- allowAdditional: true
25613
+ allowAdditional: !authoritative
25461
25614
  });
25462
25615
  if (localState === "missing") {
25463
25616
  const expected = await fetchWorkPackFileManifest(credentials, skill.slug, currentVersion.trim());
25617
+ legacyReference = expected;
25464
25618
  if (expected) {
25465
25619
  const diagnosis = await inspectWorkPackIntegrity({ paths, slug: skill.slug, expected });
25466
25620
  if (diagnosis.summary.modified || diagnosis.summary.missing || diagnosis.summary.unsafe || diagnosis.summary.unreadable || diagnosis.summary.truncated) {
25467
- 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";
25468
25630
  }
25469
- localState = await adoptWorkPackFileManifest({
25470
- packDir: target,
25471
- agentsDir: paths.agentsDir,
25472
- commandsDir: paths.commandsDir,
25473
- expected
25474
- }) ? "match" : "changed";
25475
25631
  } else if (sameVersion) {
25476
- const candidateArchive = await downloadSkill(credentials, skill.url);
25477
- if (createHash4("sha256").update(candidateArchive).digest("hex") !== skill.sha256)
25478
- return { status: "failed", restoration: "exact", code: "local-baseline-missing" };
25479
- 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";
25480
25636
  }
25637
+ if (authoritative && localState === "match") localState = await checkWorkPackTreeState(target);
25481
25638
  }
25482
- if (localState !== "match") return {
25639
+ if (localState !== "match" && !authoritative) return {
25483
25640
  status: "failed",
25484
25641
  restoration: "exact",
25485
25642
  code: localState === "missing" ? "local-baseline-missing" : "local-edits-preserved"
25486
25643
  };
25487
- if (sameVersion && !await workPackNeedsModelNormalization(target, approvedModelIds, skill.slug)) {
25644
+ retainLocalCopy = localState !== "match";
25645
+ if (!retainLocalCopy && sameVersion && !await workPackNeedsModelNormalization(target, approvedModelIds, skill.slug)) {
25488
25646
  return cleanupPendingSlugs.has(skill.slug) ? {
25489
25647
  status: "unchanged",
25490
25648
  warningCode: "cleanup-pending",
@@ -25493,7 +25651,7 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
25493
25651
  }
25494
25652
  }
25495
25653
  previousManagedPaths = await managedWorkPackPaths(paths, target);
25496
- archive = await downloadSkill(credentials, skill.url);
25654
+ archive ??= await downloadSkill(credentials, skill.url);
25497
25655
  const sha2563 = createHash4("sha256").update(archive).digest("hex");
25498
25656
  if (sha2563 !== skill.sha256) return { status: "failed", restoration: "exact", code: "checksum-mismatch" };
25499
25657
  } catch (error45) {
@@ -25507,6 +25665,8 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
25507
25665
  installWorkPackBoundary: options.installWorkPackBoundary,
25508
25666
  workPackProjectionBoundary: options.workPackProjectionBoundary,
25509
25667
  cleanupWorkPackBackup: options.cleanupWorkPackBackup,
25668
+ retainLocalCopy,
25669
+ legacyReference,
25510
25670
  approvedModelIds
25511
25671
  });
25512
25672
  cleanupPending = install.cleanup === "pending";
@@ -25524,6 +25684,9 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
25524
25684
  ...cleanupPending ? {
25525
25685
  warningCode: "cleanup-pending",
25526
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."
25527
25690
  } : {}
25528
25691
  };
25529
25692
  } catch {
@@ -25561,8 +25724,8 @@ function jsonBytes(value) {
25561
25724
  `);
25562
25725
  }
25563
25726
  async function removeLegacyDebugTraceRuntime(paths) {
25564
- const launchAgentPath = path9.join(os4.homedir(), "Library", "LaunchAgents", "com.minimal-forge.debug-trace.plist");
25565
- const launchAgent = await readFile8(launchAgentPath, "utf8").catch((error45) => {
25727
+ const launchAgentPath = path10.join(os4.homedir(), "Library", "LaunchAgents", "com.minimal-forge.debug-trace.plist");
25728
+ const launchAgent = await readFile9(launchAgentPath, "utf8").catch((error45) => {
25566
25729
  if (error45.code === "ENOENT") return void 0;
25567
25730
  throw error45;
25568
25731
  });
@@ -25584,13 +25747,13 @@ async function removeLegacyDebugTraceRuntime(paths) {
25584
25747
  "debug-trace-service.err.log",
25585
25748
  "opencode-debug-trace"
25586
25749
  ]) {
25587
- await rm4(path9.join(paths.forgeDir, filename), { force: true });
25750
+ await rm4(path10.join(paths.forgeDir, filename), { force: true });
25588
25751
  }
25589
- await rm4(path9.join(paths.forgeDir, "claude-tap-traces"), { recursive: true, force: true });
25590
- await rm4(path9.join(paths.forgeDir, "verified-claude-tap"), { recursive: true, force: true });
25752
+ await rm4(path10.join(paths.forgeDir, "claude-tap-traces"), { recursive: true, force: true });
25753
+ await rm4(path10.join(paths.forgeDir, "verified-claude-tap"), { recursive: true, force: true });
25591
25754
  }
25592
25755
  async function isManagedDebugTraceConfig(configPath) {
25593
- const raw = await readFile8(configPath, "utf8").catch((error45) => {
25756
+ const raw = await readFile9(configPath, "utf8").catch((error45) => {
25594
25757
  if (error45.code === "ENOENT") return void 0;
25595
25758
  throw error45;
25596
25759
  });
@@ -25651,10 +25814,14 @@ var WorkPackLocalEditsError = class extends Error {
25651
25814
  }
25652
25815
  code;
25653
25816
  };
25654
- async function assertWorkPackUnchangedAtBoundary(paths, target, snapshot) {
25817
+ async function assertWorkPackUnchangedAtBoundary(paths, target, snapshot, retained = false) {
25655
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
+ }
25656
25823
  if (ownership === "absent") return;
25657
- if (ownership === "foreign") throw foreignWorkPackError(path9.basename(target));
25824
+ if (ownership === "foreign") throw foreignWorkPackError(path10.basename(target));
25658
25825
  const localState = await checkWorkPackInstalledState({
25659
25826
  packDir: target,
25660
25827
  agentsDir: paths.agentsDir,
@@ -25666,8 +25833,8 @@ async function assertWorkPackUnchangedAtBoundary(paths, target, snapshot) {
25666
25833
  }
25667
25834
  if (snapshot) await assertWorkPackTreeUnchangedAtBoundary(target, snapshot);
25668
25835
  }
25669
- async function assertWorkPackTreeUnchangedAtBoundary(target, snapshot) {
25670
- 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;
25671
25838
  const localState = snapshot ? actual && sameTree(actual, snapshot) ? "match" : "changed" : await checkWorkPackTreeState(target);
25672
25839
  if (localState !== "match") {
25673
25840
  throw new WorkPackLocalEditsError(localState === "missing" ? "local-baseline-missing" : "local-edits-preserved");
@@ -25696,31 +25863,31 @@ async function preserveWorkPackExtras(target, nextPath, actual) {
25696
25863
  `A nova vers\xE3o usa o caminho adicional "${name}". O pacote anterior e os ficheiros locais foram preservados.`
25697
25864
  );
25698
25865
  }
25699
- for (const directory of directories) await mkdir5(path9.join(nextPath, directory), { recursive: true });
25866
+ for (const directory of directories) await mkdir6(path10.join(nextPath, directory), { recursive: true });
25700
25867
  for (const file2 of extras) {
25701
- const destination = path9.join(nextPath, file2.path);
25702
- await mkdir5(path9.dirname(destination), { recursive: true });
25703
- await cp(path9.join(target, file2.path), destination, { errorOnExist: true, force: false });
25704
- if (createHash4("sha256").update(await readFile8(destination)).digest("hex") !== file2.sha256)
25868
+ const destination = path10.join(nextPath, file2.path);
25869
+ await mkdir6(path10.dirname(destination), { recursive: true });
25870
+ await cp(path10.join(target, file2.path), destination, { errorOnExist: true, force: false });
25871
+ if (createHash4("sha256").update(await readFile9(destination)).digest("hex") !== file2.sha256)
25705
25872
  throw new WorkPackLocalEditsError("local-edits-preserved");
25706
25873
  }
25707
25874
  }
25708
25875
  async function installSkillArchive(paths, slug, version2, archive, options = {}) {
25709
- const tempRoot = await mkdtemp(path9.join(os4.tmpdir(), `forge-${slug}-`));
25710
- const archivePath = path9.join(tempRoot, `${slug}.tar`);
25711
- const extractPath = path9.join(tempRoot, "extract");
25712
- const nextPath = path9.join(tempRoot, slug);
25713
- const target = path9.join(paths.skillsDir, slug);
25714
- const backup = path9.join(paths.skillsDir, `${slug}.previous`);
25876
+ const tempRoot = await mkdtemp(path10.join(os4.tmpdir(), `forge-${slug}-`));
25877
+ const archivePath = path10.join(tempRoot, `${slug}.tar`);
25878
+ const extractPath = path10.join(tempRoot, "extract");
25879
+ const nextPath = path10.join(tempRoot, slug);
25880
+ const target = path10.join(paths.skillsDir, slug);
25881
+ const backup = path10.join(paths.skillsDir, `${slug}.previous`);
25715
25882
  let agentFiles;
25716
25883
  let commandFiles;
25717
25884
  let previousAgents;
25718
25885
  let previousCommands;
25719
25886
  try {
25720
- await mkdir5(extractPath, { recursive: true });
25721
- await writeFile6(archivePath, archive);
25887
+ await mkdir6(extractPath, { recursive: true });
25888
+ await writeFile7(archivePath, archive);
25722
25889
  await So({ file: archivePath, cwd: extractPath, strict: true });
25723
- const extractedSkillPath = path9.join(extractPath, slug);
25890
+ const extractedSkillPath = path10.join(extractPath, slug);
25724
25891
  await assertNoReservedMarkerAliases(extractedSkillPath);
25725
25892
  await validateSkillFolder(extractedSkillPath, slug);
25726
25893
  agentFiles = await normalizePackAgentModels(
@@ -25747,15 +25914,15 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25747
25914
  }
25748
25915
  throw error45;
25749
25916
  }
25750
- await rename6(path9.join(extractPath, slug), nextPath);
25751
- await writeFile6(path9.join(nextPath, ".forge-version"), `${version2}
25917
+ await rename7(path10.join(extractPath, slug), nextPath);
25918
+ await writeFile7(path10.join(nextPath, ".forge-version"), `${version2}
25752
25919
  `);
25753
25920
  if (agentFiles.length > 0) {
25754
- await writeFile6(path9.join(nextPath, ".forge-agents"), `${agentFiles.map((agent) => agent.filename).join("\n")}
25921
+ await writeFile7(path10.join(nextPath, ".forge-agents"), `${agentFiles.map((agent) => agent.filename).join("\n")}
25755
25922
  `);
25756
25923
  }
25757
25924
  if (commandFiles.length > 0) {
25758
- await writeFile6(path9.join(nextPath, ".forge-commands"), `${commandFiles.map((command) => command.filename).join("\n")}
25925
+ await writeFile7(path10.join(nextPath, ".forge-commands"), `${commandFiles.map((command) => command.filename).join("\n")}
25759
25926
  `);
25760
25927
  }
25761
25928
  await writeWorkPackInstalledState({ packDir: nextPath, version: version2, agents: agentFiles, commands: commandFiles });
@@ -25766,34 +25933,40 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25766
25933
  const agentTransactionState = new Map(
25767
25934
  [...agentSnapshot.keys()].map((filePath) => [
25768
25935
  filePath,
25769
- agentFiles.find((agent) => agent.filename === path9.basename(filePath))?.content
25936
+ agentFiles.find((agent) => agent.filename === path10.basename(filePath))?.content
25770
25937
  ])
25771
25938
  );
25772
25939
  const commandTransactionState = new Map(
25773
25940
  [...commandSnapshot.keys()].map((filePath) => [
25774
25941
  filePath,
25775
- commandFiles.find((command) => command.filename === path9.basename(filePath))?.content
25942
+ commandFiles.find((command) => command.filename === path10.basename(filePath))?.content
25776
25943
  ])
25777
25944
  );
25778
25945
  const previousManagedPaths = await managedWorkPackPaths(paths, target);
25779
25946
  let originalTree;
25780
25947
  let installedTree;
25948
+ let retainedProjections = [];
25781
25949
  try {
25782
25950
  if (await workPackOwnership(target) === "managed") {
25783
- originalTree = await digestPackTree(target);
25951
+ originalTree = await digestPackTree(target, options.retainLocalCopy);
25784
25952
  if (!originalTree) throw new WorkPackLocalEditsError("local-edits-preserved");
25785
- 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
+ }
25786
25959
  }
25787
25960
  installedTree = await digestPackTree(nextPath);
25788
25961
  if (!installedTree) throw new WorkPackLocalEditsError("local-edits-preserved");
25789
25962
  if (previousManagedPaths.length > 0) await options.beforeManagedPathsRemoved?.(previousManagedPaths);
25790
- await assertWorkPackUnchangedAtBoundary(paths, target, originalTree);
25963
+ await assertWorkPackUnchangedAtBoundary(paths, target, originalTree, options.retainLocalCopy);
25791
25964
  } catch (error45) {
25792
25965
  await rm4(tempRoot, { recursive: true, force: true });
25793
25966
  throw error45;
25794
25967
  }
25795
25968
  const writeProjection = options.writeWorkPackProjection ?? writeTextAtomic;
25796
- const claimedBackup = path9.join(tempRoot, `${slug}-claimed-previous`);
25969
+ const claimedBackup = path10.join(tempRoot, `${slug}-claimed-previous`);
25797
25970
  const transactionPath = `${backup}${WORK_PACK_TRANSACTION_SUFFIX}`;
25798
25971
  let targetBackedUp = false;
25799
25972
  let targetInstalled = false;
@@ -25803,7 +25976,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25803
25976
  await rm4(transactionPath, { force: true });
25804
25977
  await writeTextAtomic(transactionPath, "install\n");
25805
25978
  try {
25806
- await rename6(target, backup);
25979
+ await rename7(target, backup);
25807
25980
  targetBackedUp = true;
25808
25981
  } catch (error45) {
25809
25982
  if (error45.code !== "ENOENT") throw error45;
@@ -25811,48 +25984,52 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25811
25984
  }
25812
25985
  if (targetBackedUp) {
25813
25986
  await options.installWorkPackBoundary?.("after-backup");
25814
- await assertWorkPackUnchangedAtBoundary(paths, backup, originalTree);
25987
+ await assertWorkPackUnchangedAtBoundary(paths, backup, originalTree, options.retainLocalCopy);
25815
25988
  }
25816
- await rename6(nextPath, target);
25989
+ await rename7(nextPath, target);
25817
25990
  targetInstalled = true;
25818
25991
  for (const filename of previousAgents.filter((name) => !nextAgentNames.has(name))) {
25819
- const filePath = path9.join(paths.agentsDir, filename);
25992
+ const filePath = path10.join(paths.agentsDir, filename);
25820
25993
  await options.workPackProjectionBoundary?.("install", filePath);
25994
+ await assertRetainedProjectionState(retainedProjections, filePath);
25821
25995
  await assertProjectionState(filePath, agentSnapshot.get(filePath));
25822
25996
  await rm4(filePath, { force: true });
25823
25997
  }
25824
25998
  if (agentFiles.length > 0) {
25825
- await mkdir5(paths.agentsDir, { recursive: true });
25999
+ await mkdir6(paths.agentsDir, { recursive: true });
25826
26000
  for (const agent of agentFiles) {
25827
- const filePath = path9.join(paths.agentsDir, agent.filename);
26001
+ const filePath = path10.join(paths.agentsDir, agent.filename);
25828
26002
  await options.workPackProjectionBoundary?.("install", filePath);
26003
+ await assertRetainedProjectionState(retainedProjections, filePath);
25829
26004
  await assertProjectionState(filePath, agentSnapshot.get(filePath));
25830
26005
  await writeProjection(filePath, agent.content);
25831
26006
  }
25832
26007
  }
25833
26008
  for (const filename of previousCommands.filter((name) => !nextCommandNames.has(name))) {
25834
- const filePath = path9.join(paths.commandsDir, filename);
26009
+ const filePath = path10.join(paths.commandsDir, filename);
25835
26010
  await options.workPackProjectionBoundary?.("install", filePath);
26011
+ await assertRetainedProjectionState(retainedProjections, filePath);
25836
26012
  await assertProjectionState(filePath, commandSnapshot.get(filePath));
25837
26013
  await rm4(filePath, { force: true });
25838
26014
  }
25839
26015
  if (commandFiles.length > 0) {
25840
- await mkdir5(paths.commandsDir, { recursive: true });
26016
+ await mkdir6(paths.commandsDir, { recursive: true });
25841
26017
  for (const command of commandFiles) {
25842
- const filePath = path9.join(paths.commandsDir, command.filename);
26018
+ const filePath = path10.join(paths.commandsDir, command.filename);
25843
26019
  await options.workPackProjectionBoundary?.("install", filePath);
26020
+ await assertRetainedProjectionState(retainedProjections, filePath);
25844
26021
  await assertProjectionState(filePath, commandSnapshot.get(filePath));
25845
26022
  await writeProjection(filePath, command.content);
25846
26023
  }
25847
26024
  }
25848
- if (targetBackedUp) await assertWorkPackTreeUnchangedAtBoundary(backup, originalTree);
26025
+ if (targetBackedUp) await assertWorkPackTreeUnchangedAtBoundary(backup, originalTree, options.retainLocalCopy);
25849
26026
  if (targetBackedUp) await options.installWorkPackBoundary?.("before-commit");
25850
26027
  await assertWorkPackTreeUnchangedAtBoundary(target, installedTree);
25851
26028
  if (targetBackedUp) {
25852
- await rename6(backup, claimedBackup);
26029
+ await rename7(backup, claimedBackup);
25853
26030
  backupClaimed = true;
25854
- await assertWorkPackTreeUnchangedAtBoundary(claimedBackup, originalTree);
25855
- await writeFile6(path9.join(claimedBackup, WORK_PACK_COMMITTED_MARKER), `${version2}
26031
+ await assertWorkPackTreeUnchangedAtBoundary(claimedBackup, originalTree, options.retainLocalCopy);
26032
+ await writeFile7(path10.join(claimedBackup, WORK_PACK_COMMITTED_MARKER), `${version2}
25856
26033
  `);
25857
26034
  await writeTextAtomic(transactionPath, "committed\n");
25858
26035
  }
@@ -25860,15 +26037,15 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25860
26037
  try {
25861
26038
  if (targetInstalled) {
25862
26039
  await assertWorkPackTreeUnchangedAtBoundary(target, installedTree);
25863
- await restoreProjectionState(agentSnapshot, agentTransactionState);
25864
- await restoreProjectionState(commandSnapshot, commandTransactionState);
26040
+ await restoreProjectionState(agentSnapshot, agentTransactionState, retainedProjections);
26041
+ await restoreProjectionState(commandSnapshot, commandTransactionState, retainedProjections);
25865
26042
  }
25866
26043
  if (targetBackedUp) {
25867
- const restoredTarget = path9.join(tempRoot, `${slug}-restore`);
26044
+ const restoredTarget = path10.join(tempRoot, `${slug}-restore`);
25868
26045
  const rollbackSource = backupClaimed ? claimedBackup : backup;
25869
26046
  await cp(rollbackSource, restoredTarget, { recursive: true });
25870
26047
  if (targetInstalled) await rm4(target, { recursive: true, force: true });
25871
- await rename6(restoredTarget, target);
26048
+ await rename7(restoredTarget, target);
25872
26049
  await rm4(rollbackSource, { recursive: true, force: true });
25873
26050
  await rm4(transactionPath, { force: true });
25874
26051
  } else if (targetInstalled) {
@@ -25894,26 +26071,26 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25894
26071
  await rm4(transactionPath, { force: true });
25895
26072
  } else {
25896
26073
  cleanup2 = "pending";
25897
- if (backupClaimed) await rename6(claimedBackup, backup);
26074
+ if (backupClaimed) await rename7(claimedBackup, backup);
25898
26075
  }
25899
26076
  }
25900
26077
  await rm4(tempRoot, { recursive: true, force: true }).catch(() => void 0);
25901
26078
  return { cleanup: cleanup2 };
25902
26079
  }
25903
26080
  async function adoptLegacyWorkPackState(paths, slug, version2, archive, approvedModelIds) {
25904
- const comparisonRoot = await mkdtemp(path9.join(os4.tmpdir(), `forge-${slug}-baseline-`));
26081
+ const comparisonRoot = await mkdtemp(path10.join(os4.tmpdir(), `forge-${slug}-baseline-`));
25905
26082
  const comparisonPaths = {
25906
26083
  ...paths,
25907
- skillsDir: path9.join(comparisonRoot, "skills"),
25908
- agentsDir: path9.join(comparisonRoot, "agents"),
25909
- commandsDir: path9.join(comparisonRoot, "commands")
26084
+ skillsDir: path10.join(comparisonRoot, "skills"),
26085
+ agentsDir: path10.join(comparisonRoot, "agents"),
26086
+ commandsDir: path10.join(comparisonRoot, "commands")
25910
26087
  };
25911
26088
  try {
25912
- await mkdir5(comparisonPaths.skillsDir, { recursive: true });
26089
+ await mkdir6(comparisonPaths.skillsDir, { recursive: true });
25913
26090
  await installSkillArchive(comparisonPaths, slug, version2, archive, { approvedModelIds });
25914
26091
  return adoptWorkPackInstalledState({
25915
- expectedPackDir: path9.join(comparisonPaths.skillsDir, slug),
25916
- packDir: path9.join(paths.skillsDir, slug),
26092
+ expectedPackDir: path10.join(comparisonPaths.skillsDir, slug),
26093
+ packDir: path10.join(paths.skillsDir, slug),
25917
26094
  agentsDir: paths.agentsDir,
25918
26095
  commandsDir: paths.commandsDir,
25919
26096
  allowAdditional: true
@@ -25925,7 +26102,7 @@ async function adoptLegacyWorkPackState(paths, slug, version2, archive, approved
25925
26102
  async function recoverInterruptedWorkPackInstalls(paths, cleanupWorkPackBackup, workPackProjectionBoundary) {
25926
26103
  const cleanupPending = /* @__PURE__ */ new Set();
25927
26104
  const failures = /* @__PURE__ */ new Map();
25928
- const entries = await readdir4(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
26105
+ const entries = await readdir5(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
25929
26106
  if (error45.code === "ENOENT") return [];
25930
26107
  throw error45;
25931
26108
  });
@@ -25933,7 +26110,7 @@ async function recoverInterruptedWorkPackInstalls(paths, cleanupWorkPackBackup,
25933
26110
  if (!entry.name.endsWith(".previous")) continue;
25934
26111
  const slug = entry.name.slice(0, -".previous".length);
25935
26112
  if (!slug) continue;
25936
- const target = path9.join(paths.skillsDir, slug);
26113
+ const target = path10.join(paths.skillsDir, slug);
25937
26114
  const backup = `${target}.previous`;
25938
26115
  const transactionState = await readWorkPackTransactionState(backup);
25939
26116
  if (transactionState === "committed") {
@@ -25966,9 +26143,9 @@ async function recoverInterruptedWorkPackInstall(paths, target, cleanupWorkPackB
25966
26143
  const backup = `${target}.previous`;
25967
26144
  const backupOwnership = await workPackOwnership(backup);
25968
26145
  if (backupOwnership === "absent") return "recovered";
25969
- if (backupOwnership === "foreign") throw foreignWorkPackError(path9.basename(target));
25970
- if (await workPackOwnership(target) === "foreign") throw foreignWorkPackError(path9.basename(target));
25971
- const committed = await readFile8(path9.join(backup, WORK_PACK_COMMITTED_MARKER), "utf8").catch((error45) => {
26146
+ if (backupOwnership === "foreign") throw foreignWorkPackError(path10.basename(target));
26147
+ if (await workPackOwnership(target) === "foreign") throw foreignWorkPackError(path10.basename(target));
26148
+ const committed = await readFile9(path10.join(backup, WORK_PACK_COMMITTED_MARKER), "utf8").catch((error45) => {
25972
26149
  if (error45.code === "ENOENT") return void 0;
25973
26150
  throw error45;
25974
26151
  });
@@ -26016,38 +26193,38 @@ async function recoverInterruptedWorkPackInstall(paths, target, cleanupWorkPackB
26016
26193
  );
26017
26194
  const previousAgentNames = new Set(previousAgents.map((agent) => agent.filename));
26018
26195
  const previousCommandNames = new Set(previousCommands.map((command) => command.filename));
26019
- const recoveryRoot = await mkdtemp(path9.join(os4.tmpdir(), "forge-recover-"));
26020
- const recoveredTarget = path9.join(recoveryRoot, path9.basename(target));
26196
+ const recoveryRoot = await mkdtemp(path10.join(os4.tmpdir(), "forge-recover-"));
26197
+ const recoveredTarget = path10.join(recoveryRoot, path10.basename(target));
26021
26198
  await cp(backup, recoveredTarget, { recursive: true });
26022
26199
  try {
26023
26200
  for (const filename of currentAgents.filter((name) => !previousAgentNames.has(name))) {
26024
- const filePath = path9.join(paths.agentsDir, filename);
26201
+ const filePath = path10.join(paths.agentsDir, filename);
26025
26202
  await workPackProjectionBoundary?.("recover", filePath);
26026
26203
  await assertProjectionState(filePath, agentRecoveryState.get(filePath));
26027
26204
  await rm4(filePath, { force: true });
26028
26205
  }
26029
- await mkdir5(paths.agentsDir, { recursive: true });
26206
+ await mkdir6(paths.agentsDir, { recursive: true });
26030
26207
  for (const agent of previousAgents) {
26031
- const filePath = path9.join(paths.agentsDir, agent.filename);
26208
+ const filePath = path10.join(paths.agentsDir, agent.filename);
26032
26209
  await workPackProjectionBoundary?.("recover", filePath);
26033
26210
  await assertProjectionState(filePath, agentRecoveryState.get(filePath));
26034
26211
  await writeTextAtomic(filePath, agent.content);
26035
26212
  }
26036
26213
  for (const filename of currentCommands.filter((name) => !previousCommandNames.has(name))) {
26037
- const filePath = path9.join(paths.commandsDir, filename);
26214
+ const filePath = path10.join(paths.commandsDir, filename);
26038
26215
  await workPackProjectionBoundary?.("recover", filePath);
26039
26216
  await assertProjectionState(filePath, commandRecoveryState.get(filePath));
26040
26217
  await rm4(filePath, { force: true });
26041
26218
  }
26042
- await mkdir5(paths.commandsDir, { recursive: true });
26219
+ await mkdir6(paths.commandsDir, { recursive: true });
26043
26220
  for (const command of previousCommands) {
26044
- const filePath = path9.join(paths.commandsDir, command.filename);
26221
+ const filePath = path10.join(paths.commandsDir, command.filename);
26045
26222
  await workPackProjectionBoundary?.("recover", filePath);
26046
26223
  await assertProjectionState(filePath, commandRecoveryState.get(filePath));
26047
26224
  await writeTextAtomic(filePath, command.content);
26048
26225
  }
26049
26226
  await rm4(target, { recursive: true, force: true });
26050
- await rename6(recoveredTarget, target);
26227
+ await rename7(recoveredTarget, target);
26051
26228
  await rm4(backup, { recursive: true, force: true });
26052
26229
  await rm4(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, { force: true });
26053
26230
  } finally {
@@ -26059,7 +26236,7 @@ async function removeWorkPackBackup(backupPath) {
26059
26236
  await rm4(backupPath, { recursive: true, force: true });
26060
26237
  }
26061
26238
  async function readWorkPackTransactionFile(backup) {
26062
- return readFile8(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, "utf8").catch((error45) => {
26239
+ return readFile9(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, "utf8").catch((error45) => {
26063
26240
  if (error45.code === "ENOENT") return void 0;
26064
26241
  throw error45;
26065
26242
  });
@@ -26073,7 +26250,7 @@ function isManagedProjectionName(filename) {
26073
26250
  return filename.length > 0 && !filename.includes("/") && !filename.includes("\\") && filename !== "..";
26074
26251
  }
26075
26252
  async function recordRemovedProjection(transactionPath, kind, filename) {
26076
- const current = await readFile8(transactionPath, "utf8");
26253
+ const current = await readFile9(transactionPath, "utf8");
26077
26254
  await writeTextAtomic(transactionPath, `${current.trimEnd()}
26078
26255
  ${kind}:${filename}
26079
26256
  `);
@@ -26110,7 +26287,7 @@ async function workPackOwnership(target) {
26110
26287
  });
26111
26288
  if (!targetStat) return "absent";
26112
26289
  if (!targetStat.isDirectory()) return "foreign";
26113
- const marker = await readFile8(path9.join(target, ".forge-version"), "utf8").catch((error45) => {
26290
+ const marker = await readFile9(path10.join(target, ".forge-version"), "utf8").catch((error45) => {
26114
26291
  if (error45.code === "ENOENT") return void 0;
26115
26292
  throw error45;
26116
26293
  });
@@ -26136,11 +26313,11 @@ async function assertProjectionRecoveryIsSafe(directory, currentFiles, previousF
26136
26313
  expected.set(file2.filename, contents);
26137
26314
  }
26138
26315
  for (const [filename, contents] of expected) {
26139
- const projected = await readFile8(path9.join(directory, filename), "utf8").catch((error45) => {
26316
+ const projected = await readFile9(path10.join(directory, filename), "utf8").catch((error45) => {
26140
26317
  if (error45.code === "ENOENT") return void 0;
26141
26318
  throw error45;
26142
26319
  });
26143
- validated.set(path9.join(directory, filename), projected);
26320
+ validated.set(path10.join(directory, filename), projected);
26144
26321
  const missingPreviousProjection = missingPreviousProjectionIsLocalDeletion(
26145
26322
  filename,
26146
26323
  projected,
@@ -26158,19 +26335,19 @@ async function assertProjectionRecoveryIsSafe(directory, currentFiles, previousF
26158
26335
  return validated;
26159
26336
  }
26160
26337
  async function assertProjectionState(filePath, expected) {
26161
- const current = await readFile8(filePath, "utf8").catch((error45) => {
26338
+ const current = await readFile9(filePath, "utf8").catch((error45) => {
26162
26339
  if (error45.code === "ENOENT") return void 0;
26163
26340
  throw error45;
26164
26341
  });
26165
26342
  if (current !== expected) {
26166
- throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path9.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
26343
+ throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path10.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
26167
26344
  }
26168
26345
  }
26169
26346
  async function captureProjectionState(directory, filenames) {
26170
26347
  const snapshot = /* @__PURE__ */ new Map();
26171
26348
  for (const filename of filenames) {
26172
- const filePath = path9.join(directory, filename);
26173
- const content = await readFile8(filePath, "utf8").catch((error45) => {
26349
+ const filePath = path10.join(directory, filename);
26350
+ const content = await readFile9(filePath, "utf8").catch((error45) => {
26174
26351
  if (error45.code === "ENOENT") return void 0;
26175
26352
  throw error45;
26176
26353
  });
@@ -26178,22 +26355,26 @@ async function captureProjectionState(directory, filenames) {
26178
26355
  }
26179
26356
  return snapshot;
26180
26357
  }
26181
- async function restoreProjectionState(snapshot, transactionState) {
26358
+ async function restoreProjectionState(snapshot, transactionState, retainedProjections = []) {
26182
26359
  for (const [filePath, content] of snapshot) {
26183
26360
  if (transactionState) {
26184
- const current = await readFile8(filePath, "utf8").catch((error45) => {
26361
+ const current = await readFile9(filePath, "utf8").catch((error45) => {
26185
26362
  if (error45.code === "ENOENT") return void 0;
26186
26363
  throw error45;
26187
26364
  });
26188
26365
  if (current !== transactionState.get(filePath)) continue;
26189
26366
  }
26190
- 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 });
26191
26372
  else await writeTextAtomic(filePath, content);
26192
26373
  }
26193
26374
  }
26194
26375
  async function readPackAgentFiles(skillFolder, managedNames) {
26195
- const agentsFolder = path9.join(skillFolder, "agents");
26196
- const entries = await readdir4(agentsFolder, { withFileTypes: true }).catch((error45) => {
26376
+ const agentsFolder = path10.join(skillFolder, "agents");
26377
+ const entries = await readdir5(agentsFolder, { withFileTypes: true }).catch((error45) => {
26197
26378
  if (error45.code === "ENOENT") return [];
26198
26379
  throw error45;
26199
26380
  });
@@ -26201,7 +26382,7 @@ async function readPackAgentFiles(skillFolder, managedNames) {
26201
26382
  for (const entry of entries) {
26202
26383
  if (!entry.isFile() || !entry.name.endsWith(".md") || managedNames && !managedNames.has(entry.name)) continue;
26203
26384
  if (entry.name.startsWith("._")) continue;
26204
- const content = await readFile8(path9.join(agentsFolder, entry.name), "utf8");
26385
+ const content = await readFile9(path10.join(agentsFolder, entry.name), "utf8");
26205
26386
  validateAgentFile(entry.name, content);
26206
26387
  files.push({ filename: entry.name, content });
26207
26388
  }
@@ -26212,7 +26393,7 @@ async function normalizePackAgentModels(skillFolder, agentFiles, approvedModelId
26212
26393
  for (const agent of agentFiles) {
26213
26394
  const content = normalizePackAgentModel(agent.filename, agent.content, approvedModelIds, slug);
26214
26395
  if (content !== agent.content) {
26215
- await writeFile6(path9.join(skillFolder, "agents", agent.filename), content);
26396
+ await writeFile7(path10.join(skillFolder, "agents", agent.filename), content);
26216
26397
  }
26217
26398
  normalized.push({ ...agent, content });
26218
26399
  }
@@ -26232,8 +26413,8 @@ function normalizePackAgentModel(filename, content, approvedModelIds, slug) {
26232
26413
  return normalizePackExtensionModel(`agents/${filename}`, content, approvedModelIds, slug);
26233
26414
  }
26234
26415
  async function readPackCommandFiles(skillFolder, managedNames) {
26235
- const commandsFolder = path9.join(skillFolder, "commands");
26236
- const entries = await readdir4(commandsFolder, { withFileTypes: true }).catch((error45) => {
26416
+ const commandsFolder = path10.join(skillFolder, "commands");
26417
+ const entries = await readdir5(commandsFolder, { withFileTypes: true }).catch((error45) => {
26237
26418
  if (error45.code === "ENOENT") return [];
26238
26419
  throw error45;
26239
26420
  });
@@ -26241,7 +26422,7 @@ async function readPackCommandFiles(skillFolder, managedNames) {
26241
26422
  for (const entry of entries) {
26242
26423
  if (!entry.isFile() || !entry.name.endsWith(".md") || managedNames && !managedNames.has(entry.name)) continue;
26243
26424
  if (entry.name.startsWith("._")) continue;
26244
- const content = await readFile8(path9.join(commandsFolder, entry.name), "utf8");
26425
+ const content = await readFile9(path10.join(commandsFolder, entry.name), "utf8");
26245
26426
  validateCommandFile(entry.name, content);
26246
26427
  files.push({ filename: entry.name, content });
26247
26428
  }
@@ -26252,7 +26433,7 @@ async function normalizePackCommandModels(skillFolder, commandFiles, approvedMod
26252
26433
  for (const command of commandFiles) {
26253
26434
  const content = normalizePackExtensionModel(`commands/${command.filename}`, command.content, approvedModelIds, slug);
26254
26435
  if (content !== command.content) {
26255
- await writeFile6(path9.join(skillFolder, "commands", command.filename), content);
26436
+ await writeFile7(path10.join(skillFolder, "commands", command.filename), content);
26256
26437
  }
26257
26438
  normalized.push({ ...command, content });
26258
26439
  }
@@ -26274,7 +26455,7 @@ async function assertNoForeignAgentConflicts(agentsDir, agentFiles, ownedFilenam
26274
26455
  const owned = new Set(ownedFilenames);
26275
26456
  for (const agent of agentFiles) {
26276
26457
  if (owned.has(agent.filename)) continue;
26277
- const existing = await readFile8(path9.join(agentsDir, agent.filename), "utf8").catch((error45) => {
26458
+ const existing = await readFile9(path10.join(agentsDir, agent.filename), "utf8").catch((error45) => {
26278
26459
  if (error45.code === "ENOENT") return void 0;
26279
26460
  throw error45;
26280
26461
  });
@@ -26287,7 +26468,7 @@ async function assertNoForeignCommandConflicts(commandsDir, commandFiles, ownedF
26287
26468
  const owned = new Set(ownedFilenames);
26288
26469
  for (const command of commandFiles) {
26289
26470
  if (owned.has(command.filename)) continue;
26290
- const existing = await readFile8(path9.join(commandsDir, command.filename), "utf8").catch((error45) => {
26471
+ const existing = await readFile9(path10.join(commandsDir, command.filename), "utf8").catch((error45) => {
26291
26472
  if (error45.code === "ENOENT") return void 0;
26292
26473
  throw error45;
26293
26474
  });
@@ -26297,52 +26478,91 @@ async function assertNoForeignCommandConflicts(commandsDir, commandFiles, ownedF
26297
26478
  }
26298
26479
  }
26299
26480
  async function readAgentRecord(skillFolder) {
26300
- const raw = await readFile8(path9.join(skillFolder, ".forge-agents"), "utf8").catch(() => "");
26481
+ const raw = await readFile9(path10.join(skillFolder, ".forge-agents"), "utf8").catch(() => "");
26301
26482
  return raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.includes("/") && !line.includes("\\") && line !== "..");
26302
26483
  }
26303
26484
  async function readCommandRecord(skillFolder) {
26304
- const raw = await readFile8(path9.join(skillFolder, ".forge-commands"), "utf8").catch(() => "");
26485
+ const raw = await readFile9(path10.join(skillFolder, ".forge-commands"), "utf8").catch(() => "");
26305
26486
  return raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.includes("/") && !line.includes("\\") && line !== "..");
26306
26487
  }
26307
26488
  async function managedWorkPackPaths(paths, skillFolder) {
26308
26489
  const files = await listFilesRecursively(skillFolder);
26309
- const agents = (await readAgentRecord(skillFolder)).map((filename) => path9.join(paths.agentsDir, filename));
26310
- const commands = (await readCommandRecord(skillFolder)).map((filename) => path9.join(paths.commandsDir, filename));
26490
+ const agents = (await readAgentRecord(skillFolder)).map((filename) => path10.join(paths.agentsDir, filename));
26491
+ const commands = (await readCommandRecord(skillFolder)).map((filename) => path10.join(paths.commandsDir, filename));
26311
26492
  return [.../* @__PURE__ */ new Set([...files, ...agents, ...commands])];
26312
26493
  }
26313
26494
  async function managedWorkPackSlugs(skillsDir) {
26314
- const entries = await readdir4(skillsDir, { withFileTypes: true }).catch((error45) => {
26495
+ const entries = await readdir5(skillsDir, { withFileTypes: true }).catch((error45) => {
26315
26496
  if (error45.code === "ENOENT") return [];
26316
26497
  throw error45;
26317
26498
  });
26318
26499
  const slugs = [];
26319
26500
  for (const entry of entries) {
26320
26501
  if (!entry.isDirectory() || entry.name.endsWith(".previous")) continue;
26321
- if (await workPackOwnership(path9.join(skillsDir, entry.name)) === "managed") slugs.push(entry.name);
26502
+ if (await workPackOwnership(path10.join(skillsDir, entry.name)) === "managed") slugs.push(entry.name);
26322
26503
  }
26323
26504
  return slugs.sort((left, right) => left.localeCompare(right));
26324
26505
  }
26325
- 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) {
26326
26543
  const pathsToRemove = await managedWorkPackPaths(paths, target);
26327
26544
  if (pathsToRemove.length > 0) await options.beforeManagedPathsRemoved?.(pathsToRemove);
26328
26545
  const agents = await readAgentRecord(target);
26329
26546
  const commands = await readCommandRecord(target);
26330
- const snapshots = await Promise.all([
26331
- ...agents.map((filename) => captureExactFile(path9.join(paths.agentsDir, filename))),
26332
- ...commands.map((filename) => captureExactFile(path9.join(paths.commandsDir, filename)))
26333
- ]);
26334
- await assertWorkPackUnchangedAtBoundary(paths, target);
26335
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([
26552
+ ...agents.map((filename) => captureExactFile(path10.join(paths.agentsDir, filename))),
26553
+ ...commands.map((filename) => captureExactFile(path10.join(paths.commandsDir, filename)))
26554
+ ]);
26555
+ await assertWorkPackUnchangedAtBoundary(paths, target, original, retainLocalCopy);
26336
26556
  const transactionPath = `${backup}${WORK_PACK_TRANSACTION_SUFFIX}`;
26337
- const transactionRoot = await mkdtemp(path9.join(os4.tmpdir(), "forge-remove-"));
26338
- const claimedBackup = path9.join(transactionRoot, path9.basename(target));
26557
+ const transactionRoot = await mkdtemp(path10.join(os4.tmpdir(), "forge-remove-"));
26558
+ const claimedBackup = path10.join(transactionRoot, path10.basename(target));
26339
26559
  let projectionsRemoved = false;
26340
26560
  let backupClaimed = false;
26341
26561
  try {
26342
26562
  await rm4(backup, { recursive: true, force: true });
26343
26563
  await rm4(transactionPath, { force: true });
26344
26564
  await writeTextAtomic(transactionPath, "remove\n");
26345
- await rename6(target, backup);
26565
+ await rename7(target, backup);
26346
26566
  } catch (error45) {
26347
26567
  await rm4(transactionPath, { force: true }).catch(() => void 0);
26348
26568
  await rm4(transactionRoot, { recursive: true, force: true }).catch(() => void 0);
@@ -26350,10 +26570,10 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
26350
26570
  }
26351
26571
  try {
26352
26572
  await options.removeWorkPackBoundary?.("after-backup");
26353
- await assertWorkPackUnchangedAtBoundary(paths, backup);
26573
+ await assertWorkPackUnchangedAtBoundary(paths, backup, original, retainLocalCopy);
26354
26574
  projectionsRemoved = agents.length > 0;
26355
26575
  for (const filename of agents) {
26356
- const filePath = path9.join(paths.agentsDir, filename);
26576
+ const filePath = path10.join(paths.agentsDir, filename);
26357
26577
  await options.workPackProjectionBoundary?.("remove", filePath);
26358
26578
  await assertExactFileState(snapshots, filePath);
26359
26579
  await recordRemovedProjection(transactionPath, "agent", filename);
@@ -26362,18 +26582,18 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
26362
26582
  await options.removeWorkPackBoundary?.("after-agents");
26363
26583
  projectionsRemoved ||= commands.length > 0;
26364
26584
  for (const filename of commands) {
26365
- const filePath = path9.join(paths.commandsDir, filename);
26585
+ const filePath = path10.join(paths.commandsDir, filename);
26366
26586
  await options.workPackProjectionBoundary?.("remove", filePath);
26367
26587
  await assertExactFileState(snapshots, filePath);
26368
26588
  await recordRemovedProjection(transactionPath, "command", filename);
26369
26589
  await rm4(filePath, { force: true });
26370
26590
  }
26371
26591
  await options.removeWorkPackBoundary?.("after-commands");
26372
- await assertWorkPackTreeUnchangedAtBoundary(backup);
26592
+ await assertWorkPackTreeUnchangedAtBoundary(backup, original, retainLocalCopy);
26373
26593
  await options.removeWorkPackBoundary?.("before-commit");
26374
- await rename6(backup, claimedBackup);
26594
+ await rename7(backup, claimedBackup);
26375
26595
  backupClaimed = true;
26376
- await assertWorkPackTreeUnchangedAtBoundary(claimedBackup);
26596
+ await assertWorkPackTreeUnchangedAtBoundary(claimedBackup, original, retainLocalCopy);
26377
26597
  await writeTextAtomic(transactionPath, "committed\n");
26378
26598
  await rm4(claimedBackup, { recursive: true, force: true });
26379
26599
  await rm4(transactionPath, { force: true });
@@ -26382,13 +26602,13 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
26382
26602
  } catch (error45) {
26383
26603
  try {
26384
26604
  if (projectionsRemoved) await restoreRemovedExactFiles(snapshots);
26385
- await rename6(backupClaimed ? claimedBackup : backup, target);
26605
+ await rename7(backupClaimed ? claimedBackup : backup, target);
26386
26606
  await rm4(transactionPath, { force: true });
26387
26607
  if (projectionsRemoved) await verifyRestoredOrLocallyChangedFiles(snapshots);
26388
26608
  if (await workPackOwnership(target) !== "managed") throw new Error("restored Work Pack marker missing");
26389
26609
  await rm4(transactionRoot, { recursive: true, force: true }).catch(() => void 0);
26390
26610
  } catch (restoreError) {
26391
- throw new WorkPackRecoveryUncertainError(`Falha ao remover e restaurar o pacote de trabalho ${path9.basename(target)}`, {
26611
+ throw new WorkPackRecoveryUncertainError(`Falha ao remover e restaurar o pacote de trabalho ${path10.basename(target)}`, {
26392
26612
  cause: new AggregateError([error45, restoreError])
26393
26613
  });
26394
26614
  }
@@ -26399,7 +26619,7 @@ async function captureExactFile(filePath) {
26399
26619
  try {
26400
26620
  const info = await lstat5(filePath);
26401
26621
  if (!info.isFile()) throw new Error(`A proje\xE7\xE3o gerida n\xE3o \xE9 um ficheiro regular: ${filePath}`);
26402
- return { path: filePath, exists: true, bytes: await readFile8(filePath), mode: info.mode & 4095 };
26622
+ return { path: filePath, exists: true, bytes: await readFile9(filePath), mode: info.mode & 4095 };
26403
26623
  } catch (error45) {
26404
26624
  if (error45.code === "ENOENT") return { path: filePath, exists: false };
26405
26625
  throw error45;
@@ -26409,18 +26629,18 @@ async function assertExactFileState(snapshots, filePath) {
26409
26629
  const expected = snapshots.find((snapshot) => snapshot.path === filePath);
26410
26630
  const current = await captureExactFile(filePath);
26411
26631
  if (!expected || current.exists !== expected.exists) {
26412
- throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path9.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
26632
+ throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path10.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
26413
26633
  }
26414
26634
  if (current.exists && (!current.bytes?.equals(expected.bytes) || current.mode !== expected.mode)) {
26415
- throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path9.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
26635
+ throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path10.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
26416
26636
  }
26417
26637
  }
26418
26638
  async function restoreRemovedExactFiles(snapshots) {
26419
26639
  for (const snapshot of snapshots) {
26420
26640
  if ((await captureExactFile(snapshot.path)).exists) continue;
26421
26641
  if (!snapshot.exists) continue;
26422
- await mkdir5(path9.dirname(snapshot.path), { recursive: true });
26423
- await writeFile6(snapshot.path, snapshot.bytes);
26642
+ await mkdir6(path10.dirname(snapshot.path), { recursive: true });
26643
+ await writeFile7(snapshot.path, snapshot.bytes);
26424
26644
  await chmod4(snapshot.path, snapshot.mode);
26425
26645
  }
26426
26646
  }
@@ -26431,20 +26651,20 @@ async function verifyRestoredOrLocallyChangedFiles(snapshots) {
26431
26651
  }
26432
26652
  }
26433
26653
  async function listFilesRecursively(root) {
26434
- const entries = await readdir4(root, { withFileTypes: true }).catch((error45) => {
26654
+ const entries = await readdir5(root, { withFileTypes: true }).catch((error45) => {
26435
26655
  if (error45.code === "ENOENT") return [];
26436
26656
  throw error45;
26437
26657
  });
26438
26658
  const files = [];
26439
26659
  for (const entry of entries) {
26440
- const absolute = path9.join(root, entry.name);
26660
+ const absolute = path10.join(root, entry.name);
26441
26661
  if (entry.isDirectory()) files.push(...await listFilesRecursively(absolute));
26442
26662
  else if (entry.isFile()) files.push(absolute);
26443
26663
  }
26444
26664
  return files;
26445
26665
  }
26446
26666
  async function validateSkillFolder(folder, slug) {
26447
- const skillMd = await readFile8(path9.join(folder, "SKILL.md"), "utf8");
26667
+ const skillMd = await readFile9(path10.join(folder, "SKILL.md"), "utf8");
26448
26668
  const frontmatter = /^---\n([\s\S]+?)\n---/.exec(skillMd)?.[1] ?? "";
26449
26669
  if (!frontmatter.includes(`name: ${slug}`) && !frontmatter.includes(`name: "${slug}"`)) {
26450
26670
  throw new Error(`O campo name no frontmatter de SKILL.md tem de corresponder a ${slug}`);
@@ -26455,7 +26675,7 @@ async function validateSkillFolder(folder, slug) {
26455
26675
  }
26456
26676
  async function assertNoReservedMarkerAliases(skillFolder) {
26457
26677
  const reserved = /* @__PURE__ */ new Set([".forge-version", ".forge-agents", ".forge-commands", WORK_PACK_LOCAL_STATE_FILENAME]);
26458
- const entries = await readdir4(skillFolder);
26678
+ const entries = await readdir5(skillFolder);
26459
26679
  const marker = entries.find((entry) => reserved.has(entry.toLowerCase()));
26460
26680
  if (marker) throw new Error(`O pacote de trabalho cont\xE9m o marcador Forge reservado ${marker}`);
26461
26681
  }
@@ -26465,14 +26685,14 @@ async function writeJsonAtomic2(filePath, value) {
26465
26685
  await writeTextAtomic(filePath, content);
26466
26686
  }
26467
26687
  async function writeTextAtomic(filePath, content) {
26468
- const dir = path9.dirname(filePath);
26469
- await mkdir5(dir, { recursive: true });
26470
- const tempPath = path9.join(dir, `.${path9.basename(filePath)}.${process.pid}.tmp`);
26471
- await writeFile6(tempPath, content);
26472
- await rename6(tempPath, filePath);
26688
+ const dir = path10.dirname(filePath);
26689
+ await mkdir6(dir, { recursive: true });
26690
+ const tempPath = path10.join(dir, `.${path10.basename(filePath)}.${process.pid}.tmp`);
26691
+ await writeFile7(tempPath, content);
26692
+ await rename7(tempPath, filePath);
26473
26693
  }
26474
26694
  async function readPluginFile(pluginPath) {
26475
- return readFile8(pluginPath, "utf8").catch((error45) => {
26695
+ return readFile9(pluginPath, "utf8").catch((error45) => {
26476
26696
  if (error45.code === "ENOENT") return void 0;
26477
26697
  throw error45;
26478
26698
  });
@@ -26505,7 +26725,7 @@ function withPluginPaths(config2, pluginPaths, removePluginPaths = []) {
26505
26725
  return next;
26506
26726
  }
26507
26727
  async function readJsoncObject(filePath) {
26508
- const raw = await readFile8(filePath, "utf8").catch((error45) => {
26728
+ const raw = await readFile9(filePath, "utf8").catch((error45) => {
26509
26729
  if (error45.code === "ENOENT") return "";
26510
26730
  throw error45;
26511
26731
  });
@@ -26575,9 +26795,15 @@ antes de executar trabalho que delas dependa. Segue os processos indicados pelo
26575
26795
  utilizador quando aplic\xE1veis. N\xE3o declares que uma ferramenta ou fonte foi
26576
26796
  aprovada pela organiza\xE7\xE3o apenas por estar dispon\xEDvel.
26577
26797
 
26578
- Quando o trabalho se repete, prop\xF5e uma skill reutiliz\xE1vel. Cria ou atualiza-a
26579
- quando autorizado, sem dados privados de clientes. Publicar e distribuir a
26580
- 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.
26581
26807
 
26582
26808
  ## Entregas e comunica\xE7\xE3o
26583
26809
 
@@ -26609,15 +26835,14 @@ function isRecord5(value) {
26609
26835
  }
26610
26836
 
26611
26837
  // packages/cli/src/localWorkerSync.ts
26612
- import { readFile as readFile11 } from "node:fs/promises";
26613
- import path12 from "node:path";
26838
+ import { readFile as readFile12 } from "node:fs/promises";
26614
26839
 
26615
26840
  // packages/cli/src/recoveryLauncher.ts
26616
- import { chmod as chmod5, readFile as readFile9 } from "node:fs/promises";
26841
+ import { chmod as chmod5, readFile as readFile10 } from "node:fs/promises";
26617
26842
  import { execFileSync } from "node:child_process";
26618
- import path10 from "node:path";
26843
+ import path11 from "node:path";
26619
26844
  async function installRecoveryLauncher(paths, forgeBaseUrl, source = new URL("./repair.js", import.meta.url)) {
26620
- const program = await readFile9(source, "utf8");
26845
+ const program = await readFile10(source, "utf8");
26621
26846
  let nodePath;
26622
26847
  try {
26623
26848
  const runtime = JSON.parse(execFileSync(
@@ -26625,16 +26850,16 @@ async function installRecoveryLauncher(paths, forgeBaseUrl, source = new URL("./
26625
26850
  ["-p", 'JSON.stringify({ path: process.execPath, major: Number(process.versions.node.split(".")[0]) })'],
26626
26851
  { encoding: "utf8", timeout: 5e3, windowsHide: true }
26627
26852
  ));
26628
- if (runtime.major < 22 || typeof runtime.major !== "number" || typeof runtime.path !== "string" || !path10.isAbsolute(runtime.path)) throw new Error();
26853
+ if (runtime.major < 22 || typeof runtime.major !== "number" || typeof runtime.path !== "string" || !path11.isAbsolute(runtime.path)) throw new Error();
26629
26854
  nodePath = runtime.path;
26630
26855
  } catch {
26631
26856
  throw new Error("A recupera\xE7\xE3o precisa do Node 22 ou superior j\xE1 previsto na prepara\xE7\xE3o do computador. Pe\xE7a ao respons\xE1vel para verificar a instala\xE7\xE3o.");
26632
26857
  }
26633
26858
  const launcherContent = renderRecoveryLauncher(nodePath, process.platform);
26634
- await writeOwnerOnlyTextAtomic(path10.join(paths.forgeDir, "forge-repair.mjs"), program);
26635
- await writeOwnerOnlyTextAtomic(path10.join(paths.forgeDir, "recovery-origin.json"), JSON.stringify({ forgeBaseUrl }) + "\n");
26859
+ await writeOwnerOnlyTextAtomic(path11.join(paths.forgeDir, "forge-repair.mjs"), program);
26860
+ await writeOwnerOnlyTextAtomic(path11.join(paths.forgeDir, "recovery-origin.json"), JSON.stringify({ forgeBaseUrl }) + "\n");
26636
26861
  const windows = process.platform === "win32";
26637
- const launcher = path10.join(paths.forgeDir, windows ? "Reparar Forge.cmd" : "Reparar Forge.command");
26862
+ const launcher = path11.join(paths.forgeDir, windows ? "Reparar Forge.cmd" : "Reparar Forge.command");
26638
26863
  await writeOwnerOnlyTextAtomic(launcher, launcherContent);
26639
26864
  if (!windows) await chmod5(launcher, 448);
26640
26865
  return launcher;
@@ -26655,15 +26880,15 @@ exec '${nodePath.replace(/'/g, "'\\''")}' ./forge-repair.mjs "$@"
26655
26880
 
26656
26881
  // packages/cli/src/rollback.ts
26657
26882
  import { createHash as createHash6 } from "node:crypto";
26658
- import { chmod as chmod6, mkdir as mkdir6, readFile as readFile10, readdir as readdir5, rename as rename7, rm as rm5, stat as stat2, writeFile as writeFile7 } from "node:fs/promises";
26659
- import path11 from "node:path";
26883
+ import { chmod as chmod6, mkdir as mkdir7, readFile as readFile11, readdir as readdir6, rename as rename8, rm as rm5, stat as stat2, writeFile as writeFile8 } from "node:fs/promises";
26884
+ import path12 from "node:path";
26660
26885
  async function recordRollbackEvidencePlugin(paths, expectedContent) {
26661
26886
  if ((await readRollbackLifecycle(paths))?.state !== "pilot") return;
26662
26887
  const capsule = await readRollbackCapsule(paths);
26663
- const pluginPath = path11.join(paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
26888
+ const pluginPath = path12.join(paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
26664
26889
  const managed = capsule?.managed.files.find((file2) => file2.path === pluginPath);
26665
26890
  if (!capsule || !managed) return;
26666
- const current = await readFile10(pluginPath, "utf8").catch(() => void 0);
26891
+ const current = await readFile11(pluginPath, "utf8").catch(() => void 0);
26667
26892
  if (current !== expectedContent) return;
26668
26893
  const fingerprint = sha2562(Buffer.from(current));
26669
26894
  if (managed.sha256 === fingerprint) return;
@@ -26677,20 +26902,20 @@ async function readRollbackCapsule(paths) {
26677
26902
  return readJson(paths.rollbackCapsulePath);
26678
26903
  }
26679
26904
  async function writeProtectedJsonAtomic(filePath, value) {
26680
- const directory = path11.dirname(filePath);
26681
- await mkdir6(directory, { recursive: true, mode: 448 });
26905
+ const directory = path12.dirname(filePath);
26906
+ await mkdir7(directory, { recursive: true, mode: 448 });
26682
26907
  await protectRollbackPath(directory, "directory");
26683
- const temporary = path11.join(directory, `.${path11.basename(filePath)}.${process.pid}.tmp`);
26684
- await writeFile7(temporary, `${JSON.stringify(value, null, 2)}
26908
+ const temporary = path12.join(directory, `.${path12.basename(filePath)}.${process.pid}.tmp`);
26909
+ await writeFile8(temporary, `${JSON.stringify(value, null, 2)}
26685
26910
  `, { mode: 384 });
26686
26911
  await protectRollbackPath(temporary, "file");
26687
- await rename7(temporary, filePath);
26912
+ await rename8(temporary, filePath);
26688
26913
  }
26689
26914
  async function protectRollbackPath(filePath, kind, options = {}) {
26690
26915
  await protectOwnerOnlyPath(filePath, kind, { ...options, failureContext: "o material de rollback" });
26691
26916
  }
26692
26917
  async function readJson(filePath) {
26693
- const raw = await readFile10(filePath, "utf8").catch((error45) => {
26918
+ const raw = await readFile11(filePath, "utf8").catch((error45) => {
26694
26919
  if (error45.code === "ENOENT") return void 0;
26695
26920
  throw error45;
26696
26921
  });
@@ -26703,11 +26928,17 @@ function sha2562(value) {
26703
26928
 
26704
26929
  // packages/cli/src/localWorkerSync.ts
26705
26930
  async function syncLocalWorker(paths, credentials, manifest) {
26706
- const recovery = await recoverCoreSyncTransaction({ journalPath: path12.join(paths.forgeDir, "core-sync-journal.json") });
26707
- if (recovery.status === "uncertain") throw new CoreSyncUncertainError(recovery.message, recovery.uncertainPaths);
26931
+ const result = await applyManifest(paths, credentials, manifest, {
26932
+ beforeCore: () => prepareLocalStartup(paths, credentials),
26933
+ afterCore: () => removeWellKnownAuth(paths, credentials)
26934
+ });
26935
+ await recordRollbackEvidencePlugin(paths, renderEvidencePlugin());
26936
+ return result;
26937
+ }
26938
+ async function prepareLocalStartup(paths, credentials) {
26708
26939
  let current;
26709
26940
  try {
26710
- current = JSON.parse(await readFile11(paths.opencodeConfigPath, "utf8"));
26941
+ current = JSON.parse(await readFile12(paths.opencodeConfigPath, "utf8"));
26711
26942
  } catch {
26712
26943
  throw new Error("A configura\xE7\xE3o local n\xE3o \xE9 JSON simples v\xE1lido; preserve os ficheiros e pe\xE7a apoio.");
26713
26944
  }
@@ -26719,14 +26950,10 @@ async function syncLocalWorker(paths, credentials, manifest) {
26719
26950
  throw new Error("A configura\xE7\xE3o local foi alterada ou a c\xF3pia v\xE1lida n\xE3o corresponde \xE0 credencial; preserve os ficheiros e pe\xE7a apoio.");
26720
26951
  }
26721
26952
  await installRecoveryLauncher(paths, credentials.forgeBaseUrl);
26722
- const result = await applyManifest(paths, credentials, manifest);
26723
- await removeWellKnownAuth(paths, credentials);
26724
- await recordRollbackEvidencePlugin(paths, renderEvidencePlugin());
26725
- return result;
26726
26953
  }
26727
26954
 
26728
26955
  // packages/cli/src/openworkEngine.ts
26729
- import { lstat as lstat6, readFile as readFile12, realpath } from "node:fs/promises";
26956
+ import { lstat as lstat6, readFile as readFile13, realpath } from "node:fs/promises";
26730
26957
  import path13 from "node:path";
26731
26958
  var OPENWORK_ENGINE_HEADER = "// Minimal Forge OpenWork engine configuration\n";
26732
26959
  async function inspectOpenworkEngineConfig(directory) {
@@ -26737,7 +26964,7 @@ async function inspectOpenworkEngineConfig(directory) {
26737
26964
  if (!generatedEntry.isFile() || generatedEntry.isSymbolicLink()) throw new Error("Preserve a configura\xE7\xE3o do motor; o ficheiro gerado n\xE3o \xE9 regular.");
26738
26965
  let generated;
26739
26966
  try {
26740
- generated = JSON.parse(await readFile12(generatedPath, "utf8"));
26967
+ generated = JSON.parse(await readFile13(generatedPath, "utf8"));
26741
26968
  } catch {
26742
26969
  throw new Error("N\xE3o foi poss\xEDvel reconhecer a configura\xE7\xE3o do motor OpenCode 2.");
26743
26970
  }
@@ -26749,7 +26976,7 @@ async function inspectOpenworkEngineConfig(directory) {
26749
26976
  try {
26750
26977
  const entry = await lstat6(file2);
26751
26978
  if (!entry.isFile() || entry.isSymbolicLink()) throw new Error("Preserve o ficheiro complementar existente; n\xE3o \xE9 um ficheiro regular.");
26752
- content = await readFile12(file2, "utf8");
26979
+ content = await readFile13(file2, "utf8");
26753
26980
  } catch (error45) {
26754
26981
  if (error45.code !== "ENOENT") throw error45;
26755
26982
  }
@@ -26784,8 +27011,127 @@ async function writeOpenworkEngineConfig(directory, config2) {
26784
27011
  return { changed: true };
26785
27012
  }
26786
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
+
26787
27133
  // packages/cli/src/workPackSyncPlugin.ts
26788
- var PLUGIN_VERSION = "0.1.51";
27134
+ var PLUGIN_VERSION = "0.1.54";
26789
27135
  var FORGE_DECISION_TIMEOUT_MS = 11e4;
26790
27136
  var STATUS_FILENAME = "work-pack-startup-status.json";
26791
27137
  var activeSync = /* @__PURE__ */ new Map();
@@ -26813,7 +27159,7 @@ function createForgeTools(forgeBaseUrl, state) {
26813
27159
  function createEvidenceReporters(forgeBaseUrl, state) {
26814
27160
  const reportEvidence = async (sessionID, callID, slug, kind) => {
26815
27161
  const { forgeApiKey } = await readForgeCredentials(state.paths, forgeBaseUrl);
26816
- const credentialId = createHash7("sha256").update(forgeApiKey).digest("hex");
27162
+ const credentialId = createHash8("sha256").update(forgeApiKey).digest("hex");
26817
27163
  const report = skillUsageReporter(forgeBaseUrl, credentialId, (events) => fetch(`${forgeBaseUrl}/sync/evidence`, {
26818
27164
  method: "POST",
26819
27165
  redirect: "error",
@@ -26824,7 +27170,7 @@ function createEvidenceReporters(forgeBaseUrl, state) {
26824
27170
  report(sessionID, callID, slug, kind);
26825
27171
  };
26826
27172
  const reportReasoningLoop = (sessionID, outcome) => {
26827
- reportEvidence(sessionID, `reasoning-loop:${randomUUID4()}`, outcome, "reasoning_loop").catch(() => {
27173
+ reportEvidence(sessionID, `reasoning-loop:${randomUUID5()}`, outcome, "reasoning_loop").catch(() => {
26828
27174
  console.error("[Forge evidence] Reasoning guard identity unavailable; event not queued");
26829
27175
  });
26830
27176
  };
@@ -26832,7 +27178,7 @@ function createEvidenceReporters(forgeBaseUrl, state) {
26832
27178
  const slug = typeof name === "string" ? name.trim().toLowerCase() : "";
26833
27179
  if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) return;
26834
27180
  try {
26835
- await readFile13(path14.join(state.paths.skillsDir, slug, ".forge-version"), "utf8");
27181
+ await readFile15(path15.join(state.paths.skillsDir, slug, ".forge-version"), "utf8");
26836
27182
  } catch {
26837
27183
  return;
26838
27184
  }
@@ -26847,17 +27193,30 @@ function createEvidenceReporters(forgeBaseUrl, state) {
26847
27193
  var ForgeWorkPackSyncServer = async (_input, options) => {
26848
27194
  const forgeBaseUrl = parseForgeBaseUrl(options);
26849
27195
  const state = await startupSync(forgeBaseUrl, isLocalConfig(options), () => observeRuntime(_input), _input);
26850
- const legacyPath = path14.join(state.paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
27196
+ const legacyPath = path15.join(state.paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
26851
27197
  const ownershipSymbol = /* @__PURE__ */ Symbol.for("minimal-forge.legacy-evidence-owners.v1");
26852
27198
  const shared = globalThis;
26853
27199
  const legacyOwners = shared[ownershipSymbol] ??= /* @__PURE__ */ new Set();
26854
27200
  const legacyOwnerKey = JSON.stringify([forgeBaseUrl, legacyPath]);
26855
27201
  const client = reasoningLoopGuardClient(_input);
26856
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();
26857
27205
  return {
26858
27206
  ...client ? { event: createReasoningLoopGuard(client, console.error, reportReasoningLoop) } : {},
26859
- "tool.execute.after": async (input) => {
26860
- 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;
26861
27220
  await reportSkillInvocation(input.sessionID, input.callID, input.args?.name);
26862
27221
  },
26863
27222
  config: async (config2) => {
@@ -26866,10 +27225,10 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
26866
27225
  const name = Array.isArray(entry) ? entry[0] : entry;
26867
27226
  return name === legacyPath || name === pathToFileURL(legacyPath).href;
26868
27227
  });
26869
- const legacy = registered ? await readFile13(legacyPath, "utf8").catch(() => "") : "";
27228
+ const legacy = registered ? await readFile15(legacyPath, "utf8").catch(() => "") : "";
26870
27229
  const oldLegacyRegistered = registered && legacy.startsWith(FORGE_PLUGIN_HEADER) && legacy.includes("work_pack_invocation") && !legacy.includes("minimal-forge.skill-usage.v1");
26871
27230
  if (oldLegacyRegistered) legacyOwners.add(legacyOwnerKey);
26872
- if (oldLegacyRegistered) await writeFile8(legacyPath, renderEvidencePlugin()).catch(() => {
27231
+ if (oldLegacyRegistered) await writeFile9(legacyPath, renderEvidencePlugin()).catch(() => {
26873
27232
  console.error("[Forge evidence] Legacy hook upgrade failed; existing hook retained");
26874
27233
  });
26875
27234
  await projectCurrentExtensions(config2, state);
@@ -26887,11 +27246,11 @@ async function ForgeWorkPackSyncSetup(ctx) {
26887
27246
  const directory = ctx.options.openworkEngineConfigDir;
26888
27247
  if (typeof directory === "string" && state.manifest) {
26889
27248
  const active = process.env.OPENCODE_CONFIG_DIR;
26890
- if (!active || await realpath2(active) !== await realpath2(directory)) {
27249
+ if (!active || await realpath3(active) !== await realpath3(directory)) {
26891
27250
  throw new Error("A pasta do motor ativo mudou. Confirme a liga\xE7\xE3o Forge neste perfil do OpenWork.");
26892
27251
  }
26893
27252
  const credentials = await readForgeCredentials(state.paths, forgeBaseUrl);
26894
- const canonical = objectRecord2(parseJsonc(await readFile13(state.paths.opencodeConfigPath, "utf8")));
27253
+ const canonical = objectRecord2(parseJsonc(await readFile15(state.paths.opencodeConfigPath, "utf8")));
26895
27254
  const config2 = renderOpenworkEngineConfig(state.manifest, credentials, state.paths, directory, canonical);
26896
27255
  if (state.partialWorkPackSync) {
26897
27256
  const companion = await inspectOpenworkEngineConfig(directory);
@@ -26907,6 +27266,10 @@ async function ForgeWorkPackSyncSetup(ctx) {
26907
27266
  });
26908
27267
  syncedTools.catch(() => void 0);
26909
27268
  const { reportReasoningLoop, reportSkillInvocation } = createEvidenceReporters(forgeBaseUrl, { paths });
27269
+ const managedSkills = sync.then(
27270
+ (state) => managedSkillSession(paths, state.manifest ?? state.failedManifest),
27271
+ () => managedSkillSession(paths)
27272
+ );
26910
27273
  const directoryOf = sessionDirectoryResolver(ctx);
26911
27274
  const registrations = Object.entries(createForgeTools(forgeBaseUrl, { paths, decisionBaseUrl: forgeBaseUrl })).filter(([name]) => name !== "forge_feedback").map(([name, shape]) => openCode2Tool(name, {
26912
27275
  description: shape.description,
@@ -26920,10 +27283,18 @@ async function ForgeWorkPackSyncSetup(ctx) {
26920
27283
  await ctx.tool.transform((editor) => {
26921
27284
  for (const registration of registrations) editor.add(registration);
26922
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
+ });
26923
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;
26924
27296
  try {
26925
- const call = completedSkillCall(event);
26926
- if (call) await reportSkillInvocation(call.sessionID, call.callID, call.name);
27297
+ await reportSkillInvocation(call.sessionID, call.callID, call.name);
26927
27298
  } catch {
26928
27299
  console.error("[Forge evidence] Invocation could not be reported");
26929
27300
  }
@@ -26946,10 +27317,10 @@ function createForgeImageTool(forgeBaseUrl, gatewayBaseUrl, paths) {
26946
27317
  referencePath: tool.schema.string().optional().describe("Caminho absoluto de uma imagem PNG, JPEG ou WebP a editar, at\xE9 2,5 MB")
26947
27318
  },
26948
27319
  async execute(args, context) {
26949
- const requestId = randomUUID4();
27320
+ const requestId = randomUUID5();
26950
27321
  let referenceDataUrl;
26951
27322
  if (args.referencePath) {
26952
- const bytes = await readFile13(args.referencePath);
27323
+ const bytes = await readFile15(args.referencePath);
26953
27324
  if (bytes.byteLength > 25e5) throw new Error("A imagem de refer\xEAncia \xE9 demasiado grande. Reduza-a antes de tentar novamente.");
26954
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;
26955
27326
  if (!mime) throw new Error("A refer\xEAncia tem de ser PNG, JPEG ou WebP.");
@@ -26975,14 +27346,14 @@ function createForgeImageTool(forgeBaseUrl, gatewayBaseUrl, paths) {
26975
27346
  if (image.byteLength > 8 * 1024 * 1024 || !image.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
26976
27347
  throw new Error(`O PNG recebido \xE9 inv\xE1lido. Refer\xEAncia: ${requestId}`);
26977
27348
  }
26978
- const destination = path14.join(context.directory, `forge-image-${requestId}.png`);
26979
- await writeFile8(destination, image, { flag: "wx" });
27349
+ const destination = path15.join(context.directory, `forge-image-${requestId}.png`);
27350
+ await writeFile9(destination, image, { flag: "wx" });
26980
27351
  const reset = body.quota && new Intl.DateTimeFormat("pt-PT", { dateStyle: "long", timeZone: "Europe/Lisbon" }).format(new Date(body.quota.resetsAt));
26981
27352
  const remaining = body.quota ? ` Restam ${body.quota.remaining} imagens at\xE9 ${reset}.` : "";
26982
27353
  return {
26983
27354
  title: "Imagem criada",
26984
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.`,
26985
- 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) }]
26986
27357
  };
26987
27358
  }
26988
27359
  });
@@ -27024,9 +27395,9 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
27024
27395
  let requestBody;
27025
27396
  if (fromFile) {
27026
27397
  const file2 = await fileInsideWorkspace(context.directory, args.request_file);
27027
- const planFile = path14.join(path14.dirname(path14.dirname(file2)), "plan.json");
27028
- if (!responseDirectory && path14.basename(path14.dirname(file2)) === "requests" && await fileExists(planFile)) {
27029
- const plan = JSON.parse(await readFile13(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"));
27030
27401
  if (plan?.engine === "jev-batch" && plan.model === "typesafe/jev-1.13" && Array.isArray(plan.batches)) {
27031
27402
  let batch;
27032
27403
  for (const candidate of plan.batches) {
@@ -27039,7 +27410,7 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
27039
27410
  return createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths).execute({ plan_file: planFile, batch_id: batch.batch_id }, context);
27040
27411
  }
27041
27412
  }
27042
- const raw = await readFile13(file2, "utf8");
27413
+ const raw = await readFile15(file2, "utf8");
27043
27414
  if (Buffer.byteLength(raw) > 512 * 1024) throw new Error("O ficheiro de pedido excede 512 KiB.");
27044
27415
  let parsed;
27045
27416
  try {
@@ -27058,13 +27429,13 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
27058
27429
  if (args.state === void 0 || !args.questions || Object.keys(args.questions).length === 0) throw new Error("Indica state e questions.");
27059
27430
  requestBody = { state: args.state, questions: args.questions };
27060
27431
  }
27061
- const responseDir = await mkdtemp2(path14.join(responseDirectory ?? context.directory, ".forge-decision-"));
27062
- 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");
27063
27434
  try {
27064
27435
  const credentials = await readForgeCredentials(paths, forgeBaseUrl);
27065
- const probeFile = path14.join(responseDir, ".write-test");
27066
- await writeFile8(probeFile, "", { flag: "wx", mode: 384 });
27067
- await unlink(probeFile);
27436
+ const probeFile = path15.join(responseDir, ".write-test");
27437
+ await writeFile9(probeFile, "", { flag: "wx", mode: 384 });
27438
+ await unlink2(probeFile);
27068
27439
  context.abort.throwIfAborted();
27069
27440
  await beforeCall?.(responseFile);
27070
27441
  const response = await fetch(`${decisionBaseUrl}/v1/decisions`, {
@@ -27085,7 +27456,7 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
27085
27456
  }
27086
27457
  if (response.ok && body && typeof body === "object" && body.answers && typeof body.answers === "object") {
27087
27458
  try {
27088
- await writeFile8(responseFile, raw, { flag: "wx", mode: 384 });
27459
+ await writeFile9(responseFile, raw, { flag: "wx", mode: 384 });
27089
27460
  return JSON.stringify({ ...body, response_file: responseFile }, null, 2);
27090
27461
  } catch (error45) {
27091
27462
  return JSON.stringify({
@@ -27105,16 +27476,16 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
27105
27476
  }
27106
27477
  throw new Error(safeError);
27107
27478
  } finally {
27108
- await rmdir(responseDir).catch(() => void 0);
27479
+ await rmdir2(responseDir).catch(() => void 0);
27109
27480
  }
27110
27481
  }
27111
27482
  });
27112
27483
  }
27113
27484
  async function fileInsideWorkspace(directory, candidate) {
27114
- const workspace = await realpath2(directory);
27115
- const file2 = await realpath2(path14.resolve(workspace, candidate));
27116
- const relative = path14.relative(workspace, file2);
27117
- 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.");
27118
27489
  return file2;
27119
27490
  }
27120
27491
  async function fileExists(candidate) {
@@ -27126,10 +27497,10 @@ async function fileExists(candidate) {
27126
27497
  throw error45;
27127
27498
  }
27128
27499
  }
27129
- async function ensureJevDirectory(directory, filesystem = { stat: stat3, mkdir: mkdir7 }) {
27500
+ async function ensureJevDirectory(directory, filesystem = { stat: stat3, mkdir: mkdir8 }) {
27130
27501
  try {
27131
27502
  if ((await filesystem.stat(directory)).isDirectory()) return;
27132
- 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.`);
27133
27504
  } catch (error45) {
27134
27505
  if (error45.code !== "ENOENT") throw error45;
27135
27506
  }
@@ -27148,19 +27519,36 @@ function canonicalJson(value) {
27148
27519
  }
27149
27520
  return JSON.stringify(value);
27150
27521
  }
27151
- async function validateSavedDecision(file2, request) {
27152
- const body = JSON.parse(await readFile13(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"));
27153
27536
  const answers = body.answers;
27154
27537
  const questions = request.questions;
27155
27538
  const usage = body.usage;
27156
- 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
+ })) {
27157
27545
  throw new Error("Resposta Jev guardada inv\xE1lida; preservar o ficheiro e verificar antes de continuar.");
27158
27546
  }
27159
27547
  return body;
27160
27548
  }
27161
27549
  async function acquireJevRunLock(lockDir) {
27162
27550
  try {
27163
- await mkdir7(lockDir);
27551
+ await mkdir8(lockDir);
27164
27552
  return {};
27165
27553
  } catch (error45) {
27166
27554
  if (error45.code !== "EEXIST") throw error45;
@@ -27168,7 +27556,7 @@ async function acquireJevRunLock(lockDir) {
27168
27556
  let owner;
27169
27557
  let ownerRaw;
27170
27558
  try {
27171
- ownerRaw = await readFile13(path14.join(lockDir, "owner.json"), "utf8");
27559
+ ownerRaw = await readFile15(path15.join(lockDir, "owner.json"), "utf8");
27172
27560
  owner = JSON.parse(ownerRaw);
27173
27561
  } catch {
27174
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.");
@@ -27180,10 +27568,10 @@ async function acquireJevRunLock(lockDir) {
27180
27568
  process.kill(owner.pid, 0);
27181
27569
  } catch (error45) {
27182
27570
  if (error45.code === "ESRCH") {
27183
- const archived = `${lockDir}.interrupted-${createHash7("sha256").update(ownerRaw).digest("hex")}`;
27184
- await rename8(lockDir, archived);
27571
+ const archived = `${lockDir}.interrupted-${createHash8("sha256").update(ownerRaw).digest("hex")}`;
27572
+ await rename9(lockDir, archived);
27185
27573
  try {
27186
- await mkdir7(lockDir);
27574
+ await mkdir8(lockDir);
27187
27575
  } catch {
27188
27576
  throw new Error("Este plano j\xE1 est\xE1 em execu\xE7\xE3o; a recupera\xE7\xE3o ficou preservada.");
27189
27577
  }
@@ -27202,56 +27590,79 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27202
27590
  },
27203
27591
  async execute(args, context) {
27204
27592
  const planFile = await fileInsideWorkspace(context.directory, args.plan_file);
27205
- if (path14.basename(planFile) !== "plan.json" || path14.basename(path14.dirname(planFile)) !== "jev") throw new Error("Indica o ficheiro jev/plan.json.");
27206
- const runDir = path14.dirname(path14.dirname(planFile));
27207
- const plan = JSON.parse(await readFile13(planFile, "utf8"));
27208
- if (plan.engine !== "jev-batch" || plan.model !== "typesafe/jev-1.13" || !Array.isArray(plan.batches)) throw new Error("O plano Jev \xE9 inv\xE1lido.");
27209
- 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);
27210
27606
  const batches = args.batch_id ? allBatches.filter((batch) => batch.batch_id === args.batch_id) : allBatches;
27211
27607
  if (args.batch_id && batches.length !== 1) throw new Error("O lote indicado n\xE3o pertence ao plano Jev.");
27212
- const responsePath = path14.join(runDir, "jev", "responses");
27608
+ const responsePath = path15.join(runDir, "jev", "responses");
27213
27609
  await ensureJevDirectory(responsePath);
27214
27610
  const responseDir = await fileInsideWorkspace(context.directory, responsePath);
27215
- if (path14.dirname(responseDir) !== path14.join(runDir, "jev")) throw new Error("A pasta de respostas tem de pertencer ao run Jev.");
27216
- 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");
27217
27613
  const interrupted = await acquireJevRunLock(lockDir);
27218
27614
  let saved = 0;
27219
27615
  let skipped = 0;
27220
27616
  let recovered = 0;
27221
27617
  const repeated = [];
27222
27618
  try {
27223
- const ownerFile = path14.join(lockDir, "owner.json");
27619
+ const ownerFile = path15.join(lockDir, "owner.json");
27224
27620
  await writeOwnerOnlyTextAtomic(ownerFile, JSON.stringify({ ...interrupted, pid: process.pid, hostname: os5.hostname(), started_at: (/* @__PURE__ */ new Date()).toISOString() }));
27225
- const attemptsPath = path14.join(runDir, "jev", "attempts");
27621
+ const attemptsPath = path15.join(runDir, "jev", "attempts");
27226
27622
  await ensureJevDirectory(attemptsPath);
27227
27623
  const attemptsDir = await fileInsideWorkspace(context.directory, attemptsPath);
27228
- 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.");
27229
27625
  for (const batch of batches) {
27230
27626
  context.abort.throwIfAborted();
27231
27627
  const batchId = batch.batch_id;
27232
- 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") {
27233
27630
  throw new Error("O plano Jev cont\xE9m um lote inv\xE1lido.");
27234
27631
  }
27235
- const acceptedFile = path14.join(runDir, "jev", "accepted", `${batchId}.json`);
27236
- 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`);
27237
27634
  const requestFile = await fileInsideWorkspace(context.directory, batch.request_file);
27238
- if (path14.dirname(requestFile) !== path14.join(runDir, "jev", "requests")) throw new Error(`${batchId}: pedido fora do run.`);
27239
- const request = JSON.parse(await readFile13(requestFile, "utf8"));
27240
- 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");
27241
27643
  if (fingerprint !== batch.request_fingerprint) throw new Error(`${batchId}: fingerprint do pedido n\xE3o corresponde ao plano.`);
27242
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
+ }
27243
27654
  skipped++;
27244
27655
  continue;
27245
27656
  }
27246
27657
  if (await fileExists(responseFile)) {
27247
- const body = await validateSavedDecision(await fileInsideWorkspace(context.directory, responseFile), request);
27658
+ const body = await validateSavedDecision(await fileInsideWorkspace(context.directory, responseFile), request, smallPlan);
27248
27659
  if (args.batch_id) return JSON.stringify({ ...body, response_file: responseFile });
27249
27660
  skipped++;
27250
27661
  continue;
27251
27662
  }
27252
- const attemptsFile = path14.join(attemptsDir, `${batchId}.json`);
27663
+ const attemptsFile = path15.join(attemptsDir, `${batchId}.json`);
27253
27664
  let attempts = { request_fingerprint: fingerprint, attempts: 0, response_files: [] };
27254
- if (await fileExists(attemptsFile)) attempts = JSON.parse(await readFile13(attemptsFile, "utf8"));
27665
+ if (await fileExists(attemptsFile)) attempts = JSON.parse(await readFile15(attemptsFile, "utf8"));
27255
27666
  else if (interrupted.batch_id === batchId) {
27256
27667
  if (interrupted.request_fingerprint !== fingerprint) throw new Error(`${batchId}: fingerprint da chamada interrompida n\xE3o corresponde ao plano.`);
27257
27668
  attempts.attempts = 1;
@@ -27264,15 +27675,15 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27264
27675
  if (!await fileExists(attemptsFile) && attempts.attempts > 0) await persistAttempts();
27265
27676
  const stop = (error45, detail = {}) => JSON.stringify({ verified: false, saved, skipped, recovered, repeated, stopped_at: batchId, ...detail, error: error45 });
27266
27677
  const recoverResponse = async () => {
27267
- const legacyAllocations = interrupted.batch_id === batchId && interrupted.request_fingerprint === fingerprint ? (await readdir6(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")) : [];
27268
27679
  const candidates = [...attempts.response_files, ...legacyAllocations];
27269
27680
  for (const candidate of new Set(candidates)) {
27270
27681
  if (typeof candidate !== "string") throw new Error("Registo de recupera\xE7\xE3o inv\xE1lido.");
27271
27682
  if (!await fileExists(candidate)) continue;
27272
27683
  const file2 = await fileInsideWorkspace(context.directory, candidate);
27273
- 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.");
27274
27685
  try {
27275
- await validateSavedDecision(file2, request);
27686
+ await validateSavedDecision(file2, request, smallPlan);
27276
27687
  } catch {
27277
27688
  continue;
27278
27689
  }
@@ -27299,7 +27710,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27299
27710
  });
27300
27711
  let result;
27301
27712
  try {
27302
- result = JSON.parse(await decide.execute({ request_file: requestFile }, context));
27713
+ result = JSON.parse(await decide.execute({ state: request.state, questions }, context));
27303
27714
  } catch (error45) {
27304
27715
  if (error45 instanceof ForgeDecisionRejectedError) {
27305
27716
  attempts.attempts = previousAttempts;
@@ -27318,7 +27729,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27318
27729
  if (typeof result.response_file !== "string") return stop(String(result.persistence_error), { recovery_response: result, persistence_code: result.persistence_code });
27319
27730
  source = result.response_file;
27320
27731
  try {
27321
- await validateSavedDecision(source, request);
27732
+ await validateSavedDecision(source, request, smallPlan);
27322
27733
  } catch (error45) {
27323
27734
  return stop(error45 instanceof Error ? error45.message : "Resposta inv\xE1lida.", { recovery_file: source });
27324
27735
  }
@@ -27329,7 +27740,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27329
27740
  let identical = false;
27330
27741
  if (error45.code === "EEXIST") {
27331
27742
  try {
27332
- identical = await readFile13(source, "utf8") === await readFile13(responseFile, "utf8");
27743
+ identical = await readFile15(source, "utf8") === await readFile15(responseFile, "utf8");
27333
27744
  } catch {
27334
27745
  }
27335
27746
  }
@@ -27337,9 +27748,9 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27337
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 });
27338
27749
  }
27339
27750
  }
27340
- await unlink(source).then(() => rmdir(path14.dirname(source))).catch(() => void 0);
27751
+ await unlink2(source).then(() => rmdir2(path15.dirname(source))).catch(() => void 0);
27341
27752
  saved++;
27342
- 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 });
27343
27754
  }
27344
27755
  return JSON.stringify({
27345
27756
  verified: true,
@@ -27349,7 +27760,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27349
27760
  recovered,
27350
27761
  repeated,
27351
27762
  response_dir: responseDir,
27352
- 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."
27353
27764
  });
27354
27765
  } finally {
27355
27766
  await rm6(lockDir, { recursive: true });
@@ -27395,6 +27806,8 @@ function createForgeFeedbackTool(forgeBaseUrl, paths) {
27395
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")
27396
27807
  },
27397
27808
  async execute(args, context) {
27809
+ await context.ask({ permission: "forge_feedback", patterns: [args.kind], always: [], metadata: {} });
27810
+ context.abort.throwIfAborted();
27398
27811
  const credentials = await readForgeCredentials(paths, forgeBaseUrl);
27399
27812
  const response = await fetch(`${forgeBaseUrl}/sync/feedback`, {
27400
27813
  method: "POST",
@@ -27423,17 +27836,18 @@ async function synchronizeAtStartup(forgeBaseUrl, observe, localConfig, input) {
27423
27836
  let appliedLocalSync;
27424
27837
  let pluginUpdate;
27425
27838
  let decisionBaseUrl = forgeBaseUrl;
27839
+ let manifest;
27426
27840
  const runtime = await observe();
27427
27841
  try {
27428
27842
  await retireDebugCapture(paths);
27429
27843
  credentials = await readForgeCredentials(paths, forgeBaseUrl);
27430
- const manifest = await fetchManifest(credentials, PLUGIN_VERSION);
27844
+ manifest = await fetchManifest(credentials, PLUGIN_VERSION);
27431
27845
  decisionBaseUrl = resolveDecisionBaseUrl(manifest.gatewayBaseUrl, forgeBaseUrl);
27432
27846
  forgeConfigVerified = true;
27433
27847
  const result = localConfig ? await syncLocalWorker(paths, credentials, manifest) : await applyWorkPackManifest(paths, credentials, manifest, {});
27434
27848
  if (localConfig) {
27435
27849
  appliedLocalSync = { manifest, partialWorkPackSync: result };
27436
- const config2 = objectRecord2(parseJsonc(await readFile13(paths.opencodeConfigPath, "utf8")));
27850
+ const config2 = objectRecord2(parseJsonc(await readFile15(paths.opencodeConfigPath, "utf8")));
27437
27851
  const targetVersion = configuredWorkPackSyncPluginVersion(config2);
27438
27852
  if (targetVersion) pluginUpdate = { targetVersion, restartRequired: targetVersion !== PLUGIN_VERSION };
27439
27853
  if (pluginUpdate?.restartRequired) {
@@ -27480,12 +27894,12 @@ async function synchronizeAtStartup(forgeBaseUrl, observe, localConfig, input) {
27480
27894
  decisionBaseUrl = await savedGatewayBaseUrl(paths, credentials, forgeBaseUrl) ?? decisionBaseUrl;
27481
27895
  }
27482
27896
  const after = await managedProjectionNames(paths).catch(() => before);
27483
- return { paths, before, after, forgeConfigVerified, decisionBaseUrl, ...appliedLocalSync };
27897
+ return { paths, before, after, forgeConfigVerified, decisionBaseUrl, failedManifest: manifest, ...appliedLocalSync };
27484
27898
  }
27485
27899
  }
27486
27900
  async function savedGatewayBaseUrl(paths, credentials, forgeBaseUrl) {
27487
27901
  try {
27488
- const config2 = objectRecord2(parseJsonc(await readFile13(paths.opencodeConfigPath, "utf8")));
27902
+ const config2 = objectRecord2(parseJsonc(await readFile15(paths.opencodeConfigPath, "utf8")));
27489
27903
  const options = objectRecord2(objectRecord2(objectRecord2(config2.provider).forge).options);
27490
27904
  if (options.apiKey !== credentials.forgeApiKey || typeof options.baseURL !== "string" || !options.baseURL.endsWith("/v1")) return void 0;
27491
27905
  const origin = options.baseURL.slice(0, -"/v1".length);
@@ -27510,7 +27924,7 @@ function resolveStartupPaths() {
27510
27924
  return resolvePaths(void 0, void 0, env);
27511
27925
  }
27512
27926
  async function readForgeCredentials(paths, forgeBaseUrl) {
27513
- const raw = await readFile13(paths.opencodeAuthPath, "utf8").catch((error45) => {
27927
+ const raw = await readFile15(paths.opencodeAuthPath, "utf8").catch((error45) => {
27514
27928
  if (error45.code === "ENOENT") return void 0;
27515
27929
  throw error45;
27516
27930
  });
@@ -27554,12 +27968,12 @@ function objectRecord2(value) {
27554
27968
  return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
27555
27969
  }
27556
27970
  async function writeStatus(paths, value) {
27557
- await mkdir7(paths.forgeDir, { recursive: true });
27558
- const target = path14.join(paths.forgeDir, STATUS_FILENAME);
27559
- const temporary = path14.join(paths.forgeDir, `.${STATUS_FILENAME}.${process.pid}.tmp`);
27560
- await writeFile8(temporary, `${JSON.stringify(value, null, 2)}
27971
+ await mkdir8(paths.forgeDir, { recursive: true });
27972
+ const target = path15.join(paths.forgeDir, STATUS_FILENAME);
27973
+ const temporary = path15.join(paths.forgeDir, `.${STATUS_FILENAME}.${process.pid}.tmp`);
27974
+ await writeFile9(temporary, `${JSON.stringify(value, null, 2)}
27561
27975
  `, { mode: 384 });
27562
- await rename8(temporary, target);
27976
+ await rename9(temporary, target);
27563
27977
  }
27564
27978
  function safeErrorMessage(error45) {
27565
27979
  const message = error45 instanceof Error ? error45.message : "erro desconhecido";