arkaik 0.12.0 → 0.14.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.
package/dist/index.js CHANGED
@@ -801,14 +801,14 @@ function promiseAllObject(promisesObj) {
801
801
  }
802
802
  function randomString(length = 10) {
803
803
  const chars = "abcdefghijklmnopqrstuvwxyz";
804
- let str2 = "";
804
+ let str3 = "";
805
805
  for (let i = 0; i < length; i++) {
806
- str2 += chars[Math.floor(Math.random() * chars.length)];
806
+ str3 += chars[Math.floor(Math.random() * chars.length)];
807
807
  }
808
- return str2;
808
+ return str3;
809
809
  }
810
- function esc(str2) {
811
- return JSON.stringify(str2);
810
+ function esc(str3) {
811
+ return JSON.stringify(str3);
812
812
  }
813
813
  function slugify(input) {
814
814
  return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
@@ -922,8 +922,8 @@ var primitiveTypes = /* @__PURE__ */ new Set([
922
922
  "symbol",
923
923
  "undefined"
924
924
  ]);
925
- function escapeRegex(str2) {
926
- return str2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
925
+ function escapeRegex(str3) {
926
+ return str3.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
927
927
  }
928
928
  function clone(inst, def, params) {
929
929
  const cl = new inst._zod.constr(def ?? inst._zod.def);
@@ -15021,13 +15021,13 @@ function crossCheckJournal(bundle) {
15021
15021
  return findings;
15022
15022
  }
15023
15023
  if (journalRaw.length === 0) return findings;
15024
- const str2 = (v) => typeof v === "string" ? v : void 0;
15024
+ const str3 = (v) => typeof v === "string" ? v : void 0;
15025
15025
  const nodesRaw = Array.isArray(bundle.nodes) ? bundle.nodes : [];
15026
15026
  const edgesRaw = Array.isArray(bundle.edges) ? bundle.edges : [];
15027
15027
  const snapshotNodeStatus = /* @__PURE__ */ new Map();
15028
15028
  const snapshotDecisionStatus = /* @__PURE__ */ new Map();
15029
15029
  for (const n of nodesRaw) {
15030
- const id = str2(n?.id);
15030
+ const id = str3(n?.id);
15031
15031
  if (id !== void 0) {
15032
15032
  snapshotNodeStatus.set(id, n.status);
15033
15033
  const metadata = n.metadata;
@@ -15037,7 +15037,7 @@ function crossCheckJournal(bundle) {
15037
15037
  }
15038
15038
  const snapshotEdgeIds = /* @__PURE__ */ new Set();
15039
15039
  for (const e of edgesRaw) {
15040
- const id = str2(e?.id);
15040
+ const id = str3(e?.id);
15041
15041
  if (id !== void 0) snapshotEdgeIds.add(id);
15042
15042
  }
15043
15043
  const valid = [];
@@ -15054,9 +15054,9 @@ function crossCheckJournal(bundle) {
15054
15054
  }
15055
15055
  const ev = raw;
15056
15056
  const missing = [];
15057
- if (str2(ev.id) === void 0) missing.push("id");
15058
- if (str2(ev.ts) === void 0) missing.push("ts");
15059
- if (str2(ev.type) === void 0) missing.push("type");
15057
+ if (str3(ev.id) === void 0) missing.push("id");
15058
+ if (str3(ev.ts) === void 0) missing.push("ts");
15059
+ if (str3(ev.type) === void 0) missing.push("type");
15060
15060
  if (missing.length > 0) {
15061
15061
  findings.push({
15062
15062
  path: path6,
@@ -15073,14 +15073,14 @@ function crossCheckJournal(bundle) {
15073
15073
  const baselined = /* @__PURE__ */ new Set();
15074
15074
  for (const { ev } of valid) {
15075
15075
  if (ev.type === "node.created") {
15076
- const nid = str2(ev.node_id);
15076
+ const nid = str3(ev.node_id);
15077
15077
  if (nid) everNodes.add(nid);
15078
15078
  } else if (ev.type === "edge.added") {
15079
- const eid = str2(ev.edge_id);
15079
+ const eid = str3(ev.edge_id);
15080
15080
  if (eid) everEdges.add(eid);
15081
15081
  } else if (ev.type === "journal.baseline" && Array.isArray(ev.node_ids)) {
15082
15082
  for (const raw of ev.node_ids) {
15083
- const nid = str2(raw);
15083
+ const nid = str3(raw);
15084
15084
  if (nid) {
15085
15085
  baselined.add(nid);
15086
15086
  everNodes.add(nid);
@@ -15094,18 +15094,18 @@ function crossCheckJournal(bundle) {
15094
15094
  const lastDecisionStatus = /* @__PURE__ */ new Map();
15095
15095
  for (const ev of ordered) {
15096
15096
  if (ev.type === "node.created") {
15097
- const nid = str2(ev.node_id);
15097
+ const nid = str3(ev.node_id);
15098
15098
  if (nid) created.add(nid);
15099
15099
  } else if (ev.type === "node.status_changed") {
15100
- const nid = str2(ev.node_id);
15100
+ const nid = str3(ev.node_id);
15101
15101
  if (nid && ev.platform === void 0) {
15102
- const to = str2(ev.to);
15102
+ const to = str3(ev.to);
15103
15103
  if (to !== void 0) lastProjectStatus.set(nid, to);
15104
15104
  }
15105
15105
  } else if (ev.type === "decision.status_changed") {
15106
- const nid = str2(ev.node_id);
15106
+ const nid = str3(ev.node_id);
15107
15107
  if (nid) {
15108
- const to = str2(ev.to);
15108
+ const to = str3(ev.to);
15109
15109
  if (to !== void 0) lastDecisionStatus.set(nid, to);
15110
15110
  }
15111
15111
  }
@@ -15114,7 +15114,7 @@ function crossCheckJournal(bundle) {
15114
15114
  const nodeFields = NODE_REF_FIELDS[ev.type];
15115
15115
  if (nodeFields) {
15116
15116
  for (const field of nodeFields) {
15117
- const ref = str2(ev[field]);
15117
+ const ref = str3(ev[field]);
15118
15118
  if (ref !== void 0 && !everNodes.has(ref)) {
15119
15119
  findings.push({
15120
15120
  path: `journal[${index}].${field}`,
@@ -15127,7 +15127,7 @@ function crossCheckJournal(bundle) {
15127
15127
  }
15128
15128
  if (ev.type === "deliverable.shipped" && Array.isArray(ev.node_ids)) {
15129
15129
  ev.node_ids.forEach((raw, i) => {
15130
- const ref = str2(raw);
15130
+ const ref = str3(raw);
15131
15131
  if (ref !== void 0 && !everNodes.has(ref)) {
15132
15132
  findings.push({
15133
15133
  path: `journal[${index}].node_ids[${i}]`,
@@ -15139,7 +15139,7 @@ function crossCheckJournal(bundle) {
15139
15139
  });
15140
15140
  }
15141
15141
  if (ev.type === "edge.removed") {
15142
- const ref = str2(ev.edge_id);
15142
+ const ref = str3(ev.edge_id);
15143
15143
  if (ref !== void 0 && !everEdges.has(ref)) {
15144
15144
  findings.push({
15145
15145
  path: `journal[${index}].edge_id`,
@@ -15183,7 +15183,7 @@ function crossCheckJournal(bundle) {
15183
15183
  }
15184
15184
  const slots = reduceScreenshotSlots(ordered);
15185
15185
  nodesRaw.forEach((n, index) => {
15186
- const nodeId = str2(n?.id);
15186
+ const nodeId = str3(n?.id);
15187
15187
  if (nodeId === void 0) return;
15188
15188
  const metadata = isRecord2(n.metadata) ? n.metadata : {};
15189
15189
  const shots = isRecord2(metadata.platformScreenshots) ? metadata.platformScreenshots : {};
@@ -15202,7 +15202,7 @@ function crossCheckJournal(bundle) {
15202
15202
  agrees = slot !== void 0;
15203
15203
  says = "a data URI was recorded";
15204
15204
  } else {
15205
- const url2 = str2(last.url);
15205
+ const url2 = str3(last.url);
15206
15206
  agrees = slot === url2;
15207
15207
  says = url2 === void 0 ? "an unknown value was recorded" : `"${url2}" was recorded`;
15208
15208
  }
@@ -15275,12 +15275,12 @@ var WeighingCriteriaSetSchema = external_exports.object({
15275
15275
  criteria: documented(external_exports.array(documented(WeighingCriterionSchema))).optional(),
15276
15276
  role: leaf("positioning marks the set a project writes about itself."),
15277
15277
  status: leaf("Absent or active is active; anything else is a draft, which feeds no roll-up."),
15278
- extends: leaf("A positioning's ruler, e.g. value-contribution@1.")
15278
+ extends: leaf("A positioning's ruler, e.g. value-contribution@2.")
15279
15279
  }).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." });
15280
15280
  var WeighingMatrixSchema = external_exports.object({
15281
15281
  id: leaf("The matrix's id."),
15282
15282
  title: leaf("A human title."),
15283
- set: leaf("The set's id and major, e.g. value-contribution@1."),
15283
+ set: leaf("The set's id and major, e.g. value-contribution@2."),
15284
15284
  subjects: documented(
15285
15285
  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())
15286
15286
  ).optional().meta({ description: "What the matrix judges: { kind: query, species } or { kind: list, items }." }),
@@ -15304,6 +15304,8 @@ var WeighingAssessmentSchema = external_exports.object({
15304
15304
  refs: leaf("Ids cited: nodes, journal events, findings."),
15305
15305
  basis: documented(WeighingAssessmentBasisSchema).optional().meta({ description: "What the scorer was looking at, so a re-read can tell the score went stale." }),
15306
15306
  run: leaf("The audit or plan the score belongs to."),
15307
+ 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."),
15308
+ p_costs: leaf("Optional: the same for costs, asked independently, so both can be high."),
15307
15309
  ts: leaf("ISO 8601.")
15308
15310
  }).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." });
15309
15311
  var WeighingSectionSchema = external_exports.object({
@@ -15517,7 +15519,9 @@ var WeighingAssessmentRecordedEventSchema = external_exports.object({
15517
15519
  evidence: external_exports.string().optional(),
15518
15520
  refs: external_exports.array(external_exports.string()).optional(),
15519
15521
  basis: WeighingAssessmentBasisSchema.optional(),
15520
- run: external_exports.string().optional()
15522
+ run: external_exports.string().optional(),
15523
+ p_serves: external_exports.number().min(0).max(1).optional(),
15524
+ p_costs: external_exports.number().min(0).max(1).optional()
15521
15525
  }).catchall(external_exports.unknown());
15522
15526
  var WeighingSetSavedEventSchema = external_exports.object({ ...envelope, type: external_exports.literal("weighing.set.saved"), set: WeighingCriteriaSetSchema }).catchall(external_exports.unknown());
15523
15527
  var JOURNAL_EVENT_SCHEMAS = {
@@ -16832,6 +16836,253 @@ function isBuiltInMapId(id) {
16832
16836
  return BUILT_IN_MAP_IDS.includes(id);
16833
16837
  }
16834
16838
 
16839
+ // ../schema/src/weighing-ladders.ts
16840
+ var LADDERS = {
16841
+ "saves-time": {
16842
+ "-3": "Takes hours out of the person's life.",
16843
+ "-2": "Costs the person time on tasks they do regularly in this domain.",
16844
+ "-1": "Costs the person a little time on one task inside the product.",
16845
+ "1": "Saves a little time on one task inside the product.",
16846
+ "2": "Saves time on tasks the person does regularly in this domain.",
16847
+ "3": "Gives the person back hours of their life, the way online banking replaced trips to the bank."
16848
+ },
16849
+ simplifies: {
16850
+ "-3": "Makes a part of the person's life confusing or hard to manage.",
16851
+ "-2": "Makes a whole task in this domain clearly more complicated.",
16852
+ "-1": "Adds a step or a choice inside the product.",
16853
+ "1": "Removes a step or a choice inside the product.",
16854
+ "2": "Makes a whole task in this domain clearly simpler.",
16855
+ "3": "Makes a complicated part of the person's life simple, the way a single search box replaced browsing directories."
16856
+ },
16857
+ "makes-money": {
16858
+ "-3": "Costs the person a meaningful part of their income.",
16859
+ "-2": "Cuts a regular way the person earns in this domain.",
16860
+ "-1": "Makes earning slightly harder or costs the person a little income.",
16861
+ "1": "Helps the person earn a little, or makes earning slightly easier.",
16862
+ "2": "Gives the person a regular way to earn in this domain.",
16863
+ "3": "Provides a meaningful part of the person's income."
16864
+ },
16865
+ "reduces-risk": {
16866
+ "-3": "Exposes the person to a major loss in their life.",
16867
+ "-2": "Exposes the person to a serious loss or error in this domain.",
16868
+ "-1": "Exposes the person to a small mistake or loss inside the product.",
16869
+ "1": "Guards against a small mistake or loss inside the product.",
16870
+ "2": "Protects against a serious loss or error in this domain.",
16871
+ "3": "Protects against a major loss in the person's life, the way insurance or a full backup does."
16872
+ },
16873
+ organizes: {
16874
+ "-3": "Brings disorder to a large part of the person's life.",
16875
+ "-2": "Makes things in this domain hard to keep in order or to find.",
16876
+ "-1": "Leaves a few things in disorder inside the product.",
16877
+ "1": "Keeps a few things in order inside the product.",
16878
+ "2": "Keeps everything in this domain in order and easy to find.",
16879
+ "3": "Brings order to a large part of the person's life, the way a calendar does."
16880
+ },
16881
+ integrates: {
16882
+ "-3": "Pulls separate parts of the person's life further apart.",
16883
+ "-2": "Splits apart the several tools the person uses in this domain.",
16884
+ "-1": "Cuts the product off from one other tool the person uses.",
16885
+ "1": "Connects the product to one other tool the person uses.",
16886
+ "2": "Ties together the several tools the person uses in this domain.",
16887
+ "3": "Makes separate parts of the person's life work together as one."
16888
+ },
16889
+ connects: {
16890
+ "-3": "Separates the person from the people who matter most in their life.",
16891
+ "-2": "Makes it harder to build or keep relationships in this domain.",
16892
+ "-1": "Gets in the way of reaching someone through the product.",
16893
+ "1": "Lets the person reach someone through the product.",
16894
+ "2": "Helps the person build and keep relationships in this domain.",
16895
+ "3": "Brings the person together with the people who matter most in their life."
16896
+ },
16897
+ "reduces-effort": {
16898
+ "-3": "Puts a heavy burden of work on the person's life.",
16899
+ "-2": "Adds repetitive work to a task the person does regularly in this domain.",
16900
+ "-1": "Adds a little effort to one task inside the product.",
16901
+ "1": "Saves a little effort on one task inside the product.",
16902
+ "2": "Takes the repetitive work out of a task the person does regularly in this domain.",
16903
+ "3": "Lifts a heavy burden of work off the person's life."
16904
+ },
16905
+ "avoids-hassles": {
16906
+ "-3": "Brings a whole kind of annoyance into the person's life.",
16907
+ "-2": "Adds an annoyance that keeps coming back in this domain.",
16908
+ "-1": "Adds a small annoyance inside the product.",
16909
+ "1": "Avoids a small annoyance inside the product.",
16910
+ "2": "Avoids an annoyance that keeps coming back in this domain.",
16911
+ "3": "Takes a whole kind of annoyance out of the person's life, the way a GPS ended getting lost."
16912
+ },
16913
+ "reduces-cost": {
16914
+ "-3": "Costs the person a significant amount of money over their life.",
16915
+ "-2": "Costs the person money regularly in this domain.",
16916
+ "-1": "Costs the person a little money on one purchase.",
16917
+ "1": "Saves the person a little money on one purchase.",
16918
+ "2": "Saves the person money regularly in this domain.",
16919
+ "3": "Saves the person a significant amount of money over their life."
16920
+ },
16921
+ quality: {
16922
+ "-3": "Craft so poor the person would call it the worst they have used.",
16923
+ "-2": "The product does its job in this domain clearly worse than the usual alternatives.",
16924
+ "-1": "Something inside the product works noticeably badly.",
16925
+ "1": "Something inside the product works noticeably well.",
16926
+ "2": "The product does its job in this domain clearly better than the usual alternatives.",
16927
+ "3": "Craft so good the person would call it the best they have used."
16928
+ },
16929
+ variety: {
16930
+ "-3": "Closes off a breadth of choice the person had elsewhere.",
16931
+ "-2": "Narrows the choice in this domain.",
16932
+ "-1": "Removes a few meaningful options inside the product.",
16933
+ "1": "Offers a few meaningful options inside the product.",
16934
+ "2": "Offers a wide and meaningful choice in this domain.",
16935
+ "3": "Opens a breadth of choice the person could not get anywhere else."
16936
+ },
16937
+ "sensory-appeal": {
16938
+ "-3": "A sensory experience the person avoids.",
16939
+ "-2": "The product looks, sounds or feels bad and the person dislikes using it.",
16940
+ "-1": "An unpleasant detail the person notices in the moment.",
16941
+ "1": "A pleasant detail the person notices in the moment.",
16942
+ "2": "The product looks, sounds or feels good and the person enjoys using it.",
16943
+ "3": "A sensory experience the person seeks out for its own sake."
16944
+ },
16945
+ informs: {
16946
+ "-3": "Misleads the person deeply about the service area or domain.",
16947
+ "-2": "Confuses the person about the service area or domain.",
16948
+ "-1": "Hides from the person something about the service that they want to know.",
16949
+ "1": "Informs the person about the service.",
16950
+ "2": "Informs the person about the service area or domain.",
16951
+ "3": "Informs the person deeply and efficiently about the service area or domain."
16952
+ },
16953
+ "reduces-anxiety": {
16954
+ "-3": "Gives the person a lasting worry in their life.",
16955
+ "-2": "Stirs up a worry the person has in this domain.",
16956
+ "-1": "Adds a small worry inside the product.",
16957
+ "1": "Removes a small worry inside the product.",
16958
+ "2": "Calms a worry the person has in this domain.",
16959
+ "3": "Takes a lasting worry out of the person's life."
16960
+ },
16961
+ "rewards-me": {
16962
+ "-3": "Takes away rewards the person values as much as the product itself.",
16963
+ "-2": "Takes away perks the person regularly values.",
16964
+ "-1": "Takes away a small perk the person had.",
16965
+ "1": "Gives the person a small perk for engaging.",
16966
+ "2": "Gives the person regular perks they value.",
16967
+ "3": "Gives the person rewards they value as much as the product itself."
16968
+ },
16969
+ nostalgia: {
16970
+ "-3": "Destroys a cherished memory for good.",
16971
+ "-2": "Loses or overwrites a good memory of the past.",
16972
+ "-1": "Puts a pleasant memory at slight risk.",
16973
+ "1": "Faintly recalls a pleasant memory of the past.",
16974
+ "2": "Clearly brings back a good memory of the past.",
16975
+ "3": "Brings back a cherished past in a vivid and deeply felt way."
16976
+ },
16977
+ "design-aesthetics": {
16978
+ "-3": "Ugliness the person would be embarrassed to show to others.",
16979
+ "-2": "A design the person finds ugly.",
16980
+ "-1": "A displeasing design detail.",
16981
+ "1": "A pleasing design detail.",
16982
+ "2": "A design the person finds beautiful.",
16983
+ "3": "Beauty the person would show to others and that shapes how they feel about it."
16984
+ },
16985
+ "badge-value": {
16986
+ "-3": "Signals something the person does not want the people who matter to them to see.",
16987
+ "-2": "Clearly signals a low identity or status in a community.",
16988
+ "-1": "Gives a mild negative signal about the person to others.",
16989
+ "1": "Gives a mild signal about the person to others.",
16990
+ "2": "Clearly signals the person's identity or status in a community.",
16991
+ "3": "Signals who the person is to the people who matter to them."
16992
+ },
16993
+ wellness: {
16994
+ "-3": "Lastingly harms the person's physical or mental well-being.",
16995
+ "-2": "Noticeably worsens how the person feels over time.",
16996
+ "-1": "Slightly worsens how the person feels, in the moment.",
16997
+ "1": "Slightly improves how the person feels, in the moment.",
16998
+ "2": "Noticeably improves how the person feels over time.",
16999
+ "3": "Lastingly improves the person's physical or mental well-being."
17000
+ },
17001
+ "therapeutic-value": {
17002
+ "-3": "Deepens something that hurts the person.",
17003
+ "-2": "Makes a difficult feeling harder for the person to work through.",
17004
+ "-1": "Reopens a small emotional sore.",
17005
+ "1": "Gives a small moment of emotional relief.",
17006
+ "2": "Helps the person work through a difficult feeling.",
17007
+ "3": "Supports real healing of something that hurts the person."
17008
+ },
17009
+ "fun-entertainment": {
17010
+ "-3": "So joyless that the person avoids it and warns others.",
17011
+ "-2": "Boring or tedious to use.",
17012
+ "-1": "A dull moment.",
17013
+ "1": "A light moment of enjoyment.",
17014
+ "2": "Genuinely enjoyable to use.",
17015
+ "3": "Delight the person would seek out and tell others about."
17016
+ },
17017
+ attractiveness: {
17018
+ "-3": "Changes how unattractive the person feels in general.",
17019
+ "-2": "Clearly makes the person feel less attractive.",
17020
+ "-1": "Makes the person feel slightly worse about how they look.",
17021
+ "1": "Makes the person feel slightly better about how they look.",
17022
+ "2": "Clearly makes the person feel more attractive.",
17023
+ "3": "Changes how attractive the person feels in general."
17024
+ },
17025
+ "provides-access": {
17026
+ "-3": "Shuts the person out of something that matters in their life.",
17027
+ "-2": "Cuts the person off from a service or from people in this domain that they could otherwise reach.",
17028
+ "-1": "Puts a feature inside the product behind a barrier or closes it off.",
17029
+ "1": "Opens a feature inside the product.",
17030
+ "2": "Gives access to a service or to people in this domain that the person could not easily reach.",
17031
+ "3": "Gives access to something that matters in the person's life and that they could not get otherwise."
17032
+ },
17033
+ "provides-hope": {
17034
+ "-3": "Leaves the person believing their life cannot get better.",
17035
+ "-2": "Gives the person a reason to doubt that things in this domain can improve.",
17036
+ "-1": "Plants a small doubt.",
17037
+ "1": "Gives a small reason for optimism.",
17038
+ "2": "Gives a real reason to believe things in this domain can improve.",
17039
+ "3": "Gives a lasting belief that the person's life can get better."
17040
+ },
17041
+ "self-actualization": {
17042
+ "-3": "Pushes the person away from who they want to be.",
17043
+ "-2": "Clear drift away from who the person wants to be.",
17044
+ "-1": "A small step away from who the person wants to be.",
17045
+ "1": "A small step toward who the person wants to be.",
17046
+ "2": "Clear progress toward who the person wants to be.",
17047
+ "3": "Helps the person become who they want to be."
17048
+ },
17049
+ motivation: {
17050
+ "-3": "Drains the person's drive toward goals that matter in their life.",
17051
+ "-2": "Saps the person's energy toward a goal in this domain.",
17052
+ "-1": "A small drag on the person's drive.",
17053
+ "1": "A small nudge to act.",
17054
+ "2": "Energizes the person toward a goal in this domain.",
17055
+ "3": "Sustains the person's drive toward goals that matter in their life."
17056
+ },
17057
+ heirloom: {
17058
+ "-3": "Loses something meaningful that was meant to be passed on across time.",
17059
+ "-2": "Lets something meaningful be lost within years.",
17060
+ "-1": "Puts something worth keeping at slight risk.",
17061
+ "1": "Keeps something worth keeping for a while.",
17062
+ "2": "Preserves something meaningful for years.",
17063
+ "3": "Holds something meaningful enough to be passed on to others across time."
17064
+ },
17065
+ "affiliation-belonging": {
17066
+ "-3": "Cuts the person off from a group that matters deeply to who they are.",
17067
+ "-2": "Leaves the person out of a group in this domain.",
17068
+ "-1": "A feeling of being slightly left out of something small.",
17069
+ "1": "A feeling of being part of something small.",
17070
+ "2": "Makes the person part of a group in this domain.",
17071
+ "3": "Makes the person part of a group that matters deeply to who they are."
17072
+ },
17073
+ "self-transcendence": {
17074
+ "-3": "Works against something larger than the person themselves.",
17075
+ "-2": "Harms others in a meaningful way.",
17076
+ "-1": "Does a small harm to others.",
17077
+ "1": "Does a small good for others.",
17078
+ "2": "Helps others in a meaningful way.",
17079
+ "3": "Contributes to something larger than the person themselves."
17080
+ }
17081
+ };
17082
+ var VALUE_REACH_LADDERS = Object.freeze(
17083
+ Object.fromEntries(Object.entries(LADDERS).map(([id, ladder]) => [id, Object.freeze(ladder)]))
17084
+ );
17085
+
16835
17086
  // ../schema/src/weighing.ts
16836
17087
  var SCORER_KINDS = ["human", "agent", "rule"];
16837
17088
  var STORED_SCORER_KINDS = ["human", "agent"];
@@ -16839,6 +17090,10 @@ function scorerRank(kind) {
16839
17090
  const index = SCORER_KINDS.indexOf(kind);
16840
17091
  return index === -1 ? 0 : SCORER_KINDS.length - index;
16841
17092
  }
17093
+ var WEIGHING_PROBABILITY_FIELDS = ["p_serves", "p_costs"];
17094
+ function isWeighingProbability(value) {
17095
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
17096
+ }
16842
17097
  var WEIGHING_ASSESSMENT_RECORDED = "weighing.assessment.recorded";
16843
17098
  var WEIGHING_SET_SAVED = "weighing.set.saved";
16844
17099
  function cellKey(matrix, subject, criterion) {
@@ -16878,10 +17133,20 @@ function deepFreeze(value) {
16878
17133
  return value;
16879
17134
  }
16880
17135
  var VALUE_SET_ID = "value-contribution";
16881
- var VALUE_SET_VERSION = "1.0.0";
17136
+ var VALUE_SET_VERSION = "2.0.0";
17137
+ var VALUE_SET_V1_VERSION = "1.0.0";
16882
17138
  var VALUE_MATRIX_ID = "value";
16883
17139
  var POSITIONING_SET_ID = "positioning";
16884
17140
  var VALUE_SCALE_ANCHORS = {
17141
+ "3": "Life-wide. It gives the person this well beyond the product and its domain, in their life.",
17142
+ "2": "Across the domain. The person gets this in the whole area the product belongs to, not only inside it.",
17143
+ "1": "Within the product. A real contribution, felt while using it.",
17144
+ "0": "Unrelated: weighed and found to have nothing to do with it. (No row means nobody has weighed it yet.)",
17145
+ "-1": "Within the product. A small cost, felt while using it.",
17146
+ "-2": "Across the domain. The person notices the loss of this in the whole area the product belongs to.",
17147
+ "-3": "Life-wide. It leaves the person with the opposite of this in their life."
17148
+ };
17149
+ var VALUE_SCALE_V1_ANCHORS = {
16885
17150
  "3": "Core. The promise exists for this; take it away and the value goes.",
16886
17151
  "2": "Supports clearly. The user would notice it missing.",
16887
17152
  "1": "Touches. A side effect of the promise, not its purpose.",
@@ -16929,13 +17194,36 @@ var VALUE_TEXT = {
16929
17194
  "self-transcendence": { name: "Self-transcendence", definition: "Helps beyond the user themselves." }
16930
17195
  };
16931
17196
  var VALUE_SCALE = { min: -3, max: 3, anchors: { ...VALUE_SCALE_ANCHORS } };
17197
+ var GROUPS = Object.keys(TIER_TITLES).map((id) => ({ id, title: TIER_TITLES[id] }));
17198
+ function reachQuestion(id) {
17199
+ if (id === "informs") {
17200
+ 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?";
17201
+ }
17202
+ 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?`;
17203
+ }
16932
17204
  var VALUE_CONTRIBUTION_SET = deepFreeze({
16933
17205
  id: VALUE_SET_ID,
16934
17206
  version: VALUE_SET_VERSION,
16935
17207
  title: "Elements of value",
16936
17208
  subject: "acceptance",
16937
17209
  scale: VALUE_SCALE,
16938
- groups: Object.keys(TIER_TITLES).map((id) => ({ id, title: TIER_TITLES[id] })),
17210
+ groups: GROUPS,
17211
+ criteria: VALUE_IDS.map((id) => ({
17212
+ id,
17213
+ group: VALUE_TIERS[id],
17214
+ name: VALUE_TEXT[id].name,
17215
+ question: reachQuestion(id),
17216
+ definition: VALUE_TEXT[id].definition,
17217
+ anchors: { ...VALUE_REACH_LADDERS[id] }
17218
+ }))
17219
+ });
17220
+ var VALUE_CONTRIBUTION_SET_V1 = deepFreeze({
17221
+ id: VALUE_SET_ID,
17222
+ version: VALUE_SET_V1_VERSION,
17223
+ title: "Elements of value",
17224
+ subject: "acceptance",
17225
+ scale: { min: -3, max: 3, anchors: { ...VALUE_SCALE_V1_ANCHORS } },
17226
+ groups: GROUPS,
16939
17227
  criteria: VALUE_IDS.map((id) => ({
16940
17228
  id,
16941
17229
  group: VALUE_TIERS[id],
@@ -16947,12 +17235,12 @@ var VALUE_CONTRIBUTION_SET = deepFreeze({
16947
17235
  var VALUE_MATRIX = deepFreeze({
16948
17236
  id: VALUE_MATRIX_ID,
16949
17237
  title: "Value",
16950
- set: `${VALUE_SET_ID}@1`,
17238
+ set: `${VALUE_SET_ID}@2`,
16951
17239
  subjects: { kind: "query", species: "acceptance" },
16952
17240
  positioning: POSITIONING_SET_ID,
16953
17241
  status: "active"
16954
17242
  });
16955
- var BUILT_IN_SETS = [VALUE_CONTRIBUTION_SET];
17243
+ var BUILT_IN_SETS = [VALUE_CONTRIBUTION_SET, VALUE_CONTRIBUTION_SET_V1];
16956
17244
  var BUILT_IN_MATRICES = [VALUE_MATRIX];
16957
17245
  var isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
16958
17246
  function cleaned(set2) {
@@ -16979,22 +17267,27 @@ function resolveWeighing(section) {
16979
17267
  const sets = [...BUILT_IN_SETS];
16980
17268
  const matrices = [...BUILT_IN_MATRICES];
16981
17269
  const skipped = [];
16982
- const idOf2 = (entry) => isObject2(entry) ? { ...typeof entry.id === "string" ? { id: entry.id } : {}, ...typeof entry.role === "string" ? { role: entry.role } : {} } : {};
17270
+ const idOf3 = (entry) => isObject2(entry) ? { ...typeof entry.id === "string" ? { id: entry.id } : {}, ...typeof entry.role === "string" ? { role: entry.role } : {} } : {};
16983
17271
  (Array.isArray(section?.sets) ? section.sets : []).forEach((set2, index) => {
16984
17272
  if (isWeighingSetShape(set2) && !sets.some((s) => s.id === set2.id)) sets.push(cleaned(set2));
16985
- else skipped.push({ kind: "set", ...idOf2(set2), index });
17273
+ else skipped.push({ kind: "set", ...idOf3(set2), index });
16986
17274
  });
16987
17275
  (Array.isArray(section?.matrices) ? section.matrices : []).forEach((matrix, index) => {
16988
17276
  if (isWeighingMatrixShape(matrix) && !matrices.some((m) => m.id === matrix.id)) matrices.push(matrix);
16989
- else skipped.push({ kind: "matrix", ...idOf2(matrix), index });
17277
+ else skipped.push({ kind: "matrix", ...idOf3(matrix), index });
16990
17278
  });
16991
17279
  return { sets, matrices, skipped };
16992
17280
  }
16993
17281
  function setOfRef(resolved, ref) {
16994
17282
  const { id, major } = splitSetRef(ref);
16995
- const set2 = resolved.sets.find((candidate) => candidate.id === id);
16996
- if (set2 === void 0) return void 0;
16997
- return major === void 0 || majorOf(set2.version) === major ? set2 : void 0;
17283
+ return resolved.sets.find((candidate) => candidate.id === id && (major === void 0 || majorOf(candidate.version) === major));
17284
+ }
17285
+ function isOlderMajorRef(resolved, ref) {
17286
+ const { id, major } = splitSetRef(ref);
17287
+ const current = resolved.sets.find((candidate) => candidate.id === id);
17288
+ if (current === void 0 || major === void 0) return false;
17289
+ const now = Number(majorOf(current.version));
17290
+ return Number.isFinite(now) && Number(major) < now;
16998
17291
  }
16999
17292
 
17000
17293
  // ../schema/src/weighing-validate.ts
@@ -17078,9 +17371,11 @@ function validateWeighingSection(section, nodeSpecies, journal) {
17078
17371
  if (entry.role === "positioning") {
17079
17372
  const ruler = typeof entry.extends === "string" ? resolveRef2(entry.extends, `${path6}.extends`, `Positioning "${String(entry.id)}"`, "weighing-positioning-unknown-ruler") : void 0;
17080
17373
  if (typeof entry.extends !== "string") {
17081
- warn(`${path6}.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@1`);
17374
+ warn(`${path6}.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`);
17082
17375
  } else if (ruler !== void 0 && ruler.role === "positioning") {
17083
- warn(`${path6}.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@1`);
17376
+ warn(`${path6}.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`);
17377
+ } else if (ruler !== void 0 && isOlderMajorRef(resolved, entry.extends)) {
17378
+ warn(`${path6}.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`);
17084
17379
  }
17085
17380
  const known = new Set(ruler !== void 0 && ruler.role !== "positioning" ? ruler.criteria.map((criterion) => criterion?.id) : []);
17086
17381
  (Array.isArray(entry.criteria) ? entry.criteria : []).forEach((criterion, at2) => {
@@ -17116,7 +17411,9 @@ function validateWeighingSection(section, nodeSpecies, journal) {
17116
17411
  }
17117
17412
  }
17118
17413
  checkStatus(path6, who, entry);
17119
- if (wellFormed) resolveRef2(entry.set, `${path6}.set`, who, "weighing-unknown-set");
17414
+ if (wellFormed && resolveRef2(entry.set, `${path6}.set`, who, "weighing-unknown-set") !== void 0 && isOlderMajorRef(resolved, entry.set)) {
17415
+ warn(`${path6}.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`);
17416
+ }
17120
17417
  });
17121
17418
  const seenCells = /* @__PURE__ */ new Set();
17122
17419
  assessments.forEach((entry, index) => {
@@ -17171,6 +17468,11 @@ function validateWeighingSection(section, nodeSpecies, journal) {
17171
17468
  } else if ((entry.confidence === 2 || entry.confidence === 3) && (entry.evidence === void 0 || entry.evidence.trim() === "")) {
17172
17469
  warn(`${path6}.evidence`, "weighing-no-evidence", `${label}: confidence ${String(entry.confidence)} claims evidence and cites none`);
17173
17470
  }
17471
+ for (const field of WEIGHING_PROBABILITY_FIELDS) {
17472
+ if (entry[field] !== void 0 && !isWeighingProbability(entry[field])) {
17473
+ warn(`${path6}.${field}`, "weighing-probability-shape", `${label}: ${field} must be a number from 0 to 1 \u2014 it is ignored`);
17474
+ }
17475
+ }
17174
17476
  if (entry.refs !== void 0 && !(Array.isArray(entry.refs) && entry.refs.every((ref) => typeof ref === "string"))) {
17175
17477
  warn(`${path6}.refs`, "weighing-refs-type", `${label}: refs must be an array of id strings`);
17176
17478
  }
@@ -19590,8 +19892,64 @@ function burndownSummary(burndown, openNow) {
19590
19892
  return `${closed} closed${where2} (${tally.resolved} resolved, ${tally.accepted} accepted) \xB7 ${tally.opened} opened \xB7 ${open} open`;
19591
19893
  }
19592
19894
 
19895
+ // ../schema/src/weighing-events.ts
19896
+ var asArray2 = (value) => Array.isArray(value) ? value : [];
19897
+ function timeOf(ts) {
19898
+ const time3 = typeof ts === "string" ? Date.parse(ts) : Number.NaN;
19899
+ return Number.isNaN(time3) ? Number.NEGATIVE_INFINITY : time3;
19900
+ }
19901
+ function assessmentOfEvent(event) {
19902
+ const e = event;
19903
+ const scorer = e.scorer;
19904
+ if (typeof e.matrix !== "string" || e.matrix === "" || typeof e.subject !== "string" || e.subject === "" || typeof e.criterion !== "string" || e.criterion === "" || typeof e.level !== "number" || !Number.isInteger(e.level) || typeof e.confidence !== "number" || typeof e.ts !== "string" || e.ts === "" || typeof scorer !== "object" || scorer === null || typeof scorer.kind !== "string" || // A `rule` row is computed on read and never stored (D3): an event claiming to be one is skipped,
19905
+ // whoever appended it, so a seed can never be forged into a stored cell.
19906
+ scorer.kind === "rule" || typeof scorer.id !== "string") {
19907
+ return void 0;
19908
+ }
19909
+ const { id: _id, actor: _actor, type: _type, v: _v, ...rest } = e;
19910
+ void _id;
19911
+ void _actor;
19912
+ void _type;
19913
+ void _v;
19914
+ return rest;
19915
+ }
19916
+ function foldWeighingEvents(section, events) {
19917
+ const relevant = events.filter((event) => event?.type === WEIGHING_ASSESSMENT_RECORDED || event?.type === WEIGHING_SET_SAVED);
19918
+ if (relevant.length === 0) return section;
19919
+ const assessments = [...asArray2(section?.assessments)];
19920
+ const setTimes = /* @__PURE__ */ new Map();
19921
+ let sets = asArray2(section?.sets);
19922
+ for (const event of relevant) {
19923
+ if (event.type === WEIGHING_ASSESSMENT_RECORDED) {
19924
+ const row = assessmentOfEvent(event);
19925
+ if (row === void 0) continue;
19926
+ const key = assessmentKey(row);
19927
+ const at3 = assessments.findIndex((existing) => assessmentKey(existing) === key);
19928
+ if (at3 === -1) assessments.push(row);
19929
+ else if (timeOf(row.ts) >= timeOf(assessments[at3]?.ts)) assessments[at3] = row;
19930
+ continue;
19931
+ }
19932
+ const set2 = event.set;
19933
+ if (typeof set2 !== "object" || set2 === null || Array.isArray(set2)) continue;
19934
+ const id = set2.id;
19935
+ if (typeof id !== "string" || id === "") continue;
19936
+ const at2 = sets.findIndex((existing) => existing?.id === id);
19937
+ const time3 = timeOf(event.ts);
19938
+ if (at2 === -1) {
19939
+ sets = [...sets, set2];
19940
+ setTimes.set(id, time3);
19941
+ } else {
19942
+ const known = setTimes.get(id);
19943
+ if (known !== void 0 && time3 < known) continue;
19944
+ sets = sets.map((existing, i) => i === at2 ? set2 : existing);
19945
+ setTimes.set(id, time3);
19946
+ }
19947
+ }
19948
+ return { ...section ?? {}, sets, matrices: asArray2(section?.matrices), assessments };
19949
+ }
19950
+
19593
19951
  // ../schema/src/weighing-derive.ts
19594
- var SEED_SCORER_ID = "seed-by-claim-order";
19952
+ var SEED_SCORER_ID = "seed-claimed";
19595
19953
  var SEED_SCORER = Object.freeze({ kind: "rule", id: SEED_SCORER_ID });
19596
19954
 
19597
19955
  // src/commands/init.ts
@@ -22696,19 +23054,249 @@ function runShotCli(argv) {
22696
23054
  // src/commands/restore.ts
22697
23055
  import { existsSync as existsSync11, linkSync, mkdirSync as mkdirSync6, readFileSync as readFileSync11, unlinkSync, writeFileSync as writeFileSync10 } from "node:fs";
22698
23056
  import { join as join11, resolve as resolve11 } from "node:path";
23057
+
23058
+ // src/lib/restore-merge.ts
23059
+ var RESTORE_ACTOR = "arkaik-restore";
23060
+ var isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
23061
+ var asArray3 = (value) => Array.isArray(value) ? value : [];
23062
+ var str2 = (value) => typeof value === "string" ? value : void 0;
23063
+ var idOf2 = (item) => isRecord7(item) ? str2(item.id) : void 0;
23064
+ var winTime = (ts) => {
23065
+ const t = typeof ts === "string" ? Date.parse(ts) : NaN;
23066
+ return Number.isNaN(t) ? Number.NEGATIVE_INFINITY : t;
23067
+ };
23068
+ function sameJson(a, b) {
23069
+ if (a === b) return true;
23070
+ if (Array.isArray(a) || Array.isArray(b)) {
23071
+ return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, i) => sameJson(item, b[i]));
23072
+ }
23073
+ if (!isRecord7(a) || !isRecord7(b)) return false;
23074
+ const keys = Object.keys(a);
23075
+ return keys.length === Object.keys(b).length && keys.every((key) => key in b && sameJson(a[key], b[key]));
23076
+ }
23077
+ function unionById(primary, secondary) {
23078
+ const seen = /* @__PURE__ */ new Set();
23079
+ for (const item of primary) {
23080
+ const id = idOf2(item);
23081
+ if (id !== void 0) seen.add(id);
23082
+ }
23083
+ const merged = [...primary];
23084
+ const added = [];
23085
+ for (const item of secondary) {
23086
+ const id = idOf2(item);
23087
+ if (id !== void 0 && seen.has(id)) continue;
23088
+ if (id !== void 0) seen.add(id);
23089
+ merged.push(item);
23090
+ added.push(item);
23091
+ }
23092
+ return { merged, added };
23093
+ }
23094
+ var isIdList = (value) => Array.isArray(value) && value.every((item) => idOf2(item) !== void 0);
23095
+ function mergeMetadata(hosted, local) {
23096
+ const metadata = { ...hosted, ...local };
23097
+ const kept = [];
23098
+ for (const key of Object.keys(hosted)) {
23099
+ if (!(key in local)) {
23100
+ kept.push(key);
23101
+ continue;
23102
+ }
23103
+ const h = hosted[key];
23104
+ const l = local[key];
23105
+ if (isIdList(h) && isIdList(l)) {
23106
+ const union2 = unionById(l, h);
23107
+ metadata[key] = union2.merged;
23108
+ if (union2.added.length > 0) kept.push(key);
23109
+ } else if (isRecord7(h) && isRecord7(l)) {
23110
+ metadata[key] = { ...h, ...l };
23111
+ if (Object.keys(h).some((inner) => !(inner in l))) kept.push(key);
23112
+ }
23113
+ }
23114
+ return { metadata, kept: kept.sort() };
23115
+ }
23116
+ function reconcileStatuses(nodes, journal, localEventIds) {
23117
+ const lastStatus = /* @__PURE__ */ new Map();
23118
+ const lastDecision = /* @__PURE__ */ new Map();
23119
+ for (const event of journal) {
23120
+ if (!isRecord7(event)) continue;
23121
+ const nodeId = str2(event.node_id);
23122
+ if (nodeId === void 0 || str2(event.to) === void 0) continue;
23123
+ if (event.type === "node.status_changed" && event.platform === void 0) lastStatus.set(nodeId, event);
23124
+ else if (event.type === "decision.status_changed") lastDecision.set(nodeId, event);
23125
+ }
23126
+ const hostedOnly = (event) => {
23127
+ const id = event === void 0 ? void 0 : str2(event.id);
23128
+ return id !== void 0 && !localEventIds.has(id);
23129
+ };
23130
+ const changed = /* @__PURE__ */ new Set();
23131
+ nodes.forEach((node, index) => {
23132
+ const id = idOf2(node);
23133
+ if (id === void 0 || !isRecord7(node)) return;
23134
+ let next = node;
23135
+ const status = lastStatus.get(id);
23136
+ if (hostedOnly(status) && next.status !== status.to) next = { ...next, status: status.to };
23137
+ const decision = lastDecision.get(id);
23138
+ if (hostedOnly(decision)) {
23139
+ const metadata = isRecord7(next.metadata) ? next.metadata : {};
23140
+ if (metadata.decision_status !== decision.to) next = { ...next, metadata: { ...metadata, decision_status: decision.to } };
23141
+ }
23142
+ if (next !== node) {
23143
+ nodes[index] = next;
23144
+ changed.add(id);
23145
+ }
23146
+ });
23147
+ return [...changed].sort();
23148
+ }
23149
+ function mergeWeighing(hosted, local) {
23150
+ if (!isRecord7(hosted)) return { weighing: isRecord7(local) ? local : void 0, kept: 0 };
23151
+ if (!isRecord7(local)) {
23152
+ const kept = asArray3(hosted.sets).length + asArray3(hosted.matrices).length + asArray3(hosted.assessments).length;
23153
+ return { weighing: hosted, kept };
23154
+ }
23155
+ const sets = unionById(asArray3(local.sets), asArray3(hosted.sets));
23156
+ const matrices = unionById(asArray3(local.matrices), asArray3(hosted.matrices));
23157
+ const assessments = [...asArray3(local.assessments)];
23158
+ let keptAssessments = 0;
23159
+ const keyOf = (row) => isRecord7(row) ? assessmentKey(row) : void 0;
23160
+ for (const row of asArray3(hosted.assessments)) {
23161
+ const key = keyOf(row);
23162
+ const at2 = key === void 0 ? -1 : assessments.findIndex((existing) => keyOf(existing) === key);
23163
+ if (at2 === -1) {
23164
+ assessments.push(row);
23165
+ keptAssessments++;
23166
+ } else if (winTime(row.ts) > winTime(assessments[at2].ts)) {
23167
+ assessments[at2] = row;
23168
+ keptAssessments++;
23169
+ }
23170
+ }
23171
+ const weighing = { ...hosted, ...local };
23172
+ if (sets.merged.length > 0 || "sets" in local || "sets" in hosted) weighing.sets = sets.merged;
23173
+ if (matrices.merged.length > 0 || "matrices" in local || "matrices" in hosted) weighing.matrices = matrices.merged;
23174
+ if (assessments.length > 0 || "assessments" in local || "assessments" in hosted) weighing.assessments = assessments;
23175
+ return { weighing, kept: sets.added.length + matrices.added.length + keptAssessments };
23176
+ }
23177
+ function resaveLocalSets(hostedWeighing, hostedJournal, localWeighing, now) {
23178
+ if (!isRecord7(localWeighing)) return [];
23179
+ const savedOnHost = /* @__PURE__ */ new Set();
23180
+ for (const event of hostedJournal) {
23181
+ if (isRecord7(event) && event.type === WEIGHING_SET_SAVED && isRecord7(event.set)) {
23182
+ const id = str2(event.set.id);
23183
+ if (id !== void 0) savedOnHost.add(id);
23184
+ }
23185
+ }
23186
+ if (savedOnHost.size === 0) return [];
23187
+ const hostedReading = foldWeighingEvents(
23188
+ isRecord7(hostedWeighing) ? hostedWeighing : void 0,
23189
+ hostedJournal.filter(isRecord7)
23190
+ );
23191
+ const events = [];
23192
+ for (const set2 of asArray3(localWeighing.sets)) {
23193
+ const id = idOf2(set2);
23194
+ if (id === void 0 || !savedOnHost.has(id)) continue;
23195
+ const onHost = asArray3(hostedReading?.sets).find((existing) => idOf2(existing) === id);
23196
+ if (sameJson(onHost, set2)) continue;
23197
+ events.push(makeEvent(WEIGHING_SET_SAVED, { set: set2 }, { actor: RESTORE_ACTOR, ts: now }));
23198
+ }
23199
+ return events;
23200
+ }
23201
+ function mergeForAppend(hosted, local, now = /* @__PURE__ */ new Date()) {
23202
+ const bundle = { ...hosted, ...local };
23203
+ let metadataKeys = [];
23204
+ if (isRecord7(hosted.project) || isRecord7(local.project)) {
23205
+ const hostedProject = isRecord7(hosted.project) ? hosted.project : {};
23206
+ const localProject = isRecord7(local.project) ? local.project : {};
23207
+ const project = { ...hostedProject, ...localProject };
23208
+ if (isRecord7(hostedProject.metadata)) {
23209
+ const merged = mergeMetadata(hostedProject.metadata, isRecord7(localProject.metadata) ? localProject.metadata : {});
23210
+ project.metadata = merged.metadata;
23211
+ metadataKeys = merged.kept;
23212
+ }
23213
+ bundle.project = project;
23214
+ }
23215
+ const localProjectId = isRecord7(local.project) ? str2(local.project.id) : void 0;
23216
+ const hostedProjectId = isRecord7(hosted.project) ? str2(hosted.project.id) : void 0;
23217
+ const restamp = (item) => localProjectId !== void 0 && localProjectId !== hostedProjectId && isRecord7(item) && item.project_id === hostedProjectId ? { ...item, project_id: localProjectId } : item;
23218
+ const nodes = unionById(asArray3(local.nodes), asArray3(hosted.nodes).map(restamp));
23219
+ const edges = unionById(asArray3(local.edges), asArray3(hosted.edges).map(restamp));
23220
+ const hostedJournal = asArray3(hosted.journal);
23221
+ const localJournal = asArray3(local.journal);
23222
+ const localEventIds = new Set(localJournal.map(idOf2).filter((id) => id !== void 0));
23223
+ const hostedEventIds = new Set(hostedJournal.map(idOf2).filter((id) => id !== void 0));
23224
+ const resaved = resaveLocalSets(hosted.weighing, hostedJournal, local.weighing, now);
23225
+ const journal = orderEvents(unionById([...hostedJournal, ...resaved], localJournal).merged);
23226
+ bundle.journal = journal;
23227
+ const eventsKept = [...hostedEventIds].filter((id) => !localEventIds.has(id)).length;
23228
+ const statuses = reconcileStatuses(nodes.merged, journal, localEventIds);
23229
+ bundle.nodes = nodes.merged;
23230
+ bundle.edges = edges.merged;
23231
+ let qualityKept = false;
23232
+ if (isQualitySection(local.quality)) bundle.quality = local.quality;
23233
+ else if (isQualitySection(hosted.quality)) {
23234
+ bundle.quality = hosted.quality;
23235
+ qualityKept = true;
23236
+ } else delete bundle.quality;
23237
+ const weighing = mergeWeighing(hosted.weighing, local.weighing);
23238
+ if (weighing.weighing === void 0) delete bundle.weighing;
23239
+ else bundle.weighing = weighing.weighing;
23240
+ return {
23241
+ bundle,
23242
+ kept: {
23243
+ nodes: nodes.added.length,
23244
+ edges: edges.added.length,
23245
+ events: eventsKept,
23246
+ metadataKeys,
23247
+ statuses,
23248
+ qualityKept,
23249
+ weighingRows: weighing.kept,
23250
+ setsResaved: resaved.map((event) => String(event.set.id))
23251
+ }
23252
+ };
23253
+ }
23254
+ function describeAppendSummary(kept) {
23255
+ const parts = [];
23256
+ const n = (count, one, many = `${one}s`) => `${count} ${count === 1 ? one : many}`;
23257
+ if (kept.nodes > 0) parts.push(n(kept.nodes, "node"));
23258
+ if (kept.edges > 0) parts.push(n(kept.edges, "edge"));
23259
+ if (kept.events > 0) parts.push(n(kept.events, "journal event"));
23260
+ if (kept.metadataKeys.length > 0) parts.push(`project settings (${kept.metadataKeys.join(", ")})`);
23261
+ if (kept.qualityKept) parts.push("the quality section");
23262
+ if (kept.weighingRows > 0) parts.push(n(kept.weighingRows, "weighing row"));
23263
+ const lines = [
23264
+ parts.length === 0 ? "Append: the hosted project held nothing your bundle lacks." : `Append: kept what only the hosted project had \u2014 ${parts.join(", ")}.`
23265
+ ];
23266
+ if (kept.statuses.length > 0) {
23267
+ lines.push(` Took the hosted status of ${kept.statuses.join(", ")}: it was changed on the hosted project after your copy.`);
23268
+ }
23269
+ if (kept.setsResaved.length > 0) {
23270
+ lines.push(` Re-saved criteria set ${kept.setsResaved.join(", ")} from your bundle, so it replaces the hosted version.`);
23271
+ }
23272
+ return lines.join("\n");
23273
+ }
23274
+
23275
+ // src/commands/restore.ts
22699
23276
  var LINK_FILE4 = "docs/arkaik/arkaik.json";
22700
23277
  var DEFAULT_BUNDLE_PATH10 = "docs/arkaik/bundle.json";
22701
23278
  var DEFAULT_API_BASE2 = "https://arkaik.app";
22702
23279
  var USAGE13 = `arkaik restore [options] [path]
22703
23280
 
22704
- Replace the linked hosted project's bundle, journal AND quality section with
22705
- a local bundle \u2014
22706
- the landing step for a bootstrapped map. Before sending anything, this
22707
- exports the CURRENT hosted state (snapshot + journal) to
22708
- docs/arkaik/.backups/<timestamp>-bundle.json (next to the link file \u2014 not
22709
- wherever the local bundle happens to live) and refuses to proceed if that
22710
- backup cannot be written \u2014 the server keeps no pre-image, so this file is the
22711
- only way back if the restore turns out to be wrong.
23281
+ Land a local bundle on the linked hosted project \u2014 the landing step for a
23282
+ bootstrapped map.
23283
+
23284
+ By default this APPENDS: the local bundle is merged into what the hosted
23285
+ project already holds. Hosted-only events, nodes, edges, project settings,
23286
+ quality and weighing state are all kept; where both sides hold the same id,
23287
+ the local record wins, except a status changed on the hosted project after
23288
+ your copy. Nothing on the hosted project is removed.
23289
+
23290
+ --replace swaps the hosted bundle, journal and sections for the local ones
23291
+ wholesale, removing whatever the local bundle lacks. That is what undoing a
23292
+ restore from a backup needs, and it refuses any loss you have not allowed
23293
+ with an --allow-* flag.
23294
+
23295
+ Before a real run sends anything, this exports the CURRENT hosted state
23296
+ (snapshot + journal) to docs/arkaik/.backups/<timestamp>-bundle.json (next to
23297
+ the link file \u2014 not wherever the local bundle happens to live) and refuses to
23298
+ proceed if that backup cannot be written \u2014 the server keeps no pre-image, so
23299
+ this file is the only way back if the restore turns out to be wrong.
22712
23300
 
22713
23301
  Arguments:
22714
23302
  path Path to the local bundle JSON file
@@ -22722,6 +23310,14 @@ Options:
22722
23310
  the delta. Sends nothing destructive and takes no
22723
23311
  backup (there is nothing to protect against in this
22724
23312
  mode).
23313
+ --replace Replace the hosted project wholesale instead of
23314
+ appending to it. Anything the local bundle lacks is
23315
+ removed, so each kind of loss below refuses unless its
23316
+ --allow-* flag is passed too. Undo a restore with
23317
+ the command a real restore prints (--replace with
23318
+ every --allow-* flag).
23319
+
23320
+ Only with --replace:
22725
23321
  --allow-history-loss Proceed even though the outbound journal has fewer
22726
23322
  events than the hosted one currently holds. Without
22727
23323
  this flag, that shrink refuses outright \u2014 it usually
@@ -22735,22 +23331,6 @@ Options:
22735
23331
  local copy (edited in the app), not an intended
22736
23332
  deletion. Undoing a restore from a backup is the
22737
23333
  common case where it IS intended.
22738
- --no-quality Do not send a quality section: skip the docs/quality/
22739
- fold AND drop any section the local bundle already
22740
- carries. Does NOT by itself permit erasing the hosted
22741
- one \u2014 that needs --allow-quality-loss too, because
22742
- "don't send mine" and "destroy theirs" are different
22743
- decisions and only one of them is irreversible.
22744
- --no-weighing Do not send a weighing section: skip the docs/weighing/
22745
- fold AND drop any section the local bundle already
22746
- carries. WARNING: a restore replaces the hosted
22747
- journal, and an assessment recorded only on the hosted
22748
- project lives in that journal. The history guard
22749
- compares COUNTS, so it does NOT reliably protect those
22750
- events: a repo whose journal is as long as the hosted
22751
- one passes it while still erasing them. The backup this
22752
- command writes first holds them; the proper fix is
22753
- issue #624 (restore appends by default).
22754
23334
  --allow-quality-loss Proceed even though the restore would erase a quality
22755
23335
  section the hosted project currently has. Without this
22756
23336
  flag, that refuses outright \u2014 it usually means
@@ -22762,6 +23342,24 @@ Options:
22762
23342
  refuses outright and names the keys \u2014 those settings
22763
23343
  are usually edited in the app and never reach the
22764
23344
  repo bundle, so a restore would silently delete them.
23345
+
23346
+ Either mode:
23347
+ --no-quality Do not send a quality section: skip the docs/quality/
23348
+ fold AND drop any section the local bundle already
23349
+ carries. An append keeps the hosted section. Under
23350
+ --replace this does NOT by itself permit erasing the
23351
+ hosted one \u2014 that needs --allow-quality-loss too,
23352
+ because "don't send mine" and "destroy theirs" are
23353
+ different decisions and only one is irreversible.
23354
+ --no-weighing Do not send a weighing section: skip the docs/weighing/
23355
+ fold AND drop any section the local bundle already
23356
+ carries. An append keeps the hosted section and every
23357
+ hosted assessment event. WARNING under --replace: an
23358
+ assessment recorded only on the hosted project lives in
23359
+ the journal that --replace overwrites, and the history
23360
+ guard compares COUNTS, so it does not reliably protect
23361
+ those events. The backup this command writes first
23362
+ holds them.
22765
23363
  --audit <id> Fold ONE audit's snapshot rather than merging every
22766
23364
  audit into current state. An id that is not on disk is
22767
23365
  an error, not an empty section.
@@ -22800,12 +23398,28 @@ function describeVersionReadFailure(status, baseUrl, projectId) {
22800
23398
  }
22801
23399
  function backupNoteFor(backupPath) {
22802
23400
  if (!backupPath) return "";
22803
- return ` Your pre-restore backup is at ${backupPath}. Undo this restore with: arkaik restore ${backupPath}`;
23401
+ return ` Your pre-restore backup is at ${backupPath}. Undo this restore with: ${undoCommandFor(backupPath)}`;
23402
+ }
23403
+ function undoCommandFor(backupPath) {
23404
+ return `arkaik restore --replace --allow-history-loss --allow-deletions --allow-quality-loss --allow-metadata-loss ${backupPath}`;
23405
+ }
23406
+ function allowFlagsOf(options) {
23407
+ return [
23408
+ options.allowHistoryLoss && "--allow-history-loss",
23409
+ options.allowDeletions && "--allow-deletions",
23410
+ options.allowQualityLoss && "--allow-quality-loss",
23411
+ options.allowMetadataLoss && "--allow-metadata-loss"
23412
+ ].filter((flag) => typeof flag === "string");
23413
+ }
23414
+ function describeAllowWithoutReplace(flags) {
23415
+ return `${flags.join(", ")} only ${flags.length === 1 ? "applies" : "apply"} with --replace. restore appends by default and removes nothing, so there is no loss to allow. To replace the hosted project (for example to undo a restore from a backup), add --replace.`;
22804
23416
  }
22805
23417
  async function interpretPutResponse(res, ctx) {
22806
23418
  const base = {
22807
23419
  ok: true,
22808
23420
  dryRun: ctx.dryRun,
23421
+ mode: ctx.mode,
23422
+ kept: ctx.kept,
22809
23423
  bundlePath: ctx.bundlePath,
22810
23424
  backupPath: ctx.backupPath,
22811
23425
  requestSent: true,
@@ -22959,10 +23573,34 @@ function describeMetadataLoss(dropped, bundlePath) {
22959
23573
  `Those settings are usually edited in the app and never reach the repo bundle. Copy them into the local bundle's project.metadata (GET .../export has them) so the restore keeps them, or re-run with --allow-metadata-loss if they really are meant to go.`
22960
23574
  ].join("\n");
22961
23575
  }
23576
+ async function fetchExport(httpClient, url2, headers, dryRun) {
23577
+ const why = dryRun ? "An append preview needs it to merge." : "Refusing to restore without a backup.";
23578
+ let exported;
23579
+ try {
23580
+ const exportRes = await httpClient(url2, { headers });
23581
+ if (!exportRes.ok) {
23582
+ return `Could not export the current hosted state (${exportRes.status}). ${why} Nothing was sent.`;
23583
+ }
23584
+ const body = await safeJson(exportRes);
23585
+ exported = body.bundle;
23586
+ } catch (e) {
23587
+ return `Could not export the current hosted state: ${e.message}. ${why}`;
23588
+ }
23589
+ if (typeof exported !== "object" || exported === null || Array.isArray(exported)) {
23590
+ return `The export response was not a bundle. ${why} Nothing was sent.`;
23591
+ }
23592
+ const bundle = exported;
23593
+ if (!Array.isArray(bundle.journal) || !Array.isArray(bundle.nodes) || !Array.isArray(bundle.edges)) {
23594
+ return dryRun ? "The exported bundle is missing nodes, edges, or a journal array, so there is nothing whole to merge into. Nothing was sent." : "The exported bundle is missing nodes, edges, or a journal array \u2014 an incomplete backup would not cover what restore is about to destroy. Refusing to restore. Nothing was sent.";
23595
+ }
23596
+ return bundle;
23597
+ }
22962
23598
  async function runRestore(options = {}) {
22963
23599
  const cwd = options.cwd ?? process.cwd();
22964
23600
  const env = options.env ?? process.env;
22965
23601
  const dryRun = options.dryRun ?? false;
23602
+ const replace = options.replace ?? false;
23603
+ const mode = replace ? "replace" : "append";
22966
23604
  const allowHistoryLoss = options.allowHistoryLoss ?? false;
22967
23605
  const allowDeletions = options.allowDeletions ?? false;
22968
23606
  const noQuality = options.noQuality ?? false;
@@ -22970,6 +23608,8 @@ async function runRestore(options = {}) {
22970
23608
  const allowQualityLoss = options.allowQualityLoss ?? false;
22971
23609
  const allowMetadataLoss = options.allowMetadataLoss ?? false;
22972
23610
  const httpClient = options.httpClient ?? DEFAULT_HTTP_CLIENT;
23611
+ const strayAllowFlags = allowFlagsOf(options);
23612
+ if (strayAllowFlags.length > 0 && !replace) return fatalResult5(dryRun, describeAllowWithoutReplace(strayAllowFlags));
22973
23613
  const linkPath = join11(cwd, LINK_FILE4);
22974
23614
  if (!existsSync11(linkPath)) {
22975
23615
  return fatalResult5(dryRun, `No ${LINK_FILE4}. Run \`arkaik link\` first \u2014 restore only targets hosted projects.`);
@@ -23041,7 +23681,25 @@ async function runRestore(options = {}) {
23041
23681
  return fatalResult5(dryRun, `Could not read the project: ${e.message}`);
23042
23682
  }
23043
23683
  const putHeaders = { ...headers, "Content-Type": "application/json", "If-Match": `"${version2}"` };
23044
- const putBody = JSON.stringify({ bundle: outboundBundle });
23684
+ let exportedBundle;
23685
+ if (!(replace && dryRun)) {
23686
+ const read = await fetchExport(httpClient, `${baseUrl}/api/graph/projects/${encodedProjectId}/export`, headers, dryRun);
23687
+ if (typeof read === "string") return fatalResult5(dryRun, read, qualityFields);
23688
+ exportedBundle = read;
23689
+ }
23690
+ let sendBundle = outboundBundle;
23691
+ let kept;
23692
+ if (!replace && exportedBundle !== void 0) {
23693
+ try {
23694
+ const merged = mergeForAppend(exportedBundle, outboundBundle);
23695
+ sendBundle = merged.bundle;
23696
+ kept = merged.kept;
23697
+ } catch (e) {
23698
+ return fatalResult5(dryRun, `Could not merge the local bundle into the hosted one: ${e.message}. Nothing was sent.`, qualityFields);
23699
+ }
23700
+ }
23701
+ const putBody = JSON.stringify({ bundle: sendBundle });
23702
+ const resultCtx = { dryRun, bundlePath, version: version2, mode, kept, ...qualityFields };
23045
23703
  if (dryRun) {
23046
23704
  let res2;
23047
23705
  try {
@@ -23051,51 +23709,36 @@ async function runRestore(options = {}) {
23051
23709
  body: putBody
23052
23710
  });
23053
23711
  } catch (e) {
23054
- return { ok: true, dryRun, bundlePath, requestSent: false, errorMessage: `Network error: ${e.message}` };
23712
+ return { ok: true, dryRun, mode, kept, bundlePath, requestSent: false, errorMessage: `Network error: ${e.message}` };
23055
23713
  }
23056
- return interpretPutResponse(res2, { dryRun, bundlePath, version: version2, ...qualityFields });
23057
- }
23058
- let exported;
23059
- try {
23060
- const exportRes = await httpClient(`${baseUrl}/api/graph/projects/${encodedProjectId}/export`, { headers });
23061
- if (!exportRes.ok) {
23062
- return fatalResult5(dryRun, `Could not export the current hosted state (${exportRes.status}). Refusing to restore without a backup. Nothing was sent.`);
23063
- }
23064
- const body = await safeJson(exportRes);
23065
- exported = body.bundle;
23066
- } catch (e) {
23067
- return fatalResult5(dryRun, `Could not export the current hosted state: ${e.message}. Refusing to restore without a backup.`);
23068
- }
23069
- if (typeof exported !== "object" || exported === null || Array.isArray(exported)) {
23070
- return fatalResult5(dryRun, "The export response was not a bundle. Refusing to restore without a backup. Nothing was sent.");
23071
- }
23072
- const exportedBundle = exported;
23073
- if (!Array.isArray(exportedBundle.journal) || !Array.isArray(exportedBundle.nodes) || !Array.isArray(exportedBundle.edges)) {
23074
- return fatalResult5(
23075
- dryRun,
23076
- "The exported bundle is missing nodes, edges, or a journal array \u2014 an incomplete backup would not cover what restore is about to destroy. Refusing to restore. Nothing was sent."
23077
- );
23078
- }
23079
- const hostedEventCount = exportedBundle.journal.length;
23080
- if (journalEvents.length < hostedEventCount && !allowHistoryLoss) {
23081
- return fatalResult5(
23082
- dryRun,
23083
- `This restore would replace ${hostedEventCount} hosted journal events with ${journalEvents.length}. Nothing was sent. If that is intended, re-run with --allow-history-loss; otherwise check that ${journalPathFor(bundlePath)} exists and is current.`,
23084
- qualityFields
23085
- );
23714
+ return interpretPutResponse(res2, resultCtx);
23086
23715
  }
23087
- const hostedQuality = exportedBundle.quality;
23088
- if (isQualitySection(hostedQuality) && !isQualitySection(outboundBundle.quality) && !allowQualityLoss) {
23089
- return fatalResult5(dryRun, describeQualityLoss(hostedQuality, qualityRoot, noQuality, qualityNotice), qualityFields);
23716
+ if (exportedBundle === void 0) {
23717
+ return fatalResult5(dryRun, "Internal error: no hosted export in hand for a real restore. Nothing was sent.", qualityFields);
23090
23718
  }
23091
- const droppedKeys = droppedMetadataKeys(exportedBundle.project, outboundBundle.project);
23092
- if (droppedKeys.length > 0 && !allowMetadataLoss) {
23093
- return fatalResult5(dryRun, describeMetadataLoss(droppedKeys, bundlePath), qualityFields);
23094
- }
23095
- const removedNodes = removedIds(exportedBundle.nodes, Array.isArray(local.nodes) ? local.nodes : []);
23096
- const removedEdges = removedIds(exportedBundle.edges, Array.isArray(local.edges) ? local.edges : []);
23097
- if ((removedNodes.length > 0 || removedEdges.length > 0) && !allowDeletions) {
23098
- return fatalResult5(dryRun, describeDeletions(removedNodes, removedEdges, bundlePath), qualityFields);
23719
+ const exported = exportedBundle;
23720
+ if (replace) {
23721
+ const hostedEventCount = exported.journal.length;
23722
+ if (journalEvents.length < hostedEventCount && !allowHistoryLoss) {
23723
+ return fatalResult5(
23724
+ dryRun,
23725
+ `This restore would replace ${hostedEventCount} hosted journal events with ${journalEvents.length}. Nothing was sent. If that is intended, re-run with --allow-history-loss; otherwise check that ${journalPathFor(bundlePath)} exists and is current.`,
23726
+ qualityFields
23727
+ );
23728
+ }
23729
+ const hostedQuality = exported.quality;
23730
+ if (isQualitySection(hostedQuality) && !isQualitySection(outboundBundle.quality) && !allowQualityLoss) {
23731
+ return fatalResult5(dryRun, describeQualityLoss(hostedQuality, qualityRoot, noQuality, qualityNotice), qualityFields);
23732
+ }
23733
+ const droppedKeys = droppedMetadataKeys(exported.project, outboundBundle.project);
23734
+ if (droppedKeys.length > 0 && !allowMetadataLoss) {
23735
+ return fatalResult5(dryRun, describeMetadataLoss(droppedKeys, bundlePath), qualityFields);
23736
+ }
23737
+ const removedNodes = removedIds(exported.nodes, Array.isArray(local.nodes) ? local.nodes : []);
23738
+ const removedEdges = removedIds(exported.edges, Array.isArray(local.edges) ? local.edges : []);
23739
+ if ((removedNodes.length > 0 || removedEdges.length > 0) && !allowDeletions) {
23740
+ return fatalResult5(dryRun, describeDeletions(removedNodes, removedEdges, bundlePath), qualityFields);
23741
+ }
23099
23742
  }
23100
23743
  const backupDir = join11(cwd, "docs", "arkaik", ".backups");
23101
23744
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
@@ -23125,13 +23768,15 @@ Refusing to restore \u2014 this verb replaces the hosted project's snapshot AND
23125
23768
  return {
23126
23769
  ok: true,
23127
23770
  dryRun,
23771
+ mode,
23772
+ kept,
23128
23773
  bundlePath,
23129
23774
  backupPath,
23130
23775
  requestSent: false,
23131
23776
  errorMessage: `Network error: ${e.message}. Nothing was sent.${backupNoteFor(backupPath)}`
23132
23777
  };
23133
23778
  }
23134
- return interpretPutResponse(res, { dryRun, bundlePath, backupPath, version: version2, ...qualityFields });
23779
+ return interpretPutResponse(res, { ...resultCtx, backupPath });
23135
23780
  }
23136
23781
  function printDelta(delta) {
23137
23782
  if (!delta) return;
@@ -23165,6 +23810,9 @@ function reportRestore(result) {
23165
23810
  if (result.qualityNotice !== void 0) {
23166
23811
  console.log(result.qualityNotice);
23167
23812
  }
23813
+ if (result.kept !== void 0) {
23814
+ console.log(describeAppendSummary(result.kept));
23815
+ }
23168
23816
  if (!result.requestSent) {
23169
23817
  console.error(result.errorMessage ?? "Restore failed before a request could be sent.");
23170
23818
  process.exit(1);
@@ -23174,13 +23822,13 @@ function reportRestore(result) {
23174
23822
  console.log("[dry-run] server preview \u2014 nothing was written:");
23175
23823
  printDelta(result.delta);
23176
23824
  console.log(
23177
- "Re-run without --dry-run to apply \u2014 that run takes the backup, and only that run checks the history, deletion, quality-loss and metadata-loss guards (all four read the export, which a dry run never fetches)."
23825
+ result.mode === "replace" ? "Re-run without --dry-run to apply \u2014 that run takes the backup, and only that run checks the history, deletion, quality-loss and metadata-loss guards (all four read the export, which a dry run never fetches)." : "Re-run without --dry-run to apply \u2014 that run takes the backup first."
23178
23826
  );
23179
23827
  } else {
23180
23828
  console.log(`Restored. New version ${result.version}.`);
23181
23829
  printDelta(result.delta);
23182
23830
  if (result.backupPath) {
23183
- console.log(` Undo this restore with: arkaik restore ${result.backupPath}`);
23831
+ console.log(` Undo this restore with: ${undoCommandFor(result.backupPath)}`);
23184
23832
  }
23185
23833
  }
23186
23834
  process.exitCode = 0;
@@ -23194,6 +23842,7 @@ function reportRestore(result) {
23194
23842
  }
23195
23843
  function runRestoreCli(argv) {
23196
23844
  let dryRun = false;
23845
+ let replace = false;
23197
23846
  let allowHistoryLoss = false;
23198
23847
  let allowDeletions = false;
23199
23848
  let noQuality = false;
@@ -23212,6 +23861,8 @@ function runRestoreCli(argv) {
23212
23861
  return;
23213
23862
  } else if (arg === "--dry-run") {
23214
23863
  dryRun = true;
23864
+ } else if (arg === "--replace") {
23865
+ replace = true;
23215
23866
  } else if (arg === "--allow-history-loss") {
23216
23867
  allowHistoryLoss = true;
23217
23868
  } else if (arg === "--allow-deletions") {
@@ -23258,9 +23909,14 @@ ${USAGE13}`);
23258
23909
 
23259
23910
  ${USAGE13}`);
23260
23911
  }
23912
+ const allowFlags = allowFlagsOf({ allowHistoryLoss, allowDeletions, allowQualityLoss, allowMetadataLoss });
23913
+ if (allowFlags.length > 0 && !replace) fail10(`${describeAllowWithoutReplace(allowFlags)}
23914
+
23915
+ ${USAGE13}`);
23261
23916
  runRestore({
23262
23917
  path: positionals[0],
23263
23918
  dryRun,
23919
+ replace,
23264
23920
  allowHistoryLoss,
23265
23921
  allowDeletions,
23266
23922
  noQuality,
@@ -23527,8 +24183,8 @@ function loadFragments(cwd, manifest) {
23527
24183
 
23528
24184
  // src/lib/bootstrap/index-view.ts
23529
24185
  function tsvField(value, fallback = "") {
23530
- const str2 = value === void 0 || value === null ? fallback : String(value);
23531
- return str2.replace(/[\t\r\n]+/g, " ");
24186
+ const str3 = value === void 0 || value === null ? fallback : String(value);
24187
+ return str3.replace(/[\t\r\n]+/g, " ");
23532
24188
  }
23533
24189
  function renderIndex(bundle) {
23534
24190
  const nodes = Array.isArray(bundle.nodes) ? bundle.nodes : [];
@@ -23902,7 +24558,7 @@ function mergeJournal(base, fresh) {
23902
24558
  }
23903
24559
 
23904
24560
  // src/lib/bootstrap/merge.ts
23905
- function asArray2(value) {
24561
+ function asArray4(value) {
23906
24562
  return Array.isArray(value) ? value : [];
23907
24563
  }
23908
24564
  function mergeFragments(input) {
@@ -23910,14 +24566,14 @@ function mergeFragments(input) {
23910
24566
  const projectId = String(input.base.project?.id ?? "");
23911
24567
  const nodes = /* @__PURE__ */ new Map();
23912
24568
  const nodeOrigin = /* @__PURE__ */ new Map();
23913
- for (const node of asArray2(input.base.nodes)) {
24569
+ for (const node of asArray4(input.base.nodes)) {
23914
24570
  const id = String(node.id);
23915
24571
  nodes.set(id, { ...node });
23916
24572
  nodeOrigin.set(id, "(already in the bundle)");
23917
24573
  }
23918
24574
  const edges = /* @__PURE__ */ new Map();
23919
24575
  const edgeOrigin = /* @__PURE__ */ new Map();
23920
- for (const edge of asArray2(input.base.edges)) {
24576
+ for (const edge of asArray4(input.base.edges)) {
23921
24577
  const id = String(edge.id ?? edgeId(String(edge.source_id), String(edge.target_id)));
23922
24578
  edges.set(id, { ...edge });
23923
24579
  edgeOrigin.set(id, "(already in the bundle)");
@@ -26625,7 +27281,7 @@ Commands:
26625
27281
  live --platform <p> [ids] Mark acceptances live on one platform from a deploy (release:append token).
26626
27282
  --mentions <file> derives them from merged pull requests.
26627
27283
  shot [options] [id p value] Record screenshots: --manifest <file> to the hosted door (screenshot:append token), or into the repo bundle.
26628
- restore [options] [path] Replace the linked project's bundle, journal + quality (backs up first).
27284
+ restore [options] [path] Append a local bundle to the linked project; --replace swaps it (backs up first).
26629
27285
  bootstrap <sub> [options] One-time onboarding: mine, plan, slice, merge a map from a repo.
26630
27286
  kritik <sub> [options] Quality audits: score criteria, open findings, roll up the matrix.
26631
27287
 
@@ -26634,7 +27290,7 @@ Options:
26634
27290
  -v, --version Print the version.
26635
27291
 
26636
27292
  Run "arkaik <command> --help" for command-specific help.`;
26637
- var VERSION = "0.12.0";
27293
+ var VERSION = "0.14.0";
26638
27294
  function main(argv) {
26639
27295
  const [command, ...rest] = argv;
26640
27296
  if (command === void 0 || command === "--help" || command === "-h" || command === "help") {