@defend-tech/opencode-optima 0.1.83 → 0.1.85

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -108,17 +108,17 @@ var require_visit = __commonJS({
108
108
  visit.BREAK = BREAK;
109
109
  visit.SKIP = SKIP;
110
110
  visit.REMOVE = REMOVE;
111
- function visit_(key, node, visitor, path19) {
112
- const ctrl = callVisitor(key, node, visitor, path19);
111
+ function visit_(key, node, visitor, path22) {
112
+ const ctrl = callVisitor(key, node, visitor, path22);
113
113
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
114
- replaceNode(key, path19, ctrl);
115
- return visit_(key, ctrl, visitor, path19);
114
+ replaceNode(key, path22, ctrl);
115
+ return visit_(key, ctrl, visitor, path22);
116
116
  }
117
117
  if (typeof ctrl !== "symbol") {
118
118
  if (identity.isCollection(node)) {
119
- path19 = Object.freeze(path19.concat(node));
119
+ path22 = Object.freeze(path22.concat(node));
120
120
  for (let i = 0; i < node.items.length; ++i) {
121
- const ci = visit_(i, node.items[i], visitor, path19);
121
+ const ci = visit_(i, node.items[i], visitor, path22);
122
122
  if (typeof ci === "number")
123
123
  i = ci - 1;
124
124
  else if (ci === BREAK)
@@ -129,13 +129,13 @@ var require_visit = __commonJS({
129
129
  }
130
130
  }
131
131
  } else if (identity.isPair(node)) {
132
- path19 = Object.freeze(path19.concat(node));
133
- const ck = visit_("key", node.key, visitor, path19);
132
+ path22 = Object.freeze(path22.concat(node));
133
+ const ck = visit_("key", node.key, visitor, path22);
134
134
  if (ck === BREAK)
135
135
  return BREAK;
136
136
  else if (ck === REMOVE)
137
137
  node.key = null;
138
- const cv = visit_("value", node.value, visitor, path19);
138
+ const cv = visit_("value", node.value, visitor, path22);
139
139
  if (cv === BREAK)
140
140
  return BREAK;
141
141
  else if (cv === REMOVE)
@@ -156,17 +156,17 @@ var require_visit = __commonJS({
156
156
  visitAsync.BREAK = BREAK;
157
157
  visitAsync.SKIP = SKIP;
158
158
  visitAsync.REMOVE = REMOVE;
159
- async function visitAsync_(key, node, visitor, path19) {
160
- const ctrl = await callVisitor(key, node, visitor, path19);
159
+ async function visitAsync_(key, node, visitor, path22) {
160
+ const ctrl = await callVisitor(key, node, visitor, path22);
161
161
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
162
- replaceNode(key, path19, ctrl);
163
- return visitAsync_(key, ctrl, visitor, path19);
162
+ replaceNode(key, path22, ctrl);
163
+ return visitAsync_(key, ctrl, visitor, path22);
164
164
  }
165
165
  if (typeof ctrl !== "symbol") {
166
166
  if (identity.isCollection(node)) {
167
- path19 = Object.freeze(path19.concat(node));
167
+ path22 = Object.freeze(path22.concat(node));
168
168
  for (let i = 0; i < node.items.length; ++i) {
169
- const ci = await visitAsync_(i, node.items[i], visitor, path19);
169
+ const ci = await visitAsync_(i, node.items[i], visitor, path22);
170
170
  if (typeof ci === "number")
171
171
  i = ci - 1;
172
172
  else if (ci === BREAK)
@@ -177,13 +177,13 @@ var require_visit = __commonJS({
177
177
  }
178
178
  }
179
179
  } else if (identity.isPair(node)) {
180
- path19 = Object.freeze(path19.concat(node));
181
- const ck = await visitAsync_("key", node.key, visitor, path19);
180
+ path22 = Object.freeze(path22.concat(node));
181
+ const ck = await visitAsync_("key", node.key, visitor, path22);
182
182
  if (ck === BREAK)
183
183
  return BREAK;
184
184
  else if (ck === REMOVE)
185
185
  node.key = null;
186
- const cv = await visitAsync_("value", node.value, visitor, path19);
186
+ const cv = await visitAsync_("value", node.value, visitor, path22);
187
187
  if (cv === BREAK)
188
188
  return BREAK;
189
189
  else if (cv === REMOVE)
@@ -210,23 +210,23 @@ var require_visit = __commonJS({
210
210
  }
211
211
  return visitor;
212
212
  }
213
- function callVisitor(key, node, visitor, path19) {
213
+ function callVisitor(key, node, visitor, path22) {
214
214
  if (typeof visitor === "function")
215
- return visitor(key, node, path19);
215
+ return visitor(key, node, path22);
216
216
  if (identity.isMap(node))
217
- return visitor.Map?.(key, node, path19);
217
+ return visitor.Map?.(key, node, path22);
218
218
  if (identity.isSeq(node))
219
- return visitor.Seq?.(key, node, path19);
219
+ return visitor.Seq?.(key, node, path22);
220
220
  if (identity.isPair(node))
221
- return visitor.Pair?.(key, node, path19);
221
+ return visitor.Pair?.(key, node, path22);
222
222
  if (identity.isScalar(node))
223
- return visitor.Scalar?.(key, node, path19);
223
+ return visitor.Scalar?.(key, node, path22);
224
224
  if (identity.isAlias(node))
225
- return visitor.Alias?.(key, node, path19);
225
+ return visitor.Alias?.(key, node, path22);
226
226
  return void 0;
227
227
  }
228
- function replaceNode(key, path19, node) {
229
- const parent = path19[path19.length - 1];
228
+ function replaceNode(key, path22, node) {
229
+ const parent = path22[path22.length - 1];
230
230
  if (identity.isCollection(parent)) {
231
231
  parent.items[key] = node;
232
232
  } else if (identity.isPair(parent)) {
@@ -834,10 +834,10 @@ var require_Collection = __commonJS({
834
834
  var createNode = require_createNode();
835
835
  var identity = require_identity();
836
836
  var Node = require_Node();
837
- function collectionFromPath(schema, path19, value) {
837
+ function collectionFromPath(schema, path22, value) {
838
838
  let v = value;
839
- for (let i = path19.length - 1; i >= 0; --i) {
840
- const k = path19[i];
839
+ for (let i = path22.length - 1; i >= 0; --i) {
840
+ const k = path22[i];
841
841
  if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
842
842
  const a = [];
843
843
  a[k] = v;
@@ -856,7 +856,7 @@ var require_Collection = __commonJS({
856
856
  sourceObjects: /* @__PURE__ */ new Map()
857
857
  });
858
858
  }
859
- var isEmptyPath = (path19) => path19 == null || typeof path19 === "object" && !!path19[Symbol.iterator]().next().done;
859
+ var isEmptyPath = (path22) => path22 == null || typeof path22 === "object" && !!path22[Symbol.iterator]().next().done;
860
860
  var Collection = class extends Node.NodeBase {
861
861
  constructor(type, schema) {
862
862
  super(type);
@@ -886,11 +886,11 @@ var require_Collection = __commonJS({
886
886
  * be a Pair instance or a `{ key, value }` object, which may not have a key
887
887
  * that already exists in the map.
888
888
  */
889
- addIn(path19, value) {
890
- if (isEmptyPath(path19))
889
+ addIn(path22, value) {
890
+ if (isEmptyPath(path22))
891
891
  this.add(value);
892
892
  else {
893
- const [key, ...rest] = path19;
893
+ const [key, ...rest] = path22;
894
894
  const node = this.get(key, true);
895
895
  if (identity.isCollection(node))
896
896
  node.addIn(rest, value);
@@ -904,8 +904,8 @@ var require_Collection = __commonJS({
904
904
  * Removes a value from the collection.
905
905
  * @returns `true` if the item was found and removed.
906
906
  */
907
- deleteIn(path19) {
908
- const [key, ...rest] = path19;
907
+ deleteIn(path22) {
908
+ const [key, ...rest] = path22;
909
909
  if (rest.length === 0)
910
910
  return this.delete(key);
911
911
  const node = this.get(key, true);
@@ -919,8 +919,8 @@ var require_Collection = __commonJS({
919
919
  * scalar values from their surrounding node; to disable set `keepScalar` to
920
920
  * `true` (collections are always returned intact).
921
921
  */
922
- getIn(path19, keepScalar) {
923
- const [key, ...rest] = path19;
922
+ getIn(path22, keepScalar) {
923
+ const [key, ...rest] = path22;
924
924
  const node = this.get(key, true);
925
925
  if (rest.length === 0)
926
926
  return !keepScalar && identity.isScalar(node) ? node.value : node;
@@ -938,8 +938,8 @@ var require_Collection = __commonJS({
938
938
  /**
939
939
  * Checks if the collection includes a value with the key `key`.
940
940
  */
941
- hasIn(path19) {
942
- const [key, ...rest] = path19;
941
+ hasIn(path22) {
942
+ const [key, ...rest] = path22;
943
943
  if (rest.length === 0)
944
944
  return this.has(key);
945
945
  const node = this.get(key, true);
@@ -949,8 +949,8 @@ var require_Collection = __commonJS({
949
949
  * Sets a value in this collection. For `!!set`, `value` needs to be a
950
950
  * boolean to add/remove the item from the set.
951
951
  */
952
- setIn(path19, value) {
953
- const [key, ...rest] = path19;
952
+ setIn(path22, value) {
953
+ const [key, ...rest] = path22;
954
954
  if (rest.length === 0) {
955
955
  this.set(key, value);
956
956
  } else {
@@ -3454,9 +3454,9 @@ var require_Document = __commonJS({
3454
3454
  this.contents.add(value);
3455
3455
  }
3456
3456
  /** Adds a value to the document. */
3457
- addIn(path19, value) {
3457
+ addIn(path22, value) {
3458
3458
  if (assertCollection(this.contents))
3459
- this.contents.addIn(path19, value);
3459
+ this.contents.addIn(path22, value);
3460
3460
  }
3461
3461
  /**
3462
3462
  * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
@@ -3531,14 +3531,14 @@ var require_Document = __commonJS({
3531
3531
  * Removes a value from the document.
3532
3532
  * @returns `true` if the item was found and removed.
3533
3533
  */
3534
- deleteIn(path19) {
3535
- if (Collection.isEmptyPath(path19)) {
3534
+ deleteIn(path22) {
3535
+ if (Collection.isEmptyPath(path22)) {
3536
3536
  if (this.contents == null)
3537
3537
  return false;
3538
3538
  this.contents = null;
3539
3539
  return true;
3540
3540
  }
3541
- return assertCollection(this.contents) ? this.contents.deleteIn(path19) : false;
3541
+ return assertCollection(this.contents) ? this.contents.deleteIn(path22) : false;
3542
3542
  }
3543
3543
  /**
3544
3544
  * Returns item at `key`, or `undefined` if not found. By default unwraps
@@ -3553,10 +3553,10 @@ var require_Document = __commonJS({
3553
3553
  * scalar values from their surrounding node; to disable set `keepScalar` to
3554
3554
  * `true` (collections are always returned intact).
3555
3555
  */
3556
- getIn(path19, keepScalar) {
3557
- if (Collection.isEmptyPath(path19))
3556
+ getIn(path22, keepScalar) {
3557
+ if (Collection.isEmptyPath(path22))
3558
3558
  return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
3559
- return identity.isCollection(this.contents) ? this.contents.getIn(path19, keepScalar) : void 0;
3559
+ return identity.isCollection(this.contents) ? this.contents.getIn(path22, keepScalar) : void 0;
3560
3560
  }
3561
3561
  /**
3562
3562
  * Checks if the document includes a value with the key `key`.
@@ -3567,10 +3567,10 @@ var require_Document = __commonJS({
3567
3567
  /**
3568
3568
  * Checks if the document includes a value at `path`.
3569
3569
  */
3570
- hasIn(path19) {
3571
- if (Collection.isEmptyPath(path19))
3570
+ hasIn(path22) {
3571
+ if (Collection.isEmptyPath(path22))
3572
3572
  return this.contents !== void 0;
3573
- return identity.isCollection(this.contents) ? this.contents.hasIn(path19) : false;
3573
+ return identity.isCollection(this.contents) ? this.contents.hasIn(path22) : false;
3574
3574
  }
3575
3575
  /**
3576
3576
  * Sets a value in this document. For `!!set`, `value` needs to be a
@@ -3587,13 +3587,13 @@ var require_Document = __commonJS({
3587
3587
  * Sets a value in this document. For `!!set`, `value` needs to be a
3588
3588
  * boolean to add/remove the item from the set.
3589
3589
  */
3590
- setIn(path19, value) {
3591
- if (Collection.isEmptyPath(path19)) {
3590
+ setIn(path22, value) {
3591
+ if (Collection.isEmptyPath(path22)) {
3592
3592
  this.contents = value;
3593
3593
  } else if (this.contents == null) {
3594
- this.contents = Collection.collectionFromPath(this.schema, Array.from(path19), value);
3594
+ this.contents = Collection.collectionFromPath(this.schema, Array.from(path22), value);
3595
3595
  } else if (assertCollection(this.contents)) {
3596
- this.contents.setIn(path19, value);
3596
+ this.contents.setIn(path22, value);
3597
3597
  }
3598
3598
  }
3599
3599
  /**
@@ -5545,9 +5545,9 @@ var require_cst_visit = __commonJS({
5545
5545
  visit.BREAK = BREAK;
5546
5546
  visit.SKIP = SKIP;
5547
5547
  visit.REMOVE = REMOVE;
5548
- visit.itemAtPath = (cst, path19) => {
5548
+ visit.itemAtPath = (cst, path22) => {
5549
5549
  let item = cst;
5550
- for (const [field, index] of path19) {
5550
+ for (const [field, index] of path22) {
5551
5551
  const tok = item?.[field];
5552
5552
  if (tok && "items" in tok) {
5553
5553
  item = tok.items[index];
@@ -5556,23 +5556,23 @@ var require_cst_visit = __commonJS({
5556
5556
  }
5557
5557
  return item;
5558
5558
  };
5559
- visit.parentCollection = (cst, path19) => {
5560
- const parent = visit.itemAtPath(cst, path19.slice(0, -1));
5561
- const field = path19[path19.length - 1][0];
5559
+ visit.parentCollection = (cst, path22) => {
5560
+ const parent = visit.itemAtPath(cst, path22.slice(0, -1));
5561
+ const field = path22[path22.length - 1][0];
5562
5562
  const coll = parent?.[field];
5563
5563
  if (coll && "items" in coll)
5564
5564
  return coll;
5565
5565
  throw new Error("Parent collection not found");
5566
5566
  };
5567
- function _visit(path19, item, visitor) {
5568
- let ctrl = visitor(item, path19);
5567
+ function _visit(path22, item, visitor) {
5568
+ let ctrl = visitor(item, path22);
5569
5569
  if (typeof ctrl === "symbol")
5570
5570
  return ctrl;
5571
5571
  for (const field of ["key", "value"]) {
5572
5572
  const token = item[field];
5573
5573
  if (token && "items" in token) {
5574
5574
  for (let i = 0; i < token.items.length; ++i) {
5575
- const ci = _visit(Object.freeze(path19.concat([[field, i]])), token.items[i], visitor);
5575
+ const ci = _visit(Object.freeze(path22.concat([[field, i]])), token.items[i], visitor);
5576
5576
  if (typeof ci === "number")
5577
5577
  i = ci - 1;
5578
5578
  else if (ci === BREAK)
@@ -5583,10 +5583,10 @@ var require_cst_visit = __commonJS({
5583
5583
  }
5584
5584
  }
5585
5585
  if (typeof ctrl === "function" && field === "key")
5586
- ctrl = ctrl(item, path19);
5586
+ ctrl = ctrl(item, path22);
5587
5587
  }
5588
5588
  }
5589
- return typeof ctrl === "function" ? ctrl(item, path19) : ctrl;
5589
+ return typeof ctrl === "function" ? ctrl(item, path22) : ctrl;
5590
5590
  }
5591
5591
  exports.visit = visit;
5592
5592
  }
@@ -6871,14 +6871,14 @@ var require_parser = __commonJS({
6871
6871
  case "scalar":
6872
6872
  case "single-quoted-scalar":
6873
6873
  case "double-quoted-scalar": {
6874
- const fs18 = this.flowScalar(this.type);
6874
+ const fs21 = this.flowScalar(this.type);
6875
6875
  if (atNextItem || it.value) {
6876
- map.items.push({ start, key: fs18, sep: [] });
6876
+ map.items.push({ start, key: fs21, sep: [] });
6877
6877
  this.onKeyLine = true;
6878
6878
  } else if (it.sep) {
6879
- this.stack.push(fs18);
6879
+ this.stack.push(fs21);
6880
6880
  } else {
6881
- Object.assign(it, { key: fs18, sep: [] });
6881
+ Object.assign(it, { key: fs21, sep: [] });
6882
6882
  this.onKeyLine = true;
6883
6883
  }
6884
6884
  return;
@@ -7006,13 +7006,13 @@ var require_parser = __commonJS({
7006
7006
  case "scalar":
7007
7007
  case "single-quoted-scalar":
7008
7008
  case "double-quoted-scalar": {
7009
- const fs18 = this.flowScalar(this.type);
7009
+ const fs21 = this.flowScalar(this.type);
7010
7010
  if (!it || it.value)
7011
- fc.items.push({ start: [], key: fs18, sep: [] });
7011
+ fc.items.push({ start: [], key: fs21, sep: [] });
7012
7012
  else if (it.sep)
7013
- this.stack.push(fs18);
7013
+ this.stack.push(fs21);
7014
7014
  else
7015
- Object.assign(it, { key: fs18, sep: [] });
7015
+ Object.assign(it, { key: fs21, sep: [] });
7016
7016
  return;
7017
7017
  }
7018
7018
  case "flow-map-end":
@@ -7550,17 +7550,17 @@ var require_ignore = __commonJS({
7550
7550
  var throwError = (message, Ctor) => {
7551
7551
  throw new Ctor(message);
7552
7552
  };
7553
- var checkPath = (path19, originalPath, doThrow) => {
7554
- if (!isString(path19)) {
7553
+ var checkPath = (path22, originalPath, doThrow) => {
7554
+ if (!isString(path22)) {
7555
7555
  return doThrow(
7556
7556
  `path must be a string, but got \`${originalPath}\``,
7557
7557
  TypeError
7558
7558
  );
7559
7559
  }
7560
- if (!path19) {
7560
+ if (!path22) {
7561
7561
  return doThrow(`path must not be empty`, TypeError);
7562
7562
  }
7563
- if (checkPath.isNotRelative(path19)) {
7563
+ if (checkPath.isNotRelative(path22)) {
7564
7564
  const r = "`path.relative()`d";
7565
7565
  return doThrow(
7566
7566
  `path should be a ${r} string, but got "${originalPath}"`,
@@ -7569,7 +7569,7 @@ var require_ignore = __commonJS({
7569
7569
  }
7570
7570
  return true;
7571
7571
  };
7572
- var isNotRelative = (path19) => REGEX_TEST_INVALID_PATH.test(path19);
7572
+ var isNotRelative = (path22) => REGEX_TEST_INVALID_PATH.test(path22);
7573
7573
  checkPath.isNotRelative = isNotRelative;
7574
7574
  checkPath.convert = (p) => p;
7575
7575
  var Ignore = class {
@@ -7628,7 +7628,7 @@ var require_ignore = __commonJS({
7628
7628
  // setting `checkUnignored` to `false` could reduce additional
7629
7629
  // path matching.
7630
7630
  // @returns {TestResult} true if a file is ignored
7631
- _testOne(path19, checkUnignored) {
7631
+ _testOne(path22, checkUnignored) {
7632
7632
  let ignored = false;
7633
7633
  let unignored = false;
7634
7634
  this._rules.forEach((rule) => {
@@ -7636,7 +7636,7 @@ var require_ignore = __commonJS({
7636
7636
  if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
7637
7637
  return;
7638
7638
  }
7639
- const matched = rule.regex.test(path19);
7639
+ const matched = rule.regex.test(path22);
7640
7640
  if (matched) {
7641
7641
  ignored = !negative;
7642
7642
  unignored = negative;
@@ -7649,24 +7649,24 @@ var require_ignore = __commonJS({
7649
7649
  }
7650
7650
  // @returns {TestResult}
7651
7651
  _test(originalPath, cache, checkUnignored, slices) {
7652
- const path19 = originalPath && checkPath.convert(originalPath);
7652
+ const path22 = originalPath && checkPath.convert(originalPath);
7653
7653
  checkPath(
7654
- path19,
7654
+ path22,
7655
7655
  originalPath,
7656
7656
  this._allowRelativePaths ? RETURN_FALSE : throwError
7657
7657
  );
7658
- return this._t(path19, cache, checkUnignored, slices);
7658
+ return this._t(path22, cache, checkUnignored, slices);
7659
7659
  }
7660
- _t(path19, cache, checkUnignored, slices) {
7661
- if (path19 in cache) {
7662
- return cache[path19];
7660
+ _t(path22, cache, checkUnignored, slices) {
7661
+ if (path22 in cache) {
7662
+ return cache[path22];
7663
7663
  }
7664
7664
  if (!slices) {
7665
- slices = path19.split(SLASH);
7665
+ slices = path22.split(SLASH);
7666
7666
  }
7667
7667
  slices.pop();
7668
7668
  if (!slices.length) {
7669
- return cache[path19] = this._testOne(path19, checkUnignored);
7669
+ return cache[path22] = this._testOne(path22, checkUnignored);
7670
7670
  }
7671
7671
  const parent = this._t(
7672
7672
  slices.join(SLASH) + SLASH,
@@ -7674,24 +7674,24 @@ var require_ignore = __commonJS({
7674
7674
  checkUnignored,
7675
7675
  slices
7676
7676
  );
7677
- return cache[path19] = parent.ignored ? parent : this._testOne(path19, checkUnignored);
7677
+ return cache[path22] = parent.ignored ? parent : this._testOne(path22, checkUnignored);
7678
7678
  }
7679
- ignores(path19) {
7680
- return this._test(path19, this._ignoreCache, false).ignored;
7679
+ ignores(path22) {
7680
+ return this._test(path22, this._ignoreCache, false).ignored;
7681
7681
  }
7682
7682
  createFilter() {
7683
- return (path19) => !this.ignores(path19);
7683
+ return (path22) => !this.ignores(path22);
7684
7684
  }
7685
7685
  filter(paths) {
7686
7686
  return makeArray(paths).filter(this.createFilter());
7687
7687
  }
7688
7688
  // @returns {TestResult}
7689
- test(path19) {
7690
- return this._test(path19, this._testCache, true);
7689
+ test(path22) {
7690
+ return this._test(path22, this._testCache, true);
7691
7691
  }
7692
7692
  };
7693
7693
  var factory = (options) => new Ignore(options);
7694
- var isPathValid = (path19) => checkPath(path19 && checkPath.convert(path19), path19, RETURN_FALSE);
7694
+ var isPathValid = (path22) => checkPath(path22 && checkPath.convert(path22), path22, RETURN_FALSE);
7695
7695
  factory.isPathValid = isPathValid;
7696
7696
  factory.default = factory;
7697
7697
  module.exports = factory;
@@ -7702,16 +7702,16 @@ var require_ignore = __commonJS({
7702
7702
  const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
7703
7703
  checkPath.convert = makePosix;
7704
7704
  const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
7705
- checkPath.isNotRelative = (path19) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path19) || isNotRelative(path19);
7705
+ checkPath.isNotRelative = (path22) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path22) || isNotRelative(path22);
7706
7706
  }
7707
7707
  }
7708
7708
  });
7709
7709
 
7710
7710
  // src/plugin.js
7711
- import fs17 from "node:fs";
7711
+ import fs20 from "node:fs";
7712
7712
  var import_yaml6 = __toESM(require_dist(), 1);
7713
7713
  var import_ignore3 = __toESM(require_ignore(), 1);
7714
- import path18 from "node:path";
7714
+ import path21 from "node:path";
7715
7715
  import { tool } from "@opencode-ai/plugin/tool";
7716
7716
 
7717
7717
  // src/agents.js
@@ -9955,8 +9955,8 @@ function clickUpWebhookLogPath(worktree) {
9955
9955
  return path7.join(optimaRuntimeDir(worktree), "clickup-webhook.log.jsonl");
9956
9956
  }
9957
9957
  function clickUpWebhookAuditLogDir() {
9958
- const dataHome = process.env.XDG_DATA_HOME && path7.isAbsolute(process.env.XDG_DATA_HOME) ? process.env.XDG_DATA_HOME : path7.join(os2.homedir(), ".local", "share", "opencode");
9959
- return path7.join(dataHome, "opencode-optima");
9958
+ const dataHome2 = process.env.XDG_DATA_HOME && path7.isAbsolute(process.env.XDG_DATA_HOME) ? process.env.XDG_DATA_HOME : path7.join(os2.homedir(), ".local", "share", "opencode");
9959
+ return path7.join(dataHome2, "opencode-optima");
9960
9960
  }
9961
9961
  function clickUpWebhookAuditLogPath(at = /* @__PURE__ */ new Date(), logDir = clickUpWebhookAuditLogDir()) {
9962
9962
  return path7.join(logDir, `clickup-webhook-${at.toISOString().slice(0, 10)}.jsonl`);
@@ -13499,11 +13499,668 @@ function createGitHubApiClient(config = {}, fetchImpl = globalThis.fetch) {
13499
13499
  };
13500
13500
  }
13501
13501
 
13502
+ // src/qa/chrome.js
13503
+ import fs17 from "node:fs";
13504
+ import os6 from "node:os";
13505
+ import path18 from "node:path";
13506
+
13507
+ // src/qa/cdp.js
13508
+ import fs15 from "node:fs";
13509
+ import path16 from "node:path";
13510
+ var DEFAULT_CDP_URL = "http://127.0.0.1:9222";
13511
+ function normalizeBaseUrl(cdpUrl = "") {
13512
+ return String(cdpUrl || process.env.OPTIMA_QA_CHROME_CDP_URL || DEFAULT_CDP_URL).trim().replace(/\/+$/, "");
13513
+ }
13514
+ async function cdpJson(baseUrl, route, options = {}) {
13515
+ const response = await fetch(`${baseUrl}${route}`, options);
13516
+ if (!response.ok) throw new Error(`cdp_http_${response.status}: ${route}`);
13517
+ return response.json();
13518
+ }
13519
+ async function listCdpTargets({ cdpUrl = "" } = {}) {
13520
+ const baseUrl = normalizeBaseUrl(cdpUrl);
13521
+ return cdpJson(baseUrl, "/json/list");
13522
+ }
13523
+ async function cdpBrowserStatus({ cdpUrl = "", clickupTaskId = "", qaWindowName: qaWindowName2 = null } = {}) {
13524
+ const targets = await listCdpTargets({ cdpUrl });
13525
+ const pages = [];
13526
+ for (let index = 0; index < targets.length; index += 1) {
13527
+ const target = targets[index];
13528
+ if (target.type !== "page") continue;
13529
+ let windowName = "";
13530
+ if (target.webSocketDebuggerUrl) {
13531
+ const session = await CdpSession.connect(target.webSocketDebuggerUrl).catch(() => null);
13532
+ if (session) {
13533
+ try {
13534
+ const evaluated = await session.evaluate("window.name || ''");
13535
+ windowName = String(evaluated?.value || "");
13536
+ } finally {
13537
+ session.close();
13538
+ }
13539
+ }
13540
+ }
13541
+ pages.push({
13542
+ index,
13543
+ id: target.id,
13544
+ role: index === 0 ? "persistent_session_tab" : qaWindowName2 && windowName === qaWindowName2(clickupTaskId) ? "qa_task_tab" : "other",
13545
+ url: target.url,
13546
+ title: target.title || "",
13547
+ windowName
13548
+ });
13549
+ }
13550
+ return { ok: true, pages, serviceWorkers: targets.filter((target) => target.type === "service_worker").map((target) => target.url) };
13551
+ }
13552
+ var CdpSession = class _CdpSession {
13553
+ constructor(ws) {
13554
+ this.ws = ws;
13555
+ this.nextId = 1;
13556
+ this.pending = /* @__PURE__ */ new Map();
13557
+ this.ws.addEventListener("message", (event) => this.handleMessage(event));
13558
+ this.ws.addEventListener("close", () => this.rejectAll(new Error("cdp_websocket_closed")));
13559
+ this.ws.addEventListener("error", () => this.rejectAll(new Error("cdp_websocket_error")));
13560
+ }
13561
+ static connect(wsUrl, { timeoutMs = 1e4 } = {}) {
13562
+ return new Promise((resolve, reject) => {
13563
+ const ws = new WebSocket(wsUrl);
13564
+ const timer = setTimeout(() => {
13565
+ try {
13566
+ ws.close();
13567
+ } catch {
13568
+ }
13569
+ reject(new Error("cdp_websocket_connect_timeout"));
13570
+ }, timeoutMs);
13571
+ ws.addEventListener("open", () => {
13572
+ clearTimeout(timer);
13573
+ resolve(new _CdpSession(ws));
13574
+ }, { once: true });
13575
+ ws.addEventListener("error", () => {
13576
+ clearTimeout(timer);
13577
+ reject(new Error("cdp_websocket_connect_failed"));
13578
+ }, { once: true });
13579
+ });
13580
+ }
13581
+ handleMessage(event) {
13582
+ let message = null;
13583
+ try {
13584
+ message = JSON.parse(event.data);
13585
+ } catch {
13586
+ return;
13587
+ }
13588
+ if (!message?.id || !this.pending.has(message.id)) return;
13589
+ const pending = this.pending.get(message.id);
13590
+ this.pending.delete(message.id);
13591
+ clearTimeout(pending.timer);
13592
+ if (message.error) pending.reject(new Error(`${message.error.message || "cdp_error"}${message.error.data ? `: ${message.error.data}` : ""}`));
13593
+ else pending.resolve(message.result || {});
13594
+ }
13595
+ rejectAll(error) {
13596
+ for (const pending of this.pending.values()) {
13597
+ clearTimeout(pending.timer);
13598
+ pending.reject(error);
13599
+ }
13600
+ this.pending.clear();
13601
+ }
13602
+ send(method, params = {}, { timeoutMs = 3e4 } = {}) {
13603
+ const id = this.nextId;
13604
+ this.nextId += 1;
13605
+ return new Promise((resolve, reject) => {
13606
+ const timer = setTimeout(() => {
13607
+ this.pending.delete(id);
13608
+ reject(new Error(`cdp_command_timeout: ${method}`));
13609
+ }, timeoutMs);
13610
+ this.pending.set(id, { resolve, reject, timer });
13611
+ this.ws.send(JSON.stringify({ id, method, params }));
13612
+ });
13613
+ }
13614
+ async evaluate(expression, { timeoutMs = 3e4 } = {}) {
13615
+ const result = await this.send("Runtime.evaluate", {
13616
+ expression,
13617
+ awaitPromise: true,
13618
+ returnByValue: true
13619
+ }, { timeoutMs });
13620
+ if (result.exceptionDetails) throw new Error(result.exceptionDetails.text || "runtime_evaluate_failed");
13621
+ return result.result || null;
13622
+ }
13623
+ close() {
13624
+ try {
13625
+ this.ws.close();
13626
+ } catch {
13627
+ }
13628
+ }
13629
+ };
13630
+ async function newCdpTarget({ cdpUrl = "", startUrl = "about:blank" } = {}) {
13631
+ const baseUrl = normalizeBaseUrl(cdpUrl);
13632
+ return cdpJson(baseUrl, `/json/new?${encodeURIComponent(startUrl)}`, { method: "PUT" });
13633
+ }
13634
+ async function targetWindowName(target) {
13635
+ if (!target.webSocketDebuggerUrl) return "";
13636
+ const session = await CdpSession.connect(target.webSocketDebuggerUrl);
13637
+ try {
13638
+ const value = await session.evaluate("window.name || ''");
13639
+ return String(value?.value || "");
13640
+ } finally {
13641
+ session.close();
13642
+ }
13643
+ }
13644
+ async function ensureCdpQaTarget({ cdpUrl = "", clickupTaskId = "", startUrl = "about:blank", qaWindowName: qaWindowName2 } = {}) {
13645
+ const expected = qaWindowName2(clickupTaskId);
13646
+ const targets = (await listCdpTargets({ cdpUrl })).filter((target2) => target2.type === "page");
13647
+ for (let index = 1; index < targets.length; index += 1) {
13648
+ if (await targetWindowName(targets[index]).catch(() => "") === expected) return targets[index];
13649
+ }
13650
+ const target = await newCdpTarget({ cdpUrl, startUrl });
13651
+ const session = await CdpSession.connect(target.webSocketDebuggerUrl);
13652
+ try {
13653
+ await session.evaluate(`window.name = ${JSON.stringify(expected)}`);
13654
+ } finally {
13655
+ session.close();
13656
+ }
13657
+ return target;
13658
+ }
13659
+ function parseCdpCommand(commandJson = "") {
13660
+ if (!String(commandJson || "").trim()) return { action: "status" };
13661
+ try {
13662
+ const parsed = JSON.parse(commandJson);
13663
+ return parsed && typeof parsed === "object" ? parsed : { action: "invalid" };
13664
+ } catch {
13665
+ return { action: "script", script: String(commandJson || "") };
13666
+ }
13667
+ }
13668
+ async function pageSnapshot(session) {
13669
+ const evaluated = await session.evaluate("({ url: location.href, title: document.title })");
13670
+ return evaluated?.value || { url: "", title: "" };
13671
+ }
13672
+ async function cdpRunChromeCommand({ cdpUrl = "", clickupTaskId = "", commandJson = "", startUrl = "about:blank", artifactsDir, qaWindowName: qaWindowName2 } = {}) {
13673
+ const command = parseCdpCommand(commandJson);
13674
+ const target = await ensureCdpQaTarget({ cdpUrl, clickupTaskId, startUrl, qaWindowName: qaWindowName2 });
13675
+ const session = await CdpSession.connect(target.webSocketDebuggerUrl);
13676
+ try {
13677
+ const action = String(command.action || "status").toLowerCase();
13678
+ let result = null;
13679
+ if (action === "status") {
13680
+ result = { ok: true, page: await pageSnapshot(session) };
13681
+ } else if (action === "goto") {
13682
+ await session.send("Page.enable");
13683
+ await session.send("Page.navigate", { url: String(command.url || startUrl || "about:blank") });
13684
+ if (command.wait_ms !== false) await new Promise((resolve) => setTimeout(resolve, Number(command.wait_ms || 1e3)));
13685
+ result = { ok: true, page: await pageSnapshot(session) };
13686
+ } else if (action === "evaluate") {
13687
+ const evaluated = await session.evaluate(String(command.expression || "undefined"), { timeoutMs: Number(command.timeout_ms || 3e4) });
13688
+ result = { ok: true, result: evaluated?.value ?? evaluated };
13689
+ } else if (action === "screenshot") {
13690
+ await session.send("Page.enable");
13691
+ const captured = await session.send("Page.captureScreenshot", { format: command.format || "png", captureBeyondViewport: command.full_page !== false });
13692
+ const name = String(command.name || `screenshot-${Date.now()}.png`).replace(/[^a-zA-Z0-9._-]+/g, "-");
13693
+ const outPath = path16.join(artifactsDir, name);
13694
+ fs15.mkdirSync(path16.dirname(outPath), { recursive: true });
13695
+ fs15.writeFileSync(outPath, Buffer.from(captured.data || "", "base64"));
13696
+ result = { ok: true, path: outPath };
13697
+ } else if (action === "script") {
13698
+ const script = String(command.script || "");
13699
+ if (!script.trim()) return { ok: false, error: "script_required" };
13700
+ const cdp = { send: (method, params = {}, options = {}) => session.send(method, params, options), evaluate: (expression, options = {}) => session.evaluate(expression, options) };
13701
+ const fn = new Function("cdp", "target", "artifactsDir", "command", `return (async () => {
13702
+ ${script}
13703
+ })()`);
13704
+ result = { ok: true, result: await fn(cdp, target, artifactsDir, command) };
13705
+ } else {
13706
+ result = { ok: false, error: `unsupported_cdp_command_action: ${action}` };
13707
+ }
13708
+ return {
13709
+ ok: result.ok !== false,
13710
+ command: command.action || "script",
13711
+ tab: { windowName: qaWindowName2(clickupTaskId), ...await pageSnapshot(session) },
13712
+ artifactsDir,
13713
+ result,
13714
+ transport: "cdp"
13715
+ };
13716
+ } finally {
13717
+ session.close();
13718
+ }
13719
+ }
13720
+ async function cdpPrepareExtension({ cdpUrl = "", extensionId = "", reset = true, reload = true } = {}) {
13721
+ const targets = await listCdpTargets({ cdpUrl });
13722
+ const normalized = String(extensionId || "").trim();
13723
+ const worker = targets.find((target) => target.type === "service_worker" && (!normalized || String(target.url || "").startsWith(`chrome-extension://${normalized}/`)));
13724
+ if (!worker?.webSocketDebuggerUrl) return { ok: false, error: "extension_service_worker_not_found", serviceWorkers: targets.filter((target) => target.type === "service_worker").map((target) => target.url) };
13725
+ const session = await CdpSession.connect(worker.webSocketDebuggerUrl);
13726
+ try {
13727
+ let resetResult = { ok: true, skipped: true };
13728
+ let reloadResult = { ok: true, skipped: true };
13729
+ if (reset) {
13730
+ const evaluated = await session.evaluate(`(async () => {
13731
+ const deletedCaches = [];
13732
+ const deletedDbs = [];
13733
+ if (globalThis.chrome?.storage?.local) await chrome.storage.local.clear();
13734
+ if (globalThis.chrome?.storage?.session?.clear) await chrome.storage.session.clear();
13735
+ if (globalThis.chrome?.storage?.sync) await chrome.storage.sync.clear();
13736
+ if (globalThis.caches?.keys) {
13737
+ for (const name of await caches.keys()) {
13738
+ await caches.delete(name);
13739
+ deletedCaches.push(name);
13740
+ }
13741
+ }
13742
+ if (globalThis.indexedDB?.databases) {
13743
+ for (const db of await indexedDB.databases()) {
13744
+ if (db.name) {
13745
+ indexedDB.deleteDatabase(db.name);
13746
+ deletedDbs.push(db.name);
13747
+ }
13748
+ }
13749
+ }
13750
+ return { ok: true, deletedCaches, deletedDbs };
13751
+ })()`);
13752
+ resetResult = evaluated?.value || { ok: true };
13753
+ }
13754
+ if (reload) {
13755
+ await session.evaluate("chrome.runtime.reload()");
13756
+ reloadResult = { ok: true };
13757
+ }
13758
+ return { ok: true, reset: resetResult, reload: reloadResult };
13759
+ } finally {
13760
+ session.close();
13761
+ }
13762
+ }
13763
+
13764
+ // src/qa/queue.js
13765
+ import fs16 from "node:fs";
13766
+ import os5 from "node:os";
13767
+ import path17 from "node:path";
13768
+ var DEFAULT_QA_LEASE_MS = 5 * 60 * 1e3;
13769
+ var DEFAULT_QA_PROVIDER = "chatgpt";
13770
+ function dataHome() {
13771
+ return process.env.XDG_DATA_HOME && path17.isAbsolute(process.env.XDG_DATA_HOME) ? process.env.XDG_DATA_HOME : path17.join(os5.homedir(), ".local", "share", "opencode");
13772
+ }
13773
+ function qaRuntimeDir() {
13774
+ return path17.join(dataHome(), "opencode-optima", "qa");
13775
+ }
13776
+ function normalizeQaProvider(provider = DEFAULT_QA_PROVIDER) {
13777
+ const normalized = String(provider || DEFAULT_QA_PROVIDER).trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "-");
13778
+ return normalized || DEFAULT_QA_PROVIDER;
13779
+ }
13780
+ function qaQueueStatePath(provider = DEFAULT_QA_PROVIDER) {
13781
+ return path17.join(qaRuntimeDir(), `${normalizeQaProvider(provider)}-queue.json`);
13782
+ }
13783
+ function nowIso(now = /* @__PURE__ */ new Date()) {
13784
+ return now instanceof Date ? now.toISOString() : new Date(now).toISOString();
13785
+ }
13786
+ function normalizeClickUpTaskId(value = "") {
13787
+ return String(value || "").trim();
13788
+ }
13789
+ function emptyQaQueueState(provider = DEFAULT_QA_PROVIDER) {
13790
+ return {
13791
+ provider: normalizeQaProvider(provider),
13792
+ active: null,
13793
+ queue: [],
13794
+ history: []
13795
+ };
13796
+ }
13797
+ function readQaQueueState(provider = DEFAULT_QA_PROVIDER, statePath = qaQueueStatePath(provider)) {
13798
+ try {
13799
+ const raw = fs16.readFileSync(statePath, "utf8");
13800
+ const parsed = JSON.parse(raw);
13801
+ if (!isPlainObject(parsed)) return emptyQaQueueState(provider);
13802
+ return {
13803
+ ...emptyQaQueueState(provider),
13804
+ ...parsed,
13805
+ provider: normalizeQaProvider(parsed.provider || provider),
13806
+ queue: Array.isArray(parsed.queue) ? parsed.queue.filter(isPlainObject) : [],
13807
+ history: Array.isArray(parsed.history) ? parsed.history.filter(isPlainObject).slice(-50) : []
13808
+ };
13809
+ } catch {
13810
+ return emptyQaQueueState(provider);
13811
+ }
13812
+ }
13813
+ function writeQaQueueState(state, statePath = qaQueueStatePath(state?.provider)) {
13814
+ const normalized = {
13815
+ ...emptyQaQueueState(state?.provider),
13816
+ ...state,
13817
+ provider: normalizeQaProvider(state?.provider),
13818
+ queue: Array.isArray(state?.queue) ? state.queue.filter(isPlainObject) : [],
13819
+ history: Array.isArray(state?.history) ? state.history.filter(isPlainObject).slice(-50) : []
13820
+ };
13821
+ fs16.mkdirSync(path17.dirname(statePath), { recursive: true });
13822
+ fs16.writeFileSync(statePath, `${JSON.stringify(normalized, null, 2)}
13823
+ `, { mode: 384 });
13824
+ return normalized;
13825
+ }
13826
+ function activeExpired(active, nowMs, leaseMs) {
13827
+ if (!active?.clickupTaskId) return false;
13828
+ const last = Date.parse(active.lastActivityAt || active.grantedAt || "");
13829
+ return Number.isFinite(last) && nowMs - last > leaseMs;
13830
+ }
13831
+ function queuedIndex(state, clickupTaskId) {
13832
+ return state.queue.findIndex((entry) => entry.clickupTaskId === clickupTaskId);
13833
+ }
13834
+ function queueEntry({ clickupTaskId, sessionId = "", worktree = "", reason = "", now = /* @__PURE__ */ new Date() } = {}) {
13835
+ return {
13836
+ clickupTaskId,
13837
+ sessionId: String(sessionId || "").trim(),
13838
+ worktree: String(worktree || "").trim(),
13839
+ reason: String(reason || "").trim(),
13840
+ queuedAt: nowIso(now),
13841
+ lastRequestAt: nowIso(now)
13842
+ };
13843
+ }
13844
+ function activeEntry({ provider, clickupTaskId, sessionId = "", worktree = "", leaseMs = DEFAULT_QA_LEASE_MS, now = /* @__PURE__ */ new Date() } = {}) {
13845
+ return {
13846
+ provider: normalizeQaProvider(provider),
13847
+ clickupTaskId,
13848
+ sessionId: String(sessionId || "").trim(),
13849
+ worktree: String(worktree || "").trim(),
13850
+ grantedAt: nowIso(now),
13851
+ lastActivityAt: nowIso(now),
13852
+ leaseMs
13853
+ };
13854
+ }
13855
+ function releaseExpiredQaSlot(state, { now = /* @__PURE__ */ new Date(), leaseMs = DEFAULT_QA_LEASE_MS } = {}) {
13856
+ const normalized = { ...emptyQaQueueState(state?.provider), ...state, queue: Array.isArray(state?.queue) ? [...state.queue] : [] };
13857
+ if (!activeExpired(normalized.active, now.getTime(), leaseMs)) return { state: normalized, expired: null, promoted: null };
13858
+ const expired = normalized.active;
13859
+ normalized.history = [...normalized.history || [], { action: "expired", clickupTaskId: expired.clickupTaskId, at: nowIso(now) }].slice(-50);
13860
+ normalized.active = null;
13861
+ const promoted = normalized.queue.shift() || null;
13862
+ if (promoted) {
13863
+ normalized.active = activeEntry({ ...promoted, provider: normalized.provider, leaseMs, now });
13864
+ normalized.history = [...normalized.history || [], { action: "promoted", clickupTaskId: promoted.clickupTaskId, at: nowIso(now), reason: "expired_previous_slot" }].slice(-50);
13865
+ }
13866
+ return { state: normalized, expired, promoted };
13867
+ }
13868
+ function requestQaSlot(state, { clickupTaskId, sessionId = "", worktree = "", reason = "", now = /* @__PURE__ */ new Date(), leaseMs = DEFAULT_QA_LEASE_MS } = {}) {
13869
+ const taskId = normalizeClickUpTaskId(clickupTaskId);
13870
+ if (!taskId) return { state, ok: false, action: "invalid", reason: "clickup_task_id_required" };
13871
+ let next = { ...emptyQaQueueState(state?.provider), ...state, queue: Array.isArray(state?.queue) ? [...state.queue] : [] };
13872
+ const expiredResult = releaseExpiredQaSlot(next, { now, leaseMs });
13873
+ next = expiredResult.state;
13874
+ if (!next.active) {
13875
+ next.active = activeEntry({ provider: next.provider, clickupTaskId: taskId, sessionId, worktree, leaseMs, now });
13876
+ next.queue = next.queue.filter((entry) => entry.clickupTaskId !== taskId);
13877
+ next.history = [...next.history || [], { action: "granted", clickupTaskId: taskId, at: nowIso(now) }].slice(-50);
13878
+ return { state: next, ok: true, action: "granted", active: next.active, expired: expiredResult.expired, promoted: expiredResult.promoted };
13879
+ }
13880
+ if (next.active.clickupTaskId === taskId) {
13881
+ next.active = { ...next.active, sessionId: sessionId || next.active.sessionId || "", worktree: worktree || next.active.worktree || "", lastActivityAt: nowIso(now), leaseMs };
13882
+ next.history = [...next.history || [], { action: "renewed", clickupTaskId: taskId, at: nowIso(now) }].slice(-50);
13883
+ return { state: next, ok: true, action: "granted_existing", active: next.active, expired: expiredResult.expired, promoted: expiredResult.promoted };
13884
+ }
13885
+ const index = queuedIndex(next, taskId);
13886
+ if (index >= 0) {
13887
+ next.queue[index] = { ...next.queue[index], sessionId: sessionId || next.queue[index].sessionId || "", worktree: worktree || next.queue[index].worktree || "", reason: reason || next.queue[index].reason || "", lastRequestAt: nowIso(now) };
13888
+ } else {
13889
+ next.queue.push(queueEntry({ clickupTaskId: taskId, sessionId, worktree, reason, now }));
13890
+ }
13891
+ return {
13892
+ state: next,
13893
+ ok: false,
13894
+ action: "queued",
13895
+ active: next.active,
13896
+ position: queuedIndex(next, taskId) + 1,
13897
+ expired: expiredResult.expired,
13898
+ promoted: expiredResult.promoted
13899
+ };
13900
+ }
13901
+ function touchQaSlot(state, { clickupTaskId, now = /* @__PURE__ */ new Date(), leaseMs = DEFAULT_QA_LEASE_MS } = {}) {
13902
+ const taskId = normalizeClickUpTaskId(clickupTaskId);
13903
+ let next = { ...emptyQaQueueState(state?.provider), ...state, queue: Array.isArray(state?.queue) ? [...state.queue] : [] };
13904
+ const expiredResult = releaseExpiredQaSlot(next, { now, leaseMs });
13905
+ next = expiredResult.state;
13906
+ if (!next.active || next.active.clickupTaskId !== taskId) return { state: next, ok: false, action: "not_active_holder", active: next.active, expired: expiredResult.expired, promoted: expiredResult.promoted };
13907
+ next.active = { ...next.active, lastActivityAt: nowIso(now), leaseMs };
13908
+ return { state: next, ok: true, action: "touched", active: next.active, expired: expiredResult.expired, promoted: expiredResult.promoted };
13909
+ }
13910
+ function finishQaSlot(state, { clickupTaskId, now = /* @__PURE__ */ new Date(), leaseMs = DEFAULT_QA_LEASE_MS } = {}) {
13911
+ const taskId = normalizeClickUpTaskId(clickupTaskId);
13912
+ let next = { ...emptyQaQueueState(state?.provider), ...state, queue: Array.isArray(state?.queue) ? [...state.queue] : [] };
13913
+ const expiredResult = releaseExpiredQaSlot(next, { now, leaseMs });
13914
+ next = expiredResult.state;
13915
+ if (!next.active || next.active.clickupTaskId !== taskId) return { state: next, ok: false, action: "not_active_holder", active: next.active, expired: expiredResult.expired, promoted: expiredResult.promoted };
13916
+ const released = next.active;
13917
+ next.active = null;
13918
+ next.history = [...next.history || [], { action: "finished", clickupTaskId: taskId, at: nowIso(now) }].slice(-50);
13919
+ const promoted = next.queue.shift() || null;
13920
+ if (promoted) {
13921
+ next.active = activeEntry({ ...promoted, provider: next.provider, leaseMs, now });
13922
+ next.history = [...next.history || [], { action: "promoted", clickupTaskId: promoted.clickupTaskId, at: nowIso(now), reason: "previous_finished" }].slice(-50);
13923
+ }
13924
+ return { state: next, ok: true, action: "finished", released, promoted };
13925
+ }
13926
+
13927
+ // src/qa/chrome.js
13928
+ var DEFAULT_QA_CDP_URL = "http://127.0.0.1:9222";
13929
+ var DEFAULT_QA_PLAYWRIGHT_CONNECT_TIMEOUT_MS = 5e3;
13930
+ function providerDir(provider = DEFAULT_QA_PROVIDER) {
13931
+ return path18.join(qaRuntimeDir(), normalizeQaProvider(provider));
13932
+ }
13933
+ function defaultQaExtensionStageDir(provider = DEFAULT_QA_PROVIDER) {
13934
+ return path18.join(providerDir(provider), "extension-under-test");
13935
+ }
13936
+ function defaultQaArtifactsDir(provider = DEFAULT_QA_PROVIDER, clickupTaskId = "unknown") {
13937
+ return path18.join(providerDir(provider), "artifacts", String(clickupTaskId || "unknown"));
13938
+ }
13939
+ function normalizeCdpUrl(value = "") {
13940
+ return String(value || process.env.OPTIMA_QA_CHROME_CDP_URL || DEFAULT_QA_CDP_URL).trim() || DEFAULT_QA_CDP_URL;
13941
+ }
13942
+ async function loadPlaywrightChromium() {
13943
+ try {
13944
+ const mod = await import("playwright-core");
13945
+ return mod.chromium;
13946
+ } catch (error) {
13947
+ throw new Error(`playwright-core is required for Optima QA browser tools: ${error.message}`);
13948
+ }
13949
+ }
13950
+ function qaWindowName(clickupTaskId) {
13951
+ return `optima-qa:${String(clickupTaskId || "").trim()}`;
13952
+ }
13953
+ async function safePageWindowName(page) {
13954
+ try {
13955
+ return await page.evaluate(() => window.name || "");
13956
+ } catch {
13957
+ return "";
13958
+ }
13959
+ }
13960
+ async function findQaPage(context, clickupTaskId) {
13961
+ const expected = qaWindowName(clickupTaskId);
13962
+ const pages = context.pages();
13963
+ for (let index = 1; index < pages.length; index += 1) {
13964
+ const page = pages[index];
13965
+ if (await safePageWindowName(page) === expected) return page;
13966
+ }
13967
+ return null;
13968
+ }
13969
+ async function ensurePersistentTab(context, url = "https://chatgpt.com/") {
13970
+ const pages = context.pages();
13971
+ if (pages[0]) return pages[0];
13972
+ const page = await context.newPage();
13973
+ await page.goto(url, { waitUntil: "domcontentloaded", timeout: 3e4 }).catch(() => {
13974
+ });
13975
+ return page;
13976
+ }
13977
+ async function ensureQaPage(context, { clickupTaskId, startUrl = "https://chatgpt.com/" } = {}) {
13978
+ await ensurePersistentTab(context, startUrl);
13979
+ const existing = await findQaPage(context, clickupTaskId);
13980
+ if (existing) return existing;
13981
+ const page = await context.newPage();
13982
+ await page.goto(startUrl, { waitUntil: "domcontentloaded", timeout: 3e4 }).catch(() => {
13983
+ });
13984
+ await page.evaluate((name) => {
13985
+ window.name = name;
13986
+ }, qaWindowName(clickupTaskId)).catch(() => {
13987
+ });
13988
+ return page;
13989
+ }
13990
+ function copyExtensionSource(sourcePath, stageDir) {
13991
+ const source = String(sourcePath || "").trim();
13992
+ if (!source) return { ok: true, skipped: true, reason: "extension_path_not_provided", stageDir };
13993
+ const resolved = path18.resolve(source.replace(/^~(?=$|\/)/, os6.homedir()));
13994
+ if (!fs17.existsSync(resolved)) return { ok: false, error: `extension_path_not_found: ${resolved}`, stageDir };
13995
+ fs17.rmSync(stageDir, { recursive: true, force: true });
13996
+ fs17.mkdirSync(path18.dirname(stageDir), { recursive: true });
13997
+ fs17.cpSync(resolved, stageDir, {
13998
+ recursive: true,
13999
+ filter: (src) => !/[/\\](node_modules|\.git|dist|build|test-results)([/\\]|$)/.test(src)
14000
+ });
14001
+ return { ok: true, source: resolved, stageDir };
14002
+ }
14003
+ function extensionIdFromWorkerUrl(url = "") {
14004
+ const match = String(url || "").match(/^chrome-extension:\/\/([^/]+)/);
14005
+ return match?.[1] || "";
14006
+ }
14007
+ async function findExtensionWorker(context, extensionId = "") {
14008
+ const workers = context.serviceWorkers ? context.serviceWorkers() : [];
14009
+ const normalized = String(extensionId || "").trim();
14010
+ if (normalized) return workers.find((worker) => worker.url().startsWith(`chrome-extension://${normalized}/`)) || null;
14011
+ return workers.find((worker) => String(worker.url()).startsWith("chrome-extension://")) || null;
14012
+ }
14013
+ async function resetExtensionState(context, { extensionId = "" } = {}) {
14014
+ const worker = await findExtensionWorker(context, extensionId);
14015
+ if (!worker) return { ok: false, error: "extension_service_worker_not_found" };
14016
+ const id = extensionIdFromWorkerUrl(worker.url());
14017
+ const result = await worker.evaluate(async () => {
14018
+ const deletedCaches = [];
14019
+ const deletedDbs = [];
14020
+ if (globalThis.chrome?.storage?.local) await chrome.storage.local.clear();
14021
+ if (globalThis.chrome?.storage?.session?.clear) await chrome.storage.session.clear();
14022
+ if (globalThis.chrome?.storage?.sync) await chrome.storage.sync.clear();
14023
+ if (globalThis.caches?.keys) {
14024
+ for (const name of await caches.keys()) {
14025
+ await caches.delete(name);
14026
+ deletedCaches.push(name);
14027
+ }
14028
+ }
14029
+ if (globalThis.indexedDB?.databases) {
14030
+ for (const db of await indexedDB.databases()) {
14031
+ if (db.name) {
14032
+ indexedDB.deleteDatabase(db.name);
14033
+ deletedDbs.push(db.name);
14034
+ }
14035
+ }
14036
+ }
14037
+ return { ok: true, deletedCaches, deletedDbs };
14038
+ });
14039
+ return { extensionId: id, ...result };
14040
+ }
14041
+ async function reloadExtension(context, { extensionId = "" } = {}) {
14042
+ const worker = await findExtensionWorker(context, extensionId);
14043
+ if (!worker) return { ok: false, error: "extension_service_worker_not_found" };
14044
+ const id = extensionIdFromWorkerUrl(worker.url());
14045
+ await worker.evaluate(() => chrome.runtime.reload()).catch(() => {
14046
+ });
14047
+ return { ok: true, extensionId: id };
14048
+ }
14049
+ async function summarizeBrowser(context, { clickupTaskId = "" } = {}) {
14050
+ const pages = context.pages();
14051
+ const pageSummaries = [];
14052
+ for (let index = 0; index < pages.length; index += 1) {
14053
+ const page = pages[index];
14054
+ pageSummaries.push({
14055
+ index,
14056
+ role: index === 0 ? "persistent_session_tab" : await safePageWindowName(page) === qaWindowName(clickupTaskId) ? "qa_task_tab" : "other",
14057
+ url: page.url(),
14058
+ title: await page.title().catch(() => "")
14059
+ });
14060
+ }
14061
+ const workers = context.serviceWorkers ? context.serviceWorkers().map((worker) => worker.url()) : [];
14062
+ return { pages: pageSummaries, serviceWorkers: workers };
14063
+ }
14064
+ function parseQaCommand(commandJson = "") {
14065
+ if (!String(commandJson || "").trim()) return { action: "status" };
14066
+ try {
14067
+ const parsed = JSON.parse(commandJson);
14068
+ return parsed && typeof parsed === "object" ? parsed : { action: "invalid", error: "command_json_must_be_object" };
14069
+ } catch (error) {
14070
+ return { action: "script", script: String(commandJson || "") };
14071
+ }
14072
+ }
14073
+ async function runQaCommandOnPage(page, context, browser, command, { artifactsDir }) {
14074
+ const action = String(command.action || "status").trim().toLowerCase();
14075
+ if (action === "status") return { ok: true, page: { url: page.url(), title: await page.title().catch(() => "") } };
14076
+ if (action === "goto") {
14077
+ await page.goto(String(command.url || "https://chatgpt.com/"), { waitUntil: command.wait_until || "domcontentloaded", timeout: Number(command.timeout_ms || 3e4) });
14078
+ return { ok: true, url: page.url(), title: await page.title().catch(() => "") };
14079
+ }
14080
+ if (action === "evaluate") {
14081
+ const result = await page.evaluate(String(command.expression || "() => null"));
14082
+ return { ok: true, result };
14083
+ }
14084
+ if (action === "screenshot") {
14085
+ const name = String(command.name || `screenshot-${Date.now()}.png`).replace(/[^a-zA-Z0-9._-]+/g, "-");
14086
+ const outPath = path18.join(artifactsDir, name);
14087
+ fs17.mkdirSync(path18.dirname(outPath), { recursive: true });
14088
+ await page.screenshot({ path: outPath, fullPage: command.full_page !== false });
14089
+ return { ok: true, path: outPath };
14090
+ }
14091
+ if (action === "set_input_files") {
14092
+ const selector = String(command.selector || "input[type=file]");
14093
+ await page.setInputFiles(selector, command.files);
14094
+ return { ok: true, selector };
14095
+ }
14096
+ if (action === "script") {
14097
+ const script = String(command.script || "");
14098
+ if (!script.trim()) return { ok: false, error: "script_required" };
14099
+ const fn = new Function("page", "context", "browser", "artifactsDir", `return (async () => {
14100
+ ${script}
14101
+ })()`);
14102
+ const result = await fn(page, context, browser, artifactsDir);
14103
+ return { ok: true, result };
14104
+ }
14105
+ return { ok: false, error: `unsupported_qa_command_action: ${action}` };
14106
+ }
14107
+ async function withQaBrowser({ provider = DEFAULT_QA_PROVIDER, cdpUrl = "", clickupTaskId = "", startUrl = "https://chatgpt.com/" } = {}, callback) {
14108
+ const chromium = await loadPlaywrightChromium();
14109
+ const browser = await chromium.connectOverCDP(normalizeCdpUrl(cdpUrl), {
14110
+ timeout: Number(process.env.OPTIMA_QA_PLAYWRIGHT_CONNECT_TIMEOUT_MS || DEFAULT_QA_PLAYWRIGHT_CONNECT_TIMEOUT_MS)
14111
+ });
14112
+ try {
14113
+ const context = browser.contexts()[0] || await browser.newContext();
14114
+ const page = clickupTaskId ? await ensureQaPage(context, { clickupTaskId, startUrl }) : null;
14115
+ return await callback({ browser, context, page });
14116
+ } finally {
14117
+ await browser.close().catch(() => {
14118
+ });
14119
+ }
14120
+ }
14121
+ async function qaBrowserStatus(options = {}) {
14122
+ return withQaBrowser(options, async ({ context }) => ({ ok: true, ...await summarizeBrowser(context, { clickupTaskId: options.clickupTaskId }) })).catch(async (error) => {
14123
+ const fallback = await cdpBrowserStatus({ cdpUrl: options.cdpUrl, clickupTaskId: options.clickupTaskId, qaWindowName }).catch((fallbackError) => ({ ok: false, error: fallbackError.message }));
14124
+ return fallback.ok ? { ...fallback, fallback: "cdp", playwrightError: error.message } : { ok: false, error: error.message, fallbackError: fallback.error, cdpUrl: normalizeCdpUrl(options.cdpUrl) };
14125
+ });
14126
+ }
14127
+ async function qaPrepareExtension({ provider = DEFAULT_QA_PROVIDER, cdpUrl = "", extensionPath = "", extensionId = "", reset = true, reload = true } = {}) {
14128
+ const stageDir = defaultQaExtensionStageDir(provider);
14129
+ const sync = copyExtensionSource(extensionPath, stageDir);
14130
+ const browserResult = await withQaBrowser({ provider, cdpUrl }, async ({ context }) => {
14131
+ const resetResult = reset ? await resetExtensionState(context, { extensionId }).catch((error) => ({ ok: false, error: error.message })) : { ok: true, skipped: true };
14132
+ const reloadResult = reload ? await reloadExtension(context, { extensionId }).catch((error) => ({ ok: false, error: error.message })) : { ok: true, skipped: true };
14133
+ return { reset: resetResult, reload: reloadResult, browser: await summarizeBrowser(context) };
14134
+ }).catch(async (error) => {
14135
+ const fallback = await cdpPrepareExtension({ cdpUrl, extensionId, reset, reload }).catch((fallbackError) => ({ ok: false, error: fallbackError.message }));
14136
+ return fallback.ok ? { ...fallback, fallback: "cdp", playwrightError: error.message } : { ok: false, error: error.message, fallbackError: fallback.error };
14137
+ });
14138
+ return { sync, ...browserResult };
14139
+ }
14140
+ async function qaRunChromeCommand({ provider = DEFAULT_QA_PROVIDER, cdpUrl = "", clickupTaskId = "", commandJson = "", startUrl = "https://chatgpt.com/" } = {}) {
14141
+ const command = parseQaCommand(commandJson);
14142
+ const artifactsDir = defaultQaArtifactsDir(provider, clickupTaskId);
14143
+ return withQaBrowser({ provider, cdpUrl, clickupTaskId, startUrl }, async ({ browser, context, page }) => {
14144
+ const result = await runQaCommandOnPage(page, context, browser, command, { artifactsDir });
14145
+ return { ok: result.ok !== false, command: command.action || "script", tab: { windowName: qaWindowName(clickupTaskId), url: page.url(), title: await page.title().catch(() => "") }, artifactsDir, result };
14146
+ }).catch(async (error) => {
14147
+ const fallback = await cdpRunChromeCommand({
14148
+ cdpUrl,
14149
+ clickupTaskId,
14150
+ commandJson,
14151
+ startUrl,
14152
+ artifactsDir,
14153
+ qaWindowName
14154
+ }).catch((fallbackError) => ({ ok: false, error: fallbackError.message }));
14155
+ return fallback.ok ? { ...fallback, fallback: "cdp", playwrightError: error.message } : { ok: false, error: error.message, fallbackError: fallback.error };
14156
+ });
14157
+ }
14158
+
13502
14159
  // src/repair.js
13503
14160
  var import_yaml4 = __toESM(require_dist(), 1);
13504
14161
  var import_ignore = __toESM(require_ignore(), 1);
13505
- import fs15 from "node:fs";
13506
- import path16 from "node:path";
14162
+ import fs18 from "node:fs";
14163
+ import path19 from "node:path";
13507
14164
  var CODEMAP_SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
13508
14165
  ".js",
13509
14166
  ".ts",
@@ -13541,10 +14198,10 @@ var LEGACY_OPERATIONAL_ROOTS = /* @__PURE__ */ new Set([
13541
14198
  ]);
13542
14199
  var OPTIMA_OPERATIONAL_FOLDERS = [".optima", "templates", "dist"];
13543
14200
  function relPath(worktree, targetPath) {
13544
- return path16.relative(worktree, targetPath).split(path16.sep).join("/") || ".";
14201
+ return path19.relative(worktree, targetPath).split(path19.sep).join("/") || ".";
13545
14202
  }
13546
14203
  function normalizeCodemapRelPath(relPathValue) {
13547
- return path16.normalize(relPathValue).replace(/\\/g, "/").replace(/\/$/, "");
14204
+ return path19.normalize(relPathValue).replace(/\\/g, "/").replace(/\/$/, "");
13548
14205
  }
13549
14206
  function firstPathSegment(relPathValue) {
13550
14207
  return normalizeCodemapRelPath(relPathValue).split("/").filter(Boolean)[0] || "";
@@ -13563,8 +14220,8 @@ function isHiddenTree(relPathValue) {
13563
14220
  function loadGitIgnoreMatcher(worktree) {
13564
14221
  const ig = (0, import_ignore.default)();
13565
14222
  ig.add(".git");
13566
- const gitignorePath = path16.join(worktree, ".gitignore");
13567
- if (fs15.existsSync(gitignorePath)) ig.add(fs15.readFileSync(gitignorePath, "utf8"));
14223
+ const gitignorePath = path19.join(worktree, ".gitignore");
14224
+ if (fs18.existsSync(gitignorePath)) ig.add(fs18.readFileSync(gitignorePath, "utf8"));
13568
14225
  return ig;
13569
14226
  }
13570
14227
  function codemapSectionEntries(value) {
@@ -13583,7 +14240,7 @@ function codemapIndexedPaths(map) {
13583
14240
  }
13584
14241
  function readCodemap(filePath, unresolved, worktree) {
13585
14242
  try {
13586
- const parsed = import_yaml4.default.parse(fs15.readFileSync(filePath, "utf8"));
14243
+ const parsed = import_yaml4.default.parse(fs18.readFileSync(filePath, "utf8"));
13587
14244
  if (!parsed || typeof parsed !== "object") {
13588
14245
  unresolved.push({ category: "codemap", path: relPath(worktree, filePath), message: "CodeMap is empty or invalid; manual repair required." });
13589
14246
  return null;
@@ -13595,42 +14252,42 @@ function readCodemap(filePath, unresolved, worktree) {
13595
14252
  }
13596
14253
  }
13597
14254
  function writeCodemap(filePath, map) {
13598
- fs15.writeFileSync(filePath, import_yaml4.default.stringify(map), "utf8");
14255
+ fs18.writeFileSync(filePath, import_yaml4.default.stringify(map), "utf8");
13599
14256
  }
13600
14257
  function isIgnoredPath(ig, relativePath) {
13601
14258
  const normalized = normalizeCodemapRelPath(relativePath);
13602
14259
  return Boolean(normalized) && ig.ignores(normalized);
13603
14260
  }
13604
14261
  function hasImmediateSourceFile(dirPath, ig, worktree) {
13605
- if (!fs15.existsSync(dirPath)) return false;
13606
- for (const item of fs15.readdirSync(dirPath, { withFileTypes: true })) {
13607
- const childPath = path16.join(dirPath, item.name);
13608
- const relative = path16.relative(worktree, childPath);
14262
+ if (!fs18.existsSync(dirPath)) return false;
14263
+ for (const item of fs18.readdirSync(dirPath, { withFileTypes: true })) {
14264
+ const childPath = path19.join(dirPath, item.name);
14265
+ const relative = path19.relative(worktree, childPath);
13609
14266
  if (isIgnoredPath(ig, relative) || isOperationalRelPath(relative)) continue;
13610
- if (item.isFile() && CODEMAP_SOURCE_EXTENSIONS.has(path16.extname(item.name))) return true;
14267
+ if (item.isFile() && CODEMAP_SOURCE_EXTENSIONS.has(path19.extname(item.name))) return true;
13611
14268
  }
13612
14269
  return false;
13613
14270
  }
13614
14271
  function containsSource(dirPath, ig, worktree) {
13615
- if (!fs15.existsSync(dirPath)) return false;
13616
- const dirRelPath = path16.relative(worktree, dirPath);
14272
+ if (!fs18.existsSync(dirPath)) return false;
14273
+ const dirRelPath = path19.relative(worktree, dirPath);
13617
14274
  if (isOperationalRelPath(dirRelPath) || isHiddenTree(dirRelPath)) return false;
13618
- for (const item of fs15.readdirSync(dirPath, { withFileTypes: true })) {
13619
- const childPath = path16.join(dirPath, item.name);
13620
- const relative = path16.relative(worktree, childPath);
14275
+ for (const item of fs18.readdirSync(dirPath, { withFileTypes: true })) {
14276
+ const childPath = path19.join(dirPath, item.name);
14277
+ const relative = path19.relative(worktree, childPath);
13621
14278
  if (isIgnoredPath(ig, relative) || isOperationalRelPath(relative) || isHiddenTree(relative)) continue;
13622
- if (item.isFile() && CODEMAP_SOURCE_EXTENSIONS.has(path16.extname(item.name))) return true;
14279
+ if (item.isFile() && CODEMAP_SOURCE_EXTENSIONS.has(path19.extname(item.name))) return true;
13623
14280
  if (item.isDirectory() && containsSource(childPath, ig, worktree)) return true;
13624
14281
  }
13625
14282
  return false;
13626
14283
  }
13627
14284
  function createModuleCodemap(dirPath, worktree, deps) {
13628
- const entries = fs15.readdirSync(dirPath, { withFileTypes: true });
14285
+ const entries = fs18.readdirSync(dirPath, { withFileTypes: true });
13629
14286
  const entrypoints = [];
13630
14287
  const internals = [];
13631
- const relToRoot = path16.relative(dirPath, deps.optimaCodemapPath(worktree)).split(path16.sep).join("/");
14288
+ const relToRoot = path19.relative(dirPath, deps.optimaCodemapPath(worktree)).split(path19.sep).join("/");
13632
14289
  for (const item of entries) {
13633
- if (!item.isFile() || item.name === "codemap.yml" || !CODEMAP_SOURCE_EXTENSIONS.has(path16.extname(item.name))) continue;
14290
+ if (!item.isFile() || item.name === "codemap.yml" || !CODEMAP_SOURCE_EXTENSIONS.has(path19.extname(item.name))) continue;
13634
14291
  const bucket = /^index\.(js|ts|tsx|jsx)$|^main\.(js|ts|tsx|jsx|py|go|rs|java)$/.test(item.name) ? entrypoints : internals;
13635
14292
  bucket.push({ path: item.name });
13636
14293
  }
@@ -13643,7 +14300,7 @@ function repairSingleCodemap(codemapPath, worktree, apply, registerAction, unres
13643
14300
  const map = readCodemap(codemapPath, unresolved, worktree);
13644
14301
  if (!map) return;
13645
14302
  const isRootMap = codemapPath === deps.optimaCodemapPath(worktree);
13646
- const mapDir = path16.dirname(codemapPath);
14303
+ const mapDir = path19.dirname(codemapPath);
13647
14304
  const pathBase = isRootMap ? worktree : mapDir;
13648
14305
  let changed = false;
13649
14306
  for (const section of ["modules", "entrypoints", "sources_of_truth", "links", "internals"]) {
@@ -13654,13 +14311,13 @@ function repairSingleCodemap(codemapPath, worktree, apply, registerAction, unres
13654
14311
  }
13655
14312
  const nextEntries = [];
13656
14313
  for (const entry of originalEntries) {
13657
- if (!entry?.path || entry.path.startsWith("http://") || entry.path.startsWith("https://") || path16.isAbsolute(entry.path)) {
14314
+ if (!entry?.path || entry.path.startsWith("http://") || entry.path.startsWith("https://") || path19.isAbsolute(entry.path)) {
13658
14315
  nextEntries.push(entry);
13659
14316
  continue;
13660
14317
  }
13661
14318
  const normalizedPath = normalizeCodemapRelPath(entry.path);
13662
- const absPath = path16.join(pathBase, normalizedPath);
13663
- if (!fs15.existsSync(absPath)) {
14319
+ const absPath = path19.join(pathBase, normalizedPath);
14320
+ if (!fs18.existsSync(absPath)) {
13664
14321
  registerAction({ category: "codemap", action: apply ? "removed" : "would_remove", path: relPath(worktree, codemapPath), detail: `Remove broken ${section.slice(0, -1)} reference '${entry.path}'.` });
13665
14322
  changed = true;
13666
14323
  continue;
@@ -13669,8 +14326,8 @@ function repairSingleCodemap(codemapPath, worktree, apply, registerAction, unres
13669
14326
  const maxParts = isRootMap ? 2 : 1;
13670
14327
  if (parts.length > maxParts) {
13671
14328
  const localPath = isRootMap ? parts.slice(0, 2).join("/") : parts[0];
13672
- const localAbs = path16.join(pathBase, localPath);
13673
- if (fs15.existsSync(localAbs)) {
14329
+ const localAbs = path19.join(pathBase, localPath);
14330
+ if (fs18.existsSync(localAbs)) {
13674
14331
  nextEntries.push({ ...entry, path: localPath });
13675
14332
  changed = true;
13676
14333
  registerAction({ category: "codemap", action: apply ? "updated" : "would_update", path: relPath(worktree, codemapPath), detail: `Shorten '${entry.path}' to local path '${localPath}'.` });
@@ -13684,11 +14341,11 @@ function repairSingleCodemap(codemapPath, worktree, apply, registerAction, unres
13684
14341
  }
13685
14342
  if (Array.isArray(map[section])) map[section] = nextEntries;
13686
14343
  }
13687
- if (map.scope === "module" && !isOperationalRelPath(path16.relative(worktree, mapDir))) {
14344
+ if (map.scope === "module" && !isOperationalRelPath(path19.relative(worktree, mapDir))) {
13688
14345
  const indexed = codemapIndexedPaths(map);
13689
14346
  const internals = Array.isArray(map.internals) ? map.internals : [];
13690
- for (const item of fs15.readdirSync(mapDir, { withFileTypes: true })) {
13691
- if (!item.isFile() || item.name === "codemap.yml" || !CODEMAP_SOURCE_EXTENSIONS.has(path16.extname(item.name))) continue;
14347
+ for (const item of fs18.readdirSync(mapDir, { withFileTypes: true })) {
14348
+ if (!item.isFile() || item.name === "codemap.yml" || !CODEMAP_SOURCE_EXTENSIONS.has(path19.extname(item.name))) continue;
13692
14349
  if (indexed.has(item.name)) continue;
13693
14350
  internals.push({ path: item.name });
13694
14351
  indexed.add(item.name);
@@ -13702,13 +14359,13 @@ function repairSingleCodemap(codemapPath, worktree, apply, registerAction, unres
13702
14359
  function repairCodemaps(worktree, apply, actions, unresolved, deps) {
13703
14360
  const ig = loadGitIgnoreMatcher(worktree);
13704
14361
  const rootCodemapPath = deps.optimaCodemapPath(worktree);
13705
- const rootCodemapMissing = !fs15.existsSync(rootCodemapPath);
14362
+ const rootCodemapMissing = !fs18.existsSync(rootCodemapPath);
13706
14363
  if (rootCodemapMissing) {
13707
14364
  actions.push({ category: "codemap", action: apply ? "created" : "would_create", path: ".optima/codemap.yml", detail: "Create missing root CodeMap from template." });
13708
14365
  if (apply) deps.scaffoldOptimaRootCodemap(worktree);
13709
14366
  }
13710
- if (fs15.existsSync(rootCodemapPath)) repairSingleCodemap(rootCodemapPath, worktree, apply, (action) => actions.push(action), unresolved, deps);
13711
- const rootMap = fs15.existsSync(rootCodemapPath) ? readCodemap(rootCodemapPath, unresolved, worktree) : null;
14367
+ if (fs18.existsSync(rootCodemapPath)) repairSingleCodemap(rootCodemapPath, worktree, apply, (action) => actions.push(action), unresolved, deps);
14368
+ const rootMap = fs18.existsSync(rootCodemapPath) ? readCodemap(rootCodemapPath, unresolved, worktree) : null;
13712
14369
  let rootChanged = false;
13713
14370
  const rootModulesRepairable = rootMap && (rootMap.modules === void 0 || Array.isArray(rootMap.modules));
13714
14371
  if (rootMap) {
@@ -13720,10 +14377,10 @@ function repairCodemaps(worktree, apply, actions, unresolved, deps) {
13720
14377
  }
13721
14378
  }
13722
14379
  function walk(dirPath) {
13723
- const relative = path16.relative(worktree, dirPath);
14380
+ const relative = path19.relative(worktree, dirPath);
13724
14381
  if (relative && (isIgnoredPath(ig, relative) || isOperationalRelPath(relative) || isHiddenTree(relative))) return;
13725
- const codemapPath = path16.join(dirPath, "codemap.yml");
13726
- const hasCodemap = fs15.existsSync(codemapPath);
14382
+ const codemapPath = path19.join(dirPath, "codemap.yml");
14383
+ const hasCodemap = fs18.existsSync(codemapPath);
13727
14384
  const sourceDir = relative && containsSource(dirPath, ig, worktree);
13728
14385
  if (sourceDir && !hasCodemap && dirPath !== worktree) {
13729
14386
  if (hasImmediateSourceFile(dirPath, ig, worktree)) {
@@ -13742,19 +14399,19 @@ function repairCodemaps(worktree, apply, actions, unresolved, deps) {
13742
14399
  actions.push({ category: "codemap", action: apply ? "updated" : "would_update", path: ".optima/codemap.yml", detail: `Register top-level source module '${normalizeCodemapRelPath(relative)}'.` });
13743
14400
  }
13744
14401
  }
13745
- if (fs15.existsSync(codemapPath) && codemapPath !== rootCodemapPath) repairSingleCodemap(codemapPath, worktree, apply, (action) => actions.push(action), unresolved, deps);
13746
- for (const item of fs15.readdirSync(dirPath, { withFileTypes: true })) {
13747
- if (item.isDirectory()) walk(path16.join(dirPath, item.name));
14402
+ if (fs18.existsSync(codemapPath) && codemapPath !== rootCodemapPath) repairSingleCodemap(codemapPath, worktree, apply, (action) => actions.push(action), unresolved, deps);
14403
+ for (const item of fs18.readdirSync(dirPath, { withFileTypes: true })) {
14404
+ if (item.isDirectory()) walk(path19.join(dirPath, item.name));
13748
14405
  }
13749
14406
  }
13750
- if (fs15.existsSync(worktree)) walk(worktree);
14407
+ if (fs18.existsSync(worktree)) walk(worktree);
13751
14408
  if (rootMap && rootChanged && apply) writeCodemap(rootCodemapPath, rootMap);
13752
14409
  }
13753
14410
  function walkMarkdownFiles(dirPath) {
13754
- if (!fs15.existsSync(dirPath)) return [];
14411
+ if (!fs18.existsSync(dirPath)) return [];
13755
14412
  const files = [];
13756
- for (const entry of fs15.readdirSync(dirPath, { withFileTypes: true })) {
13757
- const entryPath = path16.join(dirPath, entry.name);
14413
+ for (const entry of fs18.readdirSync(dirPath, { withFileTypes: true })) {
14414
+ const entryPath = path19.join(dirPath, entry.name);
13758
14415
  if (entry.isDirectory()) {
13759
14416
  files.push(...walkMarkdownFiles(entryPath));
13760
14417
  } else if (entry.isFile() && entry.name.endsWith(".md")) {
@@ -13793,7 +14450,7 @@ function rewriteOptimaMarkdownReferences(content, evidenceBasePath = null) {
13793
14450
  }
13794
14451
  function optimaEvidenceBaseForFile(worktree, filePath, deps) {
13795
14452
  const evidenceRoot = deps.optimaEvidencesDir(worktree);
13796
- const relative = path16.relative(evidenceRoot, filePath).split(path16.sep).join("/");
14453
+ const relative = path19.relative(evidenceRoot, filePath).split(path19.sep).join("/");
13797
14454
  const [taskId] = relative.split("/");
13798
14455
  if (!taskId || taskId === ".." || relative.startsWith("../")) return null;
13799
14456
  return `.optima/evidences/${taskId}`;
@@ -13806,11 +14463,11 @@ function normalizeOptimaMarkdownReferences(worktree, deps) {
13806
14463
  ];
13807
14464
  const changed = [];
13808
14465
  for (const filePath of scanRoots.flatMap(walkMarkdownFiles)) {
13809
- const raw = fs15.readFileSync(filePath, "utf8");
13810
- const evidenceBasePath = filePath.startsWith(deps.optimaEvidencesDir(worktree) + path16.sep) ? optimaEvidenceBaseForFile(worktree, filePath, deps) : null;
14466
+ const raw = fs18.readFileSync(filePath, "utf8");
14467
+ const evidenceBasePath = filePath.startsWith(deps.optimaEvidencesDir(worktree) + path19.sep) ? optimaEvidenceBaseForFile(worktree, filePath, deps) : null;
13811
14468
  const rewritten = rewriteOptimaMarkdownReferences(raw, evidenceBasePath);
13812
14469
  if (rewritten !== raw) {
13813
- fs15.writeFileSync(filePath, rewritten, "utf8");
14470
+ fs18.writeFileSync(filePath, rewritten, "utf8");
13814
14471
  changed.push(relPath(worktree, filePath));
13815
14472
  }
13816
14473
  }
@@ -13818,8 +14475,8 @@ function normalizeOptimaMarkdownReferences(worktree, deps) {
13818
14475
  }
13819
14476
  function missingOptimaGitignoreRules(worktree, deps) {
13820
14477
  if (!deps.isGitRepository(worktree)) return [];
13821
- const gitignorePath = path16.join(worktree, ".gitignore");
13822
- const existing = fs15.existsSync(gitignorePath) ? fs15.readFileSync(gitignorePath, "utf8") : "";
14478
+ const gitignorePath = path19.join(worktree, ".gitignore");
14479
+ const existing = fs18.existsSync(gitignorePath) ? fs18.readFileSync(gitignorePath, "utf8") : "";
13823
14480
  const existingRules = new Set(existing.split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
13824
14481
  return deps.optimaGitignoreRules.filter((rule) => !existingRules.has(rule));
13825
14482
  }
@@ -13836,11 +14493,11 @@ function planOptimaRepair(worktree, args = {}, deps) {
13836
14493
  const apply = mode === "apply";
13837
14494
  const actions = [];
13838
14495
  const unresolved = [];
13839
- const hadOptima = fs15.existsSync(deps.optimaDir(worktree));
14496
+ const hadOptima = fs18.existsSync(deps.optimaDir(worktree));
13840
14497
  const missingGitignoreRules = missingOptimaGitignoreRules(worktree, deps);
13841
14498
  const markdownBefore = apply ? [] : walkMarkdownFiles(deps.optimaDir(worktree)).filter((filePath) => {
13842
- const raw = fs15.readFileSync(filePath, "utf8");
13843
- const evidenceBasePath = filePath.startsWith(deps.optimaEvidencesDir(worktree) + path16.sep) ? optimaEvidenceBaseForFile(worktree, filePath, deps) : null;
14499
+ const raw = fs18.readFileSync(filePath, "utf8");
14500
+ const evidenceBasePath = filePath.startsWith(deps.optimaEvidencesDir(worktree) + path19.sep) ? optimaEvidenceBaseForFile(worktree, filePath, deps) : null;
13844
14501
  return rewriteOptimaMarkdownReferences(raw, evidenceBasePath) !== raw;
13845
14502
  }).map((filePath) => relPath(worktree, filePath));
13846
14503
  if (!hadOptima) pushRepairAction(actions, "operational", apply ? "created" : "would_create", ".optima/", "Create Optima operational root.");
@@ -13849,31 +14506,31 @@ function planOptimaRepair(worktree, args = {}, deps) {
13849
14506
  [".staticeng/", deps.legacyStaticEngDir(worktree)],
13850
14507
  [".nomadwork/", deps.legacyNomadworkDir(worktree)],
13851
14508
  [".nomadworks/", deps.legacyNomadworksDir(worktree)],
13852
- ["tasks/", path16.join(worktree, "tasks")],
13853
- ["evidences/", path16.join(worktree, "evidences")],
13854
- ["docs/scrs/", path16.join(worktree, "docs", "scrs")],
13855
- ["codemap.yml", path16.join(worktree, "codemap.yml")],
13856
- ["codemap.yaml", path16.join(worktree, "codemap.yaml")]
14509
+ ["tasks/", path19.join(worktree, "tasks")],
14510
+ ["evidences/", path19.join(worktree, "evidences")],
14511
+ ["docs/scrs/", path19.join(worktree, "docs", "scrs")],
14512
+ ["codemap.yml", path19.join(worktree, "codemap.yml")],
14513
+ ["codemap.yaml", path19.join(worktree, "codemap.yaml")]
13857
14514
  ];
13858
- if (!deps.isOptimaPluginPackageWorktree(worktree)) legacySources.push(["policies/", path16.join(worktree, "policies")]);
14515
+ if (!deps.isOptimaPluginPackageWorktree(worktree)) legacySources.push(["policies/", path19.join(worktree, "policies")]);
13859
14516
  for (const [display, sourcePath] of legacySources) {
13860
- if (fs15.existsSync(sourcePath)) pushRepairAction(actions, "legacy", apply ? "migrated" : "would_migrate", display, "Move or merge legacy/root Optima artifact into .optima using preservation safeguards.");
14517
+ if (fs18.existsSync(sourcePath)) pushRepairAction(actions, "legacy", apply ? "migrated" : "would_migrate", display, "Move or merge legacy/root Optima artifact into .optima using preservation safeguards.");
13861
14518
  }
13862
14519
  if (apply) deps.migrateLegacyOptimaLayout(worktree);
13863
- const configMissing = !fs15.existsSync(deps.repoConfigPath(worktree));
14520
+ const configMissing = !fs18.existsSync(deps.repoConfigPath(worktree));
13864
14521
  if (configMissing) pushRepairAction(actions, "config", apply ? "created" : "would_create", ".optima/.config/optima.yaml", "Create missing local Optima config from template.");
13865
14522
  if (apply) deps.scaffoldOptimaConfig(worktree, args.team_mode || "full");
13866
14523
  const requiredFiles = [
13867
- [path16.join(deps.optimaTasksDir(worktree), "current.md"), "registry", ".optima/tasks/current.md", deps.currentTasksRegistryContent()],
13868
- [path16.join(deps.optimaTasksDir(worktree), "done.md"), "registry", ".optima/tasks/done.md", deps.doneTasksRegistryContent()],
13869
- [path16.join(deps.optimaScrsDir(worktree), "current.md"), "registry", ".optima/docs/scrs/current.md", deps.currentScrRegistryContent()],
13870
- [path16.join(deps.optimaScrsDir(worktree), "done.md"), "registry", ".optima/docs/scrs/done.md", deps.doneScrRegistryContent()],
13871
- [path16.join(deps.optimaTasksDir(worktree), "task-template.md"), "template", ".optima/tasks/task-template.md", deps.taskTemplateContent()],
13872
- [path16.join(deps.optimaTasksDir(worktree), "subtask-template.md"), "template", ".optima/tasks/subtask-template.md", deps.subtaskTemplateContent()],
13873
- [path16.join(deps.repoPoliciesDir(worktree), "README.md"), "policy", ".optima/policies/README.md", deps.repoLocalPoliciesReadme]
14524
+ [path19.join(deps.optimaTasksDir(worktree), "current.md"), "registry", ".optima/tasks/current.md", deps.currentTasksRegistryContent()],
14525
+ [path19.join(deps.optimaTasksDir(worktree), "done.md"), "registry", ".optima/tasks/done.md", deps.doneTasksRegistryContent()],
14526
+ [path19.join(deps.optimaScrsDir(worktree), "current.md"), "registry", ".optima/docs/scrs/current.md", deps.currentScrRegistryContent()],
14527
+ [path19.join(deps.optimaScrsDir(worktree), "done.md"), "registry", ".optima/docs/scrs/done.md", deps.doneScrRegistryContent()],
14528
+ [path19.join(deps.optimaTasksDir(worktree), "task-template.md"), "template", ".optima/tasks/task-template.md", deps.taskTemplateContent()],
14529
+ [path19.join(deps.optimaTasksDir(worktree), "subtask-template.md"), "template", ".optima/tasks/subtask-template.md", deps.subtaskTemplateContent()],
14530
+ [path19.join(deps.repoPoliciesDir(worktree), "README.md"), "policy", ".optima/policies/README.md", deps.repoLocalPoliciesReadme]
13874
14531
  ];
13875
14532
  for (const [filePath, category, displayPath, content] of requiredFiles) {
13876
- if (!fs15.existsSync(filePath)) {
14533
+ if (!fs18.existsSync(filePath)) {
13877
14534
  pushRepairAction(actions, category, apply ? "created" : "would_create", displayPath, "Create missing Optima scaffold file without overwriting existing content.");
13878
14535
  if (apply) deps.ensureFileIfMissing(filePath, content);
13879
14536
  }
@@ -13927,18 +14584,18 @@ function formatRepairResult(plan, validationResult = null, formatValidationResul
13927
14584
  // src/validate_logic.js
13928
14585
  var import_yaml5 = __toESM(require_dist(), 1);
13929
14586
  var import_ignore2 = __toESM(require_ignore(), 1);
13930
- import fs16 from "node:fs";
13931
- import path17 from "node:path";
14587
+ import fs19 from "node:fs";
14588
+ import path20 from "node:path";
13932
14589
  async function optima_validate_logic(worktree) {
13933
- const rootCodemapPath = path17.join(worktree, ".optima", "codemap.yml");
13934
- if (!fs16.existsSync(rootCodemapPath)) return { ok: false, errors: [".optima/codemap.yml not found."], warnings: [] };
14590
+ const rootCodemapPath = path20.join(worktree, ".optima", "codemap.yml");
14591
+ if (!fs19.existsSync(rootCodemapPath)) return { ok: false, errors: [".optima/codemap.yml not found."], warnings: [] };
13935
14592
  const errors = [];
13936
14593
  const warnings = [];
13937
14594
  const ig = (0, import_ignore2.default)();
13938
14595
  ig.add(".git");
13939
- const gitignorePath = path17.join(worktree, ".gitignore");
13940
- if (fs16.existsSync(gitignorePath)) {
13941
- ig.add(fs16.readFileSync(gitignorePath, "utf8"));
14596
+ const gitignorePath = path20.join(worktree, ".gitignore");
14597
+ if (fs19.existsSync(gitignorePath)) {
14598
+ ig.add(fs19.readFileSync(gitignorePath, "utf8"));
13942
14599
  }
13943
14600
  const sourceExtensions = [
13944
14601
  ".js",
@@ -13978,30 +14635,30 @@ async function optima_validate_logic(worktree) {
13978
14635
  const operationalFolders = [".optima", "templates", "dist"];
13979
14636
  const isHiddenTree2 = (relPath2) => {
13980
14637
  if (!relPath2) return false;
13981
- return relPath2.split(path17.sep).some((part) => part.startsWith("."));
14638
+ return relPath2.split(path20.sep).some((part) => part.startsWith("."));
13982
14639
  };
13983
- const firstPathSegment2 = (relPath2) => relPath2.split(path17.sep).filter(Boolean)[0] || "";
14640
+ const firstPathSegment2 = (relPath2) => relPath2.split(path20.sep).filter(Boolean)[0] || "";
13984
14641
  const isOperationalRelPath2 = (relPath2) => {
13985
14642
  if (!relPath2) return false;
13986
14643
  const firstSegment = firstPathSegment2(relPath2);
13987
14644
  if (legacyOperationalRoots.has(firstSegment)) return true;
13988
- return operationalFolders.some((f) => relPath2 === f || relPath2.startsWith(f + path17.sep));
14645
+ return operationalFolders.some((f) => relPath2 === f || relPath2.startsWith(f + path20.sep));
13989
14646
  };
13990
14647
  const getSectionEntries = (value) => {
13991
14648
  if (Array.isArray(value)) return value;
13992
14649
  if (value && typeof value === "object") return Object.values(value);
13993
14650
  return [];
13994
14651
  };
13995
- const normalizeRelativePath = (relPath2) => path17.normalize(relPath2).replace(/\\/g, "/").replace(/\/$/, "");
14652
+ const normalizeRelativePath = (relPath2) => path20.normalize(relPath2).replace(/\\/g, "/").replace(/\/$/, "");
13996
14653
  const isSourceDir = (dirPath) => {
13997
- const dirRelPath = path17.relative(worktree, dirPath);
14654
+ const dirRelPath = path20.relative(worktree, dirPath);
13998
14655
  if (isOperationalRelPath2(dirRelPath)) return false;
13999
- const items = fs16.readdirSync(dirPath, { withFileTypes: true });
14656
+ const items = fs19.readdirSync(dirPath, { withFileTypes: true });
14000
14657
  for (const item of items) {
14001
- const childPath = path17.join(dirPath, item.name);
14002
- const relPath2 = path17.relative(worktree, childPath);
14658
+ const childPath = path20.join(dirPath, item.name);
14659
+ const relPath2 = path20.relative(worktree, childPath);
14003
14660
  if (ig.ignores(relPath2) || isOperationalRelPath2(relPath2)) continue;
14004
- if (item.isFile() && sourceExtensions.includes(path17.extname(item.name))) return true;
14661
+ if (item.isFile() && sourceExtensions.includes(path20.extname(item.name))) return true;
14005
14662
  if (item.isDirectory()) {
14006
14663
  if (isSourceDir(childPath)) return true;
14007
14664
  }
@@ -14009,7 +14666,7 @@ async function optima_validate_logic(worktree) {
14009
14666
  return false;
14010
14667
  };
14011
14668
  function validateMap(filePath) {
14012
- const content = fs16.readFileSync(filePath, "utf8");
14669
+ const content = fs19.readFileSync(filePath, "utf8");
14013
14670
  let map;
14014
14671
  try {
14015
14672
  map = import_yaml5.default.parse(content);
@@ -14021,32 +14678,32 @@ async function optima_validate_logic(worktree) {
14021
14678
  errors.push(`${filePath}: Invalid YAML.`);
14022
14679
  return;
14023
14680
  }
14024
- const dir = path17.dirname(filePath);
14681
+ const dir = path20.dirname(filePath);
14025
14682
  const pathBase = filePath === rootCodemapPath ? worktree : dir;
14026
14683
  const indexedPaths = /* @__PURE__ */ new Set();
14027
14684
  const sectionsToVerify = ["modules", "entrypoints", "sources_of_truth", "links", "internals"];
14028
14685
  for (const section of sectionsToVerify) {
14029
14686
  for (const item of getSectionEntries(map[section])) {
14030
14687
  if (item?.path) {
14031
- indexedPaths.add(path17.normalize(item.path));
14688
+ indexedPaths.add(path20.normalize(item.path));
14032
14689
  if (section === "links" && (item.path.startsWith("http://") || item.path.startsWith("https://"))) {
14033
14690
  continue;
14034
14691
  }
14035
- const absPath = path17.isAbsolute(item.path) ? item.path : path17.join(pathBase, item.path);
14036
- if (!fs16.existsSync(absPath)) {
14692
+ const absPath = path20.isAbsolute(item.path) ? item.path : path20.join(pathBase, item.path);
14693
+ if (!fs19.existsSync(absPath)) {
14037
14694
  errors.push(`${filePath}: ${section.slice(0, -1)} path does not exist: ${item.path}`);
14038
14695
  }
14039
14696
  }
14040
14697
  }
14041
14698
  }
14042
- const relDir = path17.relative(worktree, dir);
14699
+ const relDir = path20.relative(worktree, dir);
14043
14700
  const isOperational = isOperationalRelPath2(relDir);
14044
14701
  if (map.scope === "module" && !isOperational) {
14045
- const items = fs16.readdirSync(dir, { withFileTypes: true });
14702
+ const items = fs19.readdirSync(dir, { withFileTypes: true });
14046
14703
  for (const item of items) {
14047
- if (item.isFile() && sourceExtensions.includes(path17.extname(item.name))) {
14704
+ if (item.isFile() && sourceExtensions.includes(path20.extname(item.name))) {
14048
14705
  if (item.name === "codemap.yml") continue;
14049
- if (!indexedPaths.has(path17.normalize(item.name))) {
14706
+ if (!indexedPaths.has(path20.normalize(item.name))) {
14050
14707
  errors.push(`${filePath}: Unindexed source file found: '${item.name}'. Every source file must be categorized in a section (e.g., 'internals').`);
14051
14708
  }
14052
14709
  }
@@ -14056,7 +14713,7 @@ async function optima_validate_logic(worktree) {
14056
14713
  for (const key of pathKeys) {
14057
14714
  for (const entry of getSectionEntries(map[key])) {
14058
14715
  if (!entry?.path || entry.path.startsWith("http://") || entry.path.startsWith("https://")) continue;
14059
- if (path17.isAbsolute(entry.path)) continue;
14716
+ if (path20.isAbsolute(entry.path)) continue;
14060
14717
  const normalizedPath = normalizeRelativePath(entry.path);
14061
14718
  if (!normalizedPath || normalizedPath === ".") continue;
14062
14719
  const parts = normalizedPath.split("/").filter((p) => p && p !== ".");
@@ -14068,18 +14725,18 @@ async function optima_validate_logic(worktree) {
14068
14725
  }
14069
14726
  }
14070
14727
  const walk = (dir) => {
14071
- const relDir = path17.relative(worktree, dir);
14728
+ const relDir = path20.relative(worktree, dir);
14072
14729
  if (relDir && ig.ignores(relDir)) return;
14073
14730
  if (isOperationalRelPath2(relDir)) return;
14074
14731
  if (isHiddenTree2(relDir)) return;
14075
- const hasCodemap = fs16.existsSync(path17.join(dir, "codemap.yml"));
14076
- const items = fs16.readdirSync(dir, { withFileTypes: true });
14077
- if (!relDir.startsWith(path17.join(".optima", "tasks", "done"))) {
14732
+ const hasCodemap = fs19.existsSync(path20.join(dir, "codemap.yml"));
14733
+ const items = fs19.readdirSync(dir, { withFileTypes: true });
14734
+ if (!relDir.startsWith(path20.join(".optima", "tasks", "done"))) {
14078
14735
  for (const item of items) {
14079
14736
  if (item.isFile() && item.name.endsWith(".md")) {
14080
- const content = fs16.readFileSync(path17.join(dir, item.name), "utf8");
14737
+ const content = fs19.readFileSync(path20.join(dir, item.name), "utf8");
14081
14738
  if (content.includes("[To be defined]") || content.includes("[Insert ")) {
14082
- const relFilePath = path17.join(relDir, item.name);
14739
+ const relFilePath = path20.join(relDir, item.name);
14083
14740
  errors.push(`Documentation Placeholder found: '${relFilePath}' still contains [To be defined] or [Insert ...] placeholders.`);
14084
14741
  }
14085
14742
  }
@@ -14089,9 +14746,9 @@ async function optima_validate_logic(worktree) {
14089
14746
  if (relDir !== "" && !hasCodemap && isSourceDir(dir) && !isOperational) {
14090
14747
  errors.push(`Missing CodeMap: Directory '${relDir}' contains source but has no codemap.yml.`);
14091
14748
  }
14092
- if (hasCodemap) validateMap(path17.join(dir, "codemap.yml"));
14749
+ if (hasCodemap) validateMap(path20.join(dir, "codemap.yml"));
14093
14750
  for (const item of items) {
14094
- if (item.isDirectory()) walk(path17.join(dir, item.name));
14751
+ if (item.isDirectory()) walk(path20.join(dir, item.name));
14095
14752
  }
14096
14753
  };
14097
14754
  validateMap(rootCodemapPath);
@@ -14105,12 +14762,13 @@ async function optima_validate_logic(worktree) {
14105
14762
 
14106
14763
  // src/plugin.js
14107
14764
  var activeWorkflows = /* @__PURE__ */ new Map();
14765
+ var activeQaQueueSchedulers = /* @__PURE__ */ new Map();
14108
14766
  function normalizeWorkflowTaskPath(taskPath) {
14109
14767
  if (typeof taskPath !== "string") return { ok: false, message: "Error: task_path is required." };
14110
14768
  const trimmed = taskPath.trim();
14111
14769
  if (!trimmed) return { ok: false, message: "Error: task_path is required." };
14112
14770
  const normalized = trimmed.replace(/\\/g, "/");
14113
- if (path18.isAbsolute(trimmed)) return { ok: true, taskPath: trimmed };
14771
+ if (path21.isAbsolute(trimmed)) return { ok: true, taskPath: trimmed };
14114
14772
  if (normalized === "tasks" || normalized.startsWith("tasks/")) {
14115
14773
  return {
14116
14774
  ok: false,
@@ -14127,10 +14785,10 @@ function normalizeWorkflowTaskPath(taskPath) {
14127
14785
  }
14128
14786
  function readTaskMetadata(taskPath, worktree) {
14129
14787
  if (!taskPath) return {};
14130
- const absoluteTaskPath = path18.isAbsolute(taskPath) ? taskPath : path18.join(worktree, taskPath);
14131
- if (!fs17.existsSync(absoluteTaskPath)) return {};
14788
+ const absoluteTaskPath = path21.isAbsolute(taskPath) ? taskPath : path21.join(worktree, taskPath);
14789
+ if (!fs20.existsSync(absoluteTaskPath)) return {};
14132
14790
  try {
14133
- const raw = fs17.readFileSync(absoluteTaskPath, "utf8");
14791
+ const raw = fs20.readFileSync(absoluteTaskPath, "utf8");
14134
14792
  const { data } = parseFrontmatter(raw);
14135
14793
  return {
14136
14794
  complexity: typeof data.complexity === "string" ? data.complexity.trim().toLowerCase() : void 0,
@@ -14153,15 +14811,15 @@ function hasActiveImplementationWorkflow() {
14153
14811
  function resolveSessionToolDirectory({ requestedDirectory, context, pluginWorktree, clickUpWebhookValidation } = {}) {
14154
14812
  const safe = safeWorktreeOrFailure(context, pluginWorktree);
14155
14813
  if (!safe.ok) return { ok: false, error: safe.message };
14156
- const requested = String(requestedDirectory || "").trim() ? path18.resolve(safe.worktree, String(requestedDirectory).trim()) : safe.worktree;
14814
+ const requested = String(requestedDirectory || "").trim() ? path21.resolve(safe.worktree, String(requestedDirectory).trim()) : safe.worktree;
14157
14815
  if (!isSafeWritableDirectory(requested)) return { ok: false, error: `Directory is not a safe writable directory: ${requested}` };
14158
14816
  if (isSameOrNestedPath(requested, safe.worktree)) return { ok: true, directory: requested, safeWorktree: safe.worktree, scope: "context_worktree" };
14159
14817
  const clickUpBasePath = clickUpWebhookValidation?.complete === true && clickUpWebhookValidation?.ok !== false ? clickUpWebhookValidation.config?.basePath : "";
14160
14818
  if (clickUpBasePath && isSameOrNestedPath(requested, clickUpBasePath)) {
14161
- return { ok: true, directory: requested, safeWorktree: safe.worktree, scope: "clickup_base_path", clickupBasePath: path18.resolve(clickUpBasePath) };
14819
+ return { ok: true, directory: requested, safeWorktree: safe.worktree, scope: "clickup_base_path", clickupBasePath: path21.resolve(clickUpBasePath) };
14162
14820
  }
14163
14821
  if (clickUpBasePath && isClickUpDerivedWorktreeSibling(requested, clickUpBasePath)) {
14164
- return { ok: true, directory: requested, safeWorktree: safe.worktree, scope: "clickup_derived_worktree", clickupBasePath: path18.resolve(clickUpBasePath) };
14822
+ return { ok: true, directory: requested, safeWorktree: safe.worktree, scope: "clickup_derived_worktree", clickupBasePath: path21.resolve(clickUpBasePath) };
14165
14823
  }
14166
14824
  return {
14167
14825
  ok: false,
@@ -14176,9 +14834,9 @@ async function OptimaPlugin(input = {}, pluginOptions = {}) {
14176
14834
  const configPath = resolveConfigPath(worktree);
14177
14835
  const discussionRegistry = loadDiscussionRegistry(worktree);
14178
14836
  let repoCfg = { agents: {}, defaults: {}, features: {} };
14179
- if (fs17.existsSync(configPath)) {
14837
+ if (fs20.existsSync(configPath)) {
14180
14838
  try {
14181
- repoCfg = import_yaml6.default.parse(fs17.readFileSync(configPath, "utf8")) || repoCfg;
14839
+ repoCfg = import_yaml6.default.parse(fs20.readFileSync(configPath, "utf8")) || repoCfg;
14182
14840
  } catch (e) {
14183
14841
  console.error(`[Optima] Failed to parse config at ${configPath}:`, e);
14184
14842
  }
@@ -14339,6 +14997,134 @@ Evidencia: ${evidencePath}` : ""
14339
14997
  applied
14340
14998
  };
14341
14999
  };
15000
+ const qaLeaseMs = Number(repoCfg.qa?.lease_ms || repoCfg.qa?.leaseMs || DEFAULT_QA_LEASE_MS) || DEFAULT_QA_LEASE_MS;
15001
+ const qaProvider = String(repoCfg.qa?.provider || DEFAULT_QA_PROVIDER);
15002
+ const qaCdpUrl = String(repoCfg.qa?.cdp_url || repoCfg.qa?.cdpUrl || process.env.OPTIMA_QA_CHROME_CDP_URL || "").trim();
15003
+ const qaTaskMetadata = async (taskId) => {
15004
+ if (!taskId || typeof runtimeClickUpClient?.getTask !== "function") return { task: null, metadata: {} };
15005
+ const task = await runtimeClickUpClient.getTask(taskId);
15006
+ const metadata = normalizeAgentMetadataJson(clickUpTaskAgentMetadata(task, clickUpWebhookValidation.config?.routing?.metadataFieldId));
15007
+ return { task, metadata };
15008
+ };
15009
+ const qaSessionFromMetadata = (metadata = {}) => {
15010
+ return metadata.optima?.sessions?.product_manager || metadata.task?.product_manager || metadata.sessions?.product_manager || "";
15011
+ };
15012
+ const qaWorktreeFromMetadata = (metadata = {}) => {
15013
+ return metadata.task?.worktree || metadata.worktree || "";
15014
+ };
15015
+ const applyQaQueuedClickUpState = async (taskId) => {
15016
+ const applied = [];
15017
+ const errors = [];
15018
+ const pmId = String(clickUpWebhookValidation.config?.routing?.productManagerAssigneeId || "").trim();
15019
+ if (!taskId || !clickUpWebhookValidation.complete || !runtimeClickUpClient) return { applied, errors };
15020
+ if (runtimeClickUpClient.updateTaskStatus) {
15021
+ try {
15022
+ await runtimeClickUpClient.updateTaskStatus({ taskId, status: "waiting QA slot" });
15023
+ applied.push("status:waiting QA slot");
15024
+ } catch (error) {
15025
+ errors.push(`status:${error.message}`);
15026
+ }
15027
+ }
15028
+ if (pmId && runtimeClickUpClient.updateTaskAssignees) {
15029
+ try {
15030
+ await runtimeClickUpClient.updateTaskAssignees({ taskId, remove: [pmId] });
15031
+ applied.push("remove_product_manager");
15032
+ } catch (error) {
15033
+ errors.push(`assignees:${error.message}`);
15034
+ }
15035
+ }
15036
+ return { applied, errors };
15037
+ };
15038
+ const wakePromotedQaTask = async (entry, { provider = qaProvider, reason = "qa_slot_available" } = {}) => {
15039
+ const taskId = String(entry?.clickupTaskId || "").trim();
15040
+ const applied = [];
15041
+ const errors = [];
15042
+ if (!taskId || !clickUpWebhookValidation.complete) return { ok: false, reason: "missing_task_or_clickup_config" };
15043
+ const pmId = String(clickUpWebhookValidation.config?.routing?.productManagerAssigneeId || "").trim();
15044
+ const humanIds = Object.values(clickUpWebhookValidation.config?.routing?.humanRoleClickUpIds || {}).map((id) => String(id || "").trim()).filter(Boolean);
15045
+ try {
15046
+ if (runtimeClickUpClient.updateTaskStatus) {
15047
+ await runtimeClickUpClient.updateTaskStatus({ taskId, status: "in progress" });
15048
+ applied.push("status:in progress");
15049
+ }
15050
+ } catch (error) {
15051
+ errors.push(`status:${error.message}`);
15052
+ }
15053
+ try {
15054
+ if (pmId && runtimeClickUpClient.updateTaskAssignees) {
15055
+ await runtimeClickUpClient.updateTaskAssignees({ taskId, add: [pmId], remove: humanIds });
15056
+ applied.push("assign_product_manager");
15057
+ }
15058
+ } catch (error) {
15059
+ errors.push(`assignees:${error.message}`);
15060
+ }
15061
+ let metadata = {};
15062
+ try {
15063
+ metadata = (await qaTaskMetadata(taskId)).metadata;
15064
+ } catch (error) {
15065
+ errors.push(`metadata:${error.message}`);
15066
+ }
15067
+ const sessionId = entry.sessionId || qaSessionFromMetadata(metadata);
15068
+ const directory = entry.worktree || qaWorktreeFromMetadata(metadata);
15069
+ if (sessionId && input.client && typeof sendOpenCodeSessionEvent === "function") {
15070
+ try {
15071
+ const prompt = [
15072
+ `[Optima QA Slot Granted]`,
15073
+ `Provider: ${provider}`,
15074
+ `ClickUp task: ${taskId}`,
15075
+ `Reason: ${reason}`,
15076
+ "",
15077
+ "Ya tienes plaza exclusiva para usar el Chrome QA. Debes llamar a `optima_qa_chrome_command` en menos de 5 minutos para conservar la plaza.",
15078
+ "Puedes conservarla mientras hagas al menos una llamada QA cada 5 minutos.",
15079
+ "Cuando termines, llama obligatoriamente a `optima_qa_finish` para resetear la extensi\xF3n y liberar la cola.",
15080
+ "La pesta\xF1a 0 es intocable: usa \xFAnicamente la pesta\xF1a QA que Optima crea para esta tarea."
15081
+ ].join("\n");
15082
+ await sendOpenCodeSessionEvent(input.client, {
15083
+ sessionId,
15084
+ agent: clickUpWebhookValidation.config.routing?.targetAgent || "workflow_product_manager",
15085
+ text: prompt,
15086
+ directory,
15087
+ opencodeBaseUrl: clickUpWebhookValidation.config.opencode?.baseUrl,
15088
+ fetchImpl: input.fetch,
15089
+ directDelivery: "steer"
15090
+ });
15091
+ applied.push("session_prompt");
15092
+ } catch (error) {
15093
+ errors.push(`session_prompt:${error.message}`);
15094
+ }
15095
+ } else {
15096
+ errors.push("session_prompt:missing_session_or_client");
15097
+ }
15098
+ return { ok: errors.length === 0, taskId, sessionId, directory, applied, errors };
15099
+ };
15100
+ const persistQaState = async (provider, state, transitions = {}) => {
15101
+ const written = writeQaQueueState(state, qaQueueStatePath(provider));
15102
+ const notifications = [];
15103
+ const promoted = transitions.promoted || null;
15104
+ if (promoted?.clickupTaskId) notifications.push(await wakePromotedQaTask(promoted, { provider, reason: transitions.reason || "qa_slot_available" }));
15105
+ return { state: written, notifications };
15106
+ };
15107
+ const scheduleQaQueueReaper = () => {
15108
+ if (input.startQaQueueScheduler === false) return;
15109
+ const provider = qaProvider || DEFAULT_QA_PROVIDER;
15110
+ const schedulerKey = `${provider}:${clickUpWebhookValidation.config?.basePath || worktree}`;
15111
+ if (activeQaQueueSchedulers.has(schedulerKey)) return;
15112
+ const interval = setInterval(async () => {
15113
+ try {
15114
+ const statePath = qaQueueStatePath(provider);
15115
+ const current = readQaQueueState(provider, statePath);
15116
+ const result = releaseExpiredQaSlot(current, { leaseMs: qaLeaseMs });
15117
+ if (result.expired || result.promoted) {
15118
+ await persistQaState(provider, result.state, { promoted: result.promoted, reason: result.expired ? "previous_slot_expired" : "qa_slot_available" });
15119
+ }
15120
+ } catch (error) {
15121
+ appendClickUpWebhookLocalLog(worktree, { type: "qa_queue_reaper_failed", provider, message: error.message });
15122
+ }
15123
+ }, Math.min(6e4, Math.max(1e4, Math.floor(qaLeaseMs / 5))));
15124
+ interval.unref?.();
15125
+ activeQaQueueSchedulers.set(schedulerKey, interval);
15126
+ };
15127
+ scheduleQaQueueReaper();
14342
15128
  const tools = {
14343
15129
  optima_init: tool({
14344
15130
  description: "Initialize the Optima workflow and CodeMap in the current repository",
@@ -14355,10 +15141,10 @@ Evidencia: ${evidencePath}` : ""
14355
15141
  }
14356
15142
  migrateLegacyOptimaLayout(toolWorktree);
14357
15143
  const cfgDir = optimaConfigDir(toolWorktree);
14358
- if (!fs17.existsSync(cfgDir)) fs17.mkdirSync(cfgDir, { recursive: true });
14359
- const optimaTmplPath = path18.join(TEMPLATES_DIR, "optima.yaml.template");
14360
- const codemapTmplPath = path18.join(TEMPLATES_DIR, "codemap.yml.template");
14361
- if (!fs17.existsSync(optimaTmplPath) || !fs17.existsSync(codemapTmplPath)) {
15144
+ if (!fs20.existsSync(cfgDir)) fs20.mkdirSync(cfgDir, { recursive: true });
15145
+ const optimaTmplPath = path21.join(TEMPLATES_DIR, "optima.yaml.template");
15146
+ const codemapTmplPath = path21.join(TEMPLATES_DIR, "codemap.yml.template");
15147
+ if (!fs20.existsSync(optimaTmplPath) || !fs20.existsSync(codemapTmplPath)) {
14362
15148
  return "Error: Initialization templates not found in plugin.";
14363
15149
  }
14364
15150
  scaffoldOptimaConfig(toolWorktree, requestedTeamMode);
@@ -14479,14 +15265,14 @@ Restart or reload OpenCode manually if the newly scaffolded config or agents are
14479
15265
  async execute(args, context) {
14480
15266
  const safe = safeWorktreeOrFailure(context, worktree);
14481
15267
  if (!safe.ok) return safe.message;
14482
- const summaryPath = path18.resolve(safe.worktree, args.summary_path || "");
14483
- if (!fs17.existsSync(summaryPath)) return `FAIL: summary_path not found: ${summaryPath}`;
14484
- const taskPath = args.task_path ? path18.resolve(safe.worktree, args.task_path) : "";
15268
+ const summaryPath = path21.resolve(safe.worktree, args.summary_path || "");
15269
+ if (!fs20.existsSync(summaryPath)) return `FAIL: summary_path not found: ${summaryPath}`;
15270
+ const taskPath = args.task_path ? path21.resolve(safe.worktree, args.task_path) : "";
14485
15271
  const payload = buildClickUpSummaryPayload({
14486
- summaryMarkdown: fs17.readFileSync(summaryPath, "utf8"),
14487
- summaryPath: path18.relative(safe.worktree, summaryPath),
14488
- taskMarkdown: taskPath && fs17.existsSync(taskPath) ? fs17.readFileSync(taskPath, "utf8") : "",
14489
- taskPath: taskPath ? path18.relative(safe.worktree, taskPath) : "",
15272
+ summaryMarkdown: fs20.readFileSync(summaryPath, "utf8"),
15273
+ summaryPath: path21.relative(safe.worktree, summaryPath),
15274
+ taskMarkdown: taskPath && fs20.existsSync(taskPath) ? fs20.readFileSync(taskPath, "utf8") : "",
15275
+ taskPath: taskPath ? path21.relative(safe.worktree, taskPath) : "",
14490
15276
  branch: args.branch,
14491
15277
  worktree: args.worktree,
14492
15278
  pr: args.pr
@@ -14579,6 +15365,116 @@ Restart or reload OpenCode manually if the newly scaffolded config or agents are
14579
15365
  }
14580
15366
  }
14581
15367
  }),
15368
+ optima_qa_browser_status: tool({
15369
+ description: "Inspect the shared Optima QA browser and queue state for a provider such as chatgpt.",
15370
+ args: {
15371
+ provider: tool.schema.string().optional().describe("QA provider. Defaults to chatgpt."),
15372
+ clickup_task_id: tool.schema.string().optional().describe("Optional ClickUp task id to identify its QA tab."),
15373
+ cdp_url: tool.schema.string().optional().describe("Optional Chrome DevTools URL. Defaults to configured QA URL or http://127.0.0.1:9222.")
15374
+ },
15375
+ async execute(args = {}) {
15376
+ const provider = String(args.provider || qaProvider || DEFAULT_QA_PROVIDER);
15377
+ const state = readQaQueueState(provider);
15378
+ const browser = await qaBrowserStatus({ provider, cdpUrl: args.cdp_url || qaCdpUrl, clickupTaskId: args.clickup_task_id || "" });
15379
+ return JSON.stringify({ ok: browser.ok !== false, provider, leaseMs: qaLeaseMs, queue: state, browser }, null, 2);
15380
+ }
15381
+ }),
15382
+ optima_qa_request_slot: tool({
15383
+ description: "Request the exclusive QA browser slot for a ClickUp task. If busy, Optima queues the task, marks it waiting QA slot, and removes Product Manager assignment.",
15384
+ args: {
15385
+ clickup_task_id: tool.schema.string().describe("ClickUp task id requesting the QA slot"),
15386
+ provider: tool.schema.string().optional().describe("QA provider. Defaults to chatgpt."),
15387
+ session_id: tool.schema.string().optional().describe("Optional OpenCode session id to wake when the slot is granted later"),
15388
+ worktree: tool.schema.string().optional().describe("Optional task worktree/directory for session wakeups"),
15389
+ reason: tool.schema.string().optional().describe("Short reason/scenario for requesting the QA slot")
15390
+ },
15391
+ async execute(args = {}) {
15392
+ const provider = String(args.provider || qaProvider || DEFAULT_QA_PROVIDER);
15393
+ const pathToState = qaQueueStatePath(provider);
15394
+ const current = readQaQueueState(provider, pathToState);
15395
+ const result = requestQaSlot(current, {
15396
+ clickupTaskId: args.clickup_task_id,
15397
+ sessionId: args.session_id,
15398
+ worktree: args.worktree,
15399
+ reason: args.reason,
15400
+ leaseMs: qaLeaseMs
15401
+ });
15402
+ let queuedClickUp = null;
15403
+ if (result.action === "queued") queuedClickUp = await applyQaQueuedClickUpState(args.clickup_task_id);
15404
+ const persisted = await persistQaState(provider, result.state, { promoted: result.promoted, reason: result.expired ? "previous_slot_expired" : "qa_slot_available" });
15405
+ const guidance = result.ok ? "QA slot granted. Use optima_qa_chrome_command within 5 minutes and then at least once every 5 minutes. Use optima_qa_finish when done." : "QA slot busy. Task has been queued; stop work on QA, wait for Optima to reassign/wake the session when your slot is granted.";
15406
+ return JSON.stringify({ ...result, state: persisted.state, notifications: persisted.notifications, queuedClickUp, guidance }, null, 2);
15407
+ }
15408
+ }),
15409
+ optima_qa_chrome_command: tool({
15410
+ description: "Run one flexible Playwright/CDP command against the shared QA Chrome for the active ClickUp task. The persistent tab 0 is never used; Optima creates/reuses a task QA tab.",
15411
+ args: {
15412
+ clickup_task_id: tool.schema.string().describe("ClickUp task id that currently owns the QA slot"),
15413
+ provider: tool.schema.string().optional().describe("QA provider. Defaults to chatgpt."),
15414
+ command_json: tool.schema.string().describe("JSON command object, or raw async JS script. Actions: status, goto, evaluate, screenshot, set_input_files, script."),
15415
+ cdp_url: tool.schema.string().optional().describe("Optional Chrome DevTools URL"),
15416
+ start_url: tool.schema.string().optional().describe("Initial URL for a new QA tab. Defaults to https://chatgpt.com/")
15417
+ },
15418
+ async execute(args = {}) {
15419
+ const provider = String(args.provider || qaProvider || DEFAULT_QA_PROVIDER);
15420
+ const pathToState = qaQueueStatePath(provider);
15421
+ const current = readQaQueueState(provider, pathToState);
15422
+ const touched = touchQaSlot(current, { clickupTaskId: args.clickup_task_id, leaseMs: qaLeaseMs });
15423
+ const persisted = await persistQaState(provider, touched.state, { promoted: touched.promoted, reason: touched.expired ? "previous_slot_expired" : "qa_slot_available" });
15424
+ if (!touched.ok) {
15425
+ return JSON.stringify({
15426
+ ok: false,
15427
+ action: touched.action,
15428
+ active: persisted.state.active,
15429
+ queue: persisted.state.queue,
15430
+ notifications: persisted.notifications,
15431
+ guidance: "You do not own the QA slot. Call optima_qa_request_slot and stop if queued."
15432
+ }, null, 2);
15433
+ }
15434
+ try {
15435
+ const result = await qaRunChromeCommand({
15436
+ provider,
15437
+ cdpUrl: args.cdp_url || qaCdpUrl,
15438
+ clickupTaskId: args.clickup_task_id,
15439
+ commandJson: args.command_json,
15440
+ startUrl: args.start_url || "https://chatgpt.com/"
15441
+ });
15442
+ return JSON.stringify({ ok: result.ok !== false, lease: persisted.state.active, notifications: persisted.notifications, chrome: result }, null, 2);
15443
+ } catch (error) {
15444
+ return JSON.stringify({ ok: false, error: error.message, lease: persisted.state.active, notifications: persisted.notifications }, null, 2);
15445
+ }
15446
+ }
15447
+ }),
15448
+ optima_qa_finish: tool({
15449
+ description: "Finish the active QA browser slot, reset/reload the extension, release the slot, and wake the next queued ClickUp task if any.",
15450
+ args: {
15451
+ clickup_task_id: tool.schema.string().describe("ClickUp task id finishing QA"),
15452
+ provider: tool.schema.string().optional().describe("QA provider. Defaults to chatgpt."),
15453
+ cdp_url: tool.schema.string().optional().describe("Optional Chrome DevTools URL"),
15454
+ extension_path: tool.schema.string().optional().describe("Optional extension path to sync into the stable QA extension-under-test directory before reset/reload"),
15455
+ extension_id: tool.schema.string().optional().describe("Optional Chrome extension id when multiple extension service workers exist"),
15456
+ reset_extension: tool.schema.boolean().optional().describe("Defaults true. Clear extension storage/caches/IndexedDB."),
15457
+ reload_extension: tool.schema.boolean().optional().describe("Defaults true. Reload the extension service worker after reset.")
15458
+ },
15459
+ async execute(args = {}) {
15460
+ const provider = String(args.provider || qaProvider || DEFAULT_QA_PROVIDER);
15461
+ const reset = args.reset_extension !== false;
15462
+ const reload = args.reload_extension !== false;
15463
+ const extension = await qaPrepareExtension({
15464
+ provider,
15465
+ cdpUrl: args.cdp_url || qaCdpUrl,
15466
+ extensionPath: args.extension_path || "",
15467
+ extensionId: args.extension_id || "",
15468
+ reset,
15469
+ reload
15470
+ }).catch((error) => ({ ok: false, error: error.message }));
15471
+ const pathToState = qaQueueStatePath(provider);
15472
+ const current = readQaQueueState(provider, pathToState);
15473
+ const result = finishQaSlot(current, { clickupTaskId: args.clickup_task_id, leaseMs: qaLeaseMs });
15474
+ const persisted = await persistQaState(provider, result.state, { promoted: result.promoted, reason: "previous_finished" });
15475
+ return JSON.stringify({ ...result, state: persisted.state, notifications: persisted.notifications, extension }, null, 2);
15476
+ }
15477
+ }),
14582
15478
  optima_clickup_create_subtasks: tool({
14583
15479
  description: "Generate dry-run ClickUp subtask creation payloads from a strict Markdown ## Subtasks section",
14584
15480
  args: {
@@ -14591,12 +15487,12 @@ Restart or reload OpenCode manually if the newly scaffolded config or agents are
14591
15487
  async execute(args, context) {
14592
15488
  const safe = safeWorktreeOrFailure(context, worktree);
14593
15489
  if (!safe.ok) return safe.message;
14594
- const markdownPath = path18.resolve(safe.worktree, args.markdown_path || "");
14595
- if (!fs17.existsSync(markdownPath)) return `FAIL: markdown_path not found: ${markdownPath}`;
15490
+ const markdownPath = path21.resolve(safe.worktree, args.markdown_path || "");
15491
+ if (!fs20.existsSync(markdownPath)) return `FAIL: markdown_path not found: ${markdownPath}`;
14596
15492
  const payload = buildClickUpCreateSubtasksPayload({
14597
15493
  parentTaskId: args.parent_task_id,
14598
- markdown: fs17.readFileSync(markdownPath, "utf8"),
14599
- sourcePath: path18.relative(safe.worktree, markdownPath),
15494
+ markdown: fs20.readFileSync(markdownPath, "utf8"),
15495
+ sourcePath: path21.relative(safe.worktree, markdownPath),
14600
15496
  parentBranch: args.parent_branch,
14601
15497
  parentTaskType: args.parent_task_type || "Tarea",
14602
15498
  apply: String(args.apply || "").toLowerCase() === "true"
@@ -14966,7 +15862,7 @@ Backfilled messages: ${backfilled}`;
14966
15862
  if (!existing) {
14967
15863
  return "FAIL: No active discussion exists for this session.";
14968
15864
  }
14969
- const discussionPath = path18.join(toolWorktree, existing.transcriptPath);
15865
+ const discussionPath = path21.join(toolWorktree, existing.transcriptPath);
14970
15866
  setDiscussionStatus(discussionPath, "summarizing");
14971
15867
  existing.status = "summarizing";
14972
15868
  saveDiscussionRegistry(toolWorktree, toolRegistry);
@@ -15018,7 +15914,7 @@ Reason: ${err.message}`;
15018
15914
  try {
15019
15915
  const sessionResult = await client.session.create({
15020
15916
  query: { directory: workflowDirectory },
15021
- body: { title: `Workflow Run: ${path18.basename(workflowTaskPath)}` }
15917
+ body: { title: `Workflow Run: ${path21.basename(workflowTaskPath)}` }
15022
15918
  });
15023
15919
  const sessionId = sessionResult.data.id;
15024
15920
  activeWorkflows.set(sessionId, { pmaSessionId, taskPath: workflowTaskPath, track: workflowTrack, directory: workflowDirectory });