@okfit/core 0.14.0 → 0.16.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.
@@ -1,12 +1,23 @@
1
+ import { GlobPattern } from "@effected/glob";
1
2
  import { EditDistance } from "@effected/source";
2
- import { DateTime } from "effect";
3
+ import { DateTime, Option, Result, Schema } from "effect";
3
4
  import { Actor } from "../Actor.js";
5
+ import { Concept } from "../Concept.js";
4
6
  import { Derive } from "../Derive.js";
5
7
  import { Diagnostic, DiagnosticRange } from "../Diagnostic.js";
8
+ import { Generated } from "../Generated.js";
9
+ import { GENERATED_AT_TOLERANCE_TEXT, generatedAtIsFuture, verificationBlockingRestamp } from "../GeneratedAtFuture.js";
10
+ import { Graph as Graph$1 } from "../Graph.js";
11
+ import { INTEGRITY_KEY } from "../Integrity.js";
12
+ import { OkfVersion } from "../OkfVersion.js";
13
+ import { Timestamp } from "../Timestamp.js";
6
14
  import { frontmatterPathRange } from "./frontmatter.js";
15
+ import { tierOf } from "./tier.js";
16
+ import { isReplaceableNull } from "./yamlPathSpan.js";
7
17
 
8
18
  // src/internal/lintRules.ts
9
- const present = (raw, key) => Object.hasOwn(raw, key) && raw[key] !== null;
19
+ /** OKF 0.3 §11.2 rule 1: a key holding null, the empty string or the empty list is absent. */
20
+ const present = (raw, key) => Object.hasOwn(raw, key) && !Concept.isAbsent(raw[key]);
10
21
  const diagnostic = (file, code, severity, message, range) => Diagnostic.make({
11
22
  file,
12
23
  code,
@@ -28,13 +39,51 @@ const perConcept = (code, body) => rule(code, (context, severity) => [...context
28
39
  return diagnostic(concept.path, code, severity, message, frontmatterPathRange(concept.document, path));
29
40
  })));
30
41
  const configUnknownKey = rule("config-unknown-key", (context, severity) => Object.keys(context.config.extensions).map((key) => diagnostic("", "config-unknown-key", severity, `Unknown config key "${key}"`, void 0)));
42
+ /**
43
+ * The config's `okf_version` only fills a root index that declares none; once the index declares a different
44
+ * version the config value is stale. Both sides compare through `OkfVersion` when they parse, as raw strings otherwise.
45
+ */
46
+ const configOkfVersionStale = rule("config-okf-version-stale", (context, severity) => {
47
+ const configured = context.config.okf_version;
48
+ const declared = OkfVersion.declared(context.bundle);
49
+ if (configured === void 0 || Option.isNone(declared)) return [];
50
+ if (Option.match(Option.all([OkfVersion.parse(configured), OkfVersion.parse(declared.value)]), {
51
+ onNone: () => configured === declared.value,
52
+ onSome: ([a, b]) => OkfVersion.compare(a, b) === 0
53
+ })) return [];
54
+ const where = context.configPath === void 0 ? "in the config" : `in ${context.configPath}`;
55
+ const head = `okf_version ${where} is "${configured}", but the bundle-root index.md declares "${declared.value}"`;
56
+ const message = Option.isSome(OkfVersion.parse(declared.value)) ? `${head}; okfit reads the bundle as "${declared.value}" and uses the config value only for a root index that declares none. Set okf_version = "${declared.value}" ${where}, or remove it` : `${head}, which is not a <major>.<minor> version; correct the declaration in index.md, then set okf_version ${where} to the same value, or remove it`;
57
+ return [diagnostic("", "config-okf-version-stale", severity, message, void 0)];
58
+ });
59
+ /**
60
+ * #471: a `generated.at` later than now counts for no verification (OKF 0.3 §5.3) and `okfit verify` refuses it;
61
+ * `okfit sync` re-stamps it to now (a file with uncommitted edits is skipped until they are committed), except when a verification would then count
62
+ * (`verificationBlockingRestamp`).
63
+ */
64
+ const generatedAtFuture = perConcept("generated-at-future", (concept, context) => {
65
+ const at = concept.frontmatter.generated?.at;
66
+ const { now } = context;
67
+ if (at === void 0 || now === void 0 || !generatedAtIsFuture(at, now)) return [];
68
+ const head = `generated.at ${instant(at)} is more than ${GENERATED_AT_TOLERANCE_TEXT} later than now (${instant(now)}), so no verification can count yet (OKF 0.3 §5.3) and okfit verify refuses this concept`;
69
+ const blocking = verificationBlockingRestamp((concept.frontmatter.verified ?? []).map((entry) => entry.at), at, now);
70
+ return [{
71
+ message: Option.isSome(blocking) ? `${head}; okfit sync will not re-stamp it, because the verification dated ${instant(blocking.value)} would then count without a re-verification; a human must correct generated.at or that verification` : `${head}; run okfit sync, which re-stamps it to now (commit any edits to it first)`,
72
+ path: ["generated", "at"]
73
+ }];
74
+ });
31
75
  const unknownType = perConcept("unknown-type", (concept, context) => Object.hasOwn(context.config.types ?? {}, concept.frontmatter.type) ? [] : [{
32
76
  message: `Type "${concept.frontmatter.type}" is not declared in [types]`,
33
77
  path: ["type"]
34
78
  }]);
35
79
  const requiredKeyMissing = perConcept("required-key-missing", (concept, context) => {
36
80
  const declared = context.config.types?.[concept.frontmatter.type]?.required ?? [];
37
- return [.../* @__PURE__ */ new Set([...context.config.concepts?.required ?? [], ...declared])].filter((key) => !present(concept.frontmatter.raw, key)).map((key) => `Required key "${key}" is missing`);
81
+ const keys = [.../* @__PURE__ */ new Set([...context.config.concepts?.required ?? [], ...declared])];
82
+ const raw = concept.frontmatter.raw;
83
+ return keys.filter((key) => !present(raw, key)).map((key) => ({
84
+ message: `Required key "${key}" is ${Object.hasOwn(raw, key) ? "empty" : "missing"}`,
85
+ path: [key]
86
+ }));
38
87
  });
39
88
  const fieldValueUnknown = perConcept("field-value-unknown", (concept, context) => {
40
89
  const fields = context.config.types?.[concept.frontmatter.type]?.fields ?? {};
@@ -50,28 +99,107 @@ const fieldValueUnknown = perConcept("field-value-unknown", (concept, context) =
50
99
  return out;
51
100
  });
52
101
  const requireVerifiedUnmet = perConcept("require-verified-unmet", (concept, context) => context.config.types?.[concept.frontmatter.type]?.require_verified === true && concept.frontmatter.status !== "draft" && (concept.frontmatter.verified ?? []).length === 0 ? [{
53
- message: `Type "${concept.frontmatter.type}" requires a verified entry`,
102
+ message: Derive.status(concept.frontmatter) === "unknown" ? `Type "${concept.frontmatter.type}" requires a verified entry; status "${Derive.rawStatus(concept.frontmatter)}" is not draft, stable or deprecated, so set it first or verify with okfit verify --stable or --draft` : `Type "${concept.frontmatter.type}" requires a verified entry`,
54
103
  path: ["status"]
55
104
  }] : []);
56
- const statusMissing = perConcept("status-missing", (concept) => concept.frontmatter.status === void 0 && (concept.frontmatter.verified ?? []).length === 0 ? ["Concept has no status and no verified entry, so it reads as stable; set status: draft or stable explicitly"] : []);
57
- const generatedMissing = perConcept("generated-missing", (concept, context) => context.config.actors?.agent !== void 0 && !present(concept.frontmatter.raw, "generated") ? [`Concept has no generated block; okfit sync will create it from actors.agent (${context.config.actors.agent}) once the body is committed, or set generated.by by hand`] : []);
105
+ const TIER_RANK = {
106
+ unverified: 0,
107
+ "machine-confirmed": 1,
108
+ "human-reviewed": 2
109
+ };
110
+ const instant = Schema.encodeSync(Timestamp);
111
+ const verifiedBeforeChange = perConcept("verified-before-change", (concept) => {
112
+ const frontmatter = concept.frontmatter;
113
+ const generatedAt = frontmatter.generated?.at;
114
+ const status = Derive.status(frontmatter);
115
+ if (generatedAt === void 0 || status === "draft" || status === "deprecated" || status === "unknown") return [];
116
+ const events = frontmatter.verified ?? [];
117
+ const all = tierOf(events);
118
+ const current = Derive.trustTier(frontmatter);
119
+ if (TIER_RANK[all] <= TIER_RANK[current]) return [];
120
+ const lost = events.map((entry, index) => ({
121
+ entry,
122
+ index
123
+ })).filter(({ entry }) => !Derive.isCurrent(frontmatter, entry.at));
124
+ const newest = (items) => items.reduce((best, item) => best === void 0 || DateTime.toEpochMillis(item.entry.at) > DateTime.toEpochMillis(best.entry.at) ? item : best, void 0);
125
+ const target = (all === "human-reviewed" ? newest(lost.filter(({ entry }) => Actor.isHuman(entry.by))) : void 0) ?? newest(lost);
126
+ if (target === void 0) return [];
127
+ return [{
128
+ message: `Verified by ${target.entry.by} at ${instant(target.entry.at)}, before the last change at ${instant(generatedAt)}; the trust tier is now ${current} (OKF 0.3 §5.3); re-run okfit verify`,
129
+ path: Concept.entryPath(frontmatter, "verified", target.index)
130
+ }];
131
+ });
132
+ const statusMissing = perConcept("status-missing", (concept) => concept.frontmatter.status === void 0 && Derive.rawStatus(concept.frontmatter) === void 0 && (concept.frontmatter.verified ?? []).length === 0 ? ["Concept has no status and no verified entry, so it reads as stable; set status: draft or stable explicitly"] : []);
133
+ /**
134
+ * R45/R46: an okfit opinion layered on the load diagnostics `frontmatter-missing` and `type-missing`
135
+ * (OKF 0.3 §3.2 allows such files). Silent when `[bundle] non_concepts` is absent; otherwise a typeless
136
+ * file no glob matches is reported, ranged like its load diagnostic. The load diagnostics are unchanged.
137
+ */
138
+ const nonConceptUnlisted = rule("non-concept-unlisted", (context, severity) => {
139
+ const globs = context.config.bundle?.non_concepts;
140
+ if (globs === void 0) return [];
141
+ const why = (code) => code === "frontmatter-missing" ? "no frontmatter" : "no type";
142
+ const patterns = globs.flatMap((glob) => {
143
+ const compiled = GlobPattern.compileResult(glob);
144
+ return Result.isSuccess(compiled) ? [compiled.success] : [];
145
+ });
146
+ return context.bundle.diagnostics.filter((d) => (d.code === "frontmatter-missing" || d.code === "type-missing") && !patterns.some((pattern) => pattern.matches(d.file))).map((d) => diagnostic(d.file, "non-concept-unlisted", severity, globs.length === 0 ? `${d.file} is not a concept (${why(d.code)}) and [bundle] non_concepts is empty, so it allows no non-concept file; add frontmatter with a type, move it out of the bundle, or add a glob that matches it to non_concepts` : `${d.file} is not a concept (${why(d.code)}) and matches no [bundle] non_concepts glob (${globs.join(", ")}); add frontmatter with a type, move it out of the bundle, or list it in non_concepts`, d.range));
147
+ });
148
+ const generatedMissing = perConcept("generated-missing", (concept, context) => {
149
+ const agent = context.config.actors?.agent;
150
+ if (agent === void 0) return [];
151
+ const frontmatter = concept.frontmatter;
152
+ if (frontmatter.generated !== void 0) return !Concept.isAbsent(frontmatter.raw.generated) || frontmatter.generated.by !== Generated.LEGACY_BY ? [] : [{
153
+ path: ["timestamp"],
154
+ message: "Concept has no generated block, only a legacy timestamp, which okfit sync cannot convert; replace it with a generated block (generated.by, and generated.at from the timestamp) by hand"
155
+ }];
156
+ const document = Option.getOrUndefined(concept.document.frontmatter);
157
+ if (document !== void 0 && Object.hasOwn(frontmatter.raw, "generated") && !isReplaceableNull(document, "generated")) return [{
158
+ path: ["generated"],
159
+ message: "Concept's generated block has no readable generated.by, so it reads as absent (OKF 0.3 §5.2), and okfit sync cannot fill in a block that is written; set generated.by by hand"
160
+ }];
161
+ return [`Concept has no generated block; okfit sync will create it from actors.agent (${agent}) once the body is committed, or set generated.by by hand`];
162
+ });
163
+ /**
164
+ * OKF 0.3 §10.3: an Attested Computation with neither a `computation` key nor an inline computation is not
165
+ * attestable. `computationBody` is already the bundle's declared reading (fenced block under 0.3, the depth-1
166
+ * section under 0.2), so a missing or blank body is the one condition. `runtime` is not required here:
167
+ * `computation-runtime-missing` reports that separately.
168
+ */
169
+ const computationMissing = rule("computation-missing", (context, severity) => [...context.bundle.concepts.values()].flatMap((concept) => {
170
+ const attested = concept.frontmatter.attested;
171
+ if (attested === void 0 || attested.computation !== void 0) return [];
172
+ const body = concept.computationBody;
173
+ if (Option.isSome(body) && body.value.trim() !== "") return [];
174
+ const heading = Option.orElse(concept.document.sectionByHeading("Computation", { depth: 1 }), () => concept.document.sectionByHeading("Computation"));
175
+ const range = Option.match(heading, {
176
+ onNone: () => frontmatterPathRange(concept.document, []),
177
+ onSome: ({ heading: node }) => DiagnosticRange.fromOffset(concept.document.source, node.position.start.offset, node.position.end.offset - node.position.start.offset)
178
+ });
179
+ const legacy = OkfVersion.legacyFallbacks(context.bundle);
180
+ const message = legacy && Option.isSome(heading) && Option.isNone(concept.document.sectionByHeading("Computation", { depth: 1 })) ? "This Attested Computation has no computation: under OKF 0.2 the Computation section must be a top-level heading, and this one is not, so it is not attestable; make it a top-level heading, or declare okf_version 0.3 and put the computation in one fenced block" : Option.isSome(heading) ? legacy ? "This Attested Computation has no computation: its top-level Computation section is empty, so it is not attestable; write the computation under it, or set computation to a file" : Option.isSome(body) ? "This Attested Computation has no computation: the first fenced code block in its Computation section is empty (OKF 0.3 §10.3), so it is not attestable; put the computation in that block, or set computation to a file" : "This Attested Computation has no computation: its Computation section holds no fenced code block (OKF 0.3 §10.3), so it is not attestable; put the computation in one fenced block, or set computation to a file" : legacy ? "This Attested Computation has no computation: it has no Computation section and no computation key, so it is not attestable; add a top-level Computation section that holds the computation, or set computation to a file" : "This Attested Computation has no computation: it has no Computation section and no computation key, so it is not attestable; add a Computation section with the computation in one fenced block, or set computation to a file";
181
+ return [diagnostic(concept.path, "computation-missing", severity, message, range)];
182
+ }));
58
183
  const actorPrefixUnknown = perConcept("actor-prefix-unknown", (concept) => {
59
- const candidates = [{
60
- by: concept.frontmatter.generated?.by,
61
- path: ["generated", "by"]
62
- }, ...(concept.frontmatter.verified ?? []).map((entry, index) => ({
63
- by: entry.by,
64
- path: [
65
- "verified",
66
- index,
67
- "by"
68
- ]
69
- }))];
184
+ const candidates = [
185
+ {
186
+ by: concept.frontmatter.generated?.by,
187
+ path: ["generated", "by"]
188
+ },
189
+ ...(concept.frontmatter.verified ?? []).map((entry, index) => ({
190
+ by: entry.by,
191
+ path: [...Concept.entryPath(concept.frontmatter, "verified", index), "by"]
192
+ })),
193
+ ...(concept.frontmatter.sources ?? []).map((entry, index) => ({
194
+ by: entry.author,
195
+ path: [...Concept.entryPath(concept.frontmatter, "sources", index), "author"]
196
+ }))
197
+ ];
70
198
  const out = [];
71
199
  for (const candidate of candidates) {
72
200
  if (candidate.by === void 0 || Actor.form(candidate.by) !== "other") continue;
73
201
  out.push({
74
- message: `Actor "${candidate.by}" uses an unknown prefix; expected human:<id>, process:<id>, or <producer>/<version>`,
202
+ message: `Actor "${candidate.by}" uses an unknown prefix; expected human:<id>, team:<id>, process:<id>, or <producer>/<version>`,
75
203
  path: candidate.path
76
204
  });
77
205
  }
@@ -79,11 +207,7 @@ const actorPrefixUnknown = perConcept("actor-prefix-unknown", (concept) => {
79
207
  });
80
208
  /** Every actor-valued frontmatter field of a concept, with the path that names it. */
81
209
  const actorsOf = (concept) => {
82
- const verifiedPath = (index) => Array.isArray(concept.frontmatter.raw.verified) ? [
83
- "verified",
84
- index,
85
- "by"
86
- ] : ["verified", "by"];
210
+ const verifiedPath = (index) => [...Concept.entryPath(concept.frontmatter, "verified", index), "by"];
87
211
  const binding = concept.frontmatter.integrity?.verified;
88
212
  return [
89
213
  ...concept.frontmatter.generated === void 0 ? [] : [{
@@ -97,7 +221,7 @@ const actorsOf = (concept) => {
97
221
  ...binding === void 0 ? [] : [{
98
222
  by: binding.by,
99
223
  path: [
100
- "integrity",
224
+ INTEGRITY_KEY,
101
225
  "verified",
102
226
  "by"
103
227
  ]
@@ -202,19 +326,22 @@ const brokenLinks = rule("broken-links", (context, severity) => {
202
326
  slugCache.set(id, slugs);
203
327
  return slugs;
204
328
  };
205
- const check = (file, raw, targetId, target, position) => {
329
+ const check = (file, raw, targetId, target, position, label = "Link target") => {
206
330
  const fragment = fragmentOf(raw);
207
331
  if (fragment === void 0 || fragment === "") return;
208
332
  const slugs = slugsOf(targetId, target);
209
333
  if (slugs.includes(fragment)) return;
210
- const message = `Link target "${raw}" exists but has no heading "#${fragment}"; ${candidateHint(fragment, slugs)}`;
334
+ const message = `${label} "${raw}" exists but has no heading "#${fragment}"; ${candidateHint(fragment, slugs)}`;
211
335
  anchors.push(diagnostic(file, "broken-links", severity, message, position));
212
336
  };
213
337
  for (const link of context.graph.edges) {
214
- if (link.data.source !== "body") continue;
338
+ const { field } = link.data;
339
+ if (link.data.source !== "body" && field === void 0) continue;
340
+ if (field === "superseded_by" && link.to === link.from) continue;
215
341
  const target = byId.get(link.to);
216
342
  if (target === void 0) continue;
217
- check(fileOf(link.from), link.data.raw, link.to, target, link.data.position);
343
+ const label = field === void 0 ? void 0 : field === "sources.resource" ? "sources[].resource" : field;
344
+ check(fileOf(link.from), link.data.raw, link.to, target, link.data.position, label);
218
345
  }
219
346
  for (const concept of context.bundle.concepts.values()) for (const link of concept.document.links) {
220
347
  if (link.url === void 0 || !link.url.startsWith("#") || link.node.type === "linkReference") continue;
@@ -224,27 +351,48 @@ const brokenLinks = rule("broken-links", (context, severity) => {
224
351
  }
225
352
  return [...dangling, ...anchors];
226
353
  });
227
- const missingIndex = rule("missing-index", (context, severity) => Derive.indexDirectories(context.bundle).filter((dir) => !context.bundle.indexes.has(dir)).map((dir) => {
354
+ const supersededByOrphan = perConcept("superseded-by-orphan", (concept) => concept.frontmatter.superseded_by !== void 0 && Derive.status(concept.frontmatter) !== "deprecated" ? [{
355
+ message: `superseded_by is set but status is not deprecated; it has a meaning only with status: deprecated`,
356
+ path: ["superseded_by"]
357
+ }] : []);
358
+ const supersededByUnresolved = perConcept("superseded-by-unresolved", (concept, context) => {
359
+ const raw = concept.frontmatter.superseded_by;
360
+ if (raw === void 0 || Derive.status(concept.frontmatter) !== "deprecated") return [];
361
+ const resolved = Graph$1.resolve(context.bundle, concept.path, raw, "superseded_by");
362
+ const reason = resolved._tag === "node" ? resolved.kind === "missing" ? void 0 : resolved.kind === "file" ? "a file that is not a concept" : resolved.id === concept.id ? "the concept itself" : void 0 : resolved._tag === "self" ? "the concept itself" : "an external value";
363
+ return reason === void 0 ? [] : [{
364
+ message: `superseded_by "${raw}" resolves to ${reason}, not a replacement concept`,
365
+ path: ["superseded_by"]
366
+ }];
367
+ });
368
+ const missingIndex = rule("missing-index", (context, severity) => Derive.indexDirectories(context.bundle).filter((dir) => !context.bundle.indexes.has(dir)).filter((dir) => !context.bundle.files.includes(dir === "" ? "index.md" : `${dir}/index.md`)).filter((dir) => !context.bundle.diagnostics.some((entry) => entry.code === "read-changed" && entry.file === (dir === "" ? "index.md" : `${dir}/index.md`))).map((dir) => {
228
369
  const message = `Directory "${dir === "" ? "." : dir}" has no index.md`;
229
370
  return diagnostic(dir === "" ? "index.md" : `${dir}/index.md`, "missing-index", severity, message, void 0);
230
371
  }));
231
372
  /** Fixed rule order (task-group decision 9). */
232
373
  const LINT_RULES = [
233
374
  configUnknownKey,
375
+ configOkfVersionStale,
234
376
  unknownType,
235
377
  requiredKeyMissing,
236
378
  fieldValueUnknown,
237
379
  requireVerifiedUnmet,
380
+ verifiedBeforeChange,
238
381
  statusMissing,
382
+ nonConceptUnlisted,
239
383
  generatedMissing,
384
+ computationMissing,
385
+ generatedAtFuture,
240
386
  actorPrefixUnknown,
241
387
  actorEmail,
242
388
  verifiedActorUnknown,
243
389
  footnoteSourceUnknown,
244
390
  footnoteUndefined,
245
391
  brokenLinks,
392
+ supersededByOrphan,
393
+ supersededByUnresolved,
246
394
  missingIndex,
247
395
  stale
248
396
  ];
249
397
 
250
- export { LINT_RULES, actorEmail, actorPrefixUnknown, brokenLinks, configUnknownKey, fieldValueUnknown, footnoteSourceUnknown, footnoteUndefined, generatedMissing, missingIndex, requireVerifiedUnmet, requiredKeyMissing, stale, statusMissing, unknownType, verifiedActorUnknown };
398
+ export { LINT_RULES, actorEmail, actorPrefixUnknown, brokenLinks, computationMissing, configOkfVersionStale, configUnknownKey, fieldValueUnknown, footnoteSourceUnknown, footnoteUndefined, generatedAtFuture, generatedMissing, missingIndex, nonConceptUnlisted, requireVerifiedUnmet, requiredKeyMissing, stale, statusMissing, supersededByOrphan, supersededByUnresolved, unknownType, verifiedActorUnknown, verifiedBeforeChange };
@@ -3,9 +3,19 @@ import { Option } from "effect";
3
3
  import { Diagnostic, DiagnosticRange } from "../Diagnostic.js";
4
4
  import { IndexDocument, IndexEntry, IndexSection } from "../IndexDocument.js";
5
5
  import { LogDocument, LogGroup, LogItem } from "../LogDocument.js";
6
+ import { OkfVersion } from "../OkfVersion.js";
7
+ import { findFrontmatterScalarSource } from "./yamlPathSpan.js";
6
8
 
7
9
  // src/internal/reserved.ts
8
10
  /**
11
+ * What an unquoted `okf_version` number says: the text the author wrote (`source`, or what YAML read when the text is
12
+ * unavailable), what YAML read it as (`reads`), and whether the text is a `<major>.<minor>` pair that can be quoted as is.
13
+ */
14
+ const unquotedMessage = (source, reads, isPair) => {
15
+ const quoteAs = isPair ? source : "<major>.<minor>";
16
+ return source === reads ? `okf_version ${source} is an unquoted number; quote it as "${quoteAs}"` : `okf_version ${source} is an unquoted number, which YAML reads as ${reads}; quote it as "${quoteAs}"`;
17
+ };
18
+ /**
9
19
  * The one parse configuration every OKF file uses: GFM with frontmatter capture
10
20
  * (effected-markdown.md section 1; `Markdown.ts:60-62`).
11
21
  *
@@ -61,16 +71,45 @@ const parseIndex = (input) => {
61
71
  const { file, dir, document } = input;
62
72
  const text = document.source;
63
73
  const diagnostics = [];
64
- let okfVersion;
74
+ const metadata = {};
65
75
  const node = Option.getOrUndefined(document.frontmatter);
66
76
  if (node !== void 0 && Option.isSome(input.frontmatter)) {
67
77
  const raw = input.frontmatter.value;
68
78
  const record = raw !== null && typeof raw === "object" && !Array.isArray(raw) ? raw : void 0;
69
- const keys = record === void 0 ? [] : Object.keys(record);
70
- if (dir === "" && record !== void 0 && keys.length === 1 && typeof record.okf_version === "string") okfVersion = record.okf_version;
79
+ if (dir !== "") diagnostics.push(diagnostic(file, "index-frontmatter", "error", "index.md below the bundle root must not carry frontmatter", rangeOf(text, node.position)));
80
+ else if (raw === null) {} else if (record === void 0) diagnostics.push(diagnostic(file, "index-frontmatter", "error", "root index.md frontmatter must be a mapping", rangeOf(text, node.position)));
71
81
  else {
72
- const message = dir === "" ? "root index.md frontmatter may only carry a string \"okf_version\"" : "index.md below the bundle root must not carry frontmatter";
73
- diagnostics.push(diagnostic(file, "index-frontmatter", "error", message, rangeOf(text, node.position)));
82
+ metadata.metadata = record;
83
+ metadata.frontmatter = node.value;
84
+ const warn = (key, message) => {
85
+ diagnostics.push(diagnostic(file, "index-metadata-invalid", "warning", message, DiagnosticRange.forFrontmatterPath(document, [key]) ?? rangeOf(text, node.position)));
86
+ };
87
+ const version = record.okf_version;
88
+ if (typeof version === "string") {
89
+ if (version !== "") {
90
+ metadata.okfVersion = version;
91
+ if (Option.isNone(OkfVersion.parse(version))) warn("okf_version", `okf_version "${version}" is not a <major>.<minor> version`);
92
+ }
93
+ } else if (typeof version === "number") {
94
+ const reads = String(version);
95
+ const source = findFrontmatterScalarSource(node, ["okf_version"]) ?? reads;
96
+ const isPair = Option.isSome(OkfVersion.parse(source));
97
+ metadata.okfVersion = source;
98
+ warn("okf_version", unquotedMessage(source, reads, isPair));
99
+ } else if (version !== null && version !== void 0) {
100
+ metadata.okfVersion = JSON.stringify(version);
101
+ warn("okf_version", "okf_version must be a quoted <major>.<minor> string");
102
+ }
103
+ for (const key of [
104
+ "title",
105
+ "description",
106
+ "license"
107
+ ]) {
108
+ const value = record[key];
109
+ if (typeof value === "string") {
110
+ if (value !== "") metadata[key] = value;
111
+ } else if (value !== null && value !== void 0) warn(key, `${key} must be a string`);
112
+ }
74
113
  }
75
114
  }
76
115
  const sections = [];
@@ -112,12 +151,13 @@ const parseIndex = (input) => {
112
151
  const fields = {
113
152
  path: file,
114
153
  dir,
115
- sections
154
+ sections,
155
+ source: text
116
156
  };
117
157
  return {
118
- document: IndexDocument.make(okfVersion === void 0 ? fields : {
158
+ document: IndexDocument.make({
119
159
  ...fields,
120
- okfVersion
160
+ ...metadata
121
161
  }),
122
162
  diagnostics
123
163
  };
@@ -190,7 +230,8 @@ const parseLog = (input) => {
190
230
  const fields = {
191
231
  path: file,
192
232
  dir,
193
- groups
233
+ groups,
234
+ source: text
194
235
  };
195
236
  return {
196
237
  document: LogDocument.make(title === void 0 ? fields : {
@@ -21,19 +21,41 @@ const sectionNodes = (section) => [Heading.make({
21
21
  bulletChar: "*",
22
22
  children: section.entries.map(entryNode)
23
23
  })];
24
+ /** True when `text` parses to a mapping with no own `okf_version` key; a parse failure or non-mapping counts as declaring one. */
25
+ const lacksOkfVersion = (text) => {
26
+ const parsed = Yaml.parseResult(text);
27
+ if (Result.isFailure(parsed)) return false;
28
+ const value = parsed.success;
29
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
30
+ return !Object.hasOwn(value, "okf_version");
31
+ };
24
32
  /**
25
- * A whole `index.md`: root frontmatter carrying only `okf_version` when given (D-21), then each section.
33
+ * A whole `index.md`: root frontmatter, then each section.
34
+ *
35
+ * With `frontmatter` the existing block is emitted verbatim, and `okf_version` is prepended only when
36
+ * `okfVersion` is given and the block declares none (a declared version is never rewritten, D6). Without
37
+ * it the block carries only `okf_version` when given (D-21).
26
38
  *
27
39
  * Rendered by `@effected/markdown`'s emitter, so titles and descriptions are escaped only where markdown
28
40
  * would otherwise read them as syntax and round-trip to the original text (issue #72), and a target the
29
41
  * emitter cannot write bare (a space, for one) is written in angle brackets.
30
42
  */
31
- const indexDocument = (sections, okfVersion) => {
32
- const frontmatter = okfVersion === void 0 ? [] : [Frontmatter.make({
43
+ const indexDocument = (sections, options = {}) => {
44
+ const { okfVersion } = options;
45
+ const frontmatter = options.frontmatter?.replace(/\r\n?/g, "\n");
46
+ const metadata = frontmatter !== void 0 && frontmatter !== "" ? void 0 : options.metadata;
47
+ const fields = {
48
+ ...okfVersion === void 0 ? {} : { okf_version: okfVersion },
49
+ ...metadata?.title === void 0 ? {} : { title: metadata.title },
50
+ ...metadata?.description === void 0 ? {} : { description: metadata.description }
51
+ };
52
+ const versionLine = Object.keys(fields).length === 0 ? void 0 : Result.getOrThrow(Yaml.stringifyResult(fields)).replace(/\n$/, "");
53
+ const value = frontmatter === void 0 || frontmatter === "" ? versionLine : versionLine !== void 0 && lacksOkfVersion(frontmatter) ? `${versionLine}\n${frontmatter}` : frontmatter;
54
+ const block = value === void 0 ? [] : [Frontmatter.make({
33
55
  format: "yaml",
34
- value: Result.getOrThrow(Yaml.stringifyResult({ okf_version: okfVersion })).replace(/\n$/, "")
56
+ value
35
57
  })];
36
- const root = Root.make({ children: [...frontmatter, ...sections.flatMap(sectionNodes)] });
58
+ const root = Root.make({ children: [...block, ...sections.flatMap(sectionNodes)] });
37
59
  return Result.getOrThrow(Markdown.stringifyResult(root));
38
60
  };
39
61
  /** `## <date>`, a blank line, then one `* item` line per item (spec §9; S-32, MD022/MD032). */
@@ -0,0 +1,7 @@
1
+ import { Actor } from "../Actor.js";
2
+
3
+ // src/internal/tier.ts
4
+ /** The trust tier of a list of verification events (OKF 0.3 §5.3, §7): none is unverified, any `human:` is human-reviewed, else machine-confirmed. */
5
+ const tierOf = (events) => events.length === 0 ? "unverified" : events.some((entry) => Actor.isHuman(entry.by)) ? "human-reviewed" : "machine-confirmed";
6
+
7
+ export { tierOf };
package/internal/walk.js CHANGED
@@ -33,6 +33,7 @@ const walk = (options) => Effect.gen(function* () {
33
33
  })).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
34
34
  return {
35
35
  files: result.matches,
36
+ links: result.links,
36
37
  unreadable
37
38
  };
38
39
  });
@@ -1,4 +1,4 @@
1
- import { YamlDocument } from "@effected/yaml";
1
+ import { YamlDocument, YamlMap, YamlScalar } from "@effected/yaml";
2
2
  import { Option, Result } from "effect";
3
3
  import { toFileOffset } from "./position.js";
4
4
 
@@ -37,7 +37,10 @@ const frontmatterPathSpan = (text, node, path) => path.length === 0 ? blockSpan(
37
37
  * The file span of the YAML node at `path`, or `undefined` when there is none (or the re-parse is
38
38
  * fatal): {@link frontmatterPathSpan} without its whole-block fallback, for a caller that would
39
39
  * rather carry no range than a wrong one. Same quoting rule: a double-quoted scalar's span covers
40
- * its quotes.
40
+ * its quotes. A bare `key:` has no value node and a tagged empty value (`key: !!null`) has no text
41
+ * (the kit reports a zero-length span just after the tag), so neither has a value span: both answer `undefined`.
42
+ * An edit that splices into the returned span relies on it being the value's own text, so it is never the key's;
43
+ * {@link findFrontmatterAnchorSpan} is the diagnostic reading.
41
44
  *
42
45
  * @internal
43
46
  */
@@ -45,10 +48,85 @@ const findFrontmatterPathSpan = (text, node, path) => {
45
48
  const parsed = parsedYamlOf(node);
46
49
  if (Result.isFailure(parsed) || parsed.success.contents === null) return void 0;
47
50
  const hit = parsed.success.contents.find(path);
48
- return Option.isNone(hit) ? void 0 : {
51
+ if (Option.isNone(hit) || hit.value.length === 0) return void 0;
52
+ return {
49
53
  offset: toFileOffset(text, hit.value.offset),
50
54
  length: hit.value.length
51
55
  };
52
56
  };
57
+ /**
58
+ * The source text of the scalar at `path`, as its author wrote it (an unquoted `0.10` reads `"0.10"`, where YAML's
59
+ * value is `0.1`), or `undefined` when the node is not a scalar with text or the re-parse is fatal. Quotes are
60
+ * included for a quoted scalar; a tag or anchor never is.
61
+ *
62
+ * @internal
63
+ */
64
+ const findFrontmatterScalarSource = (node, path) => {
65
+ const parsed = parsedYamlOf(node);
66
+ if (Result.isFailure(parsed) || parsed.success.contents === null) return void 0;
67
+ const hit = parsed.success.contents.find(path);
68
+ if (Option.isNone(hit) || !(hit.value instanceof YamlScalar)) return void 0;
69
+ const source = hit.value.sourceText(node.value);
70
+ return source === "" ? void 0 : source;
71
+ };
72
+ /**
73
+ * The file span of the key at `path` (its last segment must be a mapping key), or `undefined` when the key is not
74
+ * written or the re-parse is fatal.
75
+ *
76
+ * @internal
77
+ */
78
+ const findFrontmatterKeySpan = (text, node, path) => {
79
+ const parsed = parsedYamlOf(node);
80
+ if (Result.isFailure(parsed) || parsed.success.contents === null) return void 0;
81
+ return keySpan(text, parsed.success.contents, path);
82
+ };
83
+ /**
84
+ * Where a diagnostic about `path` points: the value's own span, or the key's when the value has no text (a bare
85
+ * `key:` or a tagged empty value), or `undefined` when neither exists. For diagnostics only: an edit must not splice
86
+ * into the key, so it uses {@link findFrontmatterPathSpan}.
87
+ *
88
+ * @internal
89
+ */
90
+ const findFrontmatterAnchorSpan = (text, node, path) => findFrontmatterPathSpan(text, node, path) ?? findFrontmatterKeySpan(text, node, path);
91
+ /**
92
+ * {@link findFrontmatterAnchorSpan} with {@link frontmatterPathSpan}'s whole-block fallback.
93
+ *
94
+ * @internal
95
+ */
96
+ const frontmatterAnchorSpan = (text, node, path) => path.length === 0 ? blockSpan(node) : findFrontmatterAnchorSpan(text, node, path) ?? blockSpan(node);
97
+ /** The pair of `map` whose key is the plain scalar `key`. */
98
+ const pairOf = (map, key) => map.items.find((item) => item.key instanceof YamlScalar && item.key.value === key);
99
+ const keySpan = (text, contents, path) => {
100
+ const key = path.at(-1);
101
+ if (typeof key !== "string") return void 0;
102
+ const parent = path.length === 1 ? Option.some(contents) : contents.find(path.slice(0, -1));
103
+ if (Option.isNone(parent) || !(parent.value instanceof YamlMap)) return void 0;
104
+ const pair = pairOf(parent.value, key);
105
+ return pair === void 0 ? void 0 : {
106
+ offset: toFileOffset(text, pair.key.offset),
107
+ length: pair.key.length
108
+ };
109
+ };
110
+ /**
111
+ * Whether the top-level `key` is a value `okfit sync` can replace whole: unwritten, a bare `key:`, or an untagged,
112
+ * unanchored plain null (`null`, `~`) in a block-style mapping. This mirrors the engine's `locateGeneratedBlock`
113
+ * (`engine/src/verify/locate.ts`), which core cannot import: a tagged or anchored null (`!!null`, `&a ~`) carries
114
+ * syntax a whole-line replace would drop or duplicate, so sync skips it as `generated-unsupported`. A re-parse that
115
+ * fails or a non-mapping document answers `false`, as the engine reports those unsupported too.
116
+ *
117
+ * @internal
118
+ */
119
+ const isReplaceableNull = (node, key) => {
120
+ const parsed = parsedYamlOf(node);
121
+ if (Result.isFailure(parsed)) return false;
122
+ const contents = parsed.success.contents;
123
+ if (!(contents instanceof YamlMap) || contents.style === "flow") return false;
124
+ const pair = pairOf(contents, key);
125
+ if (pair === void 0) return true;
126
+ const value = pair.value;
127
+ const isNull = value === null || value instanceof YamlScalar && value.style === "plain" && value.value === null && value.tag === void 0 && value.anchor === void 0;
128
+ const lineStart = node.value.lastIndexOf("\n", pair.key.offset - 1) + 1;
129
+ return isNull && node.value.slice(lineStart, pair.key.offset).trim() === "";
130
+ };
53
131
 
54
- export { findFrontmatterPathSpan, frontmatterPathSpan };
132
+ export { findFrontmatterAnchorSpan, findFrontmatterKeySpan, findFrontmatterPathSpan, findFrontmatterScalarSource, frontmatterAnchorSpan, frontmatterPathSpan, isReplaceableNull };
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@okfit/core",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "private": false,
5
- "description": "Spec-level Open Knowledge Format (OKF) v0.2 schemas, bundle loading, graph, derivation, and validation for Effect.",
5
+ "description": "Spec-level Open Knowledge Format (OKF) v0.3 schemas, bundle loading, graph, derivation, and validation for Effect.",
6
6
  "keywords": [
7
7
  "okf",
8
8
  "open-knowledge-format",
@@ -37,15 +37,15 @@
37
37
  "./package.json": "./package.json"
38
38
  },
39
39
  "peerDependencies": {
40
- "@effected/config-file": "^0.29.0",
40
+ "@effected/config-file": "^0.31.0",
41
41
  "@effected/glob": "^0.23.0",
42
42
  "@effected/jsonc": "^0.25.0",
43
- "@effected/markdown": "^0.29.0",
43
+ "@effected/markdown": "^0.32.0",
44
44
  "@effected/schemastore": "^0.33.0",
45
45
  "@effected/source": "^0.5.0",
46
46
  "@effected/toml": "^0.20.0",
47
- "@effected/walker": "^0.30.0",
48
- "@effected/yaml": "^0.30.0",
47
+ "@effected/walker": "^0.32.0",
48
+ "@effected/yaml": "^0.31.0",
49
49
  "effect": "~4.1.0"
50
50
  },
51
51
  "engines": {
@@ -5,7 +5,7 @@
5
5
  "toolPackages": [
6
6
  {
7
7
  "packageName": "@microsoft/api-extractor",
8
- "packageVersion": "7.60.1"
8
+ "packageVersion": "7.60.2"
9
9
  }
10
10
  ]
11
11
  }