arkaik-mcp 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1917 -140
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -3158,13 +3158,13 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
3158
3158
  }
3159
3159
  return propValues;
3160
3160
  });
3161
- const isObject2 = isObject;
3161
+ const isObject5 = isObject;
3162
3162
  const catchall = def.catchall;
3163
3163
  let value;
3164
3164
  inst._zod.parse = (payload, ctx) => {
3165
3165
  value ?? (value = _normalized.value);
3166
3166
  const input = payload.value;
3167
- if (!isObject2(input)) {
3167
+ if (!isObject5(input)) {
3168
3168
  payload.issues.push({
3169
3169
  expected: "object",
3170
3170
  code: "invalid_type",
@@ -3291,7 +3291,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
3291
3291
  return (payload, ctx) => fn(shape, payload, ctx);
3292
3292
  };
3293
3293
  let fastpass;
3294
- const isObject2 = isObject;
3294
+ const isObject5 = isObject;
3295
3295
  const jit = !globalConfig.jitless;
3296
3296
  const allowsEval2 = allowsEval;
3297
3297
  const fastEnabled = jit && allowsEval2.value;
@@ -3300,7 +3300,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
3300
3300
  inst._zod.parse = (payload, ctx) => {
3301
3301
  value ?? (value = _normalized.value);
3302
3302
  const input = payload.value;
3303
- if (!isObject2(input)) {
3303
+ if (!isObject5(input)) {
3304
3304
  payload.issues.push({
3305
3305
  expected: "object",
3306
3306
  code: "invalid_type",
@@ -14724,6 +14724,38 @@ var VALUE_IDS = [
14724
14724
  // social-impact (1)
14725
14725
  "self-transcendence"
14726
14726
  ];
14727
+ var VALUE_TIERS = {
14728
+ "saves-time": "functional",
14729
+ simplifies: "functional",
14730
+ "makes-money": "functional",
14731
+ "reduces-risk": "functional",
14732
+ organizes: "functional",
14733
+ integrates: "functional",
14734
+ connects: "functional",
14735
+ "reduces-effort": "functional",
14736
+ "avoids-hassles": "functional",
14737
+ "reduces-cost": "functional",
14738
+ quality: "functional",
14739
+ variety: "functional",
14740
+ "sensory-appeal": "functional",
14741
+ informs: "functional",
14742
+ "reduces-anxiety": "emotional",
14743
+ "rewards-me": "emotional",
14744
+ nostalgia: "emotional",
14745
+ "design-aesthetics": "emotional",
14746
+ "badge-value": "emotional",
14747
+ wellness: "emotional",
14748
+ "therapeutic-value": "emotional",
14749
+ "fun-entertainment": "emotional",
14750
+ attractiveness: "emotional",
14751
+ "provides-access": "emotional",
14752
+ "provides-hope": "life-changing",
14753
+ "self-actualization": "life-changing",
14754
+ motivation: "life-changing",
14755
+ heirloom: "life-changing",
14756
+ "affiliation-belonging": "life-changing",
14757
+ "self-transcendence": "social-impact"
14758
+ };
14727
14759
 
14728
14760
  // ../schema/src/legacy-status.ts
14729
14761
  var LEGACY_STATUS_IDS = ["prioritized", "blocked"];
@@ -15331,6 +15363,84 @@ function missingProvenanceNodeIds(snapshotNodeIds, events) {
15331
15363
  return missing;
15332
15364
  }
15333
15365
 
15366
+ // ../schema/src/weighing-schemas.ts
15367
+ var documented = (schema) => external_exports.union([schema, external_exports.unknown()]);
15368
+ var leaf = (description) => external_exports.unknown().optional().meta({ description });
15369
+ var WeighingConfidenceSchema = external_exports.unknown().meta({ description: "0 guess \xB7 1 inferred \xB7 2 evidenced \xB7 3 verified." });
15370
+ var WeighingScorerSchema = external_exports.object({
15371
+ kind: leaf("Who judged: human, agent or rule. A human's level beats an agent's, which beats a rule's. Any value parses; the validator warns on another kind."),
15372
+ id: leaf("A person's handle, an agent's name, or a seeding rule's id."),
15373
+ model: leaf("The model behind an agent, when it says."),
15374
+ on_behalf_of: leaf("Whom the scorer acts for: a user id, a handle or a display name, never an email. Stamped by the writer where identity is known.")
15375
+ }).catchall(external_exports.unknown()).meta({ id: "WeighingScorer", description: "Provenance of one assessment." });
15376
+ var WeighingScaleSchema = external_exports.object({
15377
+ min: leaf("The lowest level, e.g. -3."),
15378
+ max: leaf("The highest level, e.g. 3."),
15379
+ anchors: leaf("Every level described in words, keyed by the level as a string.")
15380
+ }).catchall(external_exports.unknown()).meta({ id: "WeighingScale", description: "A criteria set's scale: its bounds and every level's anchor." });
15381
+ var WeighingGroupSchema = external_exports.object({ id: leaf("The group's id."), title: leaf("The group's title.") }).catchall(external_exports.unknown()).meta({ id: "WeighingGroup", description: "A grouping of criteria \u2014 the tiers, for the value set." });
15382
+ var WeighingCriterionSchema = external_exports.object({
15383
+ id: leaf("Stable identifier. Never redefined \u2014 retired via superseded_by."),
15384
+ group: leaf("A group id \u2014 for the value set, the tier."),
15385
+ name: leaf("A short name."),
15386
+ question: leaf("The question a scorer answers."),
15387
+ definition: leaf("What the criterion means."),
15388
+ anchors: leaf("This criterion's own wording of each level \u2014 on a positioning, in the product's words."),
15389
+ weight: leaf("On a positioning: how much the product stands on it, a number above 0. Absent means 1."),
15390
+ superseded_by: leaf("The id of the criterion that replaces this one.")
15391
+ }).catchall(external_exports.unknown()).meta({ id: "WeighingCriterion", description: "One question on a scale where every level is described." });
15392
+ var WeighingCriteriaSetSchema = external_exports.object({
15393
+ id: leaf("The set's id."),
15394
+ version: leaf("Semver. Levels are comparable only within a major."),
15395
+ title: leaf("A human title."),
15396
+ subject: leaf("What the set judges: acceptance today."),
15397
+ scale: documented(WeighingScaleSchema).optional().meta({ description: "The scale. A positioning may leave it out and use its ruler's." }),
15398
+ groups: documented(external_exports.array(documented(WeighingGroupSchema))).optional(),
15399
+ criteria: documented(external_exports.array(documented(WeighingCriterionSchema))).optional(),
15400
+ role: leaf("positioning marks the set a project writes about itself."),
15401
+ status: leaf("Absent or active is active; anything else is a draft, which feeds no roll-up."),
15402
+ extends: leaf("A positioning's ruler, e.g. value-contribution@2.")
15403
+ }).catchall(external_exports.unknown()).meta({ id: "WeighingCriteriaSet", description: "A versioned list of criteria for one kind of subject. The 30 elements of value are one; a positioning is another." });
15404
+ var WeighingMatrixSchema = external_exports.object({
15405
+ id: leaf("The matrix's id."),
15406
+ title: leaf("A human title."),
15407
+ set: leaf("The set's id and major, e.g. value-contribution@2."),
15408
+ subjects: documented(
15409
+ external_exports.object({ kind: leaf("query or list."), species: leaf("For a query: the species judged."), items: leaf("For a list: the subjects.") }).catchall(external_exports.unknown())
15410
+ ).optional().meta({ description: "What the matrix judges: { kind: query, species } or { kind: list, items }." }),
15411
+ positioning: leaf("The id of the positioning set that re-weights this matrix."),
15412
+ context: leaf("The node the matrix is about, as { node_id }."),
15413
+ status: leaf("Absent or active is active; anything else is a draft.")
15414
+ }).catchall(external_exports.unknown()).meta({ id: "WeighingMatrix", description: "A criteria set applied to a list of subjects." });
15415
+ var WeighingAssessmentBasisSchema = external_exports.object({
15416
+ fingerprint: leaf("A hash of the subject's judged fields."),
15417
+ commit: leaf("The commit the scorer was looking at."),
15418
+ set_version: leaf("The full version of the set the level was read against.")
15419
+ }).catchall(external_exports.unknown());
15420
+ var WeighingAssessmentSchema = external_exports.object({
15421
+ matrix: leaf("The matrix's id. A row without it cannot be addressed: readers skip it and the validator warns."),
15422
+ subject: leaf("A node id for the value matrix."),
15423
+ criterion: leaf("A criterion id."),
15424
+ level: leaf("A whole number on the set's scale. 0 means unrelated. No half points \u2014 but any value parses; the validator warns on one off the scale."),
15425
+ scorer: documented(WeighingScorerSchema).optional().meta({ description: "Who judged. Required in practice: without it a human, an agent and a rule are indistinguishable, so the validator warns." }),
15426
+ confidence: leaf("0 guess \xB7 1 inferred \xB7 2 evidenced \xB7 3 verified."),
15427
+ evidence: leaf("Markdown."),
15428
+ refs: leaf("Ids cited: nodes, journal events, findings."),
15429
+ basis: documented(WeighingAssessmentBasisSchema).optional().meta({ description: "What the scorer was looking at, so a re-read can tell the score went stale." }),
15430
+ run: leaf("The audit or plan the score belongs to."),
15431
+ p_serves: leaf("Optional: a probabilistic scorer's certainty (0 to 1) that the subject serves the element. Certainty, not size. Any value parses; the validator warns on one outside 0..1."),
15432
+ p_costs: leaf("Optional: the same for costs, asked independently, so both can be high."),
15433
+ ts: leaf("ISO 8601.")
15434
+ }).catchall(external_exports.unknown()).meta({ id: "WeighingAssessment", description: "One (matrix \xD7 subject \xD7 criterion) judgement \u2014 latest per scorer kind wins; history lives in the journal." });
15435
+ var WeighingSectionSchema = external_exports.object({
15436
+ sets: external_exports.array(documented(WeighingCriteriaSetSchema)).optional(),
15437
+ matrices: external_exports.array(documented(WeighingMatrixSchema)).optional(),
15438
+ assessments: external_exports.array(documented(WeighingAssessmentSchema)).optional()
15439
+ }).catchall(external_exports.unknown()).meta({
15440
+ id: "WeighingSection",
15441
+ description: "The project's weighing state (docs/rfcs/weighing.md) \u2014 its own criteria sets (a positioning), matrices and assessments. The built-in value set is library content, not stored; served, cost and kept share are derived, never stored. Each list may be absent; a reader treats it as empty."
15442
+ });
15443
+
15334
15444
  // ../schema/src/journal-events.ts
15335
15445
  var envelope = {
15336
15446
  id: external_exports.string().meta({ description: "ULID \u2014 sortable, collision-free without coordination." }),
@@ -15521,6 +15631,23 @@ var QualitySignalTrippedEventSchema = external_exports.object({
15521
15631
  commit: external_exports.string().optional(),
15522
15632
  detail: external_exports.string().optional()
15523
15633
  }).catchall(external_exports.unknown());
15634
+ var WeighingAssessmentRecordedEventSchema = external_exports.object({
15635
+ ...envelope,
15636
+ type: external_exports.literal("weighing.assessment.recorded"),
15637
+ matrix: external_exports.string(),
15638
+ subject: external_exports.string(),
15639
+ criterion: external_exports.string(),
15640
+ level: external_exports.number().int(),
15641
+ scorer: WeighingScorerSchema,
15642
+ confidence: WeighingConfidenceSchema,
15643
+ evidence: external_exports.string().optional(),
15644
+ refs: external_exports.array(external_exports.string()).optional(),
15645
+ basis: WeighingAssessmentBasisSchema.optional(),
15646
+ run: external_exports.string().optional(),
15647
+ p_serves: external_exports.number().min(0).max(1).optional(),
15648
+ p_costs: external_exports.number().min(0).max(1).optional()
15649
+ }).catchall(external_exports.unknown());
15650
+ var WeighingSetSavedEventSchema = external_exports.object({ ...envelope, type: external_exports.literal("weighing.set.saved"), set: WeighingCriteriaSetSchema }).catchall(external_exports.unknown());
15524
15651
  var JOURNAL_EVENT_SCHEMAS = {
15525
15652
  "node.created": NodeCreatedEventSchema,
15526
15653
  "node.updated": NodeUpdatedEventSchema,
@@ -15544,7 +15671,9 @@ var JOURNAL_EVENT_SCHEMAS = {
15544
15671
  "quality.finding.opened": QualityFindingOpenedEventSchema,
15545
15672
  "quality.finding.resolved": QualityFindingResolvedEventSchema,
15546
15673
  "quality.finding.accepted": QualityFindingAcceptedEventSchema,
15547
- "quality.signal.tripped": QualitySignalTrippedEventSchema
15674
+ "quality.signal.tripped": QualitySignalTrippedEventSchema,
15675
+ "weighing.assessment.recorded": WeighingAssessmentRecordedEventSchema,
15676
+ "weighing.set.saved": WeighingSetSavedEventSchema
15548
15677
  };
15549
15678
  var KnownJournalEventSchema = external_exports.union([
15550
15679
  NodeCreatedEventSchema,
@@ -15569,7 +15698,9 @@ var KnownJournalEventSchema = external_exports.union([
15569
15698
  QualityFindingOpenedEventSchema,
15570
15699
  QualityFindingResolvedEventSchema,
15571
15700
  QualityFindingAcceptedEventSchema,
15572
- QualitySignalTrippedEventSchema
15701
+ QualitySignalTrippedEventSchema,
15702
+ WeighingAssessmentRecordedEventSchema,
15703
+ WeighingSetSavedEventSchema
15573
15704
  ]);
15574
15705
 
15575
15706
  // ../schema/src/quality.ts
@@ -16774,6 +16905,9 @@ var ProjectBundleSchema = external_exports.object({
16774
16905
  }),
16775
16906
  quality: QualitySectionSchema.optional().meta({
16776
16907
  description: "Optional Kritik quality state (docs/rfcs/kritik.md \xA7 4.1) \u2014 the pinned pack version, the project's surface profile, its assessments and findings. Additive: a bundle without it is not an error, and the comparative matrix is derived from it (deriveQualityMatrix), never stored."
16908
+ }),
16909
+ weighing: WeighingSectionSchema.optional().meta({
16910
+ description: "Optional weighing state (docs/rfcs/weighing.md) \u2014 the project's own criteria sets (a positioning), matrices and assessments, each assessment carrying its scorer, confidence and basis. Additive: a bundle without it is not an error, and every weight, served and cost figure is derived from it, never stored."
16777
16911
  })
16778
16912
  }).catchall(external_exports.unknown()).meta({
16779
16913
  id: "ProjectBundle",
@@ -17002,6 +17136,724 @@ function listMaps(project) {
17002
17136
  return [...BUILT_IN_MAPS, ...custom2];
17003
17137
  }
17004
17138
 
17139
+ // ../schema/src/weighing-ladders.ts
17140
+ var LADDERS = {
17141
+ "saves-time": {
17142
+ "-3": "Takes hours out of the person's life.",
17143
+ "-2": "Costs the person time on tasks they do regularly in this domain.",
17144
+ "-1": "Costs the person a little time on one task inside the product.",
17145
+ "1": "Saves a little time on one task inside the product.",
17146
+ "2": "Saves time on tasks the person does regularly in this domain.",
17147
+ "3": "Gives the person back hours of their life, the way online banking replaced trips to the bank."
17148
+ },
17149
+ simplifies: {
17150
+ "-3": "Makes a part of the person's life confusing or hard to manage.",
17151
+ "-2": "Makes a whole task in this domain clearly more complicated.",
17152
+ "-1": "Adds a step or a choice inside the product.",
17153
+ "1": "Removes a step or a choice inside the product.",
17154
+ "2": "Makes a whole task in this domain clearly simpler.",
17155
+ "3": "Makes a complicated part of the person's life simple, the way a single search box replaced browsing directories."
17156
+ },
17157
+ "makes-money": {
17158
+ "-3": "Costs the person a meaningful part of their income.",
17159
+ "-2": "Cuts a regular way the person earns in this domain.",
17160
+ "-1": "Makes earning slightly harder or costs the person a little income.",
17161
+ "1": "Helps the person earn a little, or makes earning slightly easier.",
17162
+ "2": "Gives the person a regular way to earn in this domain.",
17163
+ "3": "Provides a meaningful part of the person's income."
17164
+ },
17165
+ "reduces-risk": {
17166
+ "-3": "Exposes the person to a major loss in their life.",
17167
+ "-2": "Exposes the person to a serious loss or error in this domain.",
17168
+ "-1": "Exposes the person to a small mistake or loss inside the product.",
17169
+ "1": "Guards against a small mistake or loss inside the product.",
17170
+ "2": "Protects against a serious loss or error in this domain.",
17171
+ "3": "Protects against a major loss in the person's life, the way insurance or a full backup does."
17172
+ },
17173
+ organizes: {
17174
+ "-3": "Brings disorder to a large part of the person's life.",
17175
+ "-2": "Makes things in this domain hard to keep in order or to find.",
17176
+ "-1": "Leaves a few things in disorder inside the product.",
17177
+ "1": "Keeps a few things in order inside the product.",
17178
+ "2": "Keeps everything in this domain in order and easy to find.",
17179
+ "3": "Brings order to a large part of the person's life, the way a calendar does."
17180
+ },
17181
+ integrates: {
17182
+ "-3": "Pulls separate parts of the person's life further apart.",
17183
+ "-2": "Splits apart the several tools the person uses in this domain.",
17184
+ "-1": "Cuts the product off from one other tool the person uses.",
17185
+ "1": "Connects the product to one other tool the person uses.",
17186
+ "2": "Ties together the several tools the person uses in this domain.",
17187
+ "3": "Makes separate parts of the person's life work together as one."
17188
+ },
17189
+ connects: {
17190
+ "-3": "Separates the person from the people who matter most in their life.",
17191
+ "-2": "Makes it harder to build or keep relationships in this domain.",
17192
+ "-1": "Gets in the way of reaching someone through the product.",
17193
+ "1": "Lets the person reach someone through the product.",
17194
+ "2": "Helps the person build and keep relationships in this domain.",
17195
+ "3": "Brings the person together with the people who matter most in their life."
17196
+ },
17197
+ "reduces-effort": {
17198
+ "-3": "Puts a heavy burden of work on the person's life.",
17199
+ "-2": "Adds repetitive work to a task the person does regularly in this domain.",
17200
+ "-1": "Adds a little effort to one task inside the product.",
17201
+ "1": "Saves a little effort on one task inside the product.",
17202
+ "2": "Takes the repetitive work out of a task the person does regularly in this domain.",
17203
+ "3": "Lifts a heavy burden of work off the person's life."
17204
+ },
17205
+ "avoids-hassles": {
17206
+ "-3": "Brings a whole kind of annoyance into the person's life.",
17207
+ "-2": "Adds an annoyance that keeps coming back in this domain.",
17208
+ "-1": "Adds a small annoyance inside the product.",
17209
+ "1": "Avoids a small annoyance inside the product.",
17210
+ "2": "Avoids an annoyance that keeps coming back in this domain.",
17211
+ "3": "Takes a whole kind of annoyance out of the person's life, the way a GPS ended getting lost."
17212
+ },
17213
+ "reduces-cost": {
17214
+ "-3": "Costs the person a significant amount of money over their life.",
17215
+ "-2": "Costs the person money regularly in this domain.",
17216
+ "-1": "Costs the person a little money on one purchase.",
17217
+ "1": "Saves the person a little money on one purchase.",
17218
+ "2": "Saves the person money regularly in this domain.",
17219
+ "3": "Saves the person a significant amount of money over their life."
17220
+ },
17221
+ quality: {
17222
+ "-3": "Craft so poor the person would call it the worst they have used.",
17223
+ "-2": "The product does its job in this domain clearly worse than the usual alternatives.",
17224
+ "-1": "Something inside the product works noticeably badly.",
17225
+ "1": "Something inside the product works noticeably well.",
17226
+ "2": "The product does its job in this domain clearly better than the usual alternatives.",
17227
+ "3": "Craft so good the person would call it the best they have used."
17228
+ },
17229
+ variety: {
17230
+ "-3": "Closes off a breadth of choice the person had elsewhere.",
17231
+ "-2": "Narrows the choice in this domain.",
17232
+ "-1": "Removes a few meaningful options inside the product.",
17233
+ "1": "Offers a few meaningful options inside the product.",
17234
+ "2": "Offers a wide and meaningful choice in this domain.",
17235
+ "3": "Opens a breadth of choice the person could not get anywhere else."
17236
+ },
17237
+ "sensory-appeal": {
17238
+ "-3": "A sensory experience the person avoids.",
17239
+ "-2": "The product looks, sounds or feels bad and the person dislikes using it.",
17240
+ "-1": "An unpleasant detail the person notices in the moment.",
17241
+ "1": "A pleasant detail the person notices in the moment.",
17242
+ "2": "The product looks, sounds or feels good and the person enjoys using it.",
17243
+ "3": "A sensory experience the person seeks out for its own sake."
17244
+ },
17245
+ informs: {
17246
+ "-3": "Misleads the person deeply about the service area or domain.",
17247
+ "-2": "Confuses the person about the service area or domain.",
17248
+ "-1": "Hides from the person something about the service that they want to know.",
17249
+ "1": "Informs the person about the service.",
17250
+ "2": "Informs the person about the service area or domain.",
17251
+ "3": "Informs the person deeply and efficiently about the service area or domain."
17252
+ },
17253
+ "reduces-anxiety": {
17254
+ "-3": "Gives the person a lasting worry in their life.",
17255
+ "-2": "Stirs up a worry the person has in this domain.",
17256
+ "-1": "Adds a small worry inside the product.",
17257
+ "1": "Removes a small worry inside the product.",
17258
+ "2": "Calms a worry the person has in this domain.",
17259
+ "3": "Takes a lasting worry out of the person's life."
17260
+ },
17261
+ "rewards-me": {
17262
+ "-3": "Takes away rewards the person values as much as the product itself.",
17263
+ "-2": "Takes away perks the person regularly values.",
17264
+ "-1": "Takes away a small perk the person had.",
17265
+ "1": "Gives the person a small perk for engaging.",
17266
+ "2": "Gives the person regular perks they value.",
17267
+ "3": "Gives the person rewards they value as much as the product itself."
17268
+ },
17269
+ nostalgia: {
17270
+ "-3": "Destroys a cherished memory for good.",
17271
+ "-2": "Loses or overwrites a good memory of the past.",
17272
+ "-1": "Puts a pleasant memory at slight risk.",
17273
+ "1": "Faintly recalls a pleasant memory of the past.",
17274
+ "2": "Clearly brings back a good memory of the past.",
17275
+ "3": "Brings back a cherished past in a vivid and deeply felt way."
17276
+ },
17277
+ "design-aesthetics": {
17278
+ "-3": "Ugliness the person would be embarrassed to show to others.",
17279
+ "-2": "A design the person finds ugly.",
17280
+ "-1": "A displeasing design detail.",
17281
+ "1": "A pleasing design detail.",
17282
+ "2": "A design the person finds beautiful.",
17283
+ "3": "Beauty the person would show to others and that shapes how they feel about it."
17284
+ },
17285
+ "badge-value": {
17286
+ "-3": "Signals something the person does not want the people who matter to them to see.",
17287
+ "-2": "Clearly signals a low identity or status in a community.",
17288
+ "-1": "Gives a mild negative signal about the person to others.",
17289
+ "1": "Gives a mild signal about the person to others.",
17290
+ "2": "Clearly signals the person's identity or status in a community.",
17291
+ "3": "Signals who the person is to the people who matter to them."
17292
+ },
17293
+ wellness: {
17294
+ "-3": "Lastingly harms the person's physical or mental well-being.",
17295
+ "-2": "Noticeably worsens how the person feels over time.",
17296
+ "-1": "Slightly worsens how the person feels, in the moment.",
17297
+ "1": "Slightly improves how the person feels, in the moment.",
17298
+ "2": "Noticeably improves how the person feels over time.",
17299
+ "3": "Lastingly improves the person's physical or mental well-being."
17300
+ },
17301
+ "therapeutic-value": {
17302
+ "-3": "Deepens something that hurts the person.",
17303
+ "-2": "Makes a difficult feeling harder for the person to work through.",
17304
+ "-1": "Reopens a small emotional sore.",
17305
+ "1": "Gives a small moment of emotional relief.",
17306
+ "2": "Helps the person work through a difficult feeling.",
17307
+ "3": "Supports real healing of something that hurts the person."
17308
+ },
17309
+ "fun-entertainment": {
17310
+ "-3": "So joyless that the person avoids it and warns others.",
17311
+ "-2": "Boring or tedious to use.",
17312
+ "-1": "A dull moment.",
17313
+ "1": "A light moment of enjoyment.",
17314
+ "2": "Genuinely enjoyable to use.",
17315
+ "3": "Delight the person would seek out and tell others about."
17316
+ },
17317
+ attractiveness: {
17318
+ "-3": "Changes how unattractive the person feels in general.",
17319
+ "-2": "Clearly makes the person feel less attractive.",
17320
+ "-1": "Makes the person feel slightly worse about how they look.",
17321
+ "1": "Makes the person feel slightly better about how they look.",
17322
+ "2": "Clearly makes the person feel more attractive.",
17323
+ "3": "Changes how attractive the person feels in general."
17324
+ },
17325
+ "provides-access": {
17326
+ "-3": "Shuts the person out of something that matters in their life.",
17327
+ "-2": "Cuts the person off from a service or from people in this domain that they could otherwise reach.",
17328
+ "-1": "Puts a feature inside the product behind a barrier or closes it off.",
17329
+ "1": "Opens a feature inside the product.",
17330
+ "2": "Gives access to a service or to people in this domain that the person could not easily reach.",
17331
+ "3": "Gives access to something that matters in the person's life and that they could not get otherwise."
17332
+ },
17333
+ "provides-hope": {
17334
+ "-3": "Leaves the person believing their life cannot get better.",
17335
+ "-2": "Gives the person a reason to doubt that things in this domain can improve.",
17336
+ "-1": "Plants a small doubt.",
17337
+ "1": "Gives a small reason for optimism.",
17338
+ "2": "Gives a real reason to believe things in this domain can improve.",
17339
+ "3": "Gives a lasting belief that the person's life can get better."
17340
+ },
17341
+ "self-actualization": {
17342
+ "-3": "Pushes the person away from who they want to be.",
17343
+ "-2": "Clear drift away from who the person wants to be.",
17344
+ "-1": "A small step away from who the person wants to be.",
17345
+ "1": "A small step toward who the person wants to be.",
17346
+ "2": "Clear progress toward who the person wants to be.",
17347
+ "3": "Helps the person become who they want to be."
17348
+ },
17349
+ motivation: {
17350
+ "-3": "Drains the person's drive toward goals that matter in their life.",
17351
+ "-2": "Saps the person's energy toward a goal in this domain.",
17352
+ "-1": "A small drag on the person's drive.",
17353
+ "1": "A small nudge to act.",
17354
+ "2": "Energizes the person toward a goal in this domain.",
17355
+ "3": "Sustains the person's drive toward goals that matter in their life."
17356
+ },
17357
+ heirloom: {
17358
+ "-3": "Loses something meaningful that was meant to be passed on across time.",
17359
+ "-2": "Lets something meaningful be lost within years.",
17360
+ "-1": "Puts something worth keeping at slight risk.",
17361
+ "1": "Keeps something worth keeping for a while.",
17362
+ "2": "Preserves something meaningful for years.",
17363
+ "3": "Holds something meaningful enough to be passed on to others across time."
17364
+ },
17365
+ "affiliation-belonging": {
17366
+ "-3": "Cuts the person off from a group that matters deeply to who they are.",
17367
+ "-2": "Leaves the person out of a group in this domain.",
17368
+ "-1": "A feeling of being slightly left out of something small.",
17369
+ "1": "A feeling of being part of something small.",
17370
+ "2": "Makes the person part of a group in this domain.",
17371
+ "3": "Makes the person part of a group that matters deeply to who they are."
17372
+ },
17373
+ "self-transcendence": {
17374
+ "-3": "Works against something larger than the person themselves.",
17375
+ "-2": "Harms others in a meaningful way.",
17376
+ "-1": "Does a small harm to others.",
17377
+ "1": "Does a small good for others.",
17378
+ "2": "Helps others in a meaningful way.",
17379
+ "3": "Contributes to something larger than the person themselves."
17380
+ }
17381
+ };
17382
+ var VALUE_REACH_LADDERS = Object.freeze(
17383
+ Object.fromEntries(Object.entries(LADDERS).map(([id, ladder]) => [id, Object.freeze(ladder)]))
17384
+ );
17385
+
17386
+ // ../schema/src/weighing.ts
17387
+ var CONFIDENCE_LEVELS = [0, 1, 2, 3];
17388
+ var CONFIDENCE_ANCHORS = {
17389
+ 0: "Guess. Nothing behind it.",
17390
+ 1: "Inferred from the subject's own text.",
17391
+ 2: "Evidenced: cites something outside the subject.",
17392
+ 3: "Verified: reviewed by a human, measured, or survived a second scorer trying to refute it."
17393
+ };
17394
+ var SCORER_KINDS = ["human", "agent", "rule"];
17395
+ var STORED_SCORER_KINDS = ["human", "agent"];
17396
+ function scorerRank(kind) {
17397
+ const index = SCORER_KINDS.indexOf(kind);
17398
+ return index === -1 ? 0 : SCORER_KINDS.length - index;
17399
+ }
17400
+ var WEIGHING_PROBABILITY_FIELDS = ["p_serves", "p_costs"];
17401
+ function isWeighingProbability(value) {
17402
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
17403
+ }
17404
+ var WEIGHING_CLEAR_AT = 0.7;
17405
+ var WEIGHING_UNSETTLED_AT = 0.3;
17406
+ function isUncertainCell(row) {
17407
+ const serves = isWeighingProbability(row.p_serves) ? row.p_serves : void 0;
17408
+ const costs = isWeighingProbability(row.p_costs) ? row.p_costs : void 0;
17409
+ const same = row.level > 0 ? serves : row.level < 0 ? costs : void 0;
17410
+ const others = row.level > 0 ? [costs] : row.level < 0 ? [serves] : [serves, costs];
17411
+ return same !== void 0 && same < WEIGHING_CLEAR_AT || others.some((p) => p !== void 0 && p >= WEIGHING_UNSETTLED_AT);
17412
+ }
17413
+ var WEIGHING_ASSESSMENT_RECORDED = "weighing.assessment.recorded";
17414
+ var WEIGHING_SET_SAVED = "weighing.set.saved";
17415
+ function cellKey(matrix, subject, criterion) {
17416
+ return `${matrix}\0${subject}\0${criterion}`;
17417
+ }
17418
+ function assessmentKey(a) {
17419
+ const kind = typeof a?.scorer?.kind === "string" ? a.scorer.kind : "";
17420
+ return `${cellKey(String(a?.matrix), String(a?.subject), String(a?.criterion))}\0${kind}`;
17421
+ }
17422
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17423
+ function isWeighingAssessmentShape(row) {
17424
+ return isRecord3(row) && typeof row.matrix === "string" && typeof row.subject === "string" && typeof row.criterion === "string";
17425
+ }
17426
+ function readWeighingAssessments(section) {
17427
+ return Array.isArray(section?.assessments) ? section.assessments.filter(isWeighingAssessmentShape) : [];
17428
+ }
17429
+ function isActiveWeighingSet(set2) {
17430
+ const status = set2?.status;
17431
+ return status === void 0 || status === "active";
17432
+ }
17433
+ function splitSetRef(ref) {
17434
+ const at = ref.lastIndexOf("@");
17435
+ if (at === -1) return { id: ref, major: void 0 };
17436
+ return { id: ref.slice(0, at), major: ref.slice(at + 1) };
17437
+ }
17438
+ function majorOf(version2) {
17439
+ const match = /^(\d+)(?:\.|$)/.exec(version2);
17440
+ return match ? match[1] : void 0;
17441
+ }
17442
+ function hash53(text) {
17443
+ let h1 = 3735928559;
17444
+ let h2 = 1103547991;
17445
+ for (let i = 0; i < text.length; i++) {
17446
+ const code = text.charCodeAt(i);
17447
+ h1 = Math.imul(h1 ^ code, 2654435761);
17448
+ h2 = Math.imul(h2 ^ code, 1597334677);
17449
+ }
17450
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
17451
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
17452
+ return 4294967296 * (2097151 & h2) + (h1 >>> 0);
17453
+ }
17454
+ var squash = (text) => text.replace(/\s+/g, " ").trim();
17455
+ function acceptanceFingerprint(node) {
17456
+ const gherkin = typeof node.metadata?.gherkin === "string" ? node.metadata.gherkin : "";
17457
+ const values = Array.isArray(node.metadata?.values) ? node.metadata.values : [];
17458
+ const text = JSON.stringify([squash(node.title ?? ""), squash(gherkin), values]);
17459
+ return `fp1-${hash53(text).toString(16).padStart(14, "0")}`;
17460
+ }
17461
+ function upsertWeighingAssessment(assessments, next) {
17462
+ const key = assessmentKey(next);
17463
+ const index = assessments.findIndex((candidate) => assessmentKey(candidate) === key);
17464
+ if (index === -1) return { assessments: [...assessments, next] };
17465
+ const updated = [...assessments];
17466
+ const replaced = updated[index];
17467
+ updated[index] = next;
17468
+ return { assessments: updated, replaced };
17469
+ }
17470
+ function sortWeighingAssessments(assessments) {
17471
+ return [...assessments].sort((a, b) => {
17472
+ const text = (x) => typeof x === "string" ? x : "\uFFFF";
17473
+ const by = (x, y) => text(x) < text(y) ? -1 : text(x) > text(y) ? 1 : 0;
17474
+ return by(a?.matrix, b?.matrix) || by(a?.subject, b?.subject) || by(a?.criterion, b?.criterion) || scorerRank(b?.scorer?.kind) - scorerRank(a?.scorer?.kind);
17475
+ });
17476
+ }
17477
+
17478
+ // ../schema/src/weighing-library.ts
17479
+ function deepFreeze(value) {
17480
+ if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
17481
+ Object.freeze(value);
17482
+ for (const child of Object.values(value)) deepFreeze(child);
17483
+ }
17484
+ return value;
17485
+ }
17486
+ var VALUE_SET_ID = "value-contribution";
17487
+ var VALUE_SET_VERSION = "2.0.0";
17488
+ var VALUE_SET_V1_VERSION = "1.0.0";
17489
+ var VALUE_MATRIX_ID = "value";
17490
+ var POSITIONING_SET_ID = "positioning";
17491
+ var VALUE_SCALE_ANCHORS = {
17492
+ "3": "Life-wide. It gives the person this well beyond the product and its domain, in their life.",
17493
+ "2": "Across the domain. The person gets this in the whole area the product belongs to, not only inside it.",
17494
+ "1": "Within the product. A real contribution, felt while using it.",
17495
+ "0": "Unrelated: weighed and found to have nothing to do with it. (No row means nobody has weighed it yet.)",
17496
+ "-1": "Within the product. A small cost, felt while using it.",
17497
+ "-2": "Across the domain. The person notices the loss of this in the whole area the product belongs to.",
17498
+ "-3": "Life-wide. It leaves the person with the opposite of this in their life."
17499
+ };
17500
+ var VALUE_SCALE_V1_ANCHORS = {
17501
+ "3": "Core. The promise exists for this; take it away and the value goes.",
17502
+ "2": "Supports clearly. The user would notice it missing.",
17503
+ "1": "Touches. A side effect of the promise, not its purpose.",
17504
+ "0": "Unrelated: weighed and found to have nothing to do with it. (No row means nobody has weighed it yet.)",
17505
+ "-1": "Small friction. It costs this value a little.",
17506
+ "-2": "Works against it. The user notices the cost.",
17507
+ "-3": "Costs it at its core. The user feels the opposite."
17508
+ };
17509
+ var TIER_TITLES = {
17510
+ functional: "Functional",
17511
+ emotional: "Emotional",
17512
+ "life-changing": "Life-changing",
17513
+ "social-impact": "Social impact"
17514
+ };
17515
+ var VALUE_TEXT = {
17516
+ "saves-time": { name: "Saves time", definition: "Completes the user's task in less time." },
17517
+ simplifies: { name: "Simplifies", definition: "Reduces steps, choices, or cognitive load." },
17518
+ "makes-money": { name: "Makes money", definition: "Helps the user earn." },
17519
+ "reduces-risk": { name: "Reduces risk", definition: "Protects against loss, error, or uncertainty." },
17520
+ organizes: { name: "Organizes", definition: "Brings order to the user's things or life." },
17521
+ integrates: { name: "Integrates", definition: "Ties different tools or parts of life together." },
17522
+ connects: { name: "Connects", definition: "Brings the user together with other people." },
17523
+ "reduces-effort": { name: "Reduces effort", definition: "Same outcome, less work." },
17524
+ "avoids-hassles": { name: "Avoids hassles", definition: "Prevents friction and annoyance before it happens." },
17525
+ "reduces-cost": { name: "Reduces cost", definition: "Saves the user money." },
17526
+ quality: { name: "Quality", definition: "Superior craft or performance the user can feel." },
17527
+ variety: { name: "Variety", definition: "Meaningful choice and breadth." },
17528
+ "sensory-appeal": { name: "Sensory appeal", definition: "Looks, sounds, or feels good in the moment." },
17529
+ informs: { name: "Informs", definition: "Tells the user something they want to know." },
17530
+ "reduces-anxiety": { name: "Reduces anxiety", definition: "Calms; makes the user feel safe." },
17531
+ "rewards-me": { name: "Rewards me", definition: "Tangible perks for engagement." },
17532
+ nostalgia: { name: "Nostalgia", definition: "Positive memory of the past." },
17533
+ "design-aesthetics": { name: "Design / aesthetics", definition: "Beauty as an experienced value, beyond function." },
17534
+ "badge-value": { name: "Badge value", definition: "Signals identity or status to others." },
17535
+ wellness: { name: "Wellness", definition: "Improves physical or mental well-being." },
17536
+ "therapeutic-value": { name: "Therapeutic value", definition: "Actively supports emotional processing or healing." },
17537
+ "fun-entertainment": { name: "Fun / entertainment", definition: "Enjoyable, playful, delightful." },
17538
+ attractiveness: { name: "Attractiveness", definition: "Makes the user feel attractive." },
17539
+ "provides-access": { name: "Provides access", definition: "Grants entry to something otherwise out of reach." },
17540
+ "provides-hope": { name: "Provides hope", definition: "Reason to believe things can improve." },
17541
+ "self-actualization": { name: "Self-actualization", definition: "Helps the user become who they want to be." },
17542
+ motivation: { name: "Motivation", definition: "Energizes the user toward their goals." },
17543
+ heirloom: { name: "Heirloom", definition: "Something worth passing on across time." },
17544
+ "affiliation-belonging": { name: "Affiliation & belonging", definition: "Makes the user part of a group that matters." },
17545
+ "self-transcendence": { name: "Self-transcendence", definition: "Helps beyond the user themselves." }
17546
+ };
17547
+ var VALUE_SCALE = { min: -3, max: 3, anchors: { ...VALUE_SCALE_ANCHORS } };
17548
+ var GROUPS = Object.keys(TIER_TITLES).map((id) => ({ id, title: TIER_TITLES[id] }));
17549
+ function reachQuestion(id) {
17550
+ if (id === "informs") {
17551
+ return "Is what this promise mainly gives the person information, rather than an ability, a shortcut, a protection or a feeling? Or does it keep them from knowing something? And how far into their life does it reach?";
17552
+ }
17553
+ return `Does this promise serve, or cost, "${VALUE_TEXT[id].name}" for the person? And how far into their life does it reach: within the product, across its domain, or life-wide?`;
17554
+ }
17555
+ var VALUE_CONTRIBUTION_SET = deepFreeze({
17556
+ id: VALUE_SET_ID,
17557
+ version: VALUE_SET_VERSION,
17558
+ title: "Elements of value",
17559
+ subject: "acceptance",
17560
+ scale: VALUE_SCALE,
17561
+ groups: GROUPS,
17562
+ criteria: VALUE_IDS.map((id) => ({
17563
+ id,
17564
+ group: VALUE_TIERS[id],
17565
+ name: VALUE_TEXT[id].name,
17566
+ question: reachQuestion(id),
17567
+ definition: VALUE_TEXT[id].definition,
17568
+ anchors: { ...VALUE_REACH_LADDERS[id] }
17569
+ }))
17570
+ });
17571
+ var VALUE_CONTRIBUTION_SET_V1 = deepFreeze({
17572
+ id: VALUE_SET_ID,
17573
+ version: VALUE_SET_V1_VERSION,
17574
+ title: "Elements of value",
17575
+ subject: "acceptance",
17576
+ scale: { min: -3, max: 3, anchors: { ...VALUE_SCALE_V1_ANCHORS } },
17577
+ groups: GROUPS,
17578
+ criteria: VALUE_IDS.map((id) => ({
17579
+ id,
17580
+ group: VALUE_TIERS[id],
17581
+ name: VALUE_TEXT[id].name,
17582
+ question: `Does this promise serve, or cost, "${VALUE_TEXT[id].name}"?`,
17583
+ definition: VALUE_TEXT[id].definition
17584
+ }))
17585
+ });
17586
+ var VALUE_MATRIX = deepFreeze({
17587
+ id: VALUE_MATRIX_ID,
17588
+ title: "Value",
17589
+ set: `${VALUE_SET_ID}@2`,
17590
+ subjects: { kind: "query", species: "acceptance" },
17591
+ positioning: POSITIONING_SET_ID,
17592
+ status: "active"
17593
+ });
17594
+ var BUILT_IN_SETS = [VALUE_CONTRIBUTION_SET, VALUE_CONTRIBUTION_SET_V1];
17595
+ var BUILT_IN_MATRICES = [VALUE_MATRIX];
17596
+ var isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17597
+ function cleaned(set2) {
17598
+ const usable = set2.criteria.filter((criterion) => isObject2(criterion) && typeof criterion.id === "string");
17599
+ return usable.length === set2.criteria.length ? set2 : { ...set2, criteria: usable };
17600
+ }
17601
+ function isWeighingSetShape(set2) {
17602
+ return isObject2(set2) && typeof set2.id === "string" && typeof set2.version === "string" && Array.isArray(set2.criteria) && (isObject2(set2.scale) || set2.role === "positioning");
17603
+ }
17604
+ function isWeighingMatrixShape(matrix) {
17605
+ if (!isObject2(matrix) || typeof matrix.id !== "string" || typeof matrix.set !== "string" || !isObject2(matrix.subjects)) return false;
17606
+ const { kind, species, items } = matrix.subjects;
17607
+ return kind === "query" && typeof species === "string" || kind === "list" && Array.isArray(items);
17608
+ }
17609
+ function isUsableScale(scale) {
17610
+ return isObject2(scale) && typeof scale.min === "number" && typeof scale.max === "number" && isObject2(scale.anchors);
17611
+ }
17612
+ function weighingScaleOf(set2, resolved) {
17613
+ if (isUsableScale(set2.scale)) return set2.scale;
17614
+ const ruler = typeof set2.extends === "string" && resolved !== void 0 ? setOfRef(resolved, set2.extends) : void 0;
17615
+ return ruler !== void 0 && isUsableScale(ruler.scale) ? ruler.scale : VALUE_SCALE;
17616
+ }
17617
+ function resolveWeighing(section) {
17618
+ const sets = [...BUILT_IN_SETS];
17619
+ const matrices = [...BUILT_IN_MATRICES];
17620
+ const skipped = [];
17621
+ const idOf2 = (entry) => isObject2(entry) ? { ...typeof entry.id === "string" ? { id: entry.id } : {}, ...typeof entry.role === "string" ? { role: entry.role } : {} } : {};
17622
+ (Array.isArray(section?.sets) ? section.sets : []).forEach((set2, index) => {
17623
+ if (isWeighingSetShape(set2) && !sets.some((s) => s.id === set2.id)) sets.push(cleaned(set2));
17624
+ else skipped.push({ kind: "set", ...idOf2(set2), index });
17625
+ });
17626
+ (Array.isArray(section?.matrices) ? section.matrices : []).forEach((matrix, index) => {
17627
+ if (isWeighingMatrixShape(matrix) && !matrices.some((m) => m.id === matrix.id)) matrices.push(matrix);
17628
+ else skipped.push({ kind: "matrix", ...idOf2(matrix), index });
17629
+ });
17630
+ return { sets, matrices, skipped };
17631
+ }
17632
+ function setOfRef(resolved, ref) {
17633
+ const { id, major } = splitSetRef(ref);
17634
+ return resolved.sets.find((candidate) => candidate.id === id && (major === void 0 || majorOf(candidate.version) === major));
17635
+ }
17636
+ function isOlderMajorRef(resolved, ref) {
17637
+ const { id, major } = splitSetRef(ref);
17638
+ const current = resolved.sets.find((candidate) => candidate.id === id);
17639
+ if (current === void 0 || major === void 0) return false;
17640
+ const now = Number(majorOf(current.version));
17641
+ return Number.isFinite(now) && Number(major) < now;
17642
+ }
17643
+
17644
+ // ../schema/src/weighing-validate.ts
17645
+ var isObject3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17646
+ function validateWeighingSection(section, nodeSpecies, journal) {
17647
+ const out = [];
17648
+ const warn = (path, rule, message) => out.push({ path, rule, message });
17649
+ if (section !== void 0 && section !== null && !isObject3(section)) {
17650
+ warn("weighing", "weighing-section-shape", "The weighing section is not an object \u2014 it is ignored");
17651
+ }
17652
+ if (isObject3(section)) {
17653
+ for (const list of ["sets", "matrices", "assessments"]) {
17654
+ if (section[list] !== void 0 && !Array.isArray(section[list])) {
17655
+ warn(`weighing.${list}`, "weighing-section-shape", `weighing.${list} is not an array \u2014 it is ignored`);
17656
+ }
17657
+ }
17658
+ const sets = Array.isArray(section.sets) ? section.sets : [];
17659
+ const matrices = Array.isArray(section.matrices) ? section.matrices : [];
17660
+ const assessments = Array.isArray(section.assessments) ? section.assessments : [];
17661
+ const resolved = resolveWeighing(section);
17662
+ const resolveRef2 = (ref, path, who, unknownRule) => {
17663
+ const set2 = setOfRef(resolved, ref);
17664
+ if (set2 !== void 0) return set2;
17665
+ const named = resolved.sets.find((candidate) => candidate.id === splitSetRef(ref).id);
17666
+ if (named !== void 0) {
17667
+ warn(path, "weighing-set-ref-major", `${who} names ${ref}, but "${named.id}" is at ${named.version} \u2014 levels are comparable only within a major, so the ref resolves to nothing`);
17668
+ } else {
17669
+ warn(path, unknownRule, `${who} names set "${ref}", which is neither built in nor in this section`);
17670
+ }
17671
+ return void 0;
17672
+ };
17673
+ const positioningIds = new Set(
17674
+ resolved.matrices.map((matrix) => matrix.positioning).filter((id) => typeof id === "string")
17675
+ );
17676
+ const checkStatus = (path, who, entry) => {
17677
+ if (entry.status !== void 0 && entry.status !== "draft" && entry.status !== "active") {
17678
+ warn(`${path}.status`, "weighing-set-status", `${who}: status ${JSON.stringify(entry.status)} is not "draft" or "active" \u2014 it is read as a draft, which feeds no roll-up`);
17679
+ }
17680
+ };
17681
+ const isLevelMap = (value) => isObject3(value) && Object.values(value).every((anchor) => typeof anchor === "string");
17682
+ const seenSets = /* @__PURE__ */ new Set();
17683
+ sets.forEach((entry, index) => {
17684
+ const path = `weighing.sets[${index}]`;
17685
+ if (!isObject3(entry)) {
17686
+ warn(path, "weighing-set-shape", "A set is not an object \u2014 it is ignored");
17687
+ return;
17688
+ }
17689
+ const who = `Set "${String(entry.id)}"`;
17690
+ const wellFormed = isWeighingSetShape(entry);
17691
+ if (!wellFormed) {
17692
+ warn(path, "weighing-set-shape", `${who} needs a string id and version, a criteria array and a scale object (a positioning may leave the scale out) \u2014 it is ignored`);
17693
+ }
17694
+ if (typeof entry.id === "string") {
17695
+ if (BUILT_IN_SETS.some((set2) => set2.id === entry.id)) {
17696
+ warn(`${path}.id`, "weighing-pinned-set-redefined", `${who} is built in and pinned by version \u2014 the project's copy is ignored`);
17697
+ } else if (wellFormed) {
17698
+ if (seenSets.has(entry.id)) warn(`${path}.id`, "weighing-duplicate-set", `Duplicate set id "${entry.id}" \u2014 the first well-formed one wins, this one is ignored`);
17699
+ seenSets.add(entry.id);
17700
+ }
17701
+ }
17702
+ checkStatus(path, who, entry);
17703
+ if (isObject3(entry.scale)) {
17704
+ const scale = entry.scale;
17705
+ if (typeof scale.min !== "number" || typeof scale.max !== "number" || !isLevelMap(scale.anchors)) {
17706
+ warn(`${path}.scale`, "weighing-scale-shape", `${who}: a scale needs a numeric min and max and an anchors object of strings`);
17707
+ }
17708
+ }
17709
+ if (Array.isArray(entry.criteria)) {
17710
+ entry.criteria.forEach((criterion, at) => {
17711
+ const cpath = `${path}.criteria[${at}]`;
17712
+ if (!isObject3(criterion) || typeof criterion.id !== "string" || criterion.anchors !== void 0 && !isLevelMap(criterion.anchors)) {
17713
+ warn(cpath, "weighing-criterion-shape", `${who}: criterion ${at} needs a string id, and its anchors (if any) must be an object of strings`);
17714
+ }
17715
+ });
17716
+ }
17717
+ if (entry.role === "positioning" && !(typeof entry.id === "string" && positioningIds.has(entry.id))) {
17718
+ warn(`${path}.id`, "weighing-positioning-id", `A positioning set must have the id "${POSITIONING_SET_ID}" (the one a matrix points at) \u2014 "${String(entry.id)}" would never be applied`);
17719
+ } else if (entry.role !== "positioning" && entry.id === POSITIONING_SET_ID) {
17720
+ warn(`${path}.role`, "weighing-positioning-id", `Set "${POSITIONING_SET_ID}" is where a matrix looks for its positioning, but its role is ${JSON.stringify(entry.role)}, not "positioning" \u2014 it would never be applied`);
17721
+ }
17722
+ if (entry.role === "positioning") {
17723
+ const ruler = typeof entry.extends === "string" ? resolveRef2(entry.extends, `${path}.extends`, `Positioning "${String(entry.id)}"`, "weighing-positioning-unknown-ruler") : void 0;
17724
+ if (typeof entry.extends !== "string") {
17725
+ warn(`${path}.extends`, "weighing-positioning-unknown-ruler", `Positioning "${String(entry.id)}" does not say which set it re-weights \u2014 set extends to e.g. value-contribution@2`);
17726
+ } else if (ruler !== void 0 && ruler.role === "positioning") {
17727
+ warn(`${path}.extends`, "weighing-positioning-unknown-ruler", `Positioning "${String(entry.id)}" extends "${entry.extends}", which is itself a positioning \u2014 it must extend a criteria set such as value-contribution@2`);
17728
+ } else if (ruler !== void 0 && isOlderMajorRef(resolved, entry.extends)) {
17729
+ warn(`${path}.extends`, "weighing-positioning-old-ruler", `Positioning "${String(entry.id)}" extends ${entry.extends}, an older ruler \u2014 its weights still apply, but read its level descriptions against ${ruler.id}'s current major and save it again`);
17730
+ }
17731
+ const known = new Set(ruler !== void 0 && ruler.role !== "positioning" ? ruler.criteria.map((criterion) => criterion?.id) : []);
17732
+ (Array.isArray(entry.criteria) ? entry.criteria : []).forEach((criterion, at) => {
17733
+ if (!isObject3(criterion)) return;
17734
+ const cpath = `${path}.criteria[${at}]`;
17735
+ if (known.size > 0 && typeof criterion.id === "string" && !known.has(criterion.id)) {
17736
+ warn(`${cpath}.id`, "weighing-positioning-unknown-element", `Positioning names "${criterion.id}", which is not in ${String(entry.extends)}`);
17737
+ }
17738
+ if (criterion.weight !== void 0 && (typeof criterion.weight !== "number" || !(criterion.weight > 0))) {
17739
+ warn(`${cpath}.weight`, "weighing-positioning-weight", `Positioning weight for "${String(criterion.id)}" must be a number above 0 \u2014 leave the element out to leave it unpositioned`);
17740
+ }
17741
+ });
17742
+ }
17743
+ });
17744
+ const seenMatrices = /* @__PURE__ */ new Set();
17745
+ matrices.forEach((entry, index) => {
17746
+ const path = `weighing.matrices[${index}]`;
17747
+ if (!isObject3(entry)) {
17748
+ warn(path, "weighing-matrix-shape", "A matrix is not an object \u2014 it is ignored");
17749
+ return;
17750
+ }
17751
+ const who = `Matrix "${String(entry.id)}"`;
17752
+ const wellFormed = isWeighingMatrixShape(entry);
17753
+ if (!wellFormed) {
17754
+ warn(path, "weighing-matrix-shape", `${who} needs a string id, a set ref and a subjects object of kind query or list \u2014 it is ignored`);
17755
+ }
17756
+ if (typeof entry.id === "string") {
17757
+ if (BUILT_IN_MATRICES.some((matrix) => matrix.id === entry.id)) {
17758
+ warn(`${path}.id`, "weighing-pinned-matrix-redefined", `${who} is built in \u2014 the project's copy is ignored`);
17759
+ } else if (wellFormed) {
17760
+ if (seenMatrices.has(entry.id)) warn(`${path}.id`, "weighing-duplicate-matrix", `Duplicate matrix id "${entry.id}" \u2014 the first well-formed one wins, this one is ignored`);
17761
+ seenMatrices.add(entry.id);
17762
+ }
17763
+ }
17764
+ checkStatus(path, who, entry);
17765
+ if (wellFormed && resolveRef2(entry.set, `${path}.set`, who, "weighing-unknown-set") !== void 0 && isOlderMajorRef(resolved, entry.set)) {
17766
+ warn(`${path}.set`, "weighing-matrix-old-ruler", `${who} reads ${entry.set}, an older ruler \u2014 its levels still read, but nothing new can be scored on it; point it at the current major`);
17767
+ }
17768
+ });
17769
+ const seenCells = /* @__PURE__ */ new Set();
17770
+ assessments.forEach((entry, index) => {
17771
+ const path = `weighing.assessments[${index}]`;
17772
+ const label = `Assessment ${index}`;
17773
+ if (!isWeighingAssessmentShape(entry)) {
17774
+ warn(path, "weighing-assessment-shape", `${label}: not an object with a string matrix, subject and criterion \u2014 it cannot be addressed, so every reader skips it`);
17775
+ return;
17776
+ }
17777
+ if (typeof entry.ts !== "string" || Number.isNaN(Date.parse(entry.ts))) {
17778
+ warn(`${path}.ts`, "weighing-assessment-ts", `${label}: ts must be an ISO 8601 string \u2014 without it "latest wins" cannot order this row`);
17779
+ }
17780
+ const matrix = resolved.matrices.find((candidate) => candidate.id === entry.matrix);
17781
+ if (matrix === void 0) {
17782
+ warn(`${path}.matrix`, "weighing-unknown-matrix", `${label}: matrix "${entry.matrix}" is not defined`);
17783
+ }
17784
+ const set2 = matrix === void 0 ? void 0 : setOfRef(resolved, matrix.set);
17785
+ const criterion = set2?.criteria.find((candidate) => candidate?.id === entry.criterion);
17786
+ if (set2 !== void 0 && criterion === void 0) {
17787
+ warn(`${path}.criterion`, "weighing-unknown-criterion", `${label}: criterion "${entry.criterion}" is not in set "${set2.id}"`);
17788
+ }
17789
+ if (criterion !== void 0 && typeof criterion.superseded_by === "string" && criterion.superseded_by !== "") {
17790
+ warn(`${path}.criterion`, "weighing-retired-criterion", `${label}: criterion "${criterion.id}" is retired \u2014 superseded by "${criterion.superseded_by}"`);
17791
+ }
17792
+ const scale = set2 === void 0 ? void 0 : weighingScaleOf(set2, resolved);
17793
+ const min = typeof scale?.min === "number" ? scale.min : -3;
17794
+ const max = typeof scale?.max === "number" ? scale.max : 3;
17795
+ if (typeof entry.level !== "number" || !Number.isInteger(entry.level) || entry.level < min || entry.level > max) {
17796
+ warn(`${path}.level`, "weighing-level-range", `${label}: level must be an integer ${min}..${max} (a blank cell is the absence of the row; 0 means weighed and unrelated)`);
17797
+ }
17798
+ if (![0, 1, 2, 3].includes(entry.confidence)) {
17799
+ warn(`${path}.confidence`, "weighing-confidence-range", `${label}: confidence must be 0, 1, 2 or 3`);
17800
+ }
17801
+ const scorer = isObject3(entry.scorer) ? entry.scorer : void 0;
17802
+ if (scorer === void 0 || typeof scorer.kind !== "string" || typeof scorer.id !== "string" || scorer.id === "") {
17803
+ warn(`${path}.scorer`, "weighing-scorer-missing", `${label}: no scorer with a string kind and id \u2014 human, agent and rule levels become indistinguishable, and the row can win no cell`);
17804
+ } else if (!SCORER_KINDS.includes(scorer.kind)) {
17805
+ warn(`${path}.scorer.kind`, "weighing-scorer-kind", `${label}: scorer kind "${scorer.kind}" is not one of ${SCORER_KINDS.join(", ")} \u2014 it ranks below every other scorer`);
17806
+ } else if (!STORED_SCORER_KINDS.includes(scorer.kind)) {
17807
+ warn(`${path}.scorer.kind`, "weighing-rule-stored", `${label}: scorer kind "${scorer.kind}" is never stored \u2014 a seeding rule is computed on read`);
17808
+ }
17809
+ if (matrix?.subjects.kind === "query") {
17810
+ const species = nodeSpecies.get(entry.subject);
17811
+ if (species === void 0) {
17812
+ warn(`${path}.subject`, "weighing-unknown-subject", `${label}: subject "${entry.subject}" is not a node in this bundle`);
17813
+ } else if (species !== matrix.subjects.species) {
17814
+ warn(`${path}.subject`, "weighing-subject-species", `${label}: subject "${entry.subject}" is a ${species}, and matrix "${matrix.id}" judges ${String(matrix.subjects.species)} nodes`);
17815
+ }
17816
+ }
17817
+ if (entry.evidence !== void 0 && typeof entry.evidence !== "string") {
17818
+ warn(`${path}.evidence`, "weighing-evidence-type", `${label}: evidence must be a markdown string`);
17819
+ } else if ((entry.confidence === 2 || entry.confidence === 3) && (entry.evidence === void 0 || entry.evidence.trim() === "")) {
17820
+ warn(`${path}.evidence`, "weighing-no-evidence", `${label}: confidence ${String(entry.confidence)} claims evidence and cites none`);
17821
+ }
17822
+ for (const field of WEIGHING_PROBABILITY_FIELDS) {
17823
+ if (entry[field] !== void 0 && !isWeighingProbability(entry[field])) {
17824
+ warn(`${path}.${field}`, "weighing-probability-shape", `${label}: ${field} must be a number from 0 to 1 \u2014 it is ignored`);
17825
+ }
17826
+ }
17827
+ if (entry.refs !== void 0 && !(Array.isArray(entry.refs) && entry.refs.every((ref) => typeof ref === "string"))) {
17828
+ warn(`${path}.refs`, "weighing-refs-type", `${label}: refs must be an array of id strings`);
17829
+ }
17830
+ if (entry.basis !== void 0 && !(isObject3(entry.basis) && ["fingerprint", "commit", "set_version"].every((key) => entry.basis[key] === void 0 || typeof entry.basis[key] === "string"))) {
17831
+ warn(`${path}.basis`, "weighing-basis-shape", `${label}: basis must be an object whose fingerprint, commit and set_version are strings`);
17832
+ }
17833
+ if (scorer !== void 0 && typeof scorer.kind === "string") {
17834
+ const key = assessmentKey(entry);
17835
+ if (seenCells.has(key)) {
17836
+ warn(path, "weighing-duplicate-assessment", `${label}: a second ${scorer.kind} score for the same cell \u2014 the section stores latest-per-scorer-kind, so this cell is ambiguous`);
17837
+ }
17838
+ seenCells.add(key);
17839
+ }
17840
+ const setVersion = isObject3(entry.basis) && typeof entry.basis.set_version === "string" ? entry.basis.set_version : void 0;
17841
+ if (set2 !== void 0 && setVersion !== void 0 && majorOf(setVersion) !== majorOf(set2.version)) {
17842
+ warn(`${path}.basis.set_version`, "weighing-set-major", `${label}: scored against ${set2.id} ${setVersion}, and the set is now ${set2.version} \u2014 levels are comparable only within a major`);
17843
+ }
17844
+ });
17845
+ }
17846
+ journal.forEach((entry, index) => {
17847
+ if (!isObject3(entry)) return;
17848
+ const type = typeof entry.type === "string" ? entry.type : "";
17849
+ if (type !== WEIGHING_ASSESSMENT_RECORDED && type !== WEIGHING_SET_SAVED) return;
17850
+ if (typeof entry.actor !== "string" || entry.actor.trim() === "") {
17851
+ warn(`journal[${index}].actor`, "weighing-event-no-actor", `Journal event ${index}: ${type} has no actor \u2014 human, agent and CI scores become indistinguishable`);
17852
+ }
17853
+ });
17854
+ return out;
17855
+ }
17856
+
17005
17857
  // ../schema/src/validate.ts
17006
17858
  var VALID_STAGES = ["beta", "monitoring", "deprecated"];
17007
17859
  var VALID_VIEW_CARD_VARIANTS = ["compact", "large"];
@@ -17852,6 +18704,13 @@ function validateBundle(input) {
17852
18704
  }
17853
18705
  });
17854
18706
  }
18707
+ const weighing = bundle.weighing;
18708
+ const embeddedJournal = Array.isArray(bundle.journal) ? bundle.journal : [];
18709
+ const weighingSpecies = /* @__PURE__ */ new Map();
18710
+ for (const [id, node] of nodeMap) weighingSpecies.set(id, String(node.species));
18711
+ for (const finding of validateWeighingSection(weighing, weighingSpecies, embeddedJournal)) {
18712
+ warn(finding.path, finding.rule, finding.message);
18713
+ }
17855
18714
  for (const finding of crossCheckJournal(bundle)) findings.push(finding);
17856
18715
  return result();
17857
18716
  }
@@ -18230,7 +19089,7 @@ function edgeRemovedInput(edgeId2) {
18230
19089
  }
18231
19090
  var TOP_LEVEL_FIELDS = ["species", "title", "description", "status", "platforms"];
18232
19091
  var MAX_SCALAR_LEN = 512;
18233
- function isRecord3(value) {
19092
+ function isRecord4(value) {
18234
19093
  return typeof value === "object" && value !== null && !Array.isArray(value);
18235
19094
  }
18236
19095
  function isShortScalar(value) {
@@ -18241,8 +19100,8 @@ function valueEqual(a, b) {
18241
19100
  return JSON.stringify(a) === JSON.stringify(b);
18242
19101
  }
18243
19102
  function changedMapKeys(prev, next) {
18244
- const p = isRecord3(prev) ? prev : {};
18245
- const n = isRecord3(next) ? next : {};
19103
+ const p = isRecord4(prev) ? prev : {};
19104
+ const n = isRecord4(next) ? next : {};
18246
19105
  const changed = [];
18247
19106
  for (const key of /* @__PURE__ */ new Set([...Object.keys(p), ...Object.keys(n)])) {
18248
19107
  if (!valueEqual(p[key], n[key])) changed.push(key);
@@ -18250,8 +19109,8 @@ function changedMapKeys(prev, next) {
18250
19109
  return changed.sort();
18251
19110
  }
18252
19111
  function diffPlatformStatuses(nodeId, currentBase, nextBase, prev, next) {
18253
- const p = isRecord3(prev) ? prev : {};
18254
- const n = isRecord3(next) ? next : {};
19112
+ const p = isRecord4(prev) ? prev : {};
19113
+ const n = isRecord4(next) ? next : {};
18255
19114
  const events = [];
18256
19115
  for (const platform of [.../* @__PURE__ */ new Set([...Object.keys(p), ...Object.keys(n)])].sort()) {
18257
19116
  const from = p[platform];
@@ -18275,7 +19134,7 @@ function diffRefs(nodeId, prev, next) {
18275
19134
  const byId = (arr) => {
18276
19135
  const map2 = /* @__PURE__ */ new Map();
18277
19136
  for (const item of arr) {
18278
- if (isRecord3(item) && typeof item.id === "string") map2.set(item.id, item);
19137
+ if (isRecord4(item) && typeof item.id === "string") map2.set(item.id, item);
18279
19138
  }
18280
19139
  return map2;
18281
19140
  };
@@ -18315,8 +19174,8 @@ function diffNodeUpdate(current, patch) {
18315
19174
  }
18316
19175
  }
18317
19176
  if ("metadata" in pat) {
18318
- const prevMeta = isRecord3(current.metadata) ? current.metadata : {};
18319
- const nextMeta = isRecord3(patch.metadata) ? patch.metadata : {};
19177
+ const prevMeta = isRecord4(current.metadata) ? current.metadata : {};
19178
+ const nextMeta = isRecord4(patch.metadata) ? patch.metadata : {};
18320
19179
  const currentBase = current.status;
18321
19180
  const nextBase = "status" in pat && pat.status !== void 0 ? pat.status : current.status;
18322
19181
  for (const key of /* @__PURE__ */ new Set([...Object.keys(prevMeta), ...Object.keys(nextMeta)])) {
@@ -18600,13 +19459,13 @@ var REGRESSION_SIGNALS = {
18600
19459
  "new-severe-finding": "no open Critical or High finding on this cell",
18601
19460
  "reopened-finding": "a resolved finding stays resolved"
18602
19461
  };
18603
- var cellKey = (criterionId, surface) => `${criterionId}::${surface}`;
19462
+ var cellKey2 = (criterionId, surface) => `${criterionId}::${surface}`;
18604
19463
  var rowsOf = (value) => Array.isArray(value) ? value : [];
18605
19464
  function assessmentsByCell(state) {
18606
19465
  const cells = /* @__PURE__ */ new Map();
18607
19466
  for (const assessment of rowsOf(state?.assessments)) {
18608
19467
  if (typeof assessment?.criterion_id !== "string" || typeof assessment?.surface !== "string") continue;
18609
- cells.set(cellKey(assessment.criterion_id, assessment.surface), assessment);
19468
+ cells.set(cellKey2(assessment.criterion_id, assessment.surface), assessment);
18610
19469
  }
18611
19470
  return cells;
18612
19471
  }
@@ -18617,7 +19476,7 @@ function severeByCell(state, library) {
18617
19476
  if (!isOpenFinding(finding)) continue;
18618
19477
  const severity = severityOf(finding, library);
18619
19478
  if (severity !== "critical" && severity !== "high") continue;
18620
- const key = cellKey(finding.criterion_id, finding.surface);
19479
+ const key = cellKey2(finding.criterion_id, finding.surface);
18621
19480
  const existing = cells.get(key);
18622
19481
  if (existing === void 0) cells.set(key, [finding]);
18623
19482
  else existing.push(finding);
@@ -18673,7 +19532,7 @@ function detectRegressions(previous, next, library) {
18673
19532
 
18674
19533
  // ../schema/src/quality-trend.ts
18675
19534
  var NO_DELTA = { previous: null, delta: null };
18676
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
19535
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
18677
19536
  function frameworkMajor(version2) {
18678
19537
  if (typeof version2 !== "string") return null;
18679
19538
  const match = /^\s*v?(\d+)/.exec(version2);
@@ -18686,27 +19545,27 @@ function sameFrameworkMajor(a, b) {
18686
19545
  }
18687
19546
  function scopeOf(raw) {
18688
19547
  if (readPlanScope(raw) !== null) return void 0;
18689
- if (!isRecord4(raw) || typeof raw.since !== "string" || raw.since === "") return void 0;
19548
+ if (!isRecord5(raw) || typeof raw.since !== "string" || raw.since === "") return void 0;
18690
19549
  return { scope: { since: raw.since, cells: typeof raw.cells === "number" && Number.isFinite(raw.cells) ? raw.cells : null } };
18691
19550
  }
18692
19551
  function cleanScores(raw) {
18693
19552
  const scores = {};
18694
- if (!isRecord4(raw)) return scores;
19553
+ if (!isRecord5(raw)) return scores;
18695
19554
  for (const surface of Object.keys(raw)) {
18696
19555
  const bySurface = raw[surface];
18697
- if (!isRecord4(bySurface)) continue;
18698
- const cleaned = {};
19556
+ if (!isRecord5(bySurface)) continue;
19557
+ const cleaned2 = {};
18699
19558
  for (const domain2 of Object.keys(bySurface)) {
18700
19559
  const score = bySurface[domain2];
18701
- if (typeof score === "number" && Number.isFinite(score)) cleaned[domain2] = score;
19560
+ if (typeof score === "number" && Number.isFinite(score)) cleaned2[domain2] = score;
18702
19561
  }
18703
- scores[surface] = cleaned;
19562
+ scores[surface] = cleaned2;
18704
19563
  }
18705
19564
  return scores;
18706
19565
  }
18707
19566
  function cleanCounts(raw) {
18708
19567
  const counts = { critical: 0, high: 0, medium: 0, low: 0, info: 0 };
18709
- if (!isRecord4(raw)) return counts;
19568
+ if (!isRecord5(raw)) return counts;
18710
19569
  for (const severity of Object.keys(counts)) {
18711
19570
  const value = raw[severity];
18712
19571
  if (typeof value === "number" && Number.isFinite(value)) counts[severity] = value;
@@ -18724,7 +19583,7 @@ function liveScores(live) {
18724
19583
  const scores = {};
18725
19584
  for (const domain2 of Object.keys(live.matrix ?? {})) {
18726
19585
  const row = live.matrix[domain2];
18727
- if (!isRecord4(row)) continue;
19586
+ if (!isRecord5(row)) continue;
18728
19587
  for (const surface of Object.keys(row)) {
18729
19588
  const cell = row[surface];
18730
19589
  if (!cell || typeof cell.score !== "number") continue;
@@ -18744,7 +19603,7 @@ function deriveQualityTrend(events, profile, live) {
18744
19603
  const weights = profile?.domain_weights;
18745
19604
  const byAudit = /* @__PURE__ */ new Map();
18746
19605
  const audits = (Array.isArray(events) ? events : []).filter(
18747
- (event) => isRecord4(event) && event.type === "quality.audit.completed"
19606
+ (event) => isRecord5(event) && event.type === "quality.audit.completed"
18748
19607
  );
18749
19608
  for (const event of orderEvents(audits)) {
18750
19609
  const auditId = typeof event.audit_id === "string" ? event.audit_id : typeof event.id === "string" ? event.id : "";
@@ -18845,7 +19704,7 @@ function trendRows(trend, filter = {}) {
18845
19704
  var rowsOf2 = (value) => Array.isArray(value) ? value : [];
18846
19705
  var isString = (value) => typeof value === "string" && value !== "";
18847
19706
  var stringsOf = (value) => rowsOf2(value).filter(isString);
18848
- var cellKey2 = (criterionId, surface) => `${criterionId}::${surface}`;
19707
+ var cellKey3 = (criterionId, surface) => `${criterionId}::${surface}`;
18849
19708
  var orderedRows = (events) => orderEvents(rowsOf2(events).filter((event) => typeof event === "object" && event !== null));
18850
19709
  function isPlanRecord(event) {
18851
19710
  if (typeof event !== "object" || event === null) return false;
@@ -18929,7 +19788,7 @@ function deriveAuditScope(events, section, library, options = {}) {
18929
19788
  for (const assessment of rowsOf2(section?.assessments)) {
18930
19789
  if (!isString(assessment?.criterion_id) || !isString(assessment?.surface) || !isString(assessment?.audit_id)) continue;
18931
19790
  if (!isString(assessment.ts)) continue;
18932
- const key = cellKey2(assessment.criterion_id, assessment.surface);
19791
+ const key = cellKey3(assessment.criterion_id, assessment.surface);
18933
19792
  const byAudit = scoredAt.get(key) ?? /* @__PURE__ */ new Map();
18934
19793
  const seen = byAudit.get(assessment.audit_id);
18935
19794
  if (seen === void 0 || seen < assessment.ts) byAudit.set(assessment.audit_id, assessment.ts);
@@ -18985,7 +19844,7 @@ function deriveAuditScope(events, section, library, options = {}) {
18985
19844
  const assessmentByCell = /* @__PURE__ */ new Map();
18986
19845
  for (const assessment of rowsOf2(section?.assessments)) {
18987
19846
  if (!isString(assessment?.criterion_id) || !isString(assessment?.surface)) continue;
18988
- assessmentByCell.set(cellKey2(assessment.criterion_id, assessment.surface), assessment);
19847
+ assessmentByCell.set(cellKey3(assessment.criterion_id, assessment.surface), assessment);
18989
19848
  }
18990
19849
  const declared2 = rowsOf2(section?.profile?.surfaces).map((surface) => surface?.id).filter((id) => isString(id) && id !== CROSS_SURFACE_ID);
18991
19850
  const surfaces = declared2.length > 0 ? [...new Set(declared2)] : [...new Set([...assessmentByCell.values()].map((assessment) => assessment.surface))].filter((id) => id !== CROSS_SURFACE_ID).sort();
@@ -18998,7 +19857,7 @@ function deriveAuditScope(events, section, library, options = {}) {
18998
19857
  };
18999
19858
  const cells = /* @__PURE__ */ new Map();
19000
19859
  const addDirect = (criterionId, surface, findingId) => {
19001
- const key = cellKey2(criterionId, surface);
19860
+ const key = cellKey3(criterionId, surface);
19002
19861
  const existing = cells.get(key);
19003
19862
  if (existing === void 0) cells.set(key, { criterion_id: criterionId, surface, kind: "direct", because: [findingId] });
19004
19863
  else if (!existing.because.includes(findingId)) existing.because.push(findingId);
@@ -19027,7 +19886,7 @@ function deriveAuditScope(events, section, library, options = {}) {
19027
19886
  unscorable.push(findingId);
19028
19887
  continue;
19029
19888
  }
19030
- const live = targets.filter((surface) => countsFor(cellKey2(finding.criterion_id, surface), resolution.last));
19889
+ const live = targets.filter((surface) => countsFor(cellKey3(finding.criterion_id, surface), resolution.last));
19031
19890
  if (live.length === 0) continue;
19032
19891
  drivers.push(findingId);
19033
19892
  if (resolution.resolved_by !== void 0) resolvedBy[findingId] = resolution.resolved_by;
@@ -19037,7 +19896,7 @@ function deriveAuditScope(events, section, library, options = {}) {
19037
19896
  if (options.widen !== false && resolvedNodes.size > 0) {
19038
19897
  const nodesByCell = /* @__PURE__ */ new Map();
19039
19898
  const noteNodes = (criterionId, surface, nodes) => {
19040
- const key = cellKey2(criterionId, surface);
19899
+ const key = cellKey3(criterionId, surface);
19041
19900
  const bucket = nodesByCell.get(key) ?? /* @__PURE__ */ new Set();
19042
19901
  for (const node of nodes) bucket.add(node);
19043
19902
  nodesByCell.set(key, bucket);
@@ -19146,13 +20005,13 @@ var EVENT_CAUSE = {
19146
20005
  "quality.finding.accepted": "accepted",
19147
20006
  "quality.audit.completed": "audit"
19148
20007
  };
19149
- var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
20008
+ var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
19150
20009
  var isString2 = (value) => typeof value === "string" && value !== "";
19151
20010
  var emptyCounts = () => ({ critical: 0, high: 0, medium: 0, low: 0, info: 0 });
19152
20011
  var asSeverity = (value) => typeof value === "string" && FINDING_SEVERITIES.includes(value) ? value : null;
19153
20012
  function cleanCounts2(raw) {
19154
20013
  const counts = emptyCounts();
19155
- if (!isRecord5(raw)) return counts;
20014
+ if (!isRecord6(raw)) return counts;
19156
20015
  for (const severity of FINDING_SEVERITIES) {
19157
20016
  const value = raw[severity];
19158
20017
  if (typeof value === "number" && Number.isFinite(value) && value > 0) counts[severity] = value;
@@ -19167,7 +20026,7 @@ function deriveFindingsBurndown(events, options = {}) {
19167
20026
  const filtered = surface !== void 0 || domain2 !== void 0;
19168
20027
  const sectionById = /* @__PURE__ */ new Map();
19169
20028
  for (const finding of Array.isArray(options.findings) ? options.findings : []) {
19170
- if (isRecord5(finding) && isString2(finding.id)) sectionById.set(finding.id, finding);
20029
+ if (isRecord6(finding) && isString2(finding.id)) sectionById.set(finding.id, finding);
19171
20030
  }
19172
20031
  const inView = (where2) => {
19173
20032
  if (!filtered) return true;
@@ -19179,7 +20038,7 @@ function deriveFindingsBurndown(events, options = {}) {
19179
20038
  return true;
19180
20039
  };
19181
20040
  const relevant = (Array.isArray(events) ? events : []).filter(
19182
- (event) => isRecord5(event) && typeof event.type === "string" && event.type in EVENT_CAUSE
20041
+ (event) => isRecord6(event) && typeof event.type === "string" && event.type in EVENT_CAUSE
19183
20042
  );
19184
20043
  const openedIds = /* @__PURE__ */ new Set();
19185
20044
  const decidedIds = /* @__PURE__ */ new Set();
@@ -19370,6 +20229,450 @@ function withImplicitBaseline(events, section, library) {
19370
20229
  return baseline === null ? events : [baseline, ...events];
19371
20230
  }
19372
20231
 
20232
+ // ../schema/src/weighing-events.ts
20233
+ var WEIGHING_WRITE_LIMITS = { evidenceChars: 2e3, refs: 50, refChars: 200, fieldChars: 200 };
20234
+ var isNonEmptyString = (value) => typeof value === "string" && value !== "";
20235
+ var isObject4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
20236
+ var isValidOnBehalfOf = (value) => value.trim() !== "" && value.length <= 128 && !/[@@﹫]/.test(value) && !new RegExp("\\p{Cc}|(?![\\u200c\\u200d])\\p{Cf}", "u").test(value);
20237
+ function assessmentProblem(entry) {
20238
+ for (const field of ["subject", "criterion"]) {
20239
+ if (!isNonEmptyString(entry[field])) return `${field} must be a non-empty string`;
20240
+ }
20241
+ if (typeof entry.level !== "number" || !Number.isInteger(entry.level)) return "level must be an integer";
20242
+ if (typeof entry.confidence !== "number" || !Number.isInteger(entry.confidence) || entry.confidence < 0 || entry.confidence > 3) {
20243
+ return "confidence must be an integer 0-3";
20244
+ }
20245
+ const { evidenceChars, refs, refChars, fieldChars } = WEIGHING_WRITE_LIMITS;
20246
+ for (const field of ["matrix", "run", "commit", "model"]) {
20247
+ if (entry[field] !== void 0 && !isNonEmptyString(entry[field])) return `${field} must be a non-empty string when present`;
20248
+ }
20249
+ for (const field of ["run", "commit", "model"]) {
20250
+ if (typeof entry[field] === "string" && entry[field].length > fieldChars) return `${field} must be at most ${fieldChars} characters`;
20251
+ }
20252
+ if (entry.evidence !== void 0) {
20253
+ if (!isNonEmptyString(entry.evidence) || entry.evidence.trim() === "") return "evidence must be a non-blank string when present";
20254
+ if (entry.evidence.length > evidenceChars) return `evidence must be at most ${evidenceChars} characters`;
20255
+ }
20256
+ for (const field of WEIGHING_PROBABILITY_FIELDS) {
20257
+ if (entry[field] !== void 0 && !isWeighingProbability(entry[field])) return `${field} must be a number from 0 to 1 when present`;
20258
+ }
20259
+ if (entry.refs !== void 0) {
20260
+ if (!Array.isArray(entry.refs) || !entry.refs.every(isNonEmptyString)) return "refs must be an array of non-empty strings when present";
20261
+ if (entry.refs.length > refs) return `refs must hold at most ${refs} items`;
20262
+ if (entry.refs.some((ref) => ref.length > refChars)) return `each ref must be at most ${refChars} characters`;
20263
+ }
20264
+ return void 0;
20265
+ }
20266
+ function planWeighingEvents(section, nodes, inputs, ctx) {
20267
+ const resolved = resolveWeighing(section);
20268
+ const byId = new Map(nodes.map((node) => [node.id, node]));
20269
+ const now = ctx.now ?? /* @__PURE__ */ new Date();
20270
+ const refusals = [];
20271
+ const events = [];
20272
+ const assessments = [];
20273
+ inputs.forEach((entry, index) => {
20274
+ const refuse = (reason, detail) => refusals.push({ index, reason, detail });
20275
+ if (!isObject4(entry)) return refuse("invalid_entry", "an entry must be an object");
20276
+ if (entry.type === WEIGHING_SET_SAVED) {
20277
+ const set3 = entry.set;
20278
+ if (!isObject4(set3)) return refuse("invalid_set", "set must be an object");
20279
+ if (!isNonEmptyString(set3.id) || !isNonEmptyString(set3.version) || !isNonEmptyString(set3.subject)) {
20280
+ return refuse("invalid_set", "a set needs a non-empty id, version and subject");
20281
+ }
20282
+ if (!Array.isArray(set3.criteria)) return refuse("invalid_set", "a set needs a criteria array");
20283
+ const ruler = typeof set3.extends === "string" ? setOfRef(resolved, set3.extends) : void 0;
20284
+ if (set3.id !== POSITIONING_SET_ID || set3.role !== "positioning") {
20285
+ return refuse("invalid_set", `only the positioning can be saved: id "${POSITIONING_SET_ID}" with role "positioning"`);
20286
+ }
20287
+ if (ruler === void 0) return refuse("invalid_set", `a positioning extends a set the library holds (e.g. ${VALUE_SET_ID}@2)`);
20288
+ if (isOlderMajorRef(resolved, set3.extends)) {
20289
+ return refuse("invalid_set", `${String(set3.extends)} is an older ruler \u2014 extend ${ruler.id}'s current major instead`);
20290
+ }
20291
+ const known = new Set(ruler.criteria.map((criterion2) => criterion2.id));
20292
+ for (const criterion2 of set3.criteria) {
20293
+ if (!isNonEmptyString(criterion2?.id) || !known.has(criterion2.id)) {
20294
+ return refuse("invalid_set", `"${String(criterion2?.id)}" is not an element of ${ruler.id}`);
20295
+ }
20296
+ if (criterion2.weight !== void 0 && (typeof criterion2.weight !== "number" || !Number.isFinite(criterion2.weight) || !(criterion2.weight > 0))) {
20297
+ return refuse("invalid_set", `the weight for "${criterion2.id}" must be a number above 0 \u2014 leave the element out to leave it unpositioned`);
20298
+ }
20299
+ if (criterion2.anchors !== void 0) {
20300
+ const { min, max } = weighingScaleOf(ruler, resolved);
20301
+ const anchors = criterion2.anchors;
20302
+ if (!isObject4(anchors)) return refuse("invalid_set", `the anchors for "${criterion2.id}" must be an object of level -> words`);
20303
+ for (const [level, words] of Object.entries(anchors)) {
20304
+ if (!/^-?\d+$/.test(level) || String(Number(level)) !== level || Number(level) < min || Number(level) > max) {
20305
+ return refuse("invalid_set", `an anchor for "${criterion2.id}" is keyed "${level}", which is not a level from ${min} to ${max}`);
20306
+ }
20307
+ if (typeof words !== "string" || words.trim() === "") return refuse("invalid_set", `the anchor for "${criterion2.id}" at level ${level} must be non-empty words`);
20308
+ }
20309
+ }
20310
+ }
20311
+ if (set3.status !== void 0 && set3.status !== "draft" && set3.status !== "active") {
20312
+ return refuse("invalid_set", `status must be "draft" or "active"`);
20313
+ }
20314
+ try {
20315
+ events.push(makeEvent(WEIGHING_SET_SAVED, { set: set3 }, { actor: ctx.actor, ts: now }));
20316
+ } catch (error51) {
20317
+ return refuse("invalid_set", error51 instanceof Error ? error51.message : "the event failed its schema");
20318
+ }
20319
+ return;
20320
+ }
20321
+ if (entry.type !== WEIGHING_ASSESSMENT_RECORDED) {
20322
+ return refuse("invalid_entry", `type must be ${WEIGHING_ASSESSMENT_RECORDED} or ${WEIGHING_SET_SAVED}`);
20323
+ }
20324
+ const problem = assessmentProblem(entry);
20325
+ if (problem !== void 0) return refuse("invalid_entry", problem);
20326
+ const input = entry;
20327
+ const matrix = resolved.matrices.find((candidate) => candidate.id === (input.matrix ?? VALUE_MATRIX_ID));
20328
+ if (matrix === void 0) {
20329
+ return refuse("unknown_matrix", `no matrix "${input.matrix ?? VALUE_MATRIX_ID}" (have: ${resolved.matrices.map((m) => m.id).join(", ")})`);
20330
+ }
20331
+ const set2 = setOfRef(resolved, matrix.set);
20332
+ if (set2 === void 0) return refuse("unknown_matrix", `matrix "${matrix.id}" names set "${matrix.set}", which is not available`);
20333
+ if (isOlderMajorRef(resolved, matrix.set)) {
20334
+ return refuse("unknown_matrix", `matrix "${matrix.id}" reads ${matrix.set}, an older ruler \u2014 nothing new is scored against it; point the matrix at the current major`);
20335
+ }
20336
+ const node = byId.get(input.subject);
20337
+ const judged = matrix.subjects.kind === "query" ? node?.species === matrix.subjects.species : matrix.subjects.items.some((item) => (item?.node_id ?? item?.id) === input.subject);
20338
+ if (node === void 0 || !judged) {
20339
+ return refuse("unknown_subject", `"${input.subject}" is not a subject of matrix "${matrix.id}"`);
20340
+ }
20341
+ const criterion = set2.criteria.find((candidate) => candidate.id === input.criterion);
20342
+ if (criterion === void 0) return refuse("unknown_criterion", `"${input.criterion}" is not in set "${set2.id}"`);
20343
+ if (typeof criterion.superseded_by === "string") {
20344
+ return refuse("retired_criterion", `"${criterion.id}" is retired \u2014 score "${criterion.superseded_by}" instead`);
20345
+ }
20346
+ const scale = weighingScaleOf(set2, resolved);
20347
+ if (input.level < scale.min || input.level > scale.max) {
20348
+ return refuse("level_out_of_range", `level ${input.level} is outside ${scale.min}..${scale.max}`);
20349
+ }
20350
+ if (ctx.onBehalfOf !== void 0 && !isValidOnBehalfOf(ctx.onBehalfOf)) {
20351
+ return refuse("invalid_on_behalf_of", "on_behalf_of is a user id, a handle or a name (no control characters, at most 128 characters), never an email \u2014 sidecars are committed to repos");
20352
+ }
20353
+ const ts = now.toISOString();
20354
+ const row = {
20355
+ matrix: matrix.id,
20356
+ subject: input.subject,
20357
+ criterion: criterion.id,
20358
+ level: input.level,
20359
+ scorer: {
20360
+ kind: ctx.scorerKind,
20361
+ id: ctx.actor,
20362
+ // The model is an agent's account of itself; a person has none to claim.
20363
+ ...input.model !== void 0 && ctx.scorerKind === "agent" ? { model: input.model } : {},
20364
+ ...ctx.onBehalfOf !== void 0 ? { on_behalf_of: ctx.onBehalfOf } : {}
20365
+ // D14
20366
+ },
20367
+ confidence: input.confidence,
20368
+ ...input.evidence !== void 0 ? { evidence: input.evidence } : {},
20369
+ ...input.refs !== void 0 ? { refs: input.refs } : {},
20370
+ basis: {
20371
+ fingerprint: acceptanceFingerprint(node),
20372
+ set_version: set2.version,
20373
+ ...input.commit !== void 0 ? { commit: input.commit } : {}
20374
+ },
20375
+ ...input.run !== void 0 ? { run: input.run } : {},
20376
+ ...input.p_serves !== void 0 ? { p_serves: input.p_serves } : {},
20377
+ ...input.p_costs !== void 0 ? { p_costs: input.p_costs } : {},
20378
+ ts
20379
+ };
20380
+ const { ts: _ts, ...payload } = row;
20381
+ void _ts;
20382
+ try {
20383
+ events.push(makeEvent(WEIGHING_ASSESSMENT_RECORDED, payload, { actor: ctx.actor, ts: now }));
20384
+ } catch (error51) {
20385
+ return refuse("invalid_entry", error51 instanceof Error ? error51.message : "the event failed its schema");
20386
+ }
20387
+ assessments.push(row);
20388
+ });
20389
+ return refusals.length > 0 ? { ok: false, refusals } : { ok: true, events, assessments };
20390
+ }
20391
+
20392
+ // ../schema/src/weighing-derive.ts
20393
+ var SEED_SCORER_ID = "seed-claimed";
20394
+ var SEED_LEVEL = 1;
20395
+ var SEED_SCORER = Object.freeze({ kind: "rule", id: SEED_SCORER_ID });
20396
+ var SEED_TS = "1970-01-01T00:00:00.000Z";
20397
+ function seedLevelAt(position) {
20398
+ void position;
20399
+ return SEED_LEVEL;
20400
+ }
20401
+ function claimedElements(node, set2) {
20402
+ const known = new Set(set2.criteria.map((criterion) => criterion.id));
20403
+ const claimed = Array.isArray(node.metadata?.values) ? node.metadata.values : [];
20404
+ const seen = /* @__PURE__ */ new Set();
20405
+ const out = [];
20406
+ for (const value of claimed) {
20407
+ if (typeof value !== "string" || !known.has(value) || seen.has(value)) continue;
20408
+ seen.add(value);
20409
+ out.push(value);
20410
+ }
20411
+ return out;
20412
+ }
20413
+ function seedAssessments(node, matrix, set2) {
20414
+ const fingerprint = acceptanceFingerprint(node);
20415
+ return claimedElements(node, set2).map((criterion, position) => ({
20416
+ matrix: matrix.id,
20417
+ subject: node.id,
20418
+ criterion,
20419
+ level: seedLevelAt(position),
20420
+ scorer: SEED_SCORER,
20421
+ confidence: 0,
20422
+ basis: { fingerprint, set_version: set2.version },
20423
+ ts: SEED_TS
20424
+ }));
20425
+ }
20426
+ var tsOf = (row) => {
20427
+ const ms = typeof row.ts === "string" ? Date.parse(row.ts) : Number.NaN;
20428
+ return Number.isNaN(ms) ? Number.NEGATIVE_INFINITY : ms;
20429
+ };
20430
+ var confidenceOf = (value) => CONFIDENCE_LEVELS.includes(value) ? value : 0;
20431
+ function latestOf(rows) {
20432
+ let best;
20433
+ for (const row of rows) {
20434
+ if (best === void 0 || tsOf(row) >= tsOf(best)) best = row;
20435
+ }
20436
+ return best;
20437
+ }
20438
+ function resolveCell(criterion, stored, seed, current, claimed) {
20439
+ const human = latestOf(stored.filter((row) => row.scorer?.kind === "human"));
20440
+ const agent = latestOf(stored.filter((row) => row.scorer?.kind === "agent"));
20441
+ const winner = human ?? agent;
20442
+ if (winner === void 0) {
20443
+ if (seed === void 0) return void 0;
20444
+ return {
20445
+ criterion,
20446
+ level: seed.level,
20447
+ scorer: seed.scorer ?? SEED_SCORER,
20448
+ confidence: 0,
20449
+ source: "seed",
20450
+ stale: false,
20451
+ claimed,
20452
+ others: [],
20453
+ review: false,
20454
+ uncertain: false
20455
+ };
20456
+ }
20457
+ const basis = winner.basis;
20458
+ const staleBy = [];
20459
+ if (basis?.fingerprint !== void 0 && basis.fingerprint !== current.fingerprint) staleBy.push("subject");
20460
+ if (basis?.set_version !== void 0 && majorOf(basis.set_version) !== majorOf(current.setVersion)) staleBy.push("ruler");
20461
+ const stale = staleBy.length > 0;
20462
+ const other = winner === human ? agent : void 0;
20463
+ return {
20464
+ criterion,
20465
+ level: winner.level,
20466
+ // The winner was picked by `scorer?.kind`, so it has a scorer.
20467
+ scorer: winner.scorer,
20468
+ confidence: confidenceOf(winner.confidence),
20469
+ source: "stored",
20470
+ stale,
20471
+ ...stale ? { stale_by: staleBy } : {},
20472
+ ...typeof winner.evidence === "string" ? { evidence: winner.evidence } : {},
20473
+ claimed,
20474
+ others: other === void 0 ? [] : [other],
20475
+ review: human !== void 0 && agent !== void 0 && Math.abs(human.level - agent.level) >= 2,
20476
+ ...isWeighingProbability(winner.p_serves) ? { p_serves: winner.p_serves } : {},
20477
+ ...isWeighingProbability(winner.p_costs) ? { p_costs: winner.p_costs } : {},
20478
+ uncertain: isUncertainCell(winner)
20479
+ };
20480
+ }
20481
+ function positioningWeights(set2) {
20482
+ const weights = /* @__PURE__ */ new Map();
20483
+ for (const criterion of set2.criteria) {
20484
+ if (weights.has(criterion.id)) continue;
20485
+ weights.set(criterion.id, typeof criterion.weight === "number" && Number.isFinite(criterion.weight) && criterion.weight >= 0 ? criterion.weight : 1);
20486
+ }
20487
+ return weights;
20488
+ }
20489
+ function buildWeighingContext(section, matrixId = VALUE_MATRIX_ID) {
20490
+ const resolved = resolveWeighing(section);
20491
+ const matrix = resolved.matrices.find((candidate) => candidate.id === matrixId);
20492
+ if (matrix === void 0 || !isActiveWeighingSet(matrix)) return void 0;
20493
+ const set2 = setOfRef(resolved, matrix.set);
20494
+ if (set2 === void 0) return void 0;
20495
+ const scale = weighingScaleOf(set2, resolved);
20496
+ const byCell = /* @__PURE__ */ new Map();
20497
+ for (const row of readWeighingAssessments(section)) {
20498
+ if (row.matrix !== matrix.id || row.scorer?.kind === "rule") continue;
20499
+ if (typeof row.level !== "number" || !Number.isInteger(row.level) || row.level < scale.min || row.level > scale.max) continue;
20500
+ const key = cellKey(row.matrix, row.subject, row.criterion);
20501
+ const rows = byCell.get(key);
20502
+ if (rows === void 0) byCell.set(key, [row]);
20503
+ else rows.push(row);
20504
+ }
20505
+ const positioningSet = matrix.positioning === void 0 ? void 0 : resolved.sets.find((candidate) => candidate.id === matrix.positioning && candidate.role === "positioning");
20506
+ let positioning = null;
20507
+ if (positioningSet !== void 0 && isActiveWeighingSet(positioningSet)) {
20508
+ positioning = { set: positioningSet, weights: positioningWeights(positioningSet) };
20509
+ }
20510
+ return { matrix, set: set2, byCell, positioningSet, positioning };
20511
+ }
20512
+ function keptShare(node) {
20513
+ if (!Array.isArray(node.platforms) || node.platforms.length === 0) return null;
20514
+ const live = node.platforms.filter((platform) => {
20515
+ const status = resolvePlatformStatus(node, platform);
20516
+ return status !== void 0 && DEFAULT_DELIVERED_STATUSES.includes(status);
20517
+ }).length;
20518
+ return live / node.platforms.length;
20519
+ }
20520
+ var share = (guess, total) => total > 0 ? guess / total : 0;
20521
+ function weighPromise(node, ctx) {
20522
+ const fingerprint = acceptanceFingerprint(node);
20523
+ const current = { fingerprint, setVersion: ctx.set.version };
20524
+ const claimedList = claimedElements(node, ctx.set);
20525
+ const claimedSet = new Set(claimedList);
20526
+ const seeds = new Map(seedAssessments(node, ctx.matrix, ctx.set).map((seed) => [seed.criterion, seed]));
20527
+ const order = [...claimedList, ...ctx.set.criteria.map((criterion) => criterion.id).filter((id) => !claimedSet.has(id))];
20528
+ const cells = [];
20529
+ for (const criterion of order) {
20530
+ const stored = ctx.byCell.get(cellKey(ctx.matrix.id, node.id, criterion)) ?? [];
20531
+ const cell = resolveCell(criterion, stored, seeds.get(criterion), current, claimedSet.has(criterion));
20532
+ if (cell !== void 0) cells.push(cell);
20533
+ }
20534
+ let served = 0;
20535
+ let cost = 0;
20536
+ let servedGuess = 0;
20537
+ let costGuess = 0;
20538
+ let positionedServed = 0;
20539
+ let positionedCost = 0;
20540
+ let positionedServedGuess = 0;
20541
+ let positionedCostGuess = 0;
20542
+ const flags = { claim_not_supported: [], claim_contradicted: [], unclaimed_value: [], unclaimed_cost: [] };
20543
+ const stale = [];
20544
+ const review = [];
20545
+ const uncertain = [];
20546
+ for (const cell of cells) {
20547
+ const weight = ctx.positioning?.weights.get(cell.criterion);
20548
+ const guess = cell.confidence === 0;
20549
+ if (cell.level > 0) {
20550
+ served += cell.level;
20551
+ if (guess) servedGuess += cell.level;
20552
+ if (weight !== void 0) {
20553
+ positionedServed += cell.level * weight;
20554
+ if (guess) positionedServedGuess += cell.level * weight;
20555
+ }
20556
+ } else if (cell.level < 0) {
20557
+ cost += -cell.level;
20558
+ if (guess) costGuess += -cell.level;
20559
+ if (weight !== void 0) {
20560
+ positionedCost += -cell.level * weight;
20561
+ if (guess) positionedCostGuess += -cell.level * weight;
20562
+ }
20563
+ }
20564
+ if (cell.stale) stale.push(cell.criterion);
20565
+ if (cell.review) review.push(cell.criterion);
20566
+ if (cell.uncertain) uncertain.push(cell.criterion);
20567
+ if (cell.source === "stored") {
20568
+ if (cell.claimed) {
20569
+ if (cell.level < 0) flags.claim_contradicted.push(cell.criterion);
20570
+ else if (cell.level === 0) flags.claim_not_supported.push(cell.criterion);
20571
+ } else if (cell.level < 0) flags.unclaimed_cost.push(cell.criterion);
20572
+ else if (cell.level >= 1) flags.unclaimed_value.push(cell.criterion);
20573
+ }
20574
+ }
20575
+ return {
20576
+ node_id: node.id,
20577
+ title: node.title ?? "",
20578
+ status: node.status,
20579
+ archived: node.status === "archived",
20580
+ fingerprint,
20581
+ cells,
20582
+ served: served / 3,
20583
+ cost: cost / 3,
20584
+ positioned: ctx.positioning === null ? null : {
20585
+ served: positionedServed / 3,
20586
+ cost: positionedCost / 3,
20587
+ guesswork: { served: share(positionedServedGuess, positionedServed), cost: share(positionedCostGuess, positionedCost) }
20588
+ },
20589
+ kept_share: keptShare(node),
20590
+ guesswork: { served: share(servedGuess, served), cost: share(costGuess, cost) },
20591
+ flags,
20592
+ stale,
20593
+ review,
20594
+ uncertain
20595
+ };
20596
+ }
20597
+ function matrixSubjects(nodes, matrix) {
20598
+ const wanted = matrix.subjects.kind === "query" ? void 0 : new Set(matrix.subjects.items.map((item) => item?.node_id ?? item?.id));
20599
+ const species = matrix.subjects.kind === "query" ? matrix.subjects.species : void 0;
20600
+ const seen = /* @__PURE__ */ new Set();
20601
+ const out = [];
20602
+ for (const node of nodes) {
20603
+ if (seen.has(node.id)) continue;
20604
+ if (wanted === void 0 ? node.species !== species : !wanted.has(node.id)) continue;
20605
+ seen.add(node.id);
20606
+ out.push(node);
20607
+ }
20608
+ return out;
20609
+ }
20610
+ function deriveWeighing(nodes, section, matrixId = VALUE_MATRIX_ID) {
20611
+ const ctx = buildWeighingContext(section, matrixId);
20612
+ if (ctx === void 0) return void 0;
20613
+ const promises = matrixSubjects(nodes, ctx.matrix).map((node) => weighPromise(node, ctx));
20614
+ const empty = () => ({ promised: 0, promisedGuess: 0, kept: 0, keptGuess: 0, cost: 0, costGuess: 0 });
20615
+ const raw = new Map(ctx.set.criteria.map((criterion) => [criterion.id, empty()]));
20616
+ let assessed = 0;
20617
+ let archived = 0;
20618
+ for (const promise2 of promises) {
20619
+ if (promise2.archived) {
20620
+ archived++;
20621
+ continue;
20622
+ }
20623
+ if (promise2.cells.some((cell) => cell.source === "stored")) assessed++;
20624
+ const kept = promise2.kept_share ?? 0;
20625
+ for (const cell of promise2.cells) {
20626
+ const mass = raw.get(cell.criterion);
20627
+ if (mass === void 0) continue;
20628
+ const guess = cell.confidence === 0;
20629
+ if (cell.level > 0) {
20630
+ mass.promised += cell.level;
20631
+ mass.kept += cell.level * kept;
20632
+ if (guess) {
20633
+ mass.promisedGuess += cell.level;
20634
+ mass.keptGuess += cell.level * kept;
20635
+ }
20636
+ } else if (cell.level < 0) {
20637
+ mass.cost += -cell.level;
20638
+ if (guess) mass.costGuess += -cell.level;
20639
+ }
20640
+ }
20641
+ }
20642
+ const elements = {};
20643
+ const total = empty();
20644
+ for (const [id, mass] of raw) {
20645
+ elements[id] = {
20646
+ promised: mass.promised / 3,
20647
+ kept: mass.kept / 3,
20648
+ cost: mass.cost / 3,
20649
+ guesswork: { promised: share(mass.promisedGuess, mass.promised), kept: share(mass.keptGuess, mass.kept), cost: share(mass.costGuess, mass.cost) }
20650
+ };
20651
+ for (const key of Object.keys(total)) total[key] += mass[key];
20652
+ }
20653
+ return {
20654
+ matrix: ctx.matrix,
20655
+ set: ctx.set,
20656
+ positioning: ctx.positioningSet === void 0 ? null : { set: ctx.positioningSet, active: ctx.positioning !== null, weights: positioningWeights(ctx.positioningSet) },
20657
+ promises,
20658
+ elements,
20659
+ totals: {
20660
+ promised: total.promised / 3,
20661
+ kept: total.kept / 3,
20662
+ cost: total.cost / 3,
20663
+ guesswork: { promised: share(total.promisedGuess, total.promised), kept: share(total.keptGuess, total.kept), cost: share(total.costGuess, total.cost) },
20664
+ promises: promises.length,
20665
+ archived,
20666
+ assessed
20667
+ }
20668
+ };
20669
+ }
20670
+ function sortPromises(promises, key) {
20671
+ const value = (promise2) => key === "served" ? promise2.served : key === "cost" ? promise2.cost : key === "positioned" ? promise2.positioned?.served ?? -1 : 0;
20672
+ const byTitle = (a, b) => (a.title ?? "").localeCompare(b.title ?? "", "en") || a.node_id.localeCompare(b.node_id);
20673
+ return [...promises].sort((a, b) => key === "title" ? byTitle(a, b) : value(b) - value(a) || byTitle(a, b));
20674
+ }
20675
+
19373
20676
  // ../schema/src/cli/kritik-audit.ts
19374
20677
  import { existsSync as existsSync2, readdirSync, statSync } from "node:fs";
19375
20678
  import { join as join2 } from "node:path";
@@ -19737,7 +21040,7 @@ Record each first, or remove its scores (docs/quality/audits/<id>/scores.json),
19737
21040
  }
19738
21041
 
19739
21042
  // src/kritik-tools.ts
19740
- import { existsSync as existsSync8 } from "node:fs";
21043
+ import { existsSync as existsSync9 } from "node:fs";
19741
21044
 
19742
21045
  // ../cli/src/lib/bundle-io.ts
19743
21046
  import { existsSync as existsSync4, readFileSync as readFileSync2 } from "node:fs";
@@ -19832,8 +21135,60 @@ function resolveQualityRoot(options) {
19832
21135
  return options.fallback;
19833
21136
  }
19834
21137
 
21138
+ // ../schema/src/cli/weighing-files.ts
21139
+ import { existsSync as existsSync7, readdirSync as readdirSync4 } from "node:fs";
21140
+ import { join as join6 } from "node:path";
21141
+ var WEIGHING_DIR = "docs/weighing";
21142
+ var WEIGHING_SETS_DIR = "sets";
21143
+ var WEIGHING_ASSESSMENTS_DIR = "assessments";
21144
+ function safeId(id) {
21145
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(id)) throw new Error(`"${id}" is not a valid weighing id (kebab-case, no path separators)`);
21146
+ return id;
21147
+ }
21148
+ var weighingDir = (root) => join6(root, WEIGHING_DIR);
21149
+ var weighingSetPath = (root, setId) => join6(weighingDir(root), WEIGHING_SETS_DIR, `${safeId(setId)}.json`);
21150
+ var weighingAssessmentsPath = (root, matrixId) => join6(weighingDir(root), WEIGHING_ASSESSMENTS_DIR, `${safeId(matrixId)}.json`);
21151
+ function jsonFilesIn(dir) {
21152
+ if (!existsSync7(dir)) return [];
21153
+ return readdirSync4(dir).filter((name) => name.endsWith(".json")).sort().map((name) => join6(dir, name));
21154
+ }
21155
+ function assessmentsOfFile(file2) {
21156
+ const parsed = readJson(file2);
21157
+ const assessments = typeof parsed === "object" && parsed !== null ? parsed.assessments : void 0;
21158
+ if (!Array.isArray(assessments)) throw new Error(`${file2}: expected { "matrix": \u2026, "assessments": [] }`);
21159
+ return assessments;
21160
+ }
21161
+ function loadWeighingSets(root) {
21162
+ return jsonFilesIn(join6(weighingDir(root), WEIGHING_SETS_DIR)).map((file2) => {
21163
+ const parsed = readJson(file2);
21164
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error(`${file2}: expected a criteria set object`);
21165
+ return parsed;
21166
+ });
21167
+ }
21168
+ function loadWeighingAssessments(root) {
21169
+ return jsonFilesIn(join6(weighingDir(root), WEIGHING_ASSESSMENTS_DIR)).flatMap(assessmentsOfFile);
21170
+ }
21171
+ function loadWeighingSection(root) {
21172
+ const sets = loadWeighingSets(root);
21173
+ const assessments = loadWeighingAssessments(root);
21174
+ if (sets.length === 0 && assessments.length === 0) return void 0;
21175
+ return { sets, matrices: [], assessments: sortWeighingAssessments(assessments) };
21176
+ }
21177
+ function saveWeighingAssessments(root, matrixId, assessments) {
21178
+ const file2 = { matrix: matrixId, assessments: sortWeighingAssessments(assessments) };
21179
+ writeJson(weighingAssessmentsPath(root, matrixId), file2);
21180
+ }
21181
+ function saveWeighingSet(root, set2) {
21182
+ writeJson(weighingSetPath(root, set2.id), set2);
21183
+ }
21184
+ function loadMatrixAssessments(root, matrixId) {
21185
+ const file2 = weighingAssessmentsPath(root, matrixId);
21186
+ if (!existsSync7(file2)) return [];
21187
+ return assessmentsOfFile(file2);
21188
+ }
21189
+
19835
21190
  // ../cli/src/lib/bundle-validate.ts
19836
- import { existsSync as existsSync7, readFileSync as readFileSync4 } from "node:fs";
21191
+ import { existsSync as existsSync8, readFileSync as readFileSync4 } from "node:fs";
19837
21192
  import { basename as basename2 } from "node:path";
19838
21193
  function validateBundleAt(filePath) {
19839
21194
  const bundle = readBundle(filePath);
@@ -19848,7 +21203,7 @@ function validateBundleAt(filePath) {
19848
21203
  if (loose.journal === void 0) {
19849
21204
  const sidecarPath = journalPathFor(filePath);
19850
21205
  const folded = [];
19851
- if (existsSync7(sidecarPath)) {
21206
+ if (existsSync8(sidecarPath)) {
19852
21207
  const { events, findings } = parseJournalLines(readFileSync4(sidecarPath, "utf8"));
19853
21208
  sidecarFindings = findings;
19854
21209
  sidecarLoaded = true;
@@ -20739,7 +22094,7 @@ function buildKritikCatalog(ctx) {
20739
22094
  }
20740
22095
  const path = planPath(root, created.plan.planId);
20741
22096
  const written = args.dry_run !== true;
20742
- if (written && existsSync8(path)) {
22097
+ if (written && existsSync9(path)) {
20743
22098
  throw new ToolError(
20744
22099
  `${path} already exists \u2014 a plan file is written once, and another plan took ${created.plan.planId} meanwhile. Call kritik_plan again for the next id.`
20745
22100
  );
@@ -21195,6 +22550,482 @@ function buildKritikCatalog(ctx) {
21195
22550
  return { tools: tools2, handlers: handlers2 };
21196
22551
  }
21197
22552
 
22553
+ // src/weighing-tools.ts
22554
+ import { execFile } from "node:child_process";
22555
+
22556
+ // src/store.ts
22557
+ import { writeFileSync as writeFileSync3 } from "node:fs";
22558
+ import { resolve as resolve3 } from "node:path";
22559
+ var MCP_ACTOR = "arkaik-mcp";
22560
+ var DEFAULT_BUNDLE_PATH2 = "docs/arkaik/bundle.json";
22561
+ function resolveBundlePath(argv2, env) {
22562
+ const flagIndex = argv2.indexOf("--bundle");
22563
+ const flagValue2 = flagIndex !== -1 ? argv2[flagIndex + 1] : void 0;
22564
+ if (flagValue2) return resolve3(flagValue2);
22565
+ if (env.ARKAIK_BUNDLE) return resolve3(env.ARKAIK_BUNDLE);
22566
+ return resolve3(DEFAULT_BUNDLE_PATH2);
22567
+ }
22568
+ function loadBundle(bundlePath) {
22569
+ return validateBundleAt(bundlePath);
22570
+ }
22571
+ function nodeIdsOf(nodes) {
22572
+ return nodes.map((node) => node?.id).filter((id) => typeof id === "string");
22573
+ }
22574
+ function persistMutation(bundlePath, loaded, next, inputs) {
22575
+ const baselineNodeIds = inputs.length === 0 ? [] : missingProvenanceNodeIds(nodeIdsOf(loaded.nodes), loaded.journal);
22576
+ const events = [
22577
+ ...baselineNodeIds.length > 0 ? [makeEvent("journal.baseline", { node_ids: baselineNodeIds }, { actor: MCP_ACTOR })] : [],
22578
+ ...toJournalEvents(inputs, MCP_ACTOR)
22579
+ ];
22580
+ const nextNodes = next.nodes ?? loaded.nodes;
22581
+ const nextEdges = next.edges ?? loaded.edges;
22582
+ const candidate = {
22583
+ ...loaded.bundle,
22584
+ nodes: nextNodes,
22585
+ edges: nextEdges,
22586
+ journal: [...loaded.journal, ...events]
22587
+ };
22588
+ const result = validateBundle(candidate);
22589
+ if (result.errors.length > 0) {
22590
+ return { ok: false, errors: result.errors, warnings: result.warnings };
22591
+ }
22592
+ const journalOnDisk = loaded.sidecarLoaded || loaded.archivesLoaded.length > 0;
22593
+ const embeddedJournal = !journalOnDisk && loaded.bundle.journal !== void 0;
22594
+ if (embeddedJournal) {
22595
+ writeFileSync3(bundlePath, serializeBundle(candidate));
22596
+ } else {
22597
+ const journalPath = journalPathFor(bundlePath);
22598
+ for (const event of events) {
22599
+ appendJournalEvent(journalPath, event);
22600
+ }
22601
+ if (next.nodes !== void 0 || next.edges !== void 0) {
22602
+ const snapshot = { ...loaded.bundle, nodes: nextNodes, edges: nextEdges };
22603
+ delete snapshot.journal;
22604
+ writeFileSync3(bundlePath, serializeBundle(snapshot));
22605
+ }
22606
+ }
22607
+ return { ok: true, warnings: result.warnings, events };
22608
+ }
22609
+ function createFileStore(bundlePath) {
22610
+ return {
22611
+ async load() {
22612
+ let loaded;
22613
+ try {
22614
+ loaded = loadBundle(bundlePath);
22615
+ } catch (error51) {
22616
+ throw new Error(`Cannot load bundle at ${bundlePath}: ${error51.message}`);
22617
+ }
22618
+ return {
22619
+ loaded,
22620
+ nodes: loaded.nodes,
22621
+ edges: loaded.edges,
22622
+ project: loaded.bundle.project,
22623
+ journal: loaded.journal
22624
+ };
22625
+ },
22626
+ async persist(graph, next, inputs) {
22627
+ return persistMutation(bundlePath, graph.loaded, next, inputs);
22628
+ },
22629
+ describe() {
22630
+ return `bundle: ${bundlePath}`;
22631
+ }
22632
+ };
22633
+ }
22634
+
22635
+ // src/weighing-tools.ts
22636
+ var round2 = (value) => Math.round(value * 100) / 100;
22637
+ var GIT_CONFIG_TIMEOUT_MS = 1500;
22638
+ function gitConfigValue(root, key) {
22639
+ return new Promise((resolve4) => {
22640
+ try {
22641
+ execFile("git", ["config", "--get", key], { cwd: root, timeout: GIT_CONFIG_TIMEOUT_MS }, (error51, stdout) => {
22642
+ if (error51 !== null) return resolve4({ timedOut: error51.killed === true });
22643
+ const value = String(stdout).trim();
22644
+ resolve4({ ...value === "" ? {} : { value }, timedOut: false });
22645
+ });
22646
+ } catch {
22647
+ resolve4({ timedOut: false });
22648
+ }
22649
+ });
22650
+ }
22651
+ var ON_BEHALF_OF_NOBODY = "-";
22652
+ async function resolveOnBehalfOf(root, env = process.env) {
22653
+ const fromEnv = env.ARKAIK_ON_BEHALF_OF?.trim();
22654
+ if (fromEnv === ON_BEHALF_OF_NOBODY) return void 0;
22655
+ if (fromEnv !== void 0 && isValidOnBehalfOf(fromEnv)) return fromEnv;
22656
+ for (const key of ["arkaik.user", "user.name"]) {
22657
+ const { value, timedOut } = await gitConfigValue(root, key);
22658
+ if (timedOut) return void 0;
22659
+ if (key === "arkaik.user" && value === ON_BEHALF_OF_NOBODY) return void 0;
22660
+ if (value !== void 0 && value !== ON_BEHALF_OF_NOBODY && isValidOnBehalfOf(value)) return value;
22661
+ }
22662
+ return void 0;
22663
+ }
22664
+ function requireString2(args, key) {
22665
+ const value = args[key];
22666
+ if (typeof value !== "string" || value.length === 0) throw new ToolError(`\`${key}\` is required and must be a non-empty string.`);
22667
+ return value;
22668
+ }
22669
+ function requireInt2(args, key, min, max) {
22670
+ const value = args[key];
22671
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
22672
+ throw new ToolError(`\`${key}\` is required and must be an integer ${min} to ${max}.`);
22673
+ }
22674
+ return value;
22675
+ }
22676
+ var optionalString = (args, key) => typeof args[key] === "string" && args[key] !== "" ? args[key] : void 0;
22677
+ function cellRow(cell, withProbabilities) {
22678
+ return {
22679
+ criterion: cell.criterion,
22680
+ level: cell.level,
22681
+ scorer: cell.scorer,
22682
+ confidence: cell.confidence,
22683
+ source: cell.source,
22684
+ stale: cell.stale,
22685
+ ...cell.stale_by !== void 0 ? { stale_by: cell.stale_by } : {},
22686
+ claimed: cell.claimed,
22687
+ ...cell.evidence !== void 0 ? { evidence: cell.evidence } : {},
22688
+ ...cell.review ? { review: true } : {},
22689
+ ...cell.uncertain ? { uncertain: true } : {},
22690
+ ...withProbabilities && cell.p_serves !== void 0 ? { p_serves: cell.p_serves } : {},
22691
+ ...withProbabilities && cell.p_costs !== void 0 ? { p_costs: cell.p_costs } : {},
22692
+ ...cell.others.length > 0 ? { others: cell.others.map((row) => ({ scorer: row.scorer, level: row.level, confidence: row.confidence, ...row.evidence !== void 0 ? { evidence: row.evidence } : {} })) } : {}
22693
+ };
22694
+ }
22695
+ function promiseRow(promise2, withCells, withProbabilities = false) {
22696
+ return {
22697
+ node_id: promise2.node_id,
22698
+ title: promise2.title,
22699
+ status: promise2.status,
22700
+ served: round2(promise2.served),
22701
+ cost: round2(promise2.cost),
22702
+ positioned: promise2.positioned === null ? null : {
22703
+ served: round2(promise2.positioned.served),
22704
+ cost: round2(promise2.positioned.cost),
22705
+ guesswork: { served: round2(promise2.positioned.guesswork.served), cost: round2(promise2.positioned.guesswork.cost) }
22706
+ },
22707
+ kept_share: promise2.kept_share === null ? null : round2(promise2.kept_share),
22708
+ guesswork: { served: round2(promise2.guesswork.served), cost: round2(promise2.guesswork.cost) },
22709
+ flags: promise2.flags,
22710
+ stale: promise2.stale,
22711
+ review: promise2.review,
22712
+ uncertain: promise2.uncertain,
22713
+ ...promise2.archived ? { archived: true } : {},
22714
+ ...withCells ? { cells: promise2.cells.map((cell) => cellRow(cell, withProbabilities)) } : {}
22715
+ };
22716
+ }
22717
+ var FILTERS = ["flagged", "stale", "review", "uncertain", "unassessed"];
22718
+ function matchesFilter(promise2, filter) {
22719
+ switch (filter) {
22720
+ case "flagged":
22721
+ return Object.values(promise2.flags).some((ids) => ids.length > 0);
22722
+ case "stale":
22723
+ return promise2.stale.length > 0;
22724
+ case "review":
22725
+ return promise2.review.length > 0;
22726
+ case "uncertain":
22727
+ return promise2.uncertain.length > 0;
22728
+ case "unassessed":
22729
+ return !promise2.cells.some((cell) => cell.source === "stored");
22730
+ default:
22731
+ return true;
22732
+ }
22733
+ }
22734
+ function buildWeighingCatalog(ctx) {
22735
+ const tools2 = [];
22736
+ const handlers2 = {};
22737
+ const tool = (definition, handler) => {
22738
+ tools2.push(definition);
22739
+ handlers2[definition.name] = handler;
22740
+ };
22741
+ const load2 = async () => {
22742
+ try {
22743
+ return await ctx.store.load();
22744
+ } catch (error51) {
22745
+ throw new ToolError(`Cannot load ${ctx.store.describe()}: ${error51.message}`);
22746
+ }
22747
+ };
22748
+ const sectionOf = (graph) => {
22749
+ if (ctx.qualityRoot === void 0) return graph.loaded.bundle.weighing;
22750
+ try {
22751
+ return loadWeighingSection(ctx.qualityRoot);
22752
+ } catch (error51) {
22753
+ throw new ToolError(error51.message);
22754
+ }
22755
+ };
22756
+ const appendHosted2 = async (inputs) => {
22757
+ if (ctx.store.appendWeighingEvents === void 0) throw new ToolError(`${ctx.store.describe()} cannot record assessments.`);
22758
+ try {
22759
+ return await ctx.store.appendWeighingEvents(inputs);
22760
+ } catch (error51) {
22761
+ const refusals = error51.refusals;
22762
+ throw new ToolError(error51.message, refusals !== void 0 ? { refusals } : void 0);
22763
+ }
22764
+ };
22765
+ tool(
22766
+ {
22767
+ name: "get_matrix",
22768
+ description: "The value matrix: what each promise (acceptance) is worth, against the 30 elements of value on a signed -3..+3 scale that measures REACH in a person's life: +1 within the product, +2 across the product's domain, +3 life-wide; the negatives mirror it, and 0 is weighed and unrelated. Most real promises land at +1; +3 is rare. Each element has its own ladder of what every level means. Per promise: `served` (sum of positive levels / 3) and `cost` (sum of |negative levels| / 3), NEVER netted; `positioned` (the same over the elements the product's active positioning stands on, each times its weight); `kept_share` (platforms where it is live / platforms it applies to); `guesswork` (the share of served and of cost resting on confidence-0 cells; `positioned` carries its own, and every mass and total says how much of it is guesswork). `flags` is a partition: claim_not_supported (claimed in metadata.values but assessed 0), claim_contradicted (claimed but assessed negative), unclaimed_value (not claimed, assessed 1 or more) and unclaimed_cost (not claimed, assessed negative \u2014 authors claim intent, so a cost is never claimed). `stale` lists elements whose winning level was scored before the promise's title, Gherkin or values changed, or against an older major of the ruler; `review` lists elements where a human and an agent differ by 2 or more; `uncertain` lists elements whose winning level a probabilistic scorer was unsure of (read it as a range). A cell nobody has scored reads at a SEEDED level: every claimed value +1 (scorer rule, confidence 0), a guess, never a score \u2014 negatives are never seeded. A human's level beats an agent's beats a seed, whatever the dates. Pass `subject` for one promise with every cell, its evidence, and each element's question and ladder \u2014 what you read before calling assess. Otherwise it lists promises (sort: served | cost | positioned | title; filter: flagged | stale | review | uncertain | unassessed; limit) plus the per-element promised / kept / cost masses. `probabilities: true` adds each cell's stored p_serves / p_costs. A draft positioning feeds nothing.",
22769
+ inputSchema: {
22770
+ type: "object",
22771
+ properties: {
22772
+ matrix: { type: "string", description: `Default: ${VALUE_MATRIX_ID}.` },
22773
+ subject: { type: "string", description: "An acceptance id: return that promise with every cell." },
22774
+ sort: { type: "string", enum: ["served", "cost", "positioned", "title"], description: "Default: served, heaviest first." },
22775
+ filter: { type: "string", enum: [...FILTERS] },
22776
+ limit: { type: "integer", minimum: 1, maximum: 200, description: "Default 25." },
22777
+ probabilities: { type: "boolean", description: "With `subject`: add each cell's stored p_serves / p_costs. Default false \u2014 the `uncertain` marker is usually enough." }
22778
+ },
22779
+ additionalProperties: false
22780
+ }
22781
+ },
22782
+ async (args) => {
22783
+ const graph = await load2();
22784
+ const section = sectionOf(graph);
22785
+ const nodes = graph.nodes;
22786
+ const matrixId = optionalString(args, "matrix") ?? VALUE_MATRIX_ID;
22787
+ const view = deriveWeighing(nodes, section, matrixId);
22788
+ if (view === void 0) throw new ToolError(`No usable matrix "${matrixId}" (unknown, or a draft \u2014 a draft feeds no roll-up). The built-in one is "${VALUE_MATRIX_ID}".`);
22789
+ const positioning = view.positioning === null ? null : {
22790
+ status: view.positioning.active ? "active" : "draft",
22791
+ elements: [...view.positioning.weights].map(([id, weight]) => {
22792
+ const anchors = view.positioning?.set.criteria.find((criterion) => criterion.id === id)?.anchors;
22793
+ return { id, weight, ...anchors !== void 0 ? { anchors } : {} };
22794
+ })
22795
+ };
22796
+ const { skipped } = resolveWeighing(section);
22797
+ const notes = [];
22798
+ if (skipped.length > 0) notes.push(`${skipped.length} stored set(s) or matrix(es) are malformed or duplicated and are ignored \u2014 see \`skipped\`.`);
22799
+ if (view.positioning !== null && !view.positioning.active) notes.push("The positioning is a draft \u2014 `positioned` figures are absent until it is saved as active.");
22800
+ if (view.totals.assessed === 0) notes.push("Nothing has been assessed yet \u2014 every claimed value is seeded at +1 (confidence 0), a guess.");
22801
+ const subject = optionalString(args, "subject");
22802
+ if (subject !== void 0) {
22803
+ const promise2 = view.promises.find((candidate) => candidate.node_id === subject);
22804
+ if (promise2 === void 0) throw new ToolError(`"${subject}" is not a subject of matrix "${matrixId}" (it judges ${view.matrix.subjects.kind === "query" ? `${view.matrix.subjects.species} nodes` : "a listed set"}).`);
22805
+ return {
22806
+ matrix: { id: view.matrix.id, set: view.matrix.set, set_version: view.set.version },
22807
+ scale: weighingScaleOf(view.set),
22808
+ // Each element's own question and ladder: a level means what ITS ladder says, the scale's anchors are the fallback.
22809
+ elements: view.set.criteria.map((criterion) => ({
22810
+ id: criterion.id,
22811
+ name: criterion.name,
22812
+ tier: criterion.group,
22813
+ ...criterion.question !== void 0 ? { question: criterion.question } : {},
22814
+ ...criterion.definition !== void 0 ? { definition: criterion.definition } : {},
22815
+ ...criterion.anchors !== void 0 ? { anchors: criterion.anchors } : {}
22816
+ })),
22817
+ confidence_anchors: CONFIDENCE_ANCHORS,
22818
+ positioning,
22819
+ promise: promiseRow(promise2, true, args.probabilities === true),
22820
+ ...skipped.length > 0 ? { skipped } : {},
22821
+ ...notes.length > 0 ? { notes } : {}
22822
+ };
22823
+ }
22824
+ const sort = optionalString(args, "sort") ?? "served";
22825
+ if (!["served", "cost", "positioned", "title"].includes(sort)) throw new ToolError("`sort` must be served, cost, positioned or title.");
22826
+ const filter = optionalString(args, "filter");
22827
+ if (filter !== void 0 && !FILTERS.includes(filter)) throw new ToolError(`\`filter\` must be one of ${FILTERS.join(", ")}.`);
22828
+ const limit = typeof args.limit === "number" && Number.isInteger(args.limit) ? Math.min(Math.max(args.limit, 1), 200) : 25;
22829
+ const matching = view.promises.filter((promise2) => filter === void 0 || matchesFilter(promise2, filter));
22830
+ const ordered = sortPromises(matching, sort);
22831
+ const elements = view.set.criteria.map((criterion) => ({ criterion, mass: view.elements[criterion.id] })).filter(({ mass }) => mass.promised > 0 || mass.cost > 0).sort((a, b) => b.mass.promised - a.mass.promised).map(({ criterion, mass }) => ({
22832
+ id: criterion.id,
22833
+ name: criterion.name,
22834
+ tier: criterion.group,
22835
+ promised: round2(mass.promised),
22836
+ kept: round2(mass.kept),
22837
+ cost: round2(mass.cost),
22838
+ guesswork: { promised: round2(mass.guesswork.promised), kept: round2(mass.guesswork.kept), cost: round2(mass.guesswork.cost) }
22839
+ }));
22840
+ return {
22841
+ matrix: { id: view.matrix.id, set: view.matrix.set, set_version: view.set.version },
22842
+ positioning,
22843
+ totals: {
22844
+ promises: view.totals.promises,
22845
+ archived: view.totals.archived,
22846
+ assessed: view.totals.assessed,
22847
+ promised: round2(view.totals.promised),
22848
+ kept: round2(view.totals.kept),
22849
+ cost: round2(view.totals.cost),
22850
+ guesswork: { promised: round2(view.totals.guesswork.promised), kept: round2(view.totals.guesswork.kept), cost: round2(view.totals.guesswork.cost) }
22851
+ },
22852
+ elements,
22853
+ promises: ordered.slice(0, limit).map((promise2) => promiseRow(promise2, false)),
22854
+ matching: ordered.length,
22855
+ ...skipped.length > 0 ? { skipped } : {},
22856
+ ...notes.length > 0 ? { notes } : {}
22857
+ };
22858
+ }
22859
+ );
22860
+ tool(
22861
+ {
22862
+ name: "assess",
22863
+ description: "Record one judgement: a signed level (-3..+3) for one promise on one value element, with how sure you are and why. Read the promise first with get_matrix `subject` so you score against the element's own ladder, not from memory: the level is how far into the person's life it reaches (+1 within the product, +2 across its domain, +3 life-wide). 0 means weighed and unrelated; a negative level is a COST (the promise works against that value) \u2014 score costs you find, authors rarely claim them, and an unclaimed cost is the most valuable thing an audit returns. `confidence`: 0 guess \xB7 1 inferred from the promise's own text \xB7 2 evidenced (cites something outside it) \xB7 3 verified. `evidence` is required above confidence 0: a score without a citation is an opinion. Scored as an AGENT \u2014 a human's level for the same cell keeps winning and yours is recorded beside it, flagged for review when you differ by 2 or more. The tool stamps what you cannot: who you are (and, where it can tell, whose hands you are \u2014 in a repository that is your git author name, read from `ARKAIK_ON_BEHALF_OF`, then `git config arkaik.user`, then `git config user.name`, and written into the committed sidecar; set `arkaik.user` to `-` to record nobody), the set's version and a fingerprint of the promise, so a later edit to its title, Gherkin or values marks your score stale. In a repository it upserts docs/weighing/assessments/<matrix>.json (nothing in the journal); on a hosted project it records weighing.assessment.recorded. The write goes through the same validator-gated gate as the app's form: an unknown element, an out-of-range level or a subject that is not an acceptance refuses with the reason.",
22864
+ inputSchema: {
22865
+ type: "object",
22866
+ properties: {
22867
+ subject: { type: "string", description: "An acceptance id." },
22868
+ criterion: { type: "string", description: "A value element id, e.g. reduces-anxiety." },
22869
+ level: { type: "integer", minimum: -3, maximum: 3 },
22870
+ confidence: { type: "integer", enum: [0, 1, 2, 3] },
22871
+ evidence: { type: "string", maxLength: 2e3, description: "Markdown, at most 2,000 characters. Required when confidence is above 0." },
22872
+ refs: { type: "array", items: { type: "string", maxLength: 200 }, maxItems: 50, description: "Ids cited: nodes, journal events, findings. At most 50, each at most 200 characters." },
22873
+ model: { type: "string", maxLength: 200, description: "The model you are, when you know. At most 200 characters." },
22874
+ run: { type: "string", maxLength: 200, description: "The audit or session this score belongs to. At most 200 characters." },
22875
+ commit: { type: "string", maxLength: 200 },
22876
+ matrix: { type: "string", description: `Default: ${VALUE_MATRIX_ID}.` },
22877
+ p_serves: { type: "number", minimum: 0, maximum: 1, description: "Only from a probabilistic scorer: how sure it is (0 to 1) that the promise serves this element. Certainty, not size." },
22878
+ p_costs: { type: "number", minimum: 0, maximum: 1, description: "The same for costs, asked independently. A level its scorer was unsure of reads as a range." }
22879
+ },
22880
+ required: ["subject", "criterion", "level", "confidence"],
22881
+ additionalProperties: false
22882
+ }
22883
+ },
22884
+ async (args) => {
22885
+ const subject = requireString2(args, "subject");
22886
+ const criterion = requireString2(args, "criterion");
22887
+ const level = args.level;
22888
+ if (typeof level !== "number" || !Number.isInteger(level)) throw new ToolError("`level` is required and must be an integer (the scale is -3 to +3).");
22889
+ const confidence = requireInt2(args, "confidence", 0, 3);
22890
+ const evidence = optionalString(args, "evidence");
22891
+ if (confidence > 0 && (evidence === void 0 || evidence.trim() === "")) {
22892
+ throw new ToolError("`evidence` is required above confidence 0 \u2014 a score without a citation is an opinion, not an assessment. Say what you read, or score at confidence 0.");
22893
+ }
22894
+ const refs = Array.isArray(args.refs) ? args.refs.filter((ref) => typeof ref === "string" && ref !== "") : void 0;
22895
+ const input = {
22896
+ type: WEIGHING_ASSESSMENT_RECORDED,
22897
+ subject,
22898
+ criterion,
22899
+ level,
22900
+ confidence,
22901
+ ...optionalString(args, "matrix") !== void 0 ? { matrix: optionalString(args, "matrix") } : {},
22902
+ ...evidence !== void 0 ? { evidence } : {},
22903
+ ...refs !== void 0 && refs.length > 0 ? { refs } : {},
22904
+ ...optionalString(args, "model") !== void 0 ? { model: optionalString(args, "model") } : {},
22905
+ ...optionalString(args, "run") !== void 0 ? { run: optionalString(args, "run") } : {},
22906
+ ...optionalString(args, "commit") !== void 0 ? { commit: optionalString(args, "commit") } : {},
22907
+ // Passed as given: a value off 0..1 is the planner's to refuse, with the reason.
22908
+ ...args.p_serves !== void 0 ? { p_serves: args.p_serves } : {},
22909
+ ...args.p_costs !== void 0 ? { p_costs: args.p_costs } : {}
22910
+ };
22911
+ const graph = await load2();
22912
+ const section = sectionOf(graph);
22913
+ const nodes = graph.nodes;
22914
+ const matrixId = input.matrix ?? VALUE_MATRIX_ID;
22915
+ const view = buildWeighingContext(section, matrixId);
22916
+ if (view === void 0) {
22917
+ const matrix = resolveWeighing(section).matrices.find((candidate) => candidate.id === matrixId);
22918
+ if (matrix === void 0) throw new ToolError(`No matrix "${matrixId}". The built-in one is "${VALUE_MATRIX_ID}".`);
22919
+ if (!isActiveWeighingSet(matrix)) throw new ToolError("This matrix is a draft and feeds no roll-up; activate it first.");
22920
+ throw new ToolError(`Matrix "${matrixId}" names the set "${matrix.set}", which is not available.`);
22921
+ }
22922
+ const node = nodes.find((candidate) => candidate.id === subject);
22923
+ const before = node !== void 0 ? weighPromise(node, view).cells.find((cell) => cell.criterion === criterion) : void 0;
22924
+ const notes = [];
22925
+ if (before?.source === "stored" && before.scorer.kind === "human") {
22926
+ notes.push("A human's level already stands for this cell and keeps winning \u2014 yours is recorded beside it" + (Math.abs(before.level - level) >= 2 ? ", and the cell now sits on the review list (you differ by 2 or more)." : "."));
22927
+ }
22928
+ const anchor = view.set.criteria.find((candidate) => candidate.id === criterion)?.anchors?.[String(level)] ?? weighingScaleOf(view.set).anchors[String(level)];
22929
+ if (ctx.qualityRoot === void 0) {
22930
+ const events = await appendHosted2([input]);
22931
+ const recorded = events.find((event) => event.type === WEIGHING_ASSESSMENT_RECORDED);
22932
+ return { assessment: recorded, ...anchor !== void 0 ? { anchor } : {}, events, ...notes.length > 0 ? { notes } : {} };
22933
+ }
22934
+ const onBehalfOf = await resolveOnBehalfOf(ctx.qualityRoot);
22935
+ const plan = planWeighingEvents(section, nodes, [input], { actor: MCP_ACTOR, scorerKind: "agent", ...onBehalfOf !== void 0 ? { onBehalfOf } : {} });
22936
+ if (!plan.ok) throw new ToolError(`Assessment refused \u2014 ${plan.refusals.map((r) => `${r.reason}: ${r.detail}`).join("; ")}`, { refusals: plan.refusals });
22937
+ const row = plan.assessments[0];
22938
+ let replaced;
22939
+ try {
22940
+ const next = upsertWeighingAssessment(loadMatrixAssessments(ctx.qualityRoot, row.matrix), row);
22941
+ replaced = next.replaced;
22942
+ saveWeighingAssessments(ctx.qualityRoot, row.matrix, next.assessments);
22943
+ } catch (error51) {
22944
+ throw new ToolError(error51.message);
22945
+ }
22946
+ return {
22947
+ assessment: row,
22948
+ file: weighingAssessmentsPath(ctx.qualityRoot, row.matrix),
22949
+ ...replaced !== void 0 ? { replaced_level: replaced.level } : {},
22950
+ ...anchor !== void 0 ? { anchor } : {},
22951
+ ...notes.length > 0 ? { notes } : {}
22952
+ };
22953
+ }
22954
+ );
22955
+ tool(
22956
+ {
22957
+ name: "save_positioning",
22958
+ description: "Write the product's positioning: the elements of value it stands on, each with a weight and, optionally, what each level means IN THE PRODUCT'S OWN WORDS (e.g. for reduces-anxiety: \"3 removes a worry the user names; 0 has nothing to do with worry\"). A positioning is a criteria set: a scorer \u2014 you, or another \u2014 reads those descriptions to judge a promise, and the weights make get_matrix's `positioned` figures. It REPLACES the previous positioning whole. `status` defaults to draft, and a draft feeds no roll-up: draft one from the landing page, the decisions or a brainstorm, and leave it for a person to read and save as active \u2014 you may activate it, but a positioning is a statement of intent, so say what you drafted it from. In a repository it writes docs/weighing/sets/positioning.json; on a hosted project it records weighing.set.saved.",
22959
+ inputSchema: {
22960
+ type: "object",
22961
+ properties: {
22962
+ elements: {
22963
+ type: "array",
22964
+ minItems: 1,
22965
+ items: {
22966
+ type: "object",
22967
+ properties: {
22968
+ id: { type: "string", description: "A value element id." },
22969
+ weight: { type: "number", exclusiveMinimum: 0, description: "How much the product stands on it. Default 1." },
22970
+ anchors: { type: "object", additionalProperties: { type: "string" }, description: `Level -> description in the product's words, keyed by the level as a string ("3", "0", "-3").` }
22971
+ },
22972
+ required: ["id"],
22973
+ additionalProperties: false
22974
+ }
22975
+ },
22976
+ status: { type: "string", enum: ["draft", "active"], description: "Default: draft." },
22977
+ title: { type: "string" }
22978
+ },
22979
+ required: ["elements"],
22980
+ additionalProperties: false
22981
+ }
22982
+ },
22983
+ async (args) => {
22984
+ if (!Array.isArray(args.elements) || args.elements.length === 0) throw new ToolError("`elements` is required: at least one element of value.");
22985
+ const status = optionalString(args, "status") ?? "draft";
22986
+ if (status !== "draft" && status !== "active") throw new ToolError("`status` must be draft or active.");
22987
+ const graph = await load2();
22988
+ const section = sectionOf(graph);
22989
+ const ruler = buildWeighingContext(section)?.set;
22990
+ if (ruler === void 0) throw new ToolError(`The built-in set "${VALUE_SET_ID}" is not available.`);
22991
+ const set2 = {
22992
+ id: POSITIONING_SET_ID,
22993
+ version: "1.0.0",
22994
+ title: optionalString(args, "title") ?? "Positioning",
22995
+ subject: ruler.subject,
22996
+ scale: weighingScaleOf(ruler),
22997
+ role: "positioning",
22998
+ status,
22999
+ extends: `${ruler.id}@${ruler.version.split(".")[0]}`,
23000
+ // Passed through AS GIVEN: a weight that is a string, an anchor off the scale or an entry that is not an
23001
+ // object is the planner's to refuse (`invalid_set`, with the reason), not this tool's to quietly fix.
23002
+ criteria: args.elements.map(
23003
+ (entry) => typeof entry === "object" && entry !== null && !Array.isArray(entry) ? {
23004
+ id: entry.id,
23005
+ ...entry.weight !== void 0 ? { weight: entry.weight } : {},
23006
+ ...entry.anchors !== void 0 ? { anchors: entry.anchors } : {}
23007
+ } : entry
23008
+ )
23009
+ };
23010
+ const input = { type: WEIGHING_SET_SAVED, set: set2 };
23011
+ const notes = status === "draft" ? ["Saved as a draft: it feeds no roll-up until it is saved as active."] : [];
23012
+ if (ctx.qualityRoot === void 0) {
23013
+ const events = await appendHosted2([input]);
23014
+ return { positioning: set2, events, ...notes.length > 0 ? { notes } : {} };
23015
+ }
23016
+ const plan = planWeighingEvents(section, graph.nodes, [input], { actor: MCP_ACTOR, scorerKind: "agent" });
23017
+ if (!plan.ok) throw new ToolError(`Positioning refused \u2014 ${plan.refusals.map((r) => `${r.reason}: ${r.detail}`).join("; ")}`, { refusals: plan.refusals });
23018
+ try {
23019
+ saveWeighingSet(ctx.qualityRoot, set2);
23020
+ } catch (error51) {
23021
+ throw new ToolError(error51.message);
23022
+ }
23023
+ return { positioning: set2, file: weighingSetPath(ctx.qualityRoot, set2.id), ...notes.length > 0 ? { notes } : {} };
23024
+ }
23025
+ );
23026
+ return { tools: tools2, handlers: handlers2 };
23027
+ }
23028
+
21198
23029
  // src/tools.ts
21199
23030
  async function load(ctx) {
21200
23031
  let graph;
@@ -21211,7 +23042,7 @@ async function load(ctx) {
21211
23042
  journal: graph.journal
21212
23043
  };
21213
23044
  }
21214
- function requireString2(args, key) {
23045
+ function requireString3(args, key) {
21215
23046
  const value = args[key];
21216
23047
  if (typeof value !== "string" || value.length === 0) {
21217
23048
  throw new ToolError(`\`${key}\` is required and must be a non-empty string.`);
@@ -21249,7 +23080,7 @@ function unwrap(result) {
21249
23080
  }
21250
23081
  var UPDATABLE_NODE_FIELDS = /* @__PURE__ */ new Set(["title", "description", "status", "platforms", "metadata"]);
21251
23082
  function requirePlatform(args) {
21252
- const raw = requireString2(args, "platform");
23083
+ const raw = requireString3(args, "platform");
21253
23084
  const platform = PLATFORM_IDS.find((id) => id === raw);
21254
23085
  if (platform === void 0) {
21255
23086
  throw new ToolError(`"${raw}" is not a platform (expected one of: ${PLATFORM_IDS.join(", ")}).`);
@@ -21257,7 +23088,7 @@ function requirePlatform(args) {
21257
23088
  return platform;
21258
23089
  }
21259
23090
  function requireScreenshotForm(args) {
21260
- const raw = requireString2(args, "form");
23091
+ const raw = requireString3(args, "form");
21261
23092
  if (raw === "url" || raw === "path" || raw === "data") return raw;
21262
23093
  throw new ToolError(`"${raw}" is not a screenshot form (url, path or data).`);
21263
23094
  }
@@ -21356,7 +23187,7 @@ ${node.description ?? ""}`.toLowerCase();
21356
23187
  }
21357
23188
  },
21358
23189
  async (args) => {
21359
- const nodeId = requireString2(args, "node_id");
23190
+ const nodeId = requireString3(args, "node_id");
21360
23191
  const { nodes, edges, journal } = await load(ctx);
21361
23192
  const node = findNode(nodes, nodeId);
21362
23193
  const nodesById = new Map(nodes.map((candidate) => [candidate.id, candidate]));
@@ -21450,7 +23281,7 @@ ${node.description ?? ""}`.toLowerCase();
21450
23281
  }
21451
23282
  },
21452
23283
  async (args) => {
21453
- const mapId = requireString2(args, "map_id");
23284
+ const mapId = requireString3(args, "map_id");
21454
23285
  const { nodes, edges, project } = await load(ctx);
21455
23286
  const definition = listMaps(project).find((candidate) => candidate.id === mapId);
21456
23287
  if (!definition) throw new ToolError(`No map with id "${mapId}".`);
@@ -21494,8 +23325,8 @@ ${node.description ?? ""}`.toLowerCase();
21494
23325
  },
21495
23326
  async (args) => {
21496
23327
  const graph = await load(ctx);
21497
- const species = requireString2(args, "species");
21498
- const title = requireString2(args, "title");
23328
+ const species = requireString3(args, "species");
23329
+ const title = requireString3(args, "title");
21499
23330
  const platforms = Array.isArray(args.platforms) ? args.platforms : [];
21500
23331
  const node = {
21501
23332
  id: deriveNodeId(species, title, graph.nodes.map((candidate) => candidate.id)),
@@ -21543,7 +23374,7 @@ ${node.description ?? ""}`.toLowerCase();
21543
23374
  }
21544
23375
  },
21545
23376
  async (args) => {
21546
- const nodeId = requireString2(args, "node_id");
23377
+ const nodeId = requireString3(args, "node_id");
21547
23378
  if (typeof args.patch !== "object" || args.patch === null || Array.isArray(args.patch)) {
21548
23379
  throw new ToolError("`patch` is required and must be an object.");
21549
23380
  }
@@ -21589,10 +23420,10 @@ ${node.description ?? ""}`.toLowerCase();
21589
23420
  }
21590
23421
  },
21591
23422
  async (args) => {
21592
- const nodeId = requireString2(args, "node_id");
23423
+ const nodeId = requireString3(args, "node_id");
21593
23424
  const platform = requirePlatform(args);
21594
23425
  const form = requireScreenshotForm(args);
21595
- const value = requireString2(args, "value");
23426
+ const value = requireString3(args, "value");
21596
23427
  const graph = await load(ctx);
21597
23428
  const ops = [
21598
23429
  {
@@ -21627,7 +23458,7 @@ ${node.description ?? ""}`.toLowerCase();
21627
23458
  }
21628
23459
  },
21629
23460
  async (args) => {
21630
- const nodeId = requireString2(args, "node_id");
23461
+ const nodeId = requireString3(args, "node_id");
21631
23462
  const platform = requirePlatform(args);
21632
23463
  const graph = await load(ctx);
21633
23464
  const ops = [{ op: "remove_screenshot", node_id: nodeId, platform }];
@@ -21651,7 +23482,7 @@ ${node.description ?? ""}`.toLowerCase();
21651
23482
  }
21652
23483
  },
21653
23484
  async (args) => {
21654
- const nodeId = requireString2(args, "node_id");
23485
+ const nodeId = requireString3(args, "node_id");
21655
23486
  const graph = await load(ctx);
21656
23487
  const node = findNode(graph.nodes, nodeId);
21657
23488
  const ops = [{ op: "delete_node", node_id: nodeId }];
@@ -21681,9 +23512,9 @@ ${node.description ?? ""}`.toLowerCase();
21681
23512
  }
21682
23513
  },
21683
23514
  async (args) => {
21684
- const sourceId = requireString2(args, "source_id");
21685
- const targetId = requireString2(args, "target_id");
21686
- const edgeType = requireString2(args, "edge_type");
23515
+ const sourceId = requireString3(args, "source_id");
23516
+ const targetId = requireString3(args, "target_id");
23517
+ const edgeType = requireString3(args, "edge_type");
21687
23518
  const graph = await load(ctx);
21688
23519
  const edge = {
21689
23520
  id: edgeId(sourceId, targetId),
@@ -21718,7 +23549,7 @@ ${node.description ?? ""}`.toLowerCase();
21718
23549
  }
21719
23550
  },
21720
23551
  async (args) => {
21721
- const edgeIdArg = requireString2(args, "edge_id");
23552
+ const edgeIdArg = requireString3(args, "edge_id");
21722
23553
  const graph = await load(ctx);
21723
23554
  const edge = graph.edges.find((candidate) => candidate.id === edgeIdArg);
21724
23555
  if (!edge) throw new ToolError(`No edge with id "${edgeIdArg}".`);
@@ -21734,7 +23565,7 @@ ${node.description ?? ""}`.toLowerCase();
21734
23565
  }
21735
23566
  );
21736
23567
  const journalOnly = (type) => async (args) => {
21737
- const title = requireString2(args, "title");
23568
+ const title = requireString3(args, "title");
21738
23569
  const graph = await load(ctx);
21739
23570
  const payload = { title };
21740
23571
  if (typeof args.description === "string") payload.description = args.description;
@@ -21783,88 +23614,12 @@ ${node.description ?? ""}`.toLowerCase();
21783
23614
  const kritik = buildKritikCatalog(ctx);
21784
23615
  tools2.push(...kritik.tools);
21785
23616
  Object.assign(handlers2, kritik.handlers);
23617
+ const weighing = buildWeighingCatalog(ctx);
23618
+ tools2.push(...weighing.tools);
23619
+ Object.assign(handlers2, weighing.handlers);
21786
23620
  return { tools: tools2, handlers: handlers2 };
21787
23621
  }
21788
23622
 
21789
- // src/store.ts
21790
- import { writeFileSync as writeFileSync3 } from "node:fs";
21791
- import { resolve as resolve3 } from "node:path";
21792
- var MCP_ACTOR = "arkaik-mcp";
21793
- var DEFAULT_BUNDLE_PATH2 = "docs/arkaik/bundle.json";
21794
- function resolveBundlePath(argv2, env) {
21795
- const flagIndex = argv2.indexOf("--bundle");
21796
- const flagValue2 = flagIndex !== -1 ? argv2[flagIndex + 1] : void 0;
21797
- if (flagValue2) return resolve3(flagValue2);
21798
- if (env.ARKAIK_BUNDLE) return resolve3(env.ARKAIK_BUNDLE);
21799
- return resolve3(DEFAULT_BUNDLE_PATH2);
21800
- }
21801
- function loadBundle(bundlePath) {
21802
- return validateBundleAt(bundlePath);
21803
- }
21804
- function nodeIdsOf(nodes) {
21805
- return nodes.map((node) => node?.id).filter((id) => typeof id === "string");
21806
- }
21807
- function persistMutation(bundlePath, loaded, next, inputs) {
21808
- const baselineNodeIds = inputs.length === 0 ? [] : missingProvenanceNodeIds(nodeIdsOf(loaded.nodes), loaded.journal);
21809
- const events = [
21810
- ...baselineNodeIds.length > 0 ? [makeEvent("journal.baseline", { node_ids: baselineNodeIds }, { actor: MCP_ACTOR })] : [],
21811
- ...toJournalEvents(inputs, MCP_ACTOR)
21812
- ];
21813
- const nextNodes = next.nodes ?? loaded.nodes;
21814
- const nextEdges = next.edges ?? loaded.edges;
21815
- const candidate = {
21816
- ...loaded.bundle,
21817
- nodes: nextNodes,
21818
- edges: nextEdges,
21819
- journal: [...loaded.journal, ...events]
21820
- };
21821
- const result = validateBundle(candidate);
21822
- if (result.errors.length > 0) {
21823
- return { ok: false, errors: result.errors, warnings: result.warnings };
21824
- }
21825
- const journalOnDisk = loaded.sidecarLoaded || loaded.archivesLoaded.length > 0;
21826
- const embeddedJournal = !journalOnDisk && loaded.bundle.journal !== void 0;
21827
- if (embeddedJournal) {
21828
- writeFileSync3(bundlePath, serializeBundle(candidate));
21829
- } else {
21830
- const journalPath = journalPathFor(bundlePath);
21831
- for (const event of events) {
21832
- appendJournalEvent(journalPath, event);
21833
- }
21834
- if (next.nodes !== void 0 || next.edges !== void 0) {
21835
- const snapshot = { ...loaded.bundle, nodes: nextNodes, edges: nextEdges };
21836
- delete snapshot.journal;
21837
- writeFileSync3(bundlePath, serializeBundle(snapshot));
21838
- }
21839
- }
21840
- return { ok: true, warnings: result.warnings, events };
21841
- }
21842
- function createFileStore(bundlePath) {
21843
- return {
21844
- async load() {
21845
- let loaded;
21846
- try {
21847
- loaded = loadBundle(bundlePath);
21848
- } catch (error51) {
21849
- throw new Error(`Cannot load bundle at ${bundlePath}: ${error51.message}`);
21850
- }
21851
- return {
21852
- loaded,
21853
- nodes: loaded.nodes,
21854
- edges: loaded.edges,
21855
- project: loaded.bundle.project,
21856
- journal: loaded.journal
21857
- };
21858
- },
21859
- async persist(graph, next, inputs) {
21860
- return persistMutation(bundlePath, graph.loaded, next, inputs);
21861
- },
21862
- describe() {
21863
- return `bundle: ${bundlePath}`;
21864
- }
21865
- };
21866
- }
21867
-
21868
23623
  // src/remote-store.ts
21869
23624
  function createRemoteStore(options) {
21870
23625
  const doFetch = options.fetchImpl ?? ((...args) => fetch(...args));
@@ -22022,6 +23777,28 @@ function createRemoteStore(options) {
22022
23777
  }
22023
23778
  throw err;
22024
23779
  }
23780
+ },
23781
+ // The weighing twin of the method above, and simpler: there is no
23782
+ // retry-after-a-dropped-response story, because an assessment is
23783
+ // latest-wins per cell and scorer kind — sending it twice is the same write.
23784
+ // The server stamps the scorer (a token is an agent) and the basis, so
23785
+ // nothing about provenance travels from here, and a refusal names each
23786
+ // entry's `index`, `reason` and `detail`.
23787
+ async appendWeighingEvents(inputs) {
23788
+ try {
23789
+ const result = await request("/weighing/events", {
23790
+ method: "POST",
23791
+ body: JSON.stringify({ events: inputs })
23792
+ });
23793
+ return result.events;
23794
+ } catch (err) {
23795
+ const e = err;
23796
+ if (e.status === 422 && e.body?.error === "refused" && e.body.refusals) {
23797
+ const detail = e.body.refusals.map((r) => `entry ${r.index}: ${r.reason}${r.detail ? ` \u2014 ${r.detail}` : ""}`).join("; ");
23798
+ throw Object.assign(new Error(`Weighing events refused \u2014 ${detail}`), { refusals: e.body.refusals });
23799
+ }
23800
+ throw err;
23801
+ }
22025
23802
  }
22026
23803
  };
22027
23804
  }
@@ -22035,12 +23812,12 @@ function describeFailure(status, body) {
22035
23812
 
22036
23813
  // src/config.ts
22037
23814
  import { readFileSync as readFileSync5 } from "node:fs";
22038
- import { join as join6 } from "node:path";
23815
+ import { join as join7 } from "node:path";
22039
23816
  var LINK_FILE = "docs/arkaik/arkaik.json";
22040
23817
  var DEFAULT_BASE_URL = "https://arkaik.app";
22041
23818
  function readLinkFile(cwd) {
22042
23819
  try {
22043
- const parsed = JSON.parse(readFileSync5(join6(cwd, LINK_FILE), "utf8"));
23820
+ const parsed = JSON.parse(readFileSync5(join7(cwd, LINK_FILE), "utf8"));
22044
23821
  if (typeof parsed !== "object" || parsed === null) return null;
22045
23822
  return parsed;
22046
23823
  } catch {
@@ -22081,7 +23858,7 @@ function resolveRemoteConfig(argv2, env, cwd) {
22081
23858
  }
22082
23859
 
22083
23860
  // src/index.ts
22084
- var VERSION = "0.10.0";
23861
+ var VERSION = "0.12.0";
22085
23862
  var argv = process.argv.slice(2);
22086
23863
  if (argv.includes("--help") || argv.includes("-h")) {
22087
23864
  process.stdout.write(