polymath-society 0.2.8 → 0.2.9

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
@@ -13,9 +13,9 @@ var __export = (target, all) => {
13
13
  };
14
14
  var __copyProps = (to, from, except, desc) => {
15
15
  if (from && typeof from === "object" || typeof from === "function") {
16
- for (let key of __getOwnPropNames(from))
17
- if (!__hasOwnProp.call(to, key) && key !== except)
18
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ for (let key2 of __getOwnPropNames(from))
17
+ if (!__hasOwnProp.call(to, key2) && key2 !== except)
18
+ __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
19
19
  }
20
20
  return to;
21
21
  };
@@ -94,8 +94,8 @@ var require_secure_json_parse = __commonJS({
94
94
  }
95
95
  delete node.constructor;
96
96
  }
97
- for (const key in node) {
98
- const value = node[key];
97
+ for (const key2 in node) {
98
+ const value = node[key2];
99
99
  if (value && typeof value === "object") {
100
100
  next.push(value);
101
101
  }
@@ -599,9 +599,9 @@ async function openCursorDb(dbPath) {
599
599
  }
600
600
  }
601
601
  return {
602
- get(key) {
602
+ get(key2) {
603
603
  try {
604
- const row = db.prepare("SELECT value FROM ItemTable WHERE key = ?").get(key);
604
+ const row = db.prepare("SELECT value FROM ItemTable WHERE key = ?").get(key2);
605
605
  if (!row || row.value == null)
606
606
  return [];
607
607
  const txt = typeof row.value === "string" ? row.value : Buffer.from(row.value).toString("utf-8");
@@ -832,10 +832,10 @@ function demoteTemplateFanouts(sessions) {
832
832
  for (const s of sessions) {
833
833
  if (s.klass !== "interactive" || s.humanTurns > 2)
834
834
  continue;
835
- const key = s.firstHuman.replace(/\s+/g, " ").trim().slice(0, FANOUT_PREFIX);
836
- if (key.length < FANOUT_PREFIX)
835
+ const key2 = s.firstHuman.replace(/\s+/g, " ").trim().slice(0, FANOUT_PREFIX);
836
+ if (key2.length < FANOUT_PREFIX)
837
837
  continue;
838
- (groups.get(key) ?? groups.set(key, []).get(key)).push(s);
838
+ (groups.get(key2) ?? groups.set(key2, []).get(key2)).push(s);
839
839
  }
840
840
  for (const g of groups.values()) {
841
841
  if (g.length < FANOUT_MIN_SESSIONS)
@@ -1189,10 +1189,10 @@ async function extractUserMessages(file2) {
1189
1189
  function createMessageDeduper() {
1190
1190
  const seen = /* @__PURE__ */ new Set();
1191
1191
  return (m) => {
1192
- const key = m.uuid ?? `${m.t}|${m.text}`;
1193
- if (seen.has(key))
1192
+ const key2 = m.uuid ?? `${m.t}|${m.text}`;
1193
+ if (seen.has(key2))
1194
1194
  return false;
1195
- seen.add(key);
1195
+ seen.add(key2);
1196
1196
  return true;
1197
1197
  };
1198
1198
  }
@@ -1722,8 +1722,8 @@ async function analyze(opts = {}) {
1722
1722
  const agent = raw.filter((s) => s.klass === "agent");
1723
1723
  const byReason = /* @__PURE__ */ new Map();
1724
1724
  for (const s of agent) {
1725
- const key = s.klassReason.startsWith("cwd:") ? "cwd:<agent-dir>" : s.klassReason;
1726
- byReason.set(key, (byReason.get(key) ?? 0) + 1);
1725
+ const key2 = s.klassReason.startsWith("cwd:") ? "cwd:<agent-dir>" : s.klassReason;
1726
+ byReason.set(key2, (byReason.get(key2) ?? 0) + 1);
1727
1727
  }
1728
1728
  const records = toSessionRecords(interactive, idleGapMin);
1729
1729
  const dupCount = await markDuplicates(records);
@@ -2308,9 +2308,9 @@ var UIKEY_FOR = [
2308
2308
  ["delegation", "delegation"],
2309
2309
  ["frontier", "frontier"]
2310
2310
  ];
2311
- var GRADED_CRITERIA2 = UIKEY_FOR.map(([key, uiKey]) => {
2312
- const c = GRADED_CRITERIA.find((rc) => rc.key === key);
2313
- if (!c || !c.rungs?.length) throw new Error(`repo rubric (lib/agents/coding/criteria.ts) no longer defines graded criterion "${key}" with rungs`);
2311
+ var GRADED_CRITERIA2 = UIKEY_FOR.map(([key2, uiKey]) => {
2312
+ const c = GRADED_CRITERIA.find((rc) => rc.key === key2);
2313
+ if (!c || !c.rungs?.length) throw new Error(`repo rubric (lib/agents/coding/criteria.ts) no longer defines graded criterion "${key2}" with rungs`);
2314
2314
  return { key: c.key, uiKey, label: c.label, definition: c.definition, read: c.read, rungs: c.rungs };
2315
2315
  });
2316
2316
  var RUBRIC_FINGERPRINT2 = rubricFingerprint(GRADED_CRITERIA2);
@@ -2503,15 +2503,15 @@ function validate(raw) {
2503
2503
  for (const r of arr) {
2504
2504
  if (!r || typeof r !== "object") continue;
2505
2505
  const o = r;
2506
- const key = String(o.key ?? "");
2507
- if (!keys.has(key) || seen.has(key)) continue;
2508
- seen.add(key);
2506
+ const key2 = String(o.key ?? "");
2507
+ if (!keys.has(key2) || seen.has(key2)) continue;
2508
+ seen.add(key2);
2509
2509
  const num3 = (v) => {
2510
2510
  const n = typeof v === "number" ? v : typeof v === "string" ? Number(v) : NaN;
2511
2511
  return Number.isFinite(n) && n >= 1 && n <= 11 ? Math.round(n * 100) / 100 : null;
2512
2512
  };
2513
2513
  out.push({
2514
- key,
2514
+ key: key2,
2515
2515
  score: num3(o.score),
2516
2516
  confidence: String(o.confidence ?? "firm"),
2517
2517
  low: num3(o.low),
@@ -2862,9 +2862,9 @@ var pmode = (hist) => {
2862
2862
  const e = Object.entries(hist).map(([k, v]) => [Number(k), v]).sort((a, b) => b[1] - a[1]);
2863
2863
  return e[0]?.[0] ?? 1;
2864
2864
  };
2865
- function gradedSection(detail, key) {
2865
+ function gradedSection(detail, key2) {
2866
2866
  if (!detail) return null;
2867
- const c = detail.criteria.find((x) => x.key === key);
2867
+ const c = detail.criteria.find((x) => x.key === key2);
2868
2868
  return c && c.n > 0 ? c : null;
2869
2869
  }
2870
2870
  function buildWebProfile(p, detail) {
@@ -3034,8 +3034,8 @@ var DEFAULT_SUPABASE_URL = "https://zcbonfjgiorrxczyekxl.supabase.co";
3034
3034
  var DEFAULT_SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InpjYm9uZmpnaW9ycnhjenlla3hsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODA3MDI5MDIsImV4cCI6MjA5NjI3ODkwMn0.f2KAwstDU765i-sUucKuzA-j0xMsKRKHVHXPRNFoud4";
3035
3035
  function centralConfig() {
3036
3036
  const url = process.env.PS_SUPABASE_URL ?? DEFAULT_SUPABASE_URL;
3037
- const key = process.env.PS_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY;
3038
- return { supabaseUrl: url, supabaseAnonKey: key, configured: Boolean(url && key) };
3037
+ const key2 = process.env.PS_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY;
3038
+ return { supabaseUrl: url, supabaseAnonKey: key2, configured: Boolean(url && key2) };
3039
3039
  }
3040
3040
 
3041
3041
  // src/auth.ts
@@ -4134,8 +4134,8 @@ function splitLines(buffer, chunk) {
4134
4134
  }
4135
4135
  function extractResponseHeaders(response) {
4136
4136
  const headers = {};
4137
- response.headers.forEach((value, key) => {
4138
- headers[key] = value;
4137
+ response.headers.forEach((value, key2) => {
4138
+ headers[key2] = value;
4139
4139
  });
4140
4140
  return headers;
4141
4141
  }
@@ -4660,19 +4660,19 @@ var getRefs = (options) => {
4660
4660
  };
4661
4661
 
4662
4662
  // ../../node_modules/zod-to-json-schema/dist/esm/errorMessages.js
4663
- function addErrorMessage(res, key, errorMessage, refs) {
4663
+ function addErrorMessage(res, key2, errorMessage, refs) {
4664
4664
  if (!refs?.errorMessages)
4665
4665
  return;
4666
4666
  if (errorMessage) {
4667
4667
  res.errorMessage = {
4668
4668
  ...res.errorMessage,
4669
- [key]: errorMessage
4669
+ [key2]: errorMessage
4670
4670
  };
4671
4671
  }
4672
4672
  }
4673
- function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
4674
- res[key] = value;
4675
- addErrorMessage(res, key, errorMessage, refs);
4673
+ function setResponseValueAndErrors(res, key2, value, errorMessage, refs) {
4674
+ res[key2] = value;
4675
+ addErrorMessage(res, key2, errorMessage, refs);
4676
4676
  }
4677
4677
 
4678
4678
  // ../../node_modules/zod-to-json-schema/dist/esm/getRelativePath.js
@@ -4831,9 +4831,9 @@ var util;
4831
4831
  };
4832
4832
  util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => {
4833
4833
  const keys = [];
4834
- for (const key in object2) {
4835
- if (Object.prototype.hasOwnProperty.call(object2, key)) {
4836
- keys.push(key);
4834
+ for (const key2 in object2) {
4835
+ if (Object.prototype.hasOwnProperty.call(object2, key2)) {
4836
+ keys.push(key2);
4837
4837
  }
4838
4838
  }
4839
4839
  return keys;
@@ -5233,10 +5233,10 @@ var ParseStatus = class _ParseStatus {
5233
5233
  static async mergeObjectAsync(status, pairs) {
5234
5234
  const syncPairs = [];
5235
5235
  for (const pair of pairs) {
5236
- const key = await pair.key;
5236
+ const key2 = await pair.key;
5237
5237
  const value = await pair.value;
5238
5238
  syncPairs.push({
5239
- key,
5239
+ key: key2,
5240
5240
  value
5241
5241
  });
5242
5242
  }
@@ -5245,17 +5245,17 @@ var ParseStatus = class _ParseStatus {
5245
5245
  static mergeObjectSync(status, pairs) {
5246
5246
  const finalObject = {};
5247
5247
  for (const pair of pairs) {
5248
- const { key, value } = pair;
5249
- if (key.status === "aborted")
5248
+ const { key: key2, value } = pair;
5249
+ if (key2.status === "aborted")
5250
5250
  return INVALID;
5251
5251
  if (value.status === "aborted")
5252
5252
  return INVALID;
5253
- if (key.status === "dirty")
5253
+ if (key2.status === "dirty")
5254
5254
  status.dirty();
5255
5255
  if (value.status === "dirty")
5256
5256
  status.dirty();
5257
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
5258
- finalObject[key.value] = value.value;
5257
+ if (key2.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
5258
+ finalObject[key2.value] = value.value;
5259
5259
  }
5260
5260
  }
5261
5261
  return { status: status.value, value: finalObject };
@@ -5280,12 +5280,12 @@ var errorUtil;
5280
5280
 
5281
5281
  // ../../node_modules/zod/v3/types.js
5282
5282
  var ParseInputLazyPath = class {
5283
- constructor(parent, value, path34, key) {
5283
+ constructor(parent, value, path34, key2) {
5284
5284
  this._cachedPath = [];
5285
5285
  this.parent = parent;
5286
5286
  this.data = value;
5287
5287
  this._path = path34;
5288
- this._key = key;
5288
+ this._key = key2;
5289
5289
  }
5290
5290
  get path() {
5291
5291
  if (!this._cachedPath.length) {
@@ -7030,9 +7030,9 @@ ZodArray.create = (schema, params) => {
7030
7030
  function deepPartialify(schema) {
7031
7031
  if (schema instanceof ZodObject) {
7032
7032
  const newShape = {};
7033
- for (const key in schema.shape) {
7034
- const fieldSchema = schema.shape[key];
7035
- newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
7033
+ for (const key2 in schema.shape) {
7034
+ const fieldSchema = schema.shape[key2];
7035
+ newShape[key2] = ZodOptional.create(deepPartialify(fieldSchema));
7036
7036
  }
7037
7037
  return new ZodObject({
7038
7038
  ...schema._def,
@@ -7083,29 +7083,29 @@ var ZodObject = class _ZodObject extends ZodType {
7083
7083
  const { shape, keys: shapeKeys } = this._getCached();
7084
7084
  const extraKeys = [];
7085
7085
  if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
7086
- for (const key in ctx.data) {
7087
- if (!shapeKeys.includes(key)) {
7088
- extraKeys.push(key);
7086
+ for (const key2 in ctx.data) {
7087
+ if (!shapeKeys.includes(key2)) {
7088
+ extraKeys.push(key2);
7089
7089
  }
7090
7090
  }
7091
7091
  }
7092
7092
  const pairs = [];
7093
- for (const key of shapeKeys) {
7094
- const keyValidator = shape[key];
7095
- const value = ctx.data[key];
7093
+ for (const key2 of shapeKeys) {
7094
+ const keyValidator = shape[key2];
7095
+ const value = ctx.data[key2];
7096
7096
  pairs.push({
7097
- key: { status: "valid", value: key },
7098
- value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
7099
- alwaysSet: key in ctx.data
7097
+ key: { status: "valid", value: key2 },
7098
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key2)),
7099
+ alwaysSet: key2 in ctx.data
7100
7100
  });
7101
7101
  }
7102
7102
  if (this._def.catchall instanceof ZodNever) {
7103
7103
  const unknownKeys = this._def.unknownKeys;
7104
7104
  if (unknownKeys === "passthrough") {
7105
- for (const key of extraKeys) {
7105
+ for (const key2 of extraKeys) {
7106
7106
  pairs.push({
7107
- key: { status: "valid", value: key },
7108
- value: { status: "valid", value: ctx.data[key] }
7107
+ key: { status: "valid", value: key2 },
7108
+ value: { status: "valid", value: ctx.data[key2] }
7109
7109
  });
7110
7110
  }
7111
7111
  } else if (unknownKeys === "strict") {
@@ -7122,15 +7122,15 @@ var ZodObject = class _ZodObject extends ZodType {
7122
7122
  }
7123
7123
  } else {
7124
7124
  const catchall = this._def.catchall;
7125
- for (const key of extraKeys) {
7126
- const value = ctx.data[key];
7125
+ for (const key2 of extraKeys) {
7126
+ const value = ctx.data[key2];
7127
7127
  pairs.push({
7128
- key: { status: "valid", value: key },
7128
+ key: { status: "valid", value: key2 },
7129
7129
  value: catchall._parse(
7130
- new ParseInputLazyPath(ctx, value, ctx.path, key)
7130
+ new ParseInputLazyPath(ctx, value, ctx.path, key2)
7131
7131
  //, ctx.child(key), value, getParsedType(value)
7132
7132
  ),
7133
- alwaysSet: key in ctx.data
7133
+ alwaysSet: key2 in ctx.data
7134
7134
  });
7135
7135
  }
7136
7136
  }
@@ -7138,10 +7138,10 @@ var ZodObject = class _ZodObject extends ZodType {
7138
7138
  return Promise.resolve().then(async () => {
7139
7139
  const syncPairs = [];
7140
7140
  for (const pair of pairs) {
7141
- const key = await pair.key;
7141
+ const key2 = await pair.key;
7142
7142
  const value = await pair.value;
7143
7143
  syncPairs.push({
7144
- key,
7144
+ key: key2,
7145
7145
  value,
7146
7146
  alwaysSet: pair.alwaysSet
7147
7147
  });
@@ -7266,8 +7266,8 @@ var ZodObject = class _ZodObject extends ZodType {
7266
7266
  // }) as any;
7267
7267
  // return merged;
7268
7268
  // }
7269
- setKey(key, schema) {
7270
- return this.augment({ [key]: schema });
7269
+ setKey(key2, schema) {
7270
+ return this.augment({ [key2]: schema });
7271
7271
  }
7272
7272
  // merge<Incoming extends AnyZodObject>(
7273
7273
  // merging: Incoming
@@ -7298,9 +7298,9 @@ var ZodObject = class _ZodObject extends ZodType {
7298
7298
  }
7299
7299
  pick(mask) {
7300
7300
  const shape = {};
7301
- for (const key of util.objectKeys(mask)) {
7302
- if (mask[key] && this.shape[key]) {
7303
- shape[key] = this.shape[key];
7301
+ for (const key2 of util.objectKeys(mask)) {
7302
+ if (mask[key2] && this.shape[key2]) {
7303
+ shape[key2] = this.shape[key2];
7304
7304
  }
7305
7305
  }
7306
7306
  return new _ZodObject({
@@ -7310,9 +7310,9 @@ var ZodObject = class _ZodObject extends ZodType {
7310
7310
  }
7311
7311
  omit(mask) {
7312
7312
  const shape = {};
7313
- for (const key of util.objectKeys(this.shape)) {
7314
- if (!mask[key]) {
7315
- shape[key] = this.shape[key];
7313
+ for (const key2 of util.objectKeys(this.shape)) {
7314
+ if (!mask[key2]) {
7315
+ shape[key2] = this.shape[key2];
7316
7316
  }
7317
7317
  }
7318
7318
  return new _ZodObject({
@@ -7328,12 +7328,12 @@ var ZodObject = class _ZodObject extends ZodType {
7328
7328
  }
7329
7329
  partial(mask) {
7330
7330
  const newShape = {};
7331
- for (const key of util.objectKeys(this.shape)) {
7332
- const fieldSchema = this.shape[key];
7333
- if (mask && !mask[key]) {
7334
- newShape[key] = fieldSchema;
7331
+ for (const key2 of util.objectKeys(this.shape)) {
7332
+ const fieldSchema = this.shape[key2];
7333
+ if (mask && !mask[key2]) {
7334
+ newShape[key2] = fieldSchema;
7335
7335
  } else {
7336
- newShape[key] = fieldSchema.optional();
7336
+ newShape[key2] = fieldSchema.optional();
7337
7337
  }
7338
7338
  }
7339
7339
  return new _ZodObject({
@@ -7343,16 +7343,16 @@ var ZodObject = class _ZodObject extends ZodType {
7343
7343
  }
7344
7344
  required(mask) {
7345
7345
  const newShape = {};
7346
- for (const key of util.objectKeys(this.shape)) {
7347
- if (mask && !mask[key]) {
7348
- newShape[key] = this.shape[key];
7346
+ for (const key2 of util.objectKeys(this.shape)) {
7347
+ if (mask && !mask[key2]) {
7348
+ newShape[key2] = this.shape[key2];
7349
7349
  } else {
7350
- const fieldSchema = this.shape[key];
7350
+ const fieldSchema = this.shape[key2];
7351
7351
  let newField = fieldSchema;
7352
7352
  while (newField instanceof ZodOptional) {
7353
7353
  newField = newField._def.innerType;
7354
7354
  }
7355
- newShape[key] = newField;
7355
+ newShape[key2] = newField;
7356
7356
  }
7357
7357
  }
7358
7358
  return new _ZodObject({
@@ -7596,14 +7596,14 @@ function mergeValues(a, b) {
7596
7596
  return { valid: true, data: a };
7597
7597
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
7598
7598
  const bKeys = util.objectKeys(b);
7599
- const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
7599
+ const sharedKeys = util.objectKeys(a).filter((key2) => bKeys.indexOf(key2) !== -1);
7600
7600
  const newObj = { ...a, ...b };
7601
- for (const key of sharedKeys) {
7602
- const sharedValue = mergeValues(a[key], b[key]);
7601
+ for (const key2 of sharedKeys) {
7602
+ const sharedValue = mergeValues(a[key2], b[key2]);
7603
7603
  if (!sharedValue.valid) {
7604
7604
  return { valid: false };
7605
7605
  }
7606
- newObj[key] = sharedValue.data;
7606
+ newObj[key2] = sharedValue.data;
7607
7607
  }
7608
7608
  return { valid: true, data: newObj };
7609
7609
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
@@ -7767,11 +7767,11 @@ var ZodRecord = class _ZodRecord extends ZodType {
7767
7767
  const pairs = [];
7768
7768
  const keyType = this._def.keyType;
7769
7769
  const valueType = this._def.valueType;
7770
- for (const key in ctx.data) {
7770
+ for (const key2 in ctx.data) {
7771
7771
  pairs.push({
7772
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
7773
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
7774
- alwaysSet: key in ctx.data
7772
+ key: keyType._parse(new ParseInputLazyPath(ctx, key2, ctx.path, key2)),
7773
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key2], ctx.path, key2)),
7774
+ alwaysSet: key2 in ctx.data
7775
7775
  });
7776
7776
  }
7777
7777
  if (ctx.common.async) {
@@ -7819,9 +7819,9 @@ var ZodMap = class extends ZodType {
7819
7819
  }
7820
7820
  const keyType = this._def.keyType;
7821
7821
  const valueType = this._def.valueType;
7822
- const pairs = [...ctx.data.entries()].map(([key, value], index) => {
7822
+ const pairs = [...ctx.data.entries()].map(([key2, value], index) => {
7823
7823
  return {
7824
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
7824
+ key: keyType._parse(new ParseInputLazyPath(ctx, key2, ctx.path, [index, "key"])),
7825
7825
  value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
7826
7826
  };
7827
7827
  });
@@ -7829,30 +7829,30 @@ var ZodMap = class extends ZodType {
7829
7829
  const finalMap = /* @__PURE__ */ new Map();
7830
7830
  return Promise.resolve().then(async () => {
7831
7831
  for (const pair of pairs) {
7832
- const key = await pair.key;
7832
+ const key2 = await pair.key;
7833
7833
  const value = await pair.value;
7834
- if (key.status === "aborted" || value.status === "aborted") {
7834
+ if (key2.status === "aborted" || value.status === "aborted") {
7835
7835
  return INVALID;
7836
7836
  }
7837
- if (key.status === "dirty" || value.status === "dirty") {
7837
+ if (key2.status === "dirty" || value.status === "dirty") {
7838
7838
  status.dirty();
7839
7839
  }
7840
- finalMap.set(key.value, value.value);
7840
+ finalMap.set(key2.value, value.value);
7841
7841
  }
7842
7842
  return { status: status.value, value: finalMap };
7843
7843
  });
7844
7844
  } else {
7845
7845
  const finalMap = /* @__PURE__ */ new Map();
7846
7846
  for (const pair of pairs) {
7847
- const key = pair.key;
7847
+ const key2 = pair.key;
7848
7848
  const value = pair.value;
7849
- if (key.status === "aborted" || value.status === "aborted") {
7849
+ if (key2.status === "aborted" || value.status === "aborted") {
7850
7850
  return INVALID;
7851
7851
  }
7852
- if (key.status === "dirty" || value.status === "dirty") {
7852
+ if (key2.status === "dirty" || value.status === "dirty") {
7853
7853
  status.dirty();
7854
7854
  }
7855
- finalMap.set(key.value, value.value);
7855
+ finalMap.set(key2.value, value.value);
7856
7856
  }
7857
7857
  return { status: status.value, value: finalMap };
7858
7858
  }
@@ -9305,11 +9305,11 @@ function parseRecordDef(def, refs) {
9305
9305
  return {
9306
9306
  type: "object",
9307
9307
  required: def.keyType._def.values,
9308
- properties: def.keyType._def.values.reduce((acc, key) => ({
9308
+ properties: def.keyType._def.values.reduce((acc, key2) => ({
9309
9309
  ...acc,
9310
- [key]: parseDef(def.valueType._def, {
9310
+ [key2]: parseDef(def.valueType._def, {
9311
9311
  ...refs,
9312
- currentPath: [...refs.currentPath, "properties", key]
9312
+ currentPath: [...refs.currentPath, "properties", key2]
9313
9313
  }) ?? parseAnyDef(refs)
9314
9314
  }), {}),
9315
9315
  additionalProperties: refs.rejectedAdditionalProperties
@@ -9376,10 +9376,10 @@ function parseMapDef(def, refs) {
9376
9376
  // ../../node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
9377
9377
  function parseNativeEnumDef(def) {
9378
9378
  const object2 = def.values;
9379
- const actualKeys = Object.keys(def.values).filter((key) => {
9380
- return typeof object2[object2[key]] !== "number";
9379
+ const actualKeys = Object.keys(def.values).filter((key2) => {
9380
+ return typeof object2[object2[key2]] !== "number";
9381
9381
  });
9382
- const actualValues = actualKeys.map((key) => object2[key]);
9382
+ const actualValues = actualKeys.map((key2) => object2[key2]);
9383
9383
  const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
9384
9384
  return {
9385
9385
  type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
@@ -10992,17 +10992,17 @@ var BaseContext = (
10992
10992
  function BaseContext2(parentContext) {
10993
10993
  var self = this;
10994
10994
  self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
10995
- self.getValue = function(key) {
10996
- return self._currentContext.get(key);
10995
+ self.getValue = function(key2) {
10996
+ return self._currentContext.get(key2);
10997
10997
  };
10998
- self.setValue = function(key, value) {
10998
+ self.setValue = function(key2, value) {
10999
10999
  var context = new BaseContext2(self._currentContext);
11000
- context._currentContext.set(key, value);
11000
+ context._currentContext.set(key2, value);
11001
11001
  return context;
11002
11002
  };
11003
- self.deleteValue = function(key) {
11003
+ self.deleteValue = function(key2) {
11004
11004
  var context = new BaseContext2(self._currentContext);
11005
- context._currentContext.delete(key);
11005
+ context._currentContext.delete(key2);
11006
11006
  return context;
11007
11007
  };
11008
11008
  }
@@ -11580,22 +11580,22 @@ function getBaseTelemetryAttributes({
11580
11580
  "ai.model.provider": model.provider,
11581
11581
  "ai.model.id": model.modelId,
11582
11582
  // settings:
11583
- ...Object.entries(settings).reduce((attributes, [key, value]) => {
11584
- attributes[`ai.settings.${key}`] = value;
11583
+ ...Object.entries(settings).reduce((attributes, [key2, value]) => {
11584
+ attributes[`ai.settings.${key2}`] = value;
11585
11585
  return attributes;
11586
11586
  }, {}),
11587
11587
  // add metadata as attributes:
11588
11588
  ...Object.entries((_a17 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a17 : {}).reduce(
11589
- (attributes, [key, value]) => {
11590
- attributes[`ai.telemetry.metadata.${key}`] = value;
11589
+ (attributes, [key2, value]) => {
11590
+ attributes[`ai.telemetry.metadata.${key2}`] = value;
11591
11591
  return attributes;
11592
11592
  },
11593
11593
  {}
11594
11594
  ),
11595
11595
  // request headers
11596
- ...Object.entries(headers != null ? headers : {}).reduce((attributes, [key, value]) => {
11596
+ ...Object.entries(headers != null ? headers : {}).reduce((attributes, [key2, value]) => {
11597
11597
  if (value !== void 0) {
11598
- attributes[`ai.request.headers.${key}`] = value;
11598
+ attributes[`ai.request.headers.${key2}`] = value;
11599
11599
  }
11600
11600
  return attributes;
11601
11601
  }, {})
@@ -11715,7 +11715,7 @@ function selectTelemetryAttributes({
11715
11715
  if ((telemetry == null ? void 0 : telemetry.isEnabled) !== true) {
11716
11716
  return {};
11717
11717
  }
11718
- return Object.entries(attributes).reduce((attributes2, [key, value]) => {
11718
+ return Object.entries(attributes).reduce((attributes2, [key2, value]) => {
11719
11719
  if (value === void 0) {
11720
11720
  return attributes2;
11721
11721
  }
@@ -11724,16 +11724,16 @@ function selectTelemetryAttributes({
11724
11724
  return attributes2;
11725
11725
  }
11726
11726
  const result = value.input();
11727
- return result === void 0 ? attributes2 : { ...attributes2, [key]: result };
11727
+ return result === void 0 ? attributes2 : { ...attributes2, [key2]: result };
11728
11728
  }
11729
11729
  if (typeof value === "object" && "output" in value && typeof value.output === "function") {
11730
11730
  if ((telemetry == null ? void 0 : telemetry.recordOutputs) === false) {
11731
11731
  return attributes2;
11732
11732
  }
11733
11733
  const result = value.output();
11734
- return result === void 0 ? attributes2 : { ...attributes2, [key]: result };
11734
+ return result === void 0 ? attributes2 : { ...attributes2, [key2]: result };
11735
11735
  }
11736
- return { ...attributes2, [key]: value };
11736
+ return { ...attributes2, [key2]: value };
11737
11737
  }, {});
11738
11738
  }
11739
11739
  var name32 = "AI_NoImageGeneratedError";
@@ -17031,10 +17031,10 @@ var OpenAITranscriptionModel = class {
17031
17031
  temperature: (_d = openAIOptions.temperature) != null ? _d : void 0,
17032
17032
  timestamp_granularities: (_e = openAIOptions.timestampGranularities) != null ? _e : void 0
17033
17033
  };
17034
- for (const key in transcriptionModelOptions) {
17035
- const value = transcriptionModelOptions[key];
17034
+ for (const key2 in transcriptionModelOptions) {
17035
+ const value = transcriptionModelOptions[key2];
17036
17036
  if (value !== void 0) {
17037
- formData.append(key, String(value));
17037
+ formData.append(key2, String(value));
17038
17038
  }
17039
17039
  }
17040
17040
  }
@@ -18007,10 +18007,10 @@ var OpenAISpeechModel = class {
18007
18007
  }
18008
18008
  if (openAIOptions) {
18009
18009
  const speechModelOptions = {};
18010
- for (const key in speechModelOptions) {
18011
- const value = speechModelOptions[key];
18010
+ for (const key2 in speechModelOptions) {
18011
+ const value = speechModelOptions[key2];
18012
18012
  if (value !== void 0) {
18013
- requestBody[key] = value;
18013
+ requestBody[key2] = value;
18014
18014
  }
18015
18015
  }
18016
18016
  }
@@ -20367,28 +20367,28 @@ function runDiagnostic(input) {
20367
20367
  var REG = globalThis.__polymathDiagJobs ??= /* @__PURE__ */ new Map();
20368
20368
  var MAX_ATTEMPTS = 3;
20369
20369
  var BACKOFF_MS = 3e4;
20370
- async function runWithRetries(key, input) {
20370
+ async function runWithRetries(key2, input) {
20371
20371
  let last;
20372
20372
  for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
20373
20373
  try {
20374
20374
  return await runDiagnostic(input);
20375
20375
  } catch (e) {
20376
20376
  last = e;
20377
- console.warn(`[feedback/diagnostic] ${key}: attempt ${attempt}/${MAX_ATTEMPTS} failed \u2014 ${String(e?.message || e).slice(0, 160)}`);
20377
+ console.warn(`[feedback/diagnostic] ${key2}: attempt ${attempt}/${MAX_ATTEMPTS} failed \u2014 ${String(e?.message || e).slice(0, 160)}`);
20378
20378
  if (attempt < MAX_ATTEMPTS) await new Promise((r) => setTimeout(r, BACKOFF_MS * attempt));
20379
20379
  }
20380
20380
  }
20381
20381
  throw last;
20382
20382
  }
20383
- function startDiagnosticJob(key, input) {
20384
- const cur = REG.get(key);
20383
+ function startDiagnosticJob(key2, input) {
20384
+ const cur = REG.get(key2);
20385
20385
  if (cur && cur.status === "running") return cur;
20386
20386
  const rec = { status: "running", startedAt: Date.now() };
20387
- REG.set(key, rec);
20388
- runWithRetries(key, input).then(async (result) => {
20387
+ REG.set(key2, rec);
20388
+ runWithRetries(key2, input).then(async (result) => {
20389
20389
  rec.status = "done";
20390
20390
  rec.result = result;
20391
- await mergeIntoStateFile(key, result).catch(() => {
20391
+ await mergeIntoStateFile(key2, result).catch(() => {
20392
20392
  });
20393
20393
  }).catch((e) => {
20394
20394
  rec.status = "failed";
@@ -20396,14 +20396,14 @@ function startDiagnosticJob(key, input) {
20396
20396
  });
20397
20397
  return rec;
20398
20398
  }
20399
- function diagnosticJobStatus(key) {
20400
- return REG.get(key) ?? null;
20399
+ function diagnosticJobStatus(key2) {
20400
+ return REG.get(key2) ?? null;
20401
20401
  }
20402
- async function mergeIntoStateFile(key, diagnostic) {
20402
+ async function mergeIntoStateFile(key2, diagnostic) {
20403
20403
  const FILE = path17.join(process.env.POLYMATH_DATA_DIR || path17.join(process.cwd(), ".data"), "engine-pilot", "feedback-jobs.json");
20404
20404
  const s = await fs13.readFile(FILE, "utf8").then(JSON.parse).catch(() => ({ version: 1, jobs: {} }));
20405
20405
  const jobs = s.jobs || {};
20406
- const j = jobs[key];
20406
+ const j = jobs[key2];
20407
20407
  if (!j) return;
20408
20408
  j.draft = j.draft || {};
20409
20409
  j.draft.evidence = { ...j.draft.evidence || {}, diagnostic };
@@ -20439,17 +20439,17 @@ async function readJobs(dataDir) {
20439
20439
  async function handleState(dataDir, method, body) {
20440
20440
  const s = await readJobs(dataDir);
20441
20441
  if (method === "GET") return { status: 200, json: { jobs: s.jobs || {} } };
20442
- const key = typeof body?.key === "string" ? body.key.slice(0, 120) : "";
20443
- if (!key) return { status: 400, json: { error: "missing key" } };
20442
+ const key2 = typeof body?.key === "string" ? body.key.slice(0, 120) : "";
20443
+ if (!key2) return { status: 400, json: { error: "missing key" } };
20444
20444
  const jobs = s.jobs || {};
20445
- if (body?.job == null) delete jobs[key];
20445
+ if (body?.job == null) delete jobs[key2];
20446
20446
  else {
20447
20447
  try {
20448
20448
  if (JSON.stringify(body.job).length > 3e5) return { status: 413, json: { error: "job too large" } };
20449
20449
  } catch {
20450
20450
  return { status: 400, json: { error: "bad job" } };
20451
20451
  }
20452
- jobs[key] = body.job;
20452
+ jobs[key2] = body.job;
20453
20453
  }
20454
20454
  await fs14.mkdir(dataDir, { recursive: true });
20455
20455
  await fs14.writeFile(jobsFile(dataDir), JSON.stringify({ version: 1, jobs }, null, 2), "utf8");
@@ -20506,7 +20506,7 @@ async function handleSubmit(dataDir, body) {
20506
20506
  console.error(` [feedback/submit] stored ${String(row.id)} (${sectionKey}) for ${auth.identity.email}`);
20507
20507
  return { status: 200, json: { ok: true, verified: row } };
20508
20508
  }
20509
- function handleDiagnostic(method, body, key) {
20509
+ function handleDiagnostic(method, body, key2) {
20510
20510
  if (method === "POST") {
20511
20511
  const b = body ?? {};
20512
20512
  if (!(b.rawFeedback || "").trim()) return { status: 400, json: { error: "no feedback" } };
@@ -20517,7 +20517,7 @@ function handleDiagnostic(method, body, key) {
20517
20517
  const job2 = startDiagnosticJob(k2, { reportKind, sectionLabel: b.sectionLabel, rawFeedback: b.rawFeedback, locus: b.locus, evidence: b.evidence });
20518
20518
  return { status: 200, json: { status: job2.status, startedAt: job2.startedAt, ...job2.status === "done" ? { diagnostic: job2.result } : {} } };
20519
20519
  }
20520
- const k = (key || "").trim().slice(0, 120);
20520
+ const k = (key2 || "").trim().slice(0, 120);
20521
20521
  if (!k) return { status: 400, json: { error: "missing key" } };
20522
20522
  const job = diagnosticJobStatus(k);
20523
20523
  if (!job) return { status: 200, json: { status: "none" } };
@@ -20686,8 +20686,8 @@ async function buildCorpusDocs(importedDir, opts = {}) {
20686
20686
  );
20687
20687
  const bySession = /* @__PURE__ */ new Map();
20688
20688
  for (const it of items) {
20689
- const key = it.sessionId ?? `${source}:${it.timestamp.slice(0, 10)}`;
20690
- (bySession.get(key) ?? bySession.set(key, []).get(key)).push(it);
20689
+ const key2 = it.sessionId ?? `${source}:${it.timestamp.slice(0, 10)}`;
20690
+ (bySession.get(key2) ?? bySession.set(key2, []).get(key2)).push(it);
20691
20691
  }
20692
20692
  for (const [, session] of bySession) {
20693
20693
  session.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
@@ -20785,14 +20785,14 @@ async function loadFacetTakes(lensKey, idx) {
20785
20785
  if (!Array.isArray(facets2)) continue;
20786
20786
  const meta = idx[id] || { title: "", date: "", source: "" };
20787
20787
  for (const f of facets2) {
20788
- const key = String(f.facetKey || "");
20789
- if (!key) continue;
20788
+ const key2 = String(f.facetKey || "");
20789
+ if (!key2) continue;
20790
20790
  const score = typeof f.score === "number" ? f.score : null;
20791
20791
  const best = typeof f.bestEstimate === "number" ? f.bestEstimate : null;
20792
20792
  if (score == null && best == null) continue;
20793
20793
  const t = { id, title: meta.title || id, date: meta.date || "", source: meta.source || void 0, score, best, low: num2(f.low), high: num2(f.high), confidence: String(f.confidence || ""), gist: String(f.why || "").replace(/\s+/g, " ").trim().slice(0, 220) };
20794
- if (!byFacet.has(key)) byFacet.set(key, []);
20795
- byFacet.get(key).push(t);
20794
+ if (!byFacet.has(key2)) byFacet.set(key2, []);
20795
+ byFacet.get(key2).push(t);
20796
20796
  }
20797
20797
  }
20798
20798
  return byFacet;
@@ -20831,8 +20831,8 @@ async function readGrowthAgent() {
20831
20831
  return m ? { text: t.slice(0, m.index).trim(), docId: m[1] } : { text: t.trim(), docId: "" };
20832
20832
  };
20833
20833
  const facets2 = {};
20834
- const setFacet = (key, f) => {
20835
- if (key) facets2[key] = { score: num2(f.score), trajectory: String(f.trajectory || ""), rationale: g(f, "rationale", "reasoning") };
20834
+ const setFacet = (key2, f) => {
20835
+ if (key2) facets2[key2] = { score: num2(f.score), trajectory: String(f.trajectory || ""), rationale: g(f, "rationale", "reasoning") };
20836
20836
  };
20837
20837
  if (Array.isArray(raw.facets)) for (const f of raw.facets) setFacet(g(f, "key", "facetKey"), f);
20838
20838
  else for (const [k, v] of Object.entries(raw.facets)) setFacet(k, v || {});
@@ -20855,10 +20855,10 @@ async function compilePerson() {
20855
20855
  const idx = await loadIndex();
20856
20856
  const m = (id) => ({ id, title: idx[id]?.title || id, date: idx[id]?.date || "", source: idx[id]?.source || void 0 });
20857
20857
  const out = [];
20858
- for (const [key, lens] of PERSON_LENSES) {
20859
- const person = await fs16.readFile(path20.join(GRADES, key, "_person.json"), "utf8").then(JSON.parse).catch(() => null);
20860
- const growth = key === "growth" ? await readGrowthAgent() : null;
20861
- const byFacet = await loadFacetTakes(key, idx);
20858
+ for (const [key2, lens] of PERSON_LENSES) {
20859
+ const person = await fs16.readFile(path20.join(GRADES, key2, "_person.json"), "utf8").then(JSON.parse).catch(() => null);
20860
+ const growth = key2 === "growth" ? await readGrowthAgent() : null;
20861
+ const byFacet = await loadFacetTakes(key2, idx);
20862
20862
  const pf = (k) => (person?.facets || []).find((x) => String(x.facetKey) === k) || null;
20863
20863
  const facets2 = lens.facets.map((f) => {
20864
20864
  const g = pf(f.key);
@@ -20896,7 +20896,7 @@ async function compilePerson() {
20896
20896
  } : null;
20897
20897
  return { facetKey: f.key, name: f.name, definition: f.definition, scaleMax, grade, dist: distOf2(takes), takes };
20898
20898
  });
20899
- out.push({ key, label: lens.label, overall: String(person?.overall || ""), facets: facets2, present: !!person, ...growth ? { growthAxes: growth.axes } : {} });
20899
+ out.push({ key: key2, label: lens.label, overall: String(person?.overall || ""), facets: facets2, present: !!person, ...growth ? { growthAxes: growth.axes } : {} });
20900
20900
  }
20901
20901
  return out;
20902
20902
  }
@@ -20913,10 +20913,10 @@ async function gradeDetail(docId2, lensKey) {
20913
20913
  title: meta.title || docId2,
20914
20914
  date: meta.date || "",
20915
20915
  facets: facets2.map((f) => {
20916
- const key = String(f.facetKey || "");
20916
+ const key2 = String(f.facetKey || "");
20917
20917
  return {
20918
- facetKey: key,
20919
- name: FNAME[key] || key,
20918
+ facetKey: key2,
20919
+ name: FNAME[key2] || key2,
20920
20920
  score: num2(f.score),
20921
20921
  confidence: String(f.confidence || ""),
20922
20922
  low: num2(f.low),
@@ -20926,7 +20926,7 @@ async function gradeDetail(docId2, lensKey) {
20926
20926
  cleared: String(f.cleared || ""),
20927
20927
  penalized: String(f.penalized || ""),
20928
20928
  quotes: Array.isArray(f.quotes) ? f.quotes : [],
20929
- scaleMax: RUBRIC[key]?.rungs?.length ? 11 : 10
20929
+ scaleMax: RUBRIC[key2]?.rungs?.length ? 11 : 10
20930
20930
  };
20931
20931
  })
20932
20932
  };
@@ -21070,13 +21070,13 @@ async function loadFeedback() {
21070
21070
  }
21071
21071
  async function handlePersonFeedback(method, body) {
21072
21072
  if (method === "GET") return { status: 200, json: { entries: (await loadFeedback()).entries } };
21073
- const key = typeof body?.key === "string" ? body.key.replace(/[^a-z0-9:_-]/gi, "").slice(0, 80) : "";
21074
- if (!key) return { status: 400, json: { error: "missing key" } };
21073
+ const key2 = typeof body?.key === "string" ? body.key.replace(/[^a-z0-9:_-]/gi, "").slice(0, 80) : "";
21074
+ if (!key2) return { status: 400, json: { error: "missing key" } };
21075
21075
  const text2 = (typeof body?.text === "string" ? body.text : "").trim();
21076
21076
  const store = await loadFeedback();
21077
21077
  const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
21078
- if (text2) store.entries[key] = { text: text2, updatedAt };
21079
- else delete store.entries[key];
21078
+ if (text2) store.entries[key2] = { text: text2, updatedAt };
21079
+ else delete store.entries[key2];
21080
21080
  await fs18.mkdir(path22.dirname(FEEDBACK_FILE()), { recursive: true });
21081
21081
  await fs18.writeFile(FEEDBACK_FILE(), JSON.stringify(store, null, 2));
21082
21082
  return { status: 200, json: { ok: true, updatedAt } };
@@ -21290,14 +21290,14 @@ ${clip2(headline, 1400)}`);
21290
21290
  for (const f of d.facets) {
21291
21291
  const g = f.grade;
21292
21292
  const sc = g && (g.score != null || g.bestEstimate != null) ? `${g.score ?? g.bestEstimate}/${f.scaleMax}` : "\u2014";
21293
- const key = `${d.key}:${f.facetKey}`;
21293
+ const key2 = `${d.key}:${f.facetKey}`;
21294
21294
  const parts = [`- ${f.name} (${sc})`];
21295
- const line = facetLines[key]?.line;
21295
+ const line = facetLines[key2]?.line;
21296
21296
  if (line) parts.push(`feel-seen: ${clip2(line, 280)}`);
21297
21297
  for (const spike of (g?.spikes || []).slice(0, 2)) {
21298
21298
  if (spike?.what) parts.push(`peak: ${clip2(spike.what, 300)}${spike.title ? ` [${clip2(spike.title, 80)}${spike.date ? `, ${spike.date}` : ""}]` : ""}${spike.quote ? ` \u2014 verbatim: "${clip2(spike.quote, 240)}"` : ""}`);
21299
21299
  }
21300
- for (const dm of (peakDemos[key] || []).slice(0, 2)) {
21300
+ for (const dm of (peakDemos[key2] || []).slice(0, 2)) {
21301
21301
  const steps = (dm.steps || []).map((x) => clip2(x, 500)).filter(Boolean);
21302
21302
  if (!steps.length && !dm.why) continue;
21303
21303
  parts.push(`demonstration${dm.title ? ` [${clip2(dm.title, 90)}${dm.date ? `, ${dm.date}` : ""}]` : ""} \u2014 ordered moves:`);
@@ -21878,7 +21878,7 @@ async function writeScoreboard(codingDir, docs) {
21878
21878
  }
21879
21879
  if (!byCriterion.size) return;
21880
21880
  const blocks = [...byCriterion.entries()].sort(([a], [b]) => a < b ? -1 : 1).map(
21881
- ([key, rows]) => `## ${key}
21881
+ ([key2, rows]) => `## ${key2}
21882
21882
  ${rows.sort((a, b) => b.s - a.s).map((r) => r.line).join("\n")}`
21883
21883
  );
21884
21884
  await fs23.writeFile(
@@ -21930,10 +21930,10 @@ function promptSha(parts) {
21930
21930
  }
21931
21931
  return h.digest("hex").slice(0, 16);
21932
21932
  }
21933
- async function reusableOutput(outPath, sha, valid, key = "promptSha") {
21933
+ async function reusableOutput(outPath, sha, valid, key2 = "promptSha") {
21934
21934
  try {
21935
21935
  const o = JSON.parse(await fs24.readFile(outPath, "utf8"));
21936
- if (o[key] === sha && valid(o)) return o;
21936
+ if (o[key2] === sha && valid(o)) return o;
21937
21937
  } catch {
21938
21938
  }
21939
21939
  return null;
@@ -22548,20 +22548,20 @@ async function compileCodingProfile() {
22548
22548
  const m = /([\d.]+)\s*%/.exec(label);
22549
22549
  return m ? 100 - parseFloat(m[1]) : null;
22550
22550
  };
22551
- const ceilOf = (key) => {
22552
- const c = criteria.find((x) => x.key === key);
22551
+ const ceilOf = (key2) => {
22552
+ const c = criteria.find((x) => x.key === key2);
22553
22553
  const scores = (c?.takes ?? []).map((t) => t.score ?? t.best).filter((x) => x != null).sort((a, b) => b - a);
22554
22554
  return scores.length ? scores[Math.min(3, scores.length) - 1] : null;
22555
22555
  };
22556
- const proud = (key, fallback) => {
22557
- const t = (criteria.find((x) => x.key === key)?.takes ?? [])[0];
22556
+ const proud = (key2, fallback) => {
22557
+ const t = (criteria.find((x) => x.key === key2)?.takes ?? [])[0];
22558
22558
  if (!t?.instance) return fallback;
22559
22559
  let h = t.instance.split(/:\s|\s[—–]\s|\swith an?\s/)[0].trim().replace(/\s+/g, " ");
22560
22560
  h = h.replace(/^The user\b/, "You").replace(/\bThe user\b/g, "you").replace(/([.?!]['"’”)\]]*\s+)you\b/g, (_m, p) => p + "You");
22561
22561
  if (h.length > 150) h = h.slice(0, 148).replace(/\s+\S*$/, "") + "\u2026";
22562
22562
  return h;
22563
22563
  };
22564
- const nTk = (key) => criteria.find((x) => x.key === key)?.takes.length ?? 0;
22564
+ const nTk = (key2) => criteria.find((x) => x.key === key2)?.takes.length ?? 0;
22565
22565
  const peakWords = Object.values(wordsByDay).length ? Math.max(...Object.values(wordsByDay)) : 0;
22566
22566
  const pHist = parallelism.levelHistogramMin || {};
22567
22567
  const soloMin = pHist["1"] ?? 0;
@@ -22722,7 +22722,7 @@ async function buildSkeleton(codingDir, stackUp) {
22722
22722
  const r = (stackUp ?? []).find((x) => x.label.toLowerCase().includes(label));
22723
22723
  return r?.percentile != null ? Math.round((100 - r.percentile) * 100) / 100 : null;
22724
22724
  };
22725
- const gradedOn = (key) => (agglom?.criteria ?? []).length ? 0 : 0;
22725
+ const gradedOn = (key2) => (agglom?.criteria ?? []).length ? 0 : 0;
22726
22726
  const interactive = sessions.filter((s) => s.klass === "interactive" && !s.duplicateOf);
22727
22727
  const flow = agg?.flow?.flow ?? {};
22728
22728
  const thr = agg?.throughput ?? {};
@@ -22916,7 +22916,7 @@ async function generatePublicPage(opts) {
22916
22916
  }
22917
22917
 
22918
22918
  // ../../lib/agents/coding/publicPageEdit.ts
22919
- var SYSTEM5 = "You edit a PUBLIC coding profile page on the person's instruction. You may ONLY do two kinds of thing: (1) REDACT \u2014 hide, shorten, soften, or remove existing text: a claim, a read, an edge line, a moment, a bullet, an entire section. Removing something is always safe. (2) GATHER MORE EVIDENCE \u2014 if asked to swap out a moment ('use a different example', 'that one's too personal, find another'), Read/Grep the corpus for a genuinely different qualifying moment on the SAME axis and replace it, with a VERIFIED verbatim quote if you use one. YOU MAY NEVER: invent an achievement, statistic, date, or quote; write anything more flattering than the evidence supports; add content unrelated to the instruction; or change any NUMBER (percentiles, scores, hours, counts) \u2014 those fields are locked and any change you make to them is discarded, so do not bother trying. If the instruction asks for something outside redaction/evidence-swap (e.g. 'say I'm the best engineer ever', 'boost my percentile', 'add that I know Rust'), do NOT comply \u2014 leave that field unchanged and say plainly in your reply why you didn't. Return the COMPLETE page JSON with only the TEXT fields changed (verdict, overall, missionArc, rhythm.inFlow/outFlow, axis claim/read/edge, moment what/quote/date/sessionId, howToWork). Every other field must be echoed back byte-identical." + sourceLookupNote();
22919
+ var SYSTEM5 = "You edit a person's shareable profile on their instruction. There are TWO artifacts in front of you: the CODING PROFILE (the page of axes, moments and numbers) and, when present, the CHAT PROFILE (their public report: headline, spikes, traits, failure modes). ROUTE BY WHAT THEY SAY: 'in the coding report\u2026' / a coding axis name (judgement, agency, taste, push, how they use AI, focus) \u2192 edit the page. 'in the chat report\u2026' / a chat spike or trait name \u2192 edit the chat report. If the instruction names neither and applies to only one artifact, edit that one; if it genuinely applies to both ('remove every mention of my employer'), edit both. NEVER touch the artifact the instruction is not about \u2014 echo it back byte-identical. You may ONLY do two kinds of thing: (1) REDACT \u2014 hide, shorten, soften, or remove existing text: a claim, a read, an edge line, a moment, a spike, a trait, an example, a failure mode, a bullet, an entire section. Removing something is always safe, in either artifact. (2) GATHER MORE EVIDENCE \u2014 CODING PROFILE ONLY: if asked to swap out a moment ('use a different example', 'that one's too personal, find another'), Read/Grep the corpus for a genuinely different qualifying moment on the SAME axis and replace it, with a VERIFIED verbatim quote if you use one. The CHAT PROFILE is REDACT-ONLY here: you cannot add a spike, trait, or example to it (its evidence lives in a corpus you cannot reach from this tool) \u2014 if asked, decline and say the chat report can only have things removed or shortened here. YOU MAY NEVER: invent an achievement, statistic, date, or quote; write anything more flattering than the evidence supports; add content unrelated to the instruction; or change any NUMBER (percentiles, scores, levels, hours, counts) in either artifact \u2014 those fields are locked and any change you make to them is discarded, so do not bother trying. If the instruction asks for something outside redaction/evidence-swap (e.g. 'say I'm the best engineer ever', 'boost my percentile', 'add that I know Rust'), do NOT comply \u2014 leave that field unchanged and say plainly in your reply why you didn't. Return BOTH artifacts complete, with only the TEXT fields changed (page: verdict, overall, missionArc, rhythm.inFlow/outFlow, axis claim/read/edge, moment what/quote/date/sessionId, howToWork; chat: headline, spike titles, trait label/body/con, example title/detail, failure modes, drives, wants, howToWorkWithHim). Every other field must be echoed back byte-identical." + sourceLookupNote();
22920
22920
  var norm = (s) => s.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter((w) => w.length > 2);
22921
22921
  function grounded(newText, contextText) {
22922
22922
  const nt = norm(newText);
@@ -22977,19 +22977,90 @@ function clampToProtected(edited, original) {
22977
22977
  });
22978
22978
  return out;
22979
22979
  }
22980
+ var key = (s) => (s ?? "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
22981
+ function matchBy(items, label) {
22982
+ const byFacet = /* @__PURE__ */ new Map(), byLabel = /* @__PURE__ */ new Map();
22983
+ for (const it of items) {
22984
+ if (it.facet) byFacet.set(key(it.facet), it);
22985
+ byLabel.set(key(label(it)), it);
22986
+ }
22987
+ return (e) => e.facet && byFacet.get(key(e.facet)) || byLabel.get(key(label(e)));
22988
+ }
22989
+ function clampChatExamples(edited, orig) {
22990
+ if (!orig?.length) return orig;
22991
+ if (!Array.isArray(edited)) return orig;
22992
+ const find = matchBy(orig, (e) => e.title ?? "");
22993
+ const out = edited.map((e) => ({ e, o: find(e) })).filter((p) => !!p.o).map(({ e, o }) => ({
22994
+ ...o,
22995
+ // date + provenance: from the original
22996
+ title: keepIfGrounded(e.title, o.title, `${o.title} ${[o.detail ?? []].flat().join(" ")}`).slice(0, 200),
22997
+ detail: Array.isArray(e.detail) ? e.detail.map((d, i) => keepIfGrounded(d, [o.detail ?? []].flat()[i] ?? "", [o.detail ?? []].flat().join(" "))).filter(Boolean).slice(0, 6) : o.detail
22998
+ }));
22999
+ return out.length ? out : void 0;
23000
+ }
23001
+ function clampChatReport(edited, original) {
23002
+ const findSpike = matchBy(original.spikes ?? [], (s) => s.title);
23003
+ const spikes = (Array.isArray(edited.spikes) ? edited.spikes : original.spikes ?? []).map((e) => ({ e, o: findSpike(e) })).filter((p) => !!p.o).map(({ e, o }) => {
23004
+ const findTrait = matchBy(o.traits ?? [], (t) => t.label);
23005
+ const traits = (Array.isArray(e.traits) ? e.traits : o.traits ?? []).map((te) => ({ te, to: findTrait(te) })).filter((p) => !!p.to).map(({ te, to }) => {
23006
+ const ctx = `${to.label} ${to.body} ${to.con ?? ""} ${(to.examples ?? []).map((x) => `${x.title} ${[x.detail ?? []].flat().join(" ")}`).join(" ")}`;
23007
+ return {
23008
+ ...to,
23009
+ // facet, score, percentile, fromPersonalLife: PROTECTED
23010
+ label: keepIfGrounded(te.label, to.label, ctx).slice(0, 200),
23011
+ body: keepIfGrounded(te.body, to.body, ctx).slice(0, 900),
23012
+ con: te.con === void 0 ? to.con : te.con ? keepIfGrounded(te.con, to.con ?? "", ctx).slice(0, 400) || void 0 : void 0,
23013
+ // personal-life traits never carry receipts, edited or not
23014
+ examples: to.fromPersonalLife ? void 0 : clampChatExamples(te.examples, to.examples)
23015
+ };
23016
+ });
23017
+ return {
23018
+ ...o,
23019
+ // facet, score, percentile: PROTECTED
23020
+ title: keepIfGrounded(e.title, o.title, `${o.title} ${(o.traits ?? []).map((t) => `${t.label} ${t.body}`).join(" ")}`).slice(0, 200),
23021
+ traits
23022
+ };
23023
+ });
23024
+ const findFm = matchBy(original.failureModes ?? [], (f) => f.label);
23025
+ const failureModes = Array.isArray(edited.failureModes) ? edited.failureModes.map((e) => ({ e, o: findFm(e) })).filter((p) => !!p.o).map(({ e, o }) => ({
23026
+ ...o,
23027
+ frequency: o.frequency,
23028
+ // an absolute count, framed by the grader: PROTECTED
23029
+ label: keepIfGrounded(e.label, o.label, `${o.label} ${o.body ?? ""}`).slice(0, 200),
23030
+ body: e.body === void 0 ? o.body : e.body ? keepIfGrounded(e.body, o.body ?? "", `${o.label} ${o.body ?? ""}`).slice(0, 600) || void 0 : void 0
23031
+ })) : original.failureModes;
23032
+ return {
23033
+ ...original,
23034
+ // level, radar, generatedAt, editLog: PROTECTED, always original
23035
+ headline: keepIfGrounded(edited.headline, original.headline, original.headline).slice(0, 300),
23036
+ spikes,
23037
+ failureModes: failureModes?.length ? failureModes : void 0,
23038
+ drives: edited.drives === void 0 ? original.drives : edited.drives ? keepIfGrounded(edited.drives, original.drives ?? "", original.drives ?? "").slice(0, 900) || void 0 : void 0,
23039
+ wants: Array.isArray(edited.wants) ? edited.wants.map((w) => keepIfGrounded(w, "", (original.wants ?? []).join(" "))).filter(Boolean).slice(0, 8) : original.wants,
23040
+ howToWorkWithHim: Array.isArray(edited.howToWorkWithHim) ? edited.howToWorkWithHim.map((b) => keepIfGrounded(b, "", (original.howToWorkWithHim ?? []).join(" "))).filter(Boolean).slice(0, 6) : original.howToWorkWithHim
23041
+ };
23042
+ }
22980
23043
  async function editPublicPage(opts) {
22981
23044
  const last = opts.messages.filter((m) => m.role === "user").pop();
22982
23045
  if (!last?.content?.trim()) return { status: 400, json: { error: "an instruction is required" } };
22983
23046
  const convo = opts.messages.slice(-6).map((m) => `${m.role === "user" ? "USER" : "EDITOR"}: ${m.content}`).join("\n");
22984
- const prompt = `CURRENT PAGE:
23047
+ const chat = opts.chatReport ?? null;
23048
+ const prompt = `CODING PROFILE (the page):
22985
23049
  \`\`\`json
22986
23050
  ${JSON.stringify(opts.page, null, 1)}
22987
23051
  \`\`\`
22988
23052
 
22989
- CONVERSATION:
23053
+ ` + (chat ? `CHAT PROFILE (their public report \u2014 REDACT-ONLY):
23054
+ \`\`\`json
23055
+ ${JSON.stringify({ ...chat, radar: void 0, level: void 0, editLog: void 0 }, null, 1)}
23056
+ \`\`\`
23057
+
23058
+ ` : `CHAT PROFILE: none exists yet \u2014 every instruction is about the coding profile.
23059
+
23060
+ `) + `CONVERSATION:
22990
23061
  ${convo}
22991
23062
 
22992
- Apply the user's LAST instruction within your allowed actions (redact, or gather-more-evidence). Output ONE fenced json block: { "page": <complete page, text fields updated>, "reply": "one short plain sentence on what you did or why you declined" }`;
23063
+ Apply the user's LAST instruction to the RIGHT artifact, within your allowed actions (redact; gather-more-evidence on the coding page only). Output ONE fenced json block: { "page": <complete page>, ${chat ? `"chatReport": <complete chat report>, ` : ""}"reply": "one short plain sentence naming WHICH report you changed and what you did, or why you declined" }`;
22993
23064
  try {
22994
23065
  const run3 = await invokeAgent2({
22995
23066
  prompt,
@@ -23006,7 +23077,11 @@ Apply the user's LAST instruction within your allowed actions (redact, or gather
23006
23077
  const originalIds = new Set(opts.page.axes.flatMap((a) => a.moments.map((m) => m.sessionId).filter(Boolean)));
23007
23078
  await verifyQuotes(opts.codingDir, clamped.axes);
23008
23079
  for (const ax of clamped.axes) ax.moments = ax.moments.filter((m) => m.sessionId && originalIds.has(m.sessionId) || m.quote);
23009
- return { status: 200, json: { page: clamped, reply: String(j.reply ?? "Done.").slice(0, 300) } };
23080
+ const chatOut = chat ? j.chatReport ? clampChatReport(j.chatReport, chat) : chat : void 0;
23081
+ return {
23082
+ status: 200,
23083
+ json: { page: clamped, ...chatOut ? { chatReport: chatOut } : {}, reply: String(j.reply ?? "Done.").slice(0, 300) }
23084
+ };
23010
23085
  } catch (e) {
23011
23086
  return { status: 502, json: { error: e.message.slice(0, 200) } };
23012
23087
  }
@@ -23018,6 +23093,40 @@ async function localChatReport() {
23018
23093
  const rep = await loadPublicReport().catch(() => null);
23019
23094
  return rep && hasContent(rep) ? rep : null;
23020
23095
  }
23096
+ async function handleSharedReportGet(dataDir) {
23097
+ const cfg = centralConfig();
23098
+ if (!cfg.configured) return { status: 200, json: { shared: null, reason: "central services are disabled in this build" } };
23099
+ const auth = await getAccessToken(dataDir);
23100
+ if (!auth) return { status: 200, json: { shared: null, reason: "signed-out" } };
23101
+ try {
23102
+ const r = await fetch(`${cfg.supabaseUrl}/rest/v1/reports?user_id=eq.${encodeURIComponent(auth.identity.userId)}&select=content,verification,created_at,updated_at`, {
23103
+ headers: { apikey: cfg.supabaseAnonKey, authorization: `Bearer ${auth.token}` }
23104
+ });
23105
+ if (!r.ok) return { status: 502, json: { error: `couldn't read your shared report (HTTP ${r.status})` } };
23106
+ const rows = await r.json();
23107
+ const row = rows[0];
23108
+ if (!row?.content) return { status: 200, json: { shared: null } };
23109
+ const c = row.content;
23110
+ return {
23111
+ status: 200,
23112
+ json: {
23113
+ shared: {
23114
+ // updated_at, NOT created_at: submit_report UPSERTS one row per user
23115
+ // (`on conflict (user_id) do update`), so created_at is the FIRST
23116
+ // share ever while the content is the LATEST — dating today's page
23117
+ // "July 3" would be a lie about the thing on screen.
23118
+ sharedAt: row.updated_at ?? row.created_at ?? null,
23119
+ verification: row.verification ?? null,
23120
+ // coding-pr1 carries {page, chatReport?}; the older pr1 is chat-only
23121
+ page: c.format === "coding-pr1" ? c.page ?? null : null,
23122
+ chatReport: c.chatReport ?? (c.format === "pr1" ? c.report ?? null : null)
23123
+ }
23124
+ }
23125
+ };
23126
+ } catch (e) {
23127
+ return { status: 502, json: { error: e.message.slice(0, 200) } };
23128
+ }
23129
+ }
23021
23130
  async function handlePublicCodingPageGet(dataDir) {
23022
23131
  const page = await readJson4(path32.join(dataDir, "coding", "coding-public.json"), null);
23023
23132
  const chatReport = await localChatReport();
@@ -23039,7 +23148,12 @@ async function handlePublicCodingPageEdit(dataDir, body) {
23039
23148
  const page = body.page;
23040
23149
  const messages = Array.isArray(body.messages) ? body.messages : [];
23041
23150
  if (!page || !Array.isArray(page.axes)) return { status: 400, json: { error: "page + messages are required" } };
23042
- const out = await editPublicPage({ page, messages, codingDir: path32.join(dataDir, "coding") });
23151
+ const chatReport = await localChatReport();
23152
+ const out = await editPublicPage({ page, chatReport, messages, codingDir: path32.join(dataDir, "coding") });
23153
+ const edited = out.json.chatReport;
23154
+ if (out.status === 200 && edited && chatReport && JSON.stringify(edited) !== JSON.stringify(chatReport)) {
23155
+ await savePublicReport({ ...edited, editLog: [...chatReport.editLog ?? [], { instruction: messages.filter((m) => m.role === "user").pop()?.content ?? "", at: (/* @__PURE__ */ new Date()).toISOString() }].slice(-50) });
23156
+ }
23043
23157
  return out;
23044
23158
  }
23045
23159
  async function handlePublicCodingPageShare(dataDir, body) {
@@ -23140,13 +23254,13 @@ async function handleShare(res, body, opts, dataDir) {
23140
23254
  const all = opts.shareSections ?? opts.profile?.sections ?? {};
23141
23255
  const sections = {};
23142
23256
  if (parsed.sectionsData && typeof parsed.sectionsData === "object" && !Array.isArray(parsed.sectionsData)) {
23143
- for (const key of Object.keys(parsed.sectionsData)) {
23144
- if (key in all && parsed.sectionsData[key] != null) sections[key] = parsed.sectionsData[key];
23257
+ for (const key2 of Object.keys(parsed.sectionsData)) {
23258
+ if (key2 in all && parsed.sectionsData[key2] != null) sections[key2] = parsed.sectionsData[key2];
23145
23259
  }
23146
23260
  } else {
23147
23261
  const wanted = parsed.all ? Object.keys(all) : Array.isArray(parsed.sections) ? parsed.sections : [];
23148
- for (const key of wanted) {
23149
- if (key in all && all[key] != null) sections[key] = all[key];
23262
+ for (const key2 of wanted) {
23263
+ if (key2 in all && all[key2] != null) sections[key2] = all[key2];
23150
23264
  }
23151
23265
  }
23152
23266
  if (Object.keys(sections).length === 0) {
@@ -23294,8 +23408,8 @@ function startServer(opts) {
23294
23408
  return;
23295
23409
  }
23296
23410
  }
23297
- const key = new URL(url, serverUrl || "http://localhost").searchParams.get("key") || void 0;
23298
- const out = handleDiagnostic(req.method || "GET", body, key);
23411
+ const key2 = new URL(url, serverUrl || "http://localhost").searchParams.get("key") || void 0;
23412
+ const out = handleDiagnostic(req.method || "GET", body, key2);
23299
23413
  json(res, out.status, out.json);
23300
23414
  return;
23301
23415
  }
@@ -23370,6 +23484,11 @@ function startServer(opts) {
23370
23484
  json(res, out.status, out.json);
23371
23485
  return;
23372
23486
  }
23487
+ if (req.method === "GET" && route === "/api/shared-report") {
23488
+ const out = await handleSharedReportGet(dataDir);
23489
+ json(res, out.status, out.json);
23490
+ return;
23491
+ }
23373
23492
  if (req.method === "POST" && route === "/api/public-coding-page/generate") {
23374
23493
  const out = await handlePublicCodingPageGenerate(dataDir, liveProfile);
23375
23494
  json(res, out.status, out.json);