@sentropic/h2a 0.98.7-rc.2 → 0.98.7-rc.3

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 (57) hide show
  1. package/.codex-plugin/plugin.json +1 -0
  2. package/dist/bin.js +3 -0
  3. package/dist/bin.js.map +1 -1
  4. package/dist/cli.d.ts.map +1 -1
  5. package/dist/cli.js +38 -38
  6. package/dist/cli.js.map +1 -1
  7. package/dist/focus-build.d.ts +10 -0
  8. package/dist/focus-build.d.ts.map +1 -0
  9. package/dist/focus-build.js +175 -0
  10. package/dist/focus-build.js.map +1 -0
  11. package/dist/hosts/native-convergence.d.ts +36 -0
  12. package/dist/hosts/native-convergence.d.ts.map +1 -1
  13. package/dist/hosts/native-convergence.js +60 -4
  14. package/dist/hosts/native-convergence.js.map +1 -1
  15. package/dist/hosts/native-files.d.ts +5 -0
  16. package/dist/hosts/native-files.d.ts.map +1 -1
  17. package/dist/hosts/native-files.js +4 -0
  18. package/dist/hosts/native-files.js.map +1 -1
  19. package/dist/hosts/native-inspection.js +1 -1
  20. package/dist/hosts/native-inspection.js.map +1 -1
  21. package/dist/hosts/native-questions.d.ts +2 -0
  22. package/dist/hosts/native-questions.d.ts.map +1 -0
  23. package/dist/hosts/native-questions.js +22 -0
  24. package/dist/hosts/native-questions.js.map +1 -0
  25. package/dist/hosts/native-toml.d.ts.map +1 -1
  26. package/dist/hosts/native-toml.js +2 -0
  27. package/dist/hosts/native-toml.js.map +1 -1
  28. package/dist/hosts/plugin.d.ts +27 -0
  29. package/dist/hosts/plugin.d.ts.map +1 -1
  30. package/dist/hosts/plugin.js +28 -2
  31. package/dist/hosts/plugin.js.map +1 -1
  32. package/dist/hosts/vibe-discovery.js +1 -1
  33. package/dist/hosts/vibe-discovery.js.map +1 -1
  34. package/dist/hosts/vibe-equipment.d.ts +1 -0
  35. package/dist/hosts/vibe-equipment.d.ts.map +1 -1
  36. package/dist/hosts/vibe-equipment.js +14 -1
  37. package/dist/hosts/vibe-equipment.js.map +1 -1
  38. package/dist/runtime/mcp/tools.d.ts.map +1 -1
  39. package/dist/runtime/mcp/tools.js +5 -4
  40. package/dist/runtime/mcp/tools.js.map +1 -1
  41. package/focus-kit/dossier.schema.json +193 -0
  42. package/focus-kit/dossier.template.json +39 -0
  43. package/focus-kit/ecosystem.json +853 -0
  44. package/focus-kit/renderer-manifest.json +24 -0
  45. package/focus-kit/renderer.html +278 -0
  46. package/focus-kit/validator.mjs +789 -0
  47. package/hooks/hooks.json +11 -1
  48. package/hooks/workspace-scope-grant.mjs +22 -0
  49. package/hooks/workspace-scope-guard.mjs +277 -0
  50. package/hooks/workspace-scope-shell.mjs +558 -0
  51. package/hooks/workspace-scope-state.mjs +71 -0
  52. package/package.json +11 -5
  53. package/skills/h2a/SKILL.md +19 -0
  54. package/skills/h2a-run/SKILL.md +19 -0
  55. package/skills/harness/SKILL.md +19 -0
  56. package/skills/harness/track-report/SKILL.md +14 -0
  57. package/skills/harness/using-harness/SKILL.md +19 -0
@@ -0,0 +1,789 @@
1
+ /*!
2
+ MIT License
3
+
4
+ Copyright (c) 2025 Fabien Antoine
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+
24
+ */
25
+
26
+ // packages/focus/src/validation/readability.ts
27
+ var READABILITY_BUDGETS = { low: 2, medium: 8, high: 30 };
28
+ var READABILITY_LIMITS = {
29
+ minOwnerRequestQuoteLength: 8,
30
+ minStakesLength: 20,
31
+ minQuestionContextLength: 20,
32
+ minOptionsPerQuestion: 2,
33
+ maxOptionsPerQuestion: 4,
34
+ maxQuestionReadingMinutes: 2,
35
+ maxDossierBudgetMinutes: 30,
36
+ wordsPerMinute: 180,
37
+ maxHeadingLength: 100,
38
+ maxDecisionLineLength: 300,
39
+ maxOptionLabelLength: 100,
40
+ maxConsequenceLength: 160,
41
+ maxOptionBodyLength: 300
42
+ };
43
+ var CODE_PATTERN = /\b(?:[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+|[A-Z][A-Z0-9]*\d[A-Z0-9]*[a-z]?|[A-Z]{2,})\b/g;
44
+ var PLAIN_TOKENS = /* @__PURE__ */ new Set(["GO", "NO-GO", "NO", "PENDING", "DEFERRED", "LR", "RL", "TB", "BT", "TD", "UTF-8"]);
45
+ var CHOICE_PATTERN = /\beither\b[\s\S]{0,160}?\bor\b|\bsoit\b[\s\S]{0,160}?\bsoit\b|\b(?:instead of|rather than|plut[oô]t que|versus|vs\.?|choos(?:e|ing) between|choisir entre)\b/i;
46
+ var SUBOPTION_PATTERN = /(?:^|[\n\r\u2028\u2029])\s*(?:[-*+•‣>]|\d+[.)]|[a-z][.)])\s+\S|\([a-z]\)[\s\S]*\([a-z]\)|\b(?:sub[- ]?options?|sous[- ]?options?)\b/i;
47
+ var LINE_BREAK = /[\n\r\u2028\u2029]/;
48
+ var blank = (text) => !text?.trim();
49
+ var asRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
50
+ var minutesFor = (texts) => (texts.join(" ").match(/\S+/gu)?.length ?? 0) / READABILITY_LIMITS.wordsPerMinute;
51
+ var validateDecisionDossierReadability = (doc) => {
52
+ const issues = [];
53
+ const refuse = (path, code, message) => {
54
+ issues.push({ path, code, message });
55
+ };
56
+ const r = doc.readability;
57
+ const quote = r?.ownerRequestQuote?.trim() ?? "";
58
+ if (r?.noOwnerRequest === true) {
59
+ refuse(
60
+ "$.readability.noOwnerRequest",
61
+ quote ? "conflicting_owner_request" : "presentation_blocked",
62
+ quote ? "A quoted owner request conflicts with noOwnerRequest: keep the literal request and remove the flag." : "No owner request: presentation is blocked until the owner's literal request is quoted."
63
+ );
64
+ } else if (!quote) {
65
+ refuse("$.readability.ownerRequestQuote", "missing_owner_request", "Quote the literal owner request this dossier serves, or set noOwnerRequest to block presentation explicitly.");
66
+ } else if (quote.length < READABILITY_LIMITS.minOwnerRequestQuoteLength) {
67
+ refuse("$.readability.ownerRequestQuote", "owner_request_too_short", "Quote the full literal owner request so the owner recognizes their own intention.");
68
+ }
69
+ if (blank(r?.stakes)) {
70
+ refuse("$.readability.stakes", "missing_stakes", "State why the decision matters to the owner, using plain words about cost, time or consequences.");
71
+ } else if (r.stakes.trim().length < READABILITY_LIMITS.minStakesLength) {
72
+ refuse("$.readability.stakes", "stakes_too_short", "Explain the actual consequence for the owner in at least 20 characters; an internal label is insufficient.");
73
+ }
74
+ const level = r?.stakesLevel;
75
+ if (!level || !Object.hasOwn(READABILITY_BUDGETS, level)) {
76
+ refuse("$.readability.stakesLevel", "missing_stakes_level", "Declare stakesLevel: low for a small reversible inconvenience, medium for cost/disruption, high for lasting or major impact.");
77
+ }
78
+ const budget = r?.readingBudgetMinutes;
79
+ const budgetValid = budget !== void 0 && Number.isFinite(budget) && budget >= 1 && budget <= READABILITY_LIMITS.maxDossierBudgetMinutes;
80
+ if (budget === void 0) {
81
+ refuse("$.readability.readingBudgetMinutes", "missing_reading_budget", "Declare a total reading budget in minutes proportionate to the stakes: low up to 2, medium up to 8, high up to 30.");
82
+ } else if (!budgetValid) {
83
+ refuse("$.readability.readingBudgetMinutes", "reading_budget_out_of_range", "The total reading budget must be a finite number between 1 and 30 minutes.");
84
+ } else if (level && Object.hasOwn(READABILITY_BUDGETS, level) && budget > READABILITY_BUDGETS[level]) {
85
+ refuse("$.readability.readingBudgetMinutes", "reading_budget_disproportionate", `The ${level} stakes budget is at most ${READABILITY_BUDGETS[level]} minutes; shorten this dossier or justify a different stakes level.`);
86
+ }
87
+ const glossary = /* @__PURE__ */ new Map();
88
+ r?.glossary?.forEach((entry, i) => {
89
+ if (blank(entry.term) || blank(entry.definition)) {
90
+ refuse(`$.readability.glossary[${i}]`, "empty_glossary_entry", "Give every glossary term a definition in plain words visible to the reader.");
91
+ } else {
92
+ const term = entry.term.trim();
93
+ if (glossary.has(term) || entry.definition.trim() === term) {
94
+ refuse(`$.readability.glossary[${i}]`, "invalid_glossary_entry", "Use one definition per term and expand its meaning; repeating the code does not explain it.");
95
+ }
96
+ if ((entry.definition.match(CODE_PATTERN) ?? []).some((code) => !PLAIN_TOKENS.has(code))) {
97
+ refuse(
98
+ `$.readability.glossary[${i}].definition`,
99
+ "invalid_glossary_entry",
100
+ "Explain each term independently in plain words, without itself or another code, even one defined elsewhere."
101
+ );
102
+ }
103
+ glossary.set(term, entry.definition);
104
+ }
105
+ });
106
+ const checkCodes = (text, path) => {
107
+ for (const code of new Set(text?.match(CODE_PATTERN) ?? [])) {
108
+ if (!PLAIN_TOKENS.has(code) && !glossary.has(code)) {
109
+ refuse(path, "undefined_code", `Unexpanded code or acronym "${code}": define it in the visible glossary in plain words, or rewrite it.`);
110
+ }
111
+ }
112
+ };
113
+ const shared = [];
114
+ const visible = (text, path) => {
115
+ checkCodes(text, path);
116
+ if (text) shared.push(text);
117
+ };
118
+ for (const field of ["title", "subject"]) {
119
+ visible(doc[field], `$.${field}`);
120
+ if (blank(doc[field])) refuse(
121
+ `$.${field}`,
122
+ "empty_heading",
123
+ "Name the subject and decision in a short, non-empty line the owner understands."
124
+ );
125
+ checkLine(doc[field], `$.${field}`, READABILITY_LIMITS.maxHeadingLength);
126
+ }
127
+ visible(quote, "$.readability.ownerRequestQuote");
128
+ visible(r?.stakes, "$.readability.stakes");
129
+ r?.glossary?.forEach((entry, i) => {
130
+ shared.push(entry.term);
131
+ visible(entry.definition, `$.readability.glossary[${i}].definition`);
132
+ });
133
+ const checkSteps = (steps, path) => {
134
+ steps.forEach((step, i) => {
135
+ visible(step.author, `${path}[${i}].author`);
136
+ visible(step.summary, `${path}[${i}].summary`);
137
+ });
138
+ };
139
+ checkSteps(doc.amendmentTrace, "$.amendmentTrace");
140
+ doc.interactions.forEach((action, i) => visible(action.label, `$.interactions[${i}].label`));
141
+ const questions = doc.sections.filter((s) => s.kind === "question");
142
+ const questionIds = new Set(questions.map((q) => q.id));
143
+ if (!questions.length) refuse("$.sections", "missing_question", "A decision dossier needs an explicit question with context, options and a recommendation.");
144
+ const checkQuestionRef = (questionId, path, required) => {
145
+ if (blank(questionId)) {
146
+ if (required) refuse(path, "hidden_decision", "This content implies a choice without an explicit question: set questionId to the question the owner must answer.");
147
+ } else if (!questionIds.has(questionId)) {
148
+ refuse(path, "unknown_question_ref", `Question "${questionId}" does not exist in this dossier; link to an explicit question.`);
149
+ }
150
+ };
151
+ const optionSets = doc.sections.filter((s) => s.kind === "optionSet");
152
+ let totalQuestionMinutes = 0;
153
+ doc.sections.forEach((section, i) => {
154
+ const path = `$.sections[${i}]`;
155
+ switch (section.kind) {
156
+ case "prose":
157
+ visible(section.markdown, `${path}.markdown`);
158
+ checkQuestionRef(section.questionId, `${path}.questionId`, CHOICE_PATTERN.test(section.markdown));
159
+ break;
160
+ case "outcome":
161
+ visible(section.statement, `${path}.statement`);
162
+ checkQuestionRef(section.questionId, `${path}.questionId`, section.modality !== "comment" || CHOICE_PATTERN.test(section.statement));
163
+ break;
164
+ case "diagram":
165
+ visible(section.alt, `${path}.alt`);
166
+ if (section.scene === void 0) visible(section.source, `${path}.source`);
167
+ else checkCodes(section.source, `${path}.source`);
168
+ for (const [family, field] of [["entities", "name"], ["relations", "label"]]) {
169
+ for (const [id, member] of Object.entries(asRecord(section.scene?.[family]))) {
170
+ const attribute = asRecord(asRecord(asRecord(member).attributes)[field]);
171
+ if (attribute.kind === "text" && typeof attribute.value === "string") {
172
+ visible(attribute.value, `${path}.scene.${family}.${id}.attributes.${field}.value`);
173
+ }
174
+ }
175
+ }
176
+ break;
177
+ case "amendmentTrace":
178
+ checkSteps(section.steps, `${path}.steps`);
179
+ break;
180
+ case "optionSet":
181
+ checkQuestionRef(section.questionId, `${path}.questionId`, true);
182
+ checkCodes(section.title, `${path}.title`);
183
+ checkLine(section.title, `${path}.title`, READABILITY_LIMITS.maxHeadingLength);
184
+ section.options.forEach((option, j) => checkOption(option, `${path}.options[${j}]`));
185
+ break;
186
+ case "question": {
187
+ if (blank(section.question)) refuse(`${path}.question`, "empty_question", "State the explicit decision the owner needs to make in this question.");
188
+ if (blank(section.context)) {
189
+ refuse(`${path}.context`, "missing_question_context", "Add representative context in plain words so the question can be understood on its own.");
190
+ } else if (section.context.trim().length < READABILITY_LIMITS.minQuestionContextLength) {
191
+ refuse(`${path}.context`, "question_context_too_short", "Give representative context of at least 20 characters, including what changes for the owner.");
192
+ }
193
+ if (blank(section.recommendedAnswer)) refuse(`${path}.recommendedAnswer`, "missing_recommendation", "Recommend an option with a short reason that relates to the owner's request and stakes.");
194
+ checkLine(section.question, `${path}.question`, READABILITY_LIMITS.maxDecisionLineLength);
195
+ checkLine(section.recommendedAnswer, `${path}.recommendedAnswer`, READABILITY_LIMITS.maxDecisionLineLength);
196
+ const linked = optionSets.filter((set) => set.questionId === section.id);
197
+ const options = linked.flatMap((set) => set.options);
198
+ if (options.length < 2 || options.length > 4) refuse(path, "option_count", `Each question needs 2\u20134 short options; this question has ${options.length}.`);
199
+ if (!options.some((option) => option.id === section.recommendedOptionId)) {
200
+ refuse(`${path}.recommendedOptionId`, "unknown_recommended_option", "Identify the recommended option by its id among this question's options, with the reason in recommendedAnswer.");
201
+ }
202
+ const texts = [
203
+ section.question,
204
+ section.context,
205
+ section.recommendedAnswer,
206
+ section.answer,
207
+ options.find((option) => option.id === section.recommendedOptionId)?.label,
208
+ ...linked.map((set) => set.title),
209
+ ...options.flatMap((o) => [o.label, o.consequence, o.body, o.annotationComment])
210
+ ];
211
+ checkCodes(section.question, `${path}.question`);
212
+ checkCodes(section.context, `${path}.context`);
213
+ checkCodes(section.recommendedAnswer, `${path}.recommendedAnswer`);
214
+ checkCodes(section.answer, `${path}.answer`);
215
+ const minutes = section.readingTimeMinutes;
216
+ const minimum = minutesFor(texts);
217
+ if (minutes === void 0) {
218
+ refuse(`${path}.readingTimeMinutes`, "missing_reading_time", "Estimate the time to read this question, context and options in readingTimeMinutes (up to 2 minutes).");
219
+ } else if (!Number.isFinite(minutes) || minutes <= 0 || minutes > 2) {
220
+ refuse(`${path}.readingTimeMinutes`, "reading_time_exceeded", "Each question must take a positive finite time of at most 2 minutes; shorten or split it.");
221
+ } else {
222
+ if (minutes < minimum) refuse(`${path}.readingTimeMinutes`, "reading_time_underestimated", `This question needs at least ${minimum.toFixed(2)} minutes at 180 words/minute; shorten it or correct its estimate (maximum 2 minutes).`);
223
+ totalQuestionMinutes += Math.max(minutes, minimum);
224
+ }
225
+ break;
226
+ }
227
+ }
228
+ });
229
+ if (budgetValid && totalQuestionMinutes + minutesFor(shared) > budget) {
230
+ refuse("$.readability.readingBudgetMinutes", "reading_budget_exceeded", "The questions plus shared context and glossary exceed the declared reading budget; shorten the dossier to match its stakes.");
231
+ }
232
+ return issues;
233
+ function checkLine(text, path, max) {
234
+ if (!text) return;
235
+ if (text.trim().length > max || LINE_BREAK.test(text)) refuse(
236
+ path,
237
+ "decision_line_too_long",
238
+ `Use one short line of at most ${max} characters; put explanation in the question context.`
239
+ );
240
+ if (SUBOPTION_PATTERN.test(text)) refuse(
241
+ path,
242
+ "nested_suboptions",
243
+ "Expose sub-choices as separate options or questions, without nested lists or inline branches."
244
+ );
245
+ }
246
+ function checkOption(option, path) {
247
+ const fields = [
248
+ { field: "label", text: option.label, max: READABILITY_LIMITS.maxOptionLabelLength, code: "option_too_long" },
249
+ { field: "consequence", text: option.consequence, max: READABILITY_LIMITS.maxConsequenceLength, code: "consequence_too_long" },
250
+ { field: "body", text: option.body, max: READABILITY_LIMITS.maxOptionBodyLength, code: "option_too_long" },
251
+ { field: "annotationComment", text: option.annotationComment, max: READABILITY_LIMITS.maxOptionBodyLength, code: "option_too_long" }
252
+ ];
253
+ if (blank(option.label)) refuse(`${path}.label`, "empty_option_label", "Name this option in a few plain words so the owner can compare it at a glance.");
254
+ if (blank(option.consequence)) refuse(`${path}.consequence`, "missing_consequence", "Add a one-line consequence: what choosing this option changes for the owner.");
255
+ for (const { field, text, max, code } of fields) {
256
+ if (!text) continue;
257
+ checkCodes(text, `${path}.${field}`);
258
+ if (text.trim().length > max || LINE_BREAK.test(text)) refuse(`${path}.${field}`, code, `Keep this option ${field} to one short line of at most ${max} characters; move necessary context to the question.`);
259
+ if (SUBOPTION_PATTERN.test(text) || CHOICE_PATTERN.test(text)) refuse(`${path}.${field}`, "nested_suboptions", "This option hides sub-options: expose the choices as separate options or as a separate question.");
260
+ }
261
+ }
262
+ };
263
+
264
+ // packages/focus/src/validation/index.ts
265
+ var DOSSIER_SCHEMA_ID = "urn:sentropic:focus:DecisionDossierDocument:1.0.0";
266
+ var DOSSIER_SCHEMA_VERSION = "1.0.0";
267
+ var DecisionDossierValidationError = class extends Error {
268
+ issues;
269
+ constructor(issues) {
270
+ super(
271
+ `invalid DecisionDossierDocument: ${issues.map((issue2) => `${issue2.path} ${issue2.code}: ${issue2.message}`).join("; ")}`
272
+ );
273
+ this.name = "DecisionDossierValidationError";
274
+ this.issues = issues;
275
+ }
276
+ };
277
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
278
+ var issue = (path, code, message) => ({
279
+ path,
280
+ code,
281
+ message
282
+ });
283
+ var checkClosedObject = (value, path, allowed, required, stringKeys, issues) => {
284
+ if (!isRecord(value)) {
285
+ issues.push(issue(path, "invalid_type", "expected an object"));
286
+ return void 0;
287
+ }
288
+ const allowedSet = new Set(allowed);
289
+ for (const key of Object.keys(value)) {
290
+ if (!allowedSet.has(key)) {
291
+ issues.push(issue(`${path}.${key}`, "unknown_field", "field not in the closed schema"));
292
+ }
293
+ }
294
+ for (const key of required) {
295
+ if (value[key] === void 0) {
296
+ issues.push(issue(`${path}.${key}`, "missing_field", "required field is missing"));
297
+ }
298
+ }
299
+ for (const key of stringKeys) {
300
+ if (value[key] !== void 0 && typeof value[key] !== "string") {
301
+ issues.push(issue(`${path}.${key}`, "invalid_type", "expected a string"));
302
+ }
303
+ }
304
+ return value;
305
+ };
306
+ var checkEnum = (value, path, allowed, issues) => {
307
+ if (typeof value !== "string" || !allowed.includes(value)) {
308
+ issues.push(
309
+ issue(path, "invalid_enum", `expected one of: ${allowed.join(" | ")}`)
310
+ );
311
+ }
312
+ };
313
+ var TOP_REQUIRED = [
314
+ "ref",
315
+ "subject",
316
+ "title",
317
+ "hash",
318
+ "cursor",
319
+ "sections",
320
+ "interactions",
321
+ "provenance",
322
+ "amendmentTrace"
323
+ ];
324
+ var TOP_STRINGS = ["ref", "subject", "title", "hash", "cursor"];
325
+ var TOP_ALLOWED = [...TOP_REQUIRED, "readability"];
326
+ var checkOptionNode = (value, path, issues) => {
327
+ const start = issues.length;
328
+ const node = checkClosedObject(
329
+ value,
330
+ path,
331
+ ["kind", "id", "targetRef", "label", "body", "annotation", "annotationComment", "consequence"],
332
+ ["kind", "id", "targetRef", "label", "annotation"],
333
+ ["id", "targetRef", "label", "body", "annotationComment", "consequence"],
334
+ issues
335
+ );
336
+ if (node === void 0) return void 0;
337
+ if (node["kind"] !== "option") {
338
+ issues.push(issue(`${path}.kind`, "invalid_discriminator", 'expected "option"'));
339
+ }
340
+ checkEnum(node["annotation"], `${path}.annotation`, ["none", "accept", "reject", "comment"], issues);
341
+ if (issues.length !== start) return void 0;
342
+ return {
343
+ kind: "option",
344
+ id: node["id"],
345
+ targetRef: node["targetRef"],
346
+ label: node["label"],
347
+ ...typeof node["body"] === "string" ? { body: node["body"] } : {},
348
+ annotation: node["annotation"],
349
+ ...typeof node["annotationComment"] === "string" ? { annotationComment: node["annotationComment"] } : {},
350
+ ...typeof node["consequence"] === "string" ? { consequence: node["consequence"] } : {}
351
+ };
352
+ };
353
+ var checkAmendmentStep = (value, path, issues) => {
354
+ const start = issues.length;
355
+ const step = checkClosedObject(
356
+ value,
357
+ path,
358
+ ["at", "author", "summary"],
359
+ ["at", "author", "summary"],
360
+ ["at", "author", "summary"],
361
+ issues
362
+ );
363
+ if (step === void 0 || issues.length !== start) return void 0;
364
+ return { at: step["at"], author: step["author"], summary: step["summary"] };
365
+ };
366
+ var checkSectionNode = (value, path, issues) => {
367
+ if (!isRecord(value)) {
368
+ issues.push(issue(path, "invalid_type", "expected an object"));
369
+ return void 0;
370
+ }
371
+ const kind = value["kind"];
372
+ if (kind !== "prose" && kind !== "question" && kind !== "optionSet" && kind !== "outcome" && kind !== "amendmentTrace" && kind !== "diagram") {
373
+ issues.push(
374
+ issue(
375
+ `${path}.kind`,
376
+ typeof kind === "undefined" ? "missing_field" : "unknown_node_kind",
377
+ `unknown section kind ${typeof kind === "string" ? `"${kind}"` : " discriminant"}`
378
+ )
379
+ );
380
+ return void 0;
381
+ }
382
+ const start = issues.length;
383
+ switch (kind) {
384
+ case "prose": {
385
+ const node = checkClosedObject(
386
+ value,
387
+ path,
388
+ ["kind", "id", "targetRef", "markdown", "questionId"],
389
+ ["kind", "id", "targetRef", "markdown"],
390
+ ["id", "targetRef", "markdown", "questionId"],
391
+ issues
392
+ );
393
+ if (node === void 0 || issues.length !== start) return void 0;
394
+ return { kind: "prose", id: node["id"], targetRef: node["targetRef"], markdown: node["markdown"], ...typeof node["questionId"] === "string" ? { questionId: node["questionId"] } : {} };
395
+ }
396
+ case "question": {
397
+ const node = checkClosedObject(
398
+ value,
399
+ path,
400
+ ["kind", "id", "targetRef", "question", "recommendedAnswer", "answer", "state", "context", "readingTimeMinutes", "recommendedOptionId"],
401
+ ["kind", "id", "targetRef", "question", "state"],
402
+ ["id", "targetRef", "question", "recommendedAnswer", "answer", "context", "recommendedOptionId"],
403
+ issues
404
+ );
405
+ if (node === void 0) return void 0;
406
+ checkEnum(node["state"], `${path}.state`, ["open", "answered", "validated"], issues);
407
+ if (node["readingTimeMinutes"] !== void 0 && (typeof node["readingTimeMinutes"] !== "number" || !Number.isFinite(node["readingTimeMinutes"]))) {
408
+ issues.push(issue(`${path}.readingTimeMinutes`, "invalid_type", "expected a finite number"));
409
+ }
410
+ if (issues.length !== start) return void 0;
411
+ return {
412
+ kind: "question",
413
+ id: node["id"],
414
+ targetRef: node["targetRef"],
415
+ question: node["question"],
416
+ ...typeof node["recommendedAnswer"] === "string" ? { recommendedAnswer: node["recommendedAnswer"] } : {},
417
+ ...typeof node["answer"] === "string" ? { answer: node["answer"] } : {},
418
+ state: node["state"],
419
+ ...typeof node["context"] === "string" ? { context: node["context"] } : {},
420
+ ...typeof node["recommendedOptionId"] === "string" ? { recommendedOptionId: node["recommendedOptionId"] } : {},
421
+ ...typeof node["readingTimeMinutes"] === "number" ? { readingTimeMinutes: node["readingTimeMinutes"] } : {}
422
+ };
423
+ }
424
+ case "optionSet": {
425
+ const node = checkClosedObject(
426
+ value,
427
+ path,
428
+ ["kind", "id", "targetRef", "title", "options", "questionId"],
429
+ ["kind", "id", "targetRef", "options"],
430
+ ["id", "targetRef", "title", "questionId"],
431
+ issues
432
+ );
433
+ if (node === void 0) return void 0;
434
+ const options = [];
435
+ if (!Array.isArray(node["options"])) {
436
+ issues.push(issue(`${path}.options`, "invalid_type", "expected an array"));
437
+ } else {
438
+ node["options"].forEach((option, index) => {
439
+ const checked = checkOptionNode(option, `${path}.options[${index}]`, issues);
440
+ if (checked !== void 0) options.push(checked);
441
+ });
442
+ }
443
+ if (issues.length !== start) return void 0;
444
+ return {
445
+ kind: "optionSet",
446
+ id: node["id"],
447
+ targetRef: node["targetRef"],
448
+ ...typeof node["title"] === "string" ? { title: node["title"] } : {},
449
+ options,
450
+ ...typeof node["questionId"] === "string" ? { questionId: node["questionId"] } : {}
451
+ };
452
+ }
453
+ case "outcome": {
454
+ const node = checkClosedObject(
455
+ value,
456
+ path,
457
+ ["kind", "id", "targetRef", "modality", "statement", "questionId"],
458
+ ["kind", "id", "targetRef", "modality", "statement"],
459
+ ["id", "targetRef", "statement", "questionId"],
460
+ issues
461
+ );
462
+ if (node === void 0) return void 0;
463
+ checkEnum(node["modality"], `${path}.modality`, ["decision", "orientation", "amendment", "comment"], issues);
464
+ if (issues.length !== start) return void 0;
465
+ return {
466
+ kind: "outcome",
467
+ id: node["id"],
468
+ targetRef: node["targetRef"],
469
+ modality: node["modality"],
470
+ statement: node["statement"],
471
+ ...typeof node["questionId"] === "string" ? { questionId: node["questionId"] } : {}
472
+ };
473
+ }
474
+ case "amendmentTrace": {
475
+ const node = checkClosedObject(
476
+ value,
477
+ path,
478
+ ["kind", "id", "targetRef", "steps"],
479
+ ["kind", "id", "targetRef", "steps"],
480
+ ["id", "targetRef"],
481
+ issues
482
+ );
483
+ if (node === void 0) return void 0;
484
+ const steps = [];
485
+ if (!Array.isArray(node["steps"])) {
486
+ issues.push(issue(`${path}.steps`, "invalid_type", "expected an array"));
487
+ } else {
488
+ node["steps"].forEach((step, index) => {
489
+ const checked = checkAmendmentStep(step, `${path}.steps[${index}]`, issues);
490
+ if (checked !== void 0) steps.push(checked);
491
+ });
492
+ }
493
+ if (issues.length !== start) return void 0;
494
+ return {
495
+ kind: "amendmentTrace",
496
+ id: node["id"],
497
+ targetRef: node["targetRef"],
498
+ steps
499
+ };
500
+ }
501
+ case "diagram": {
502
+ const node = checkClosedObject(
503
+ value,
504
+ path,
505
+ ["kind", "id", "targetRef", "syntax", "source", "alt", "scene"],
506
+ ["kind", "id", "targetRef", "syntax", "source", "alt"],
507
+ ["id", "targetRef", "source", "alt"],
508
+ issues
509
+ );
510
+ if (node === void 0) return void 0;
511
+ checkEnum(node["syntax"], `${path}.syntax`, ["mermaid", "plantuml"], issues);
512
+ if (node["scene"] !== void 0 && !isRecord(node["scene"])) {
513
+ issues.push(issue(`${path}.scene`, "invalid_type", "expected a diagram-core SemanticDocument object"));
514
+ }
515
+ if (issues.length !== start) return void 0;
516
+ return {
517
+ kind: "diagram",
518
+ id: node["id"],
519
+ targetRef: node["targetRef"],
520
+ syntax: node["syntax"],
521
+ source: node["source"],
522
+ alt: node["alt"],
523
+ ...node["scene"] === void 0 ? {} : { scene: node["scene"] }
524
+ };
525
+ }
526
+ }
527
+ };
528
+ var checkInteraction = (value, path, issues) => {
529
+ const start = issues.length;
530
+ const affordance = checkClosedObject(
531
+ value,
532
+ path,
533
+ ["name", "targetRef", "label", "enabled"],
534
+ ["name", "targetRef", "label", "enabled"],
535
+ ["name", "targetRef", "label"],
536
+ issues
537
+ );
538
+ if (affordance === void 0) return void 0;
539
+ if (affordance["enabled"] !== false) {
540
+ issues.push(
541
+ issue(`${path}.enabled`, "enabled_action", "snapshot interactions must stay disabled (enabled:false)")
542
+ );
543
+ }
544
+ if (issues.length !== start) return void 0;
545
+ return {
546
+ name: affordance["name"],
547
+ targetRef: affordance["targetRef"],
548
+ label: affordance["label"],
549
+ enabled: false
550
+ };
551
+ };
552
+ var checkGlossaryEntry = (value, path, issues) => {
553
+ const start = issues.length;
554
+ const entry = checkClosedObject(
555
+ value,
556
+ path,
557
+ ["term", "definition"],
558
+ ["term", "definition"],
559
+ ["term", "definition"],
560
+ issues
561
+ );
562
+ if (entry === void 0 || issues.length !== start) return void 0;
563
+ return { term: entry["term"], definition: entry["definition"] };
564
+ };
565
+ var checkReadability = (value, path, issues) => {
566
+ const start = issues.length;
567
+ const block = checkClosedObject(
568
+ value,
569
+ path,
570
+ ["ownerRequestQuote", "noOwnerRequest", "stakes", "stakesLevel", "readingBudgetMinutes", "glossary"],
571
+ [],
572
+ ["ownerRequestQuote", "stakes"],
573
+ issues
574
+ );
575
+ if (block === void 0) return void 0;
576
+ if (block["stakesLevel"] !== void 0) {
577
+ checkEnum(block["stakesLevel"], `${path}.stakesLevel`, ["low", "medium", "high"], issues);
578
+ }
579
+ if (block["noOwnerRequest"] !== void 0 && typeof block["noOwnerRequest"] !== "boolean") {
580
+ issues.push(issue(`${path}.noOwnerRequest`, "invalid_type", "expected a boolean"));
581
+ }
582
+ if (block["readingBudgetMinutes"] !== void 0 && (typeof block["readingBudgetMinutes"] !== "number" || !Number.isFinite(block["readingBudgetMinutes"]))) {
583
+ issues.push(issue(`${path}.readingBudgetMinutes`, "invalid_type", "expected a finite number"));
584
+ }
585
+ let glossary;
586
+ if (block["glossary"] !== void 0) {
587
+ glossary = [];
588
+ if (!Array.isArray(block["glossary"])) {
589
+ issues.push(issue(`${path}.glossary`, "invalid_type", "expected an array"));
590
+ } else {
591
+ block["glossary"].forEach((entry, index) => {
592
+ const checked = checkGlossaryEntry(entry, `${path}.glossary[${index}]`, issues);
593
+ if (checked !== void 0) glossary.push(checked);
594
+ });
595
+ }
596
+ }
597
+ if (issues.length !== start) return void 0;
598
+ return {
599
+ ...typeof block["ownerRequestQuote"] === "string" ? { ownerRequestQuote: block["ownerRequestQuote"] } : {},
600
+ ...typeof block["noOwnerRequest"] === "boolean" ? { noOwnerRequest: block["noOwnerRequest"] } : {},
601
+ ...typeof block["stakes"] === "string" ? { stakes: block["stakes"] } : {},
602
+ ...block["stakesLevel"] !== void 0 ? { stakesLevel: block["stakesLevel"] } : {},
603
+ ...typeof block["readingBudgetMinutes"] === "number" ? { readingBudgetMinutes: block["readingBudgetMinutes"] } : {},
604
+ ...glossary !== void 0 ? { glossary } : {}
605
+ };
606
+ };
607
+ var validateDecisionDossierStructure = (value) => {
608
+ const issues = [];
609
+ const doc = checkClosedObject(value, "$", [...TOP_ALLOWED], [...TOP_REQUIRED], [...TOP_STRINGS], issues);
610
+ if (doc === void 0) return { ok: false, issues };
611
+ const sections = [];
612
+ if (!Array.isArray(doc["sections"])) {
613
+ issues.push(issue("$.sections", "invalid_type", "expected an array"));
614
+ } else {
615
+ doc["sections"].forEach((section, index) => {
616
+ const checked = checkSectionNode(section, `$.sections[${index}]`, issues);
617
+ if (checked !== void 0) sections.push(checked);
618
+ });
619
+ }
620
+ const interactions = [];
621
+ if (!Array.isArray(doc["interactions"])) {
622
+ issues.push(issue("$.interactions", "invalid_type", "expected an array"));
623
+ } else {
624
+ doc["interactions"].forEach((interaction, index) => {
625
+ const checked = checkInteraction(interaction, `$.interactions[${index}]`, issues);
626
+ if (checked !== void 0) interactions.push(checked);
627
+ });
628
+ }
629
+ let provenance;
630
+ const rawProvenance = checkClosedObject(
631
+ doc["provenance"],
632
+ "$.provenance",
633
+ ["source", "readAt", "comprehensionEvidence"],
634
+ ["source", "readAt"],
635
+ ["source", "readAt"],
636
+ issues
637
+ );
638
+ if (rawProvenance !== void 0) {
639
+ let evidence;
640
+ if (rawProvenance["comprehensionEvidence"] !== void 0) {
641
+ const evidenceStart = issues.length;
642
+ const rawEvidence = checkClosedObject(
643
+ rawProvenance["comprehensionEvidence"],
644
+ "$.provenance.comprehensionEvidence",
645
+ ["subject", "dossierHash", "signature"],
646
+ ["subject", "dossierHash"],
647
+ ["subject", "dossierHash", "signature"],
648
+ issues
649
+ );
650
+ if (rawEvidence !== void 0 && issues.length === evidenceStart) {
651
+ evidence = {
652
+ subject: rawEvidence["subject"],
653
+ dossierHash: rawEvidence["dossierHash"],
654
+ ...typeof rawEvidence["signature"] === "string" ? { signature: rawEvidence["signature"] } : {}
655
+ };
656
+ }
657
+ }
658
+ provenance = {
659
+ source: rawProvenance["source"],
660
+ readAt: rawProvenance["readAt"],
661
+ ...evidence !== void 0 ? { comprehensionEvidence: evidence } : {}
662
+ };
663
+ }
664
+ const amendmentTrace = [];
665
+ if (!Array.isArray(doc["amendmentTrace"])) {
666
+ issues.push(issue("$.amendmentTrace", "invalid_type", "expected an array"));
667
+ } else {
668
+ doc["amendmentTrace"].forEach((step, index) => {
669
+ const checked = checkAmendmentStep(step, `$.amendmentTrace[${index}]`, issues);
670
+ if (checked !== void 0) amendmentTrace.push(checked);
671
+ });
672
+ }
673
+ let readability;
674
+ if (doc["readability"] !== void 0) {
675
+ readability = checkReadability(doc["readability"], "$.readability", issues);
676
+ }
677
+ if (issues.length > 0 || provenance === void 0 || doc["readability"] !== void 0 && readability === void 0) {
678
+ return { ok: false, issues };
679
+ }
680
+ if (typeof doc["ref"] !== "string" || typeof doc["subject"] !== "string" || typeof doc["title"] !== "string" || typeof doc["hash"] !== "string" || typeof doc["cursor"] !== "string") {
681
+ return { ok: false, issues };
682
+ }
683
+ return {
684
+ ok: true,
685
+ value: {
686
+ ref: doc["ref"],
687
+ subject: doc["subject"],
688
+ title: doc["title"],
689
+ hash: doc["hash"],
690
+ cursor: doc["cursor"],
691
+ sections,
692
+ interactions,
693
+ provenance,
694
+ amendmentTrace,
695
+ ...readability !== void 0 ? { readability } : {}
696
+ }
697
+ };
698
+ };
699
+ var validateDecisionDossierSemantics = (doc) => {
700
+ const issues = [];
701
+ const seen = /* @__PURE__ */ new Map();
702
+ const registerId = (id, path) => {
703
+ const first = seen.get(id);
704
+ if (first !== void 0) {
705
+ issues.push(issue(path, "duplicate_id", `node id "${id}" already used at ${first}`));
706
+ } else {
707
+ seen.set(id, path);
708
+ }
709
+ };
710
+ doc.sections.forEach((section, index) => {
711
+ const path = `$.sections[${index}]`;
712
+ registerId(section.id, `${path}.id`);
713
+ if (section.kind === "optionSet") {
714
+ section.options.forEach((option, optionIndex) => {
715
+ registerId(option.id, `${path}.options[${optionIndex}].id`);
716
+ });
717
+ }
718
+ });
719
+ const resolvable = /* @__PURE__ */ new Set([doc.ref]);
720
+ for (const section of doc.sections) {
721
+ resolvable.add(section.id);
722
+ resolvable.add(section.targetRef);
723
+ if (section.kind === "optionSet") {
724
+ for (const option of section.options) {
725
+ resolvable.add(option.id);
726
+ resolvable.add(option.targetRef);
727
+ }
728
+ }
729
+ }
730
+ doc.interactions.forEach((interaction, index) => {
731
+ if (!resolvable.has(interaction.targetRef)) {
732
+ issues.push(
733
+ issue(
734
+ `$.interactions[${index}].targetRef`,
735
+ "unresolved_target",
736
+ `interaction target "${interaction.targetRef}" resolves to no node`
737
+ )
738
+ );
739
+ }
740
+ });
741
+ const evidence = doc.provenance.comprehensionEvidence;
742
+ if (evidence !== void 0 && evidence.dossierHash !== doc.hash) {
743
+ issues.push(
744
+ issue(
745
+ "$.provenance.comprehensionEvidence.dossierHash",
746
+ "evidence_mismatch",
747
+ "comprehension evidence does not match the snapshot hash"
748
+ )
749
+ );
750
+ }
751
+ return issues;
752
+ };
753
+ var validateDecisionDossierDocument = (value) => {
754
+ const structural = validateDecisionDossierStructure(value);
755
+ if (!structural.ok) return structural;
756
+ const semantic = validateDecisionDossierSemantics(structural.value);
757
+ if (semantic.length > 0) return { ok: false, issues: semantic };
758
+ return structural;
759
+ };
760
+ var assertDecisionDossierDocument = (value) => {
761
+ const result = validateDecisionDossierDocument(value);
762
+ if (!result.ok) throw new DecisionDossierValidationError(result.issues);
763
+ return result.value;
764
+ };
765
+ var validateDecisionDossierForPresentation = (value) => {
766
+ const result = validateDecisionDossierDocument(value);
767
+ if (!result.ok) return result;
768
+ const issues = validateDecisionDossierReadability(result.value);
769
+ return issues.length > 0 ? { ok: false, issues } : result;
770
+ };
771
+ var assertDecisionDossierForPresentation = (value) => {
772
+ const result = validateDecisionDossierForPresentation(value);
773
+ if (!result.ok) throw new DecisionDossierValidationError(result.issues);
774
+ return result.value;
775
+ };
776
+ export {
777
+ DOSSIER_SCHEMA_ID,
778
+ DOSSIER_SCHEMA_VERSION,
779
+ DecisionDossierValidationError,
780
+ READABILITY_BUDGETS,
781
+ READABILITY_LIMITS,
782
+ assertDecisionDossierDocument,
783
+ assertDecisionDossierForPresentation,
784
+ validateDecisionDossierDocument,
785
+ validateDecisionDossierForPresentation,
786
+ validateDecisionDossierReadability,
787
+ validateDecisionDossierSemantics,
788
+ validateDecisionDossierStructure
789
+ };