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

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