@okfit/core 0.13.5 → 0.15.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/Actor.js CHANGED
@@ -9,7 +9,7 @@ const form = (actor) => {
9
9
  const slash = actor.indexOf("/");
10
10
  if (slash !== -1 && (colon === -1 || slash < colon)) return "producer";
11
11
  const prefix = colon === -1 ? "" : actor.slice(0, colon);
12
- return prefix === "human" ? "human" : prefix === "process" ? "process" : "other";
12
+ return prefix === "human" ? "human" : prefix === "team" ? "team" : prefix === "process" ? "process" : "other";
13
13
  };
14
14
  const GLOB_RE = /[*?]/u;
15
15
  /** `*` is any run of non-whitespace, `?` one non-whitespace character; everything else is literal. */
@@ -15,14 +15,14 @@ var ComputationParameter = class extends Schema.Class("ComputationParameter")({
15
15
  * @public
16
16
  */
17
17
  var ComputationExecutor = class extends Schema.Class("ComputationExecutor")({
18
- resource: Schema.String,
19
- receipt: Schema.Array(Schema.String)
18
+ resource: Schema.optionalKey(Schema.String),
19
+ receipt: Schema.optionalKey(Schema.Array(Schema.String))
20
20
  }) {};
21
21
  /**
22
22
  * The deterministic attester that checks an executor's receipt.
23
23
  * @public
24
24
  */
25
- var ComputationAttester = class extends Schema.Class("ComputationAttester")({ resource: Schema.String }) {};
25
+ var ComputationAttester = class extends Schema.Class("ComputationAttester")({ resource: Schema.optionalKey(Schema.String) }) {};
26
26
  /**
27
27
  * The `Attested Computation` family (D-20). `runtime` absent means lint
28
28
  * `computation-runtime-missing`; the concept still loads.
package/Bundle.js CHANGED
@@ -1,3 +1,7 @@
1
+ import { FrontmatterDecodeError, MarkdownDocument, MarkdownVisitor, YamlFrontmatter } from "@effected/markdown";
2
+ import { DescendError, PosixPath, confineReal } from "@effected/walker";
3
+ import { YamlParseError } from "@effected/yaml";
4
+ import { Effect, FileSystem, Option, Path, Result, Schema } from "effect";
1
5
  import { Concept } from "./Concept.js";
2
6
  import { ConceptId } from "./ConceptId.js";
3
7
  import { Diagnostic, DiagnosticRange } from "./Diagnostic.js";
@@ -8,10 +12,7 @@ import { toFileOffset } from "./internal/position.js";
8
12
  import { OPTIONS, parseIndex, parseLog } from "./internal/reserved.js";
9
13
  import { DEFAULT_PRUNE, walk } from "./internal/walk.js";
10
14
  import { LogDocument } from "./LogDocument.js";
11
- import { Effect, FileSystem, Option, Path, Result, Schema } from "effect";
12
- import { FrontmatterDecodeError, MarkdownDocument, YamlFrontmatter } from "@effected/markdown";
13
- import { DescendError, PosixPath } from "@effected/walker";
14
- import { YamlParseError } from "@effected/yaml";
15
+ import { OkfVersion } from "./OkfVersion.js";
15
16
 
16
17
  // src/Bundle.ts
17
18
  /**
@@ -58,7 +59,14 @@ var BundleDepthExceededError = class extends Schema.TaggedError()("BundleDepthEx
58
59
  };
59
60
  /**
60
61
  * One concept file after loading: typed frontmatter, the parsed body, and the
61
- * `# Computation` section body when present (D-20).
62
+ * inline computation when present.
63
+ *
64
+ * @remarks
65
+ * `computationBody` is the inline form only. 0.3 or later: the code of the first fenced block in
66
+ * the first `Computation` section at any heading level (an empty fence yields an empty string; no
67
+ * fence is `None`). 0.2 or undeclared: the body of the depth-1 `Computation` section. When
68
+ * `attested.computation` is set, the file that path names is the computation (OKF 0.3 10.3 rule 1)
69
+ * and this field is not authoritative; core does not read that file.
62
70
  *
63
71
  * @public
64
72
  */
@@ -97,6 +105,32 @@ const diagnostic = (file, code, severity, message, range) => Diagnostic.make(ran
97
105
  message,
98
106
  range
99
107
  });
108
+ /** CommonMark: a fence opens with three backticks or tildes after at most three spaces; four or more is indented code. */
109
+ const FENCE_OPENING = /^ {0,3}(```|~~~)/;
110
+ /**
111
+ * OKF 0.3 10.3: the code of the first fenced block in the first `Computation` section, in source order.
112
+ *
113
+ * @remarks
114
+ * Blocks nested in a list item or block quote count (R17): the section's blocks are walked depth first.
115
+ * A deeper sub-heading does not end the section (`sectionByHeading` keeps its subsections), and the first
116
+ * fenced block wins even when it sits in a list item before a root-level fence. A code node's position starts
117
+ * at the fence character when it is fenced and at its indentation when it is an indented block, so the fence
118
+ * test reads from the node's own start; its `value` already has the container's indentation and `> ` markers
119
+ * removed and the inner relative indentation kept.
120
+ */
121
+ const fencedComputation = (document) => Option.flatMapNullishOr(document.sectionByHeading("Computation"), (section) => {
122
+ const first = section.children[0];
123
+ const last = section.children[section.children.length - 1];
124
+ if (first === void 0 || last === void 0) return void 0;
125
+ const from = first.position.start.offset;
126
+ const to = last.position.end.offset;
127
+ for (const event of MarkdownVisitor.walk(document.root)) {
128
+ if (event._tag !== "Enter" || event.node.type !== "code") continue;
129
+ const offset = event.node.position.start.offset;
130
+ if (offset < from || offset >= to) continue;
131
+ if (FENCE_OPENING.test(document.source.slice(offset, offset + 6))) return event.node.value;
132
+ }
133
+ });
100
134
  const blockRange = (text, node) => DiagnosticRange.fromOffset(text, node.position.start.offset, node.position.end.offset - node.position.start.offset);
101
135
  /** Group A's `dirname` returns `"."` for a bundle-root file; `LoadedBundle` keys the root `""`. */
102
136
  const directoryKey = (relativePath) => {
@@ -121,8 +155,8 @@ const loadMarkdown = (file, text) => Effect.gen(function* () {
121
155
  const reserved = ConceptId.isReservedFile(file);
122
156
  const fence = detectFence(text);
123
157
  if (fence === "unclosed") return { diagnostics: [diagnostic(file, "frontmatter-unclosed", "error", "frontmatter opens with --- but never closes", DiagnosticRange.fromOffset(text, 0, 3))] };
124
- if (fence === "absent" && !reserved) return { diagnostics: [diagnostic(file, "frontmatter-missing", "error", "concept files must start with a --- frontmatter block")] };
125
- const parsed = MarkdownDocument.parseResult(text, OPTIONS);
158
+ if (fence === "absent" && !reserved) return { diagnostics: [diagnostic(file, "frontmatter-missing", "warning", "no frontmatter, so this file is not a concept and is skipped")] };
159
+ const parsed = Bundle.parseDocument(text);
126
160
  if (Result.isFailure(parsed)) {
127
161
  const d = parsed.failure.diagnostic;
128
162
  return { diagnostics: [diagnostic(file, "frontmatter-unparseable", "error", d.message, DiagnosticRange.fromOffset(text, d.offset, d.length))] };
@@ -166,7 +200,6 @@ const loadMarkdown = (file, text) => Effect.gen(function* () {
166
200
  const diagnostics = [...decoded.diagnostics, ...result.diagnostics];
167
201
  const id = ConceptId.fromPath(file);
168
202
  if (Option.isNone(result.concept) || Option.isNone(id)) return { diagnostics };
169
- const computation = document.sectionByHeading("Computation", { depth: 1 });
170
203
  return {
171
204
  diagnostics,
172
205
  concept: LoadedConcept.make({
@@ -174,7 +207,7 @@ const loadMarkdown = (file, text) => Effect.gen(function* () {
174
207
  path: file,
175
208
  frontmatter: result.concept.value,
176
209
  document,
177
- computationBody: Option.map(computation, (section) => section.body)
210
+ computationBody: Bundle.inlineComputation(document, "legacy")
178
211
  })
179
212
  };
180
213
  });
@@ -184,9 +217,23 @@ const loadMarkdown = (file, text) => Effect.gen(function* () {
184
217
  *
185
218
  * @public
186
219
  */
187
- var Bundle = class {
220
+ var Bundle = class Bundle {
188
221
  constructor() {}
189
222
  /**
223
+ * Parse Markdown text exactly as `Bundle.load` parses every bundle file (frontmatter on), so a tool that
224
+ * scans a file the loader did not keep as a concept reads its body the way a concept's is read.
225
+ */
226
+ static parseDocument = (text) => MarkdownDocument.parseResult(text, OPTIONS);
227
+ /**
228
+ * Pure. The inline computation of `document` under one reading of the spec: `"legacy"` (OKF 0.2) is the body
229
+ * of the depth-1 `Computation` section, `"current"` (OKF 0.3 section 10.3) is the first fenced block of the
230
+ * first `Computation` section at any heading level. `None` when the reading finds nothing. `Bundle.load` calls
231
+ * this for the reading its bundle's declared version selects; a tool comparing the two readings calls it twice.
232
+ *
233
+ * @public
234
+ */
235
+ static inlineComputation = (document, reading) => reading === "legacy" ? Option.map(document.sectionByHeading("Computation", { depth: 1 }), (section) => section.body) : fencedComputation(document);
236
+ /**
190
237
  * Load the bundle at `options.root` (D-8, D-9, D-11 to D-14, D-21). Content never
191
238
  * fails: every bad file becomes a diagnostic and loading continues (spec 8). A walk
192
239
  * that descends past `options.maxDepth` fails typed with `BundleDepthExceededError`
@@ -226,11 +273,30 @@ var Bundle = class {
226
273
  prune: new Set(options.prune ?? DEFAULT_PRUNE)
227
274
  }).pipe(Effect.mapError(toLoadError));
228
275
  const diagnostics = walked.unreadable.map(({ path: dir, reason }) => diagnostic(dir, "walk-unreadable", "warning", `directory "${dir}" could not be read (${reason}); its files are not part of the bundle`));
276
+ const files = [];
277
+ for (const file of walked.files) {
278
+ if ((yield* fs.lstat(path.join(root, file)).pipe(Effect.mapError((cause) => new BundleReadError({
279
+ root,
280
+ path: file,
281
+ cause
282
+ })))).type === "SymbolicLink") {
283
+ const refused = yield* confineReal(root, path.join(root, file)).pipe(Effect.match({
284
+ onFailure: (error) => error,
285
+ onSuccess: () => void 0
286
+ }));
287
+ if (refused !== void 0) {
288
+ const why = refused.reason === "outside" ? "resolves outside the bundle root" : "could not be resolved, so it cannot be shown to stay inside the bundle root";
289
+ diagnostics.push(diagnostic(file, "symlink-escape", "warning", `symbolic link ${why}; it is not read and not part of the bundle`));
290
+ continue;
291
+ }
292
+ }
293
+ files.push(file);
294
+ }
229
295
  const concepts = /* @__PURE__ */ new Map();
230
296
  const indexes = /* @__PURE__ */ new Map();
231
297
  const logs = /* @__PURE__ */ new Map();
232
298
  const directories = /* @__PURE__ */ new Set();
233
- for (const file of walked.files) {
299
+ for (const file of files) {
234
300
  if (!file.endsWith(".md")) continue;
235
301
  const text = yield* fs.readFileString(path.join(root, file)).pipe(Effect.mapError((cause) => new BundleReadError({
236
302
  root,
@@ -246,15 +312,25 @@ var Bundle = class {
246
312
  if (outcome.index !== void 0) indexes.set(outcome.index.dir, outcome.index);
247
313
  if (outcome.log !== void 0) logs.set(outcome.log.dir, outcome.log);
248
314
  }
249
- return LoadedBundle.make({
315
+ const bundle = LoadedBundle.make({
250
316
  root,
251
- files: walked.files,
317
+ files,
252
318
  directories: [...directories].sort(),
253
319
  concepts,
254
320
  indexes,
255
321
  logs,
256
322
  diagnostics
257
323
  });
324
+ if (OkfVersion.legacyFallbacks(bundle)) return bundle;
325
+ const located = /* @__PURE__ */ new Map();
326
+ for (const [conceptId, concept] of concepts) located.set(conceptId, LoadedConcept.make({
327
+ ...concept,
328
+ computationBody: Bundle.inlineComputation(concept.document, "current")
329
+ }));
330
+ return LoadedBundle.make({
331
+ ...bundle,
332
+ concepts: located
333
+ });
258
334
  });
259
335
  };
260
336
 
package/Concept.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { Schema } from "effect";
1
2
  import { AttestedComputation } from "./AttestedComputation.js";
2
3
  import { Generated } from "./Generated.js";
3
4
  import { Integrity } from "./Integrity.js";
@@ -5,7 +6,6 @@ import { Source, UsageWindow } from "./Source.js";
5
6
  import { Status } from "./Status.js";
6
7
  import { Timestamp } from "./Timestamp.js";
7
8
  import { Verification } from "./Verification.js";
8
- import { Schema } from "effect";
9
9
 
10
10
  // src/Concept.ts
11
11
  /**
@@ -13,6 +13,21 @@ import { Schema } from "effect";
13
13
  * @public
14
14
  */
15
15
  const ATTESTED_COMPUTATION_TYPE = "Attested Computation";
16
+ const YamlPath = Schema.Array(Schema.Union([Schema.String, Schema.Number]));
17
+ /**
18
+ * The YAML path of each kept entry of the four list families, in kept order. Tolerant
19
+ * reading drops an unreadable entry, so a kept entry's decoded index is not its YAML
20
+ * index; every range or edit path computed from a list family comes from here, through
21
+ * `Concept.entryPath`. A single item (a bare mapping) records `["sources"]`.
22
+ *
23
+ * @public
24
+ */
25
+ var EntryPaths = class extends Schema.Class("EntryPaths")({
26
+ tags: Schema.optionalKey(Schema.Array(YamlPath)),
27
+ sources: Schema.optionalKey(Schema.Array(YamlPath)),
28
+ verified: Schema.optionalKey(Schema.Array(YamlPath)),
29
+ parameters: Schema.optionalKey(Schema.Array(YamlPath))
30
+ }) {};
16
31
  /**
17
32
  * A typed OKF concept: the stage-1 envelope (`type`), every optional family,
18
33
  * unknown keys in `extensions`, and the whole decoded mapping in `raw`.
@@ -36,10 +51,23 @@ var Concept = class extends Schema.Class("Concept")({
36
51
  verified: Schema.optionalKey(Verification.List),
37
52
  status: Schema.optionalKey(Status),
38
53
  stale_after: Schema.optionalKey(Timestamp),
54
+ superseded_by: Schema.optionalKey(Schema.String),
39
55
  integrity: Schema.optionalKey(Integrity),
40
56
  attested: Schema.optionalKey(AttestedComputation),
57
+ entries: Schema.optionalKey(EntryPaths),
41
58
  extensions: Schema.Record(Schema.String, Schema.Unknown),
42
59
  raw: Schema.Record(Schema.String, Schema.Unknown)
43
- }) {};
60
+ }) {
61
+ /**
62
+ * The YAML path of the `position`-th kept entry of a list family. Without recorded
63
+ * `entries` (a hand-built concept) it falls back to `[family, position]`, or `[family]`
64
+ * when `raw[family]` is not a list.
65
+ */
66
+ static entryPath(concept, family, position) {
67
+ const recorded = concept.entries?.[family]?.[position];
68
+ if (recorded !== void 0) return recorded;
69
+ return Array.isArray(concept.raw[family]) ? [family, position] : [family];
70
+ }
71
+ };
44
72
 
45
- export { ATTESTED_COMPUTATION_TYPE, Concept };
73
+ export { ATTESTED_COMPUTATION_TYPE, Concept, EntryPaths };
package/ConceptId.js CHANGED
@@ -1,5 +1,5 @@
1
- import { Option, Schema } from "effect";
2
1
  import { PosixPath } from "@effected/walker";
2
+ import { Option, Schema } from "effect";
3
3
 
4
4
  // src/ConceptId.ts
5
5
  const RESERVED_BASENAMES = /* @__PURE__ */ new Set(["index.md", "log.md"]);
package/Derive.js CHANGED
@@ -1,21 +1,30 @@
1
- import { Actor } from "./Actor.js";
2
- import { indexDocument, logEntry } from "./internal/templates.js";
3
- import { DateTime, Schema } from "effect";
4
1
  import { PosixPath } from "@effected/walker";
2
+ import { DateTime, Schema } from "effect";
3
+ import { isAbsent } from "./internal/conceptDecode.js";
4
+ import { indexDocument, logEntry } from "./internal/templates.js";
5
+ import { tierOf } from "./internal/tier.js";
5
6
 
6
7
  // src/Derive.ts
7
- /** Trust tier from `verified` (OKF 0.2 §5.3): none maps to unverified; only non-human maps to machine-confirmed; any `human:` maps to human-reviewed. @public */
8
+ /**
9
+ * Trust tier from the current `verified` events (OKF 0.3 §5.3, §7): no current event is unverified; current events
10
+ * none of which is `human:` (a `team:` or unknown scheme included) are machine-confirmed; any current `human:` event
11
+ * is human-reviewed. An event before the last `generated.at` is history: it stays in the file and counts for nothing.
12
+ * @public
13
+ */
8
14
  const TrustTier = Schema.Literals([
9
15
  "unverified",
10
16
  "machine-confirmed",
11
17
  "human-reviewed"
12
18
  ]);
13
- /** Three-way staleness; `unknown` means no `stale_after`. @public */
19
+ /** Staleness; `unknown` means no `stale_after`, `malformed` a `stale_after` okfit cannot read (OKF 0.3 §5.5). @public */
14
20
  const Staleness = Schema.Literals([
15
21
  "fresh",
16
22
  "stale",
17
- "unknown"
23
+ "unknown",
24
+ "malformed"
18
25
  ]);
26
+ /** `stale_after` is present in `raw` (not `null`, `""` or `[]`) yet did not decode to an instant. */
27
+ const isMalformedStaleAfter = (concept) => concept.stale_after === void 0 && !isAbsent(concept.raw.stale_after);
19
28
  const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
20
29
  const oneLine = (text) => text.replace(/\s+/g, " ").trim();
21
30
  /** The bundle-relative directory of `path`; `""` for a file at the bundle root. */
@@ -27,17 +36,53 @@ const relativeTarget = (dir, path) => dir !== "" && path.startsWith(`${dir}/`) ?
27
36
  /** Pure derivations (D-10, D-36): trust tier, status, staleness against a supplied instant, index/log rendering. @public */
28
37
  var Derive = class Derive {
29
38
  constructor() {}
30
- /** Any `human:` verifier means human-reviewed; otherwise machine-confirmed; none means unverified. */
39
+ /**
40
+ * Whether a verification event at `at` is current for `concept` (OKF 0.3 §5.3): `at` is equal to or later than
41
+ * `generated.at` by instant, or `generated` or `generated.at` is absent. It reads only `generated`, so a caller holding
42
+ * no whole concept passes `{ generated }`.
43
+ *
44
+ * @public
45
+ */
46
+ static isCurrent = (concept, at) => {
47
+ const generatedAt = concept.generated?.at;
48
+ return generatedAt === void 0 || DateTime.toEpochMillis(at) >= DateTime.toEpochMillis(generatedAt);
49
+ };
50
+ /**
51
+ * The decoded `verified` entries that are current ({@link Derive.isCurrent}), in list order. Earlier events stay
52
+ * in the file as history (OKF 0.3 §5.3) and are not returned.
53
+ *
54
+ * @public
55
+ */
56
+ static currentVerifications = (concept) => (concept.verified ?? []).filter((entry) => Derive.isCurrent(concept, entry.at));
57
+ /**
58
+ * The trust tier from {@link Derive.currentVerifications} only (OKF 0.3 §5.3, §7; §11.2 makes it a MUST for every
59
+ * bundle): none is unverified, any `human:` verifier is human-reviewed, otherwise machine-confirmed.
60
+ *
61
+ * @public
62
+ */
31
63
  static trustTier = (concept) => {
32
- const verified = concept.verified ?? [];
33
- if (verified.length === 0) return "unverified";
34
- return verified.some((entry) => Actor.isHuman(entry.by)) ? "human-reviewed" : "machine-confirmed";
64
+ return tierOf(Derive.currentVerifications(concept));
65
+ };
66
+ /**
67
+ * The typed status; `unknown` when `raw.status` is present (not `null`, `""` or `[]`) but outside the
68
+ * vocabulary; `stable` when absent (OKF 0.3 §5.4).
69
+ */
70
+ static status = (concept) => {
71
+ if (concept.status !== void 0) return concept.status;
72
+ return Derive.rawStatus(concept) === void 0 ? "stable" : "unknown";
35
73
  };
36
- /** Absent `status` reads as `stable` (OKF 0.2 §5.4). */
37
- static status = (concept) => concept.status ?? "stable";
38
- /** `stale` when `now >= stale_after` (OKF 0.2 §5.5); `unknown` without `stale_after`. */
74
+ /** The `status` value as written, as text for display; `undefined` when absent, `null`, `""` or `[]`. */
75
+ static rawStatus = (concept) => {
76
+ const value = concept.raw.status;
77
+ if (isAbsent(value)) return void 0;
78
+ return typeof value === "string" ? value : JSON.stringify(value);
79
+ };
80
+ /**
81
+ * `stale` when `now >= stale_after` (OKF 0.3 §5.5); `unknown` without `stale_after`; `malformed`
82
+ * when `raw.stale_after` is present (not `null`, `""` or `[]`) but unreadable, so never fresh and never stale.
83
+ */
39
84
  static staleness = (concept, now) => {
40
- if (concept.stale_after === void 0) return "unknown";
85
+ if (concept.stale_after === void 0) return isMalformedStaleAfter(concept) ? "malformed" : "unknown";
41
86
  return DateTime.toEpochMillis(now) >= DateTime.toEpochMillis(concept.stale_after) ? "stale" : "fresh";
42
87
  };
43
88
  /** Boolean form of {@link Derive.staleness} (D-36). */
@@ -62,7 +107,24 @@ var Derive = class Derive {
62
107
  }
63
108
  return out.sort((a, b) => compare(a.id, b.id));
64
109
  };
65
- /** Frontmatter `title`, else the file name without `.md` (OKF 0.2 §4.1). */
110
+ /**
111
+ * Every concept in `bundle` whose {@link Derive.staleness} is `malformed` (OKF 0.3 §5.5: an unreadable
112
+ * `stale_after` is never fresh), with the value as written, sorted by id ascending. `staleReport` never
113
+ * lists these. A malformed value does not depend on the instant, so there is no `now` argument.
114
+ */
115
+ static malformedStaleAfter = (bundle) => {
116
+ const out = [];
117
+ for (const [id, concept] of bundle.concepts) {
118
+ if (!isMalformedStaleAfter(concept.frontmatter)) continue;
119
+ const value = concept.frontmatter.raw.stale_after;
120
+ out.push({
121
+ id,
122
+ raw: typeof value === "string" ? value : JSON.stringify(value)
123
+ });
124
+ }
125
+ return out.sort((a, b) => compare(a.id, b.id));
126
+ };
127
+ /** Frontmatter `title`, else the file name without `.md` (OKF 0.3 §4.1). */
66
128
  static title = (concept) => concept.frontmatter.title ?? PosixPath.basename(concept.path).replace(/\.md$/, "");
67
129
  /** One H1 per `type` (sorted), entries sorted by title, then `# Subdirectories` (D-36; spec §8). */
68
130
  static renderIndex = (dir, concepts, options = {}) => {
@@ -89,7 +151,11 @@ var Derive = class Derive {
89
151
  target: `${name}/index.md`
90
152
  }))
91
153
  });
92
- return indexDocument(sections, options.okfVersion);
154
+ return indexDocument(sections, {
155
+ ...options.okfVersion === void 0 ? {} : { okfVersion: options.okfVersion },
156
+ ...options.frontmatter === void 0 ? {} : { frontmatter: options.frontmatter },
157
+ ...options.metadata === void 0 ? {} : { metadata: options.metadata }
158
+ });
93
159
  };
94
160
  /** `## <date>` plus one `* <item>` line per item, newline-terminated (D-36). */
95
161
  static renderLogEntry = (entry) => logEntry(entry.date, entry.items);
package/Diagnostic.js CHANGED
@@ -1,6 +1,6 @@
1
- import { frontmatterPathSpan } from "./internal/yamlPathSpan.js";
2
- import { Option, Schema } from "effect";
3
1
  import { LineIndex } from "@effected/source";
2
+ import { Option, Schema } from "effect";
3
+ import { frontmatterPathSpan } from "./internal/yamlPathSpan.js";
4
4
 
5
5
  // src/Diagnostic.ts
6
6
  /** @public */
@@ -11,10 +11,8 @@ const DiagnosticSeverity = Schema.Literals([
11
11
  ]);
12
12
  /** Always `"error"`, never configurable (D-33). @public */
13
13
  const ConformanceCode = Schema.Literals([
14
- "frontmatter-missing",
15
14
  "frontmatter-unclosed",
16
15
  "frontmatter-unparseable",
17
- "type-missing",
18
16
  "index-frontmatter",
19
17
  "index-malformed",
20
18
  "log-heading-invalid",
@@ -28,6 +26,7 @@ const LintCode = Schema.Literals([
28
26
  "required-key-missing",
29
27
  "field-value-unknown",
30
28
  "require-verified-unmet",
29
+ "verified-before-change",
31
30
  "family-invalid",
32
31
  "computation-runtime-missing",
33
32
  "footnote-source-unknown",
@@ -36,6 +35,7 @@ const LintCode = Schema.Literals([
36
35
  "actor-prefix-unknown",
37
36
  "legacy-timestamp",
38
37
  "config-unknown-key",
38
+ "config-okf-version-stale",
39
39
  "stale",
40
40
  "walk-unreadable",
41
41
  "generated-at-drift",
@@ -47,7 +47,22 @@ const LintCode = Schema.Literals([
47
47
  "surface-unmatched",
48
48
  "verified-drift",
49
49
  "actor-email",
50
- "verified-actor-unknown"
50
+ "verified-actor-unknown",
51
+ "resource-ignored",
52
+ "resource-untracked",
53
+ "resource-outside-project",
54
+ "superseded-by-orphan",
55
+ "superseded-by-unresolved",
56
+ "index-metadata-invalid",
57
+ "entry-ignored",
58
+ "value-malformed",
59
+ "value-unknown",
60
+ "frontmatter-missing",
61
+ "type-missing",
62
+ "symlink-escape",
63
+ "non-concept-unlisted",
64
+ "computation-missing",
65
+ "generated-at-future"
51
66
  ]);
52
67
  /** @public */
53
68
  const DiagnosticCode = Schema.Union([ConformanceCode, LintCode]);
package/Generated.js CHANGED
@@ -1,6 +1,6 @@
1
+ import { Schema } from "effect";
1
2
  import { Actor } from "./Actor.js";
2
3
  import { Timestamp } from "./Timestamp.js";
3
- import { Schema } from "effect";
4
4
 
5
5
  // src/Generated.ts
6
6
  /**
@@ -13,7 +13,7 @@ var Generated = class extends Schema.Class("Generated")({
13
13
  /**
14
14
  * Legacy (pre-integrity) body digest, read only as a migration fallback and never
15
15
  * written. Lenient on purpose: a malformed legacy value must never fail the
16
- * `generated` family and drop `by`/`at`. `okfit sync` moves it to `integrity.generated.body`.
16
+ * `generated` family and drop `by`/`at`. `okfit sync` moves it to `x-okfit-integrity.generated.body`.
17
17
  */
18
18
  body_sha256: Schema.optionalKey(Schema.String)
19
19
  }) {
@@ -0,0 +1,33 @@
1
+ import { DateTime, Duration, Option } from "effect";
2
+
3
+ // src/GeneratedAtFuture.ts
4
+ /**
5
+ * How far past now a `generated.at` may sit before okfit treats it as a future stamp: five minutes, the allowance for
6
+ * ordinary clock skew between machines. The lint `generated-at-future` and the repair in `okfit sync` both read it
7
+ * through {@link generatedAtIsFuture}.
8
+ *
9
+ * @public
10
+ */
11
+ const GENERATED_AT_TOLERANCE = Duration.minutes(5);
12
+ /**
13
+ * Whether `generatedAt` is more than {@link GENERATED_AT_TOLERANCE} later than `now`. Exactly the tolerance is not
14
+ * future; one millisecond more is.
15
+ *
16
+ * @public
17
+ */
18
+ const generatedAtIsFuture = (generatedAt, now) => DateTime.isGreaterThan(generatedAt, DateTime.addDuration(now, GENERATED_AT_TOLERANCE));
19
+ /**
20
+ * The earliest verification time `V` with `startOf(now, "second") <= V < generatedAt`, the verifications that
21
+ * re-stamping `generatedAt` down to now would turn from not current into current (OKF 0.3 §5.3). `okfit sync` skips
22
+ * such a re-stamp; the lint `generated-at-future` names the verification instead of promising the repair. `now` is
23
+ * truncated to the whole second because stamps are written in whole seconds. None when no verification falls in the
24
+ * window.
25
+ *
26
+ * @public
27
+ */
28
+ const verificationBlockingRestamp = (verifiedAts, generatedAt, now) => {
29
+ const from = DateTime.startOf(now, "second");
30
+ return verifiedAts.filter((at) => !DateTime.isLessThan(at, from) && DateTime.isLessThan(at, generatedAt)).reduce((earliest, at) => Option.isSome(earliest) && !DateTime.isLessThan(at, earliest.value) ? earliest : Option.some(at), Option.none());
31
+ };
32
+
33
+ export { GENERATED_AT_TOLERANCE, generatedAtIsFuture, verificationBlockingRestamp };
package/Graph.js CHANGED
@@ -1,6 +1,8 @@
1
+ import { Graph as Graph$1, Option, Schema } from "effect";
2
+ import { Derive } from "./Derive.js";
1
3
  import { DiagnosticRange } from "./Diagnostic.js";
2
4
  import { frontmatterFieldSpan, pathFieldsOf, resolvePathField, resolveTarget } from "./internal/links.js";
3
- import { Graph as Graph$1, Option, Schema } from "effect";
5
+ import { OkfVersion } from "./OkfVersion.js";
4
6
 
5
7
  // src/Graph.ts
6
8
  /**
@@ -117,14 +119,17 @@ var LinkGraph = class LinkGraph {
117
119
  }
118
120
  };
119
121
  const indexes = /* @__PURE__ */ new WeakMap();
122
+ /** Builds the lookup sets and the version-gated root fallback for one loaded bundle: the single place the gate is computed. */
123
+ const buildIndex = (bundle) => ({
124
+ files: new Set(bundle.files),
125
+ concepts: new Set(bundle.concepts.keys()),
126
+ rootFallback: OkfVersion.legacyFallbacks(bundle)
127
+ });
120
128
  /** The lookup sets for one loaded bundle, built once: a bundle is immutable after load. */
121
129
  const indexOf = (bundle) => {
122
130
  const cached = indexes.get(bundle);
123
131
  if (cached !== void 0) return cached;
124
- const built = {
125
- files: new Set(bundle.files),
126
- concepts: new Set(bundle.concepts.keys())
127
- };
132
+ const built = buildIndex(bundle);
128
133
  indexes.set(bundle, built);
129
134
  return built;
130
135
  };
@@ -133,25 +138,55 @@ const indexOf = (bundle) => {
133
138
  *
134
139
  * @public
135
140
  */
136
- var Graph = class {
141
+ var Graph = class Graph {
137
142
  constructor() {}
138
143
  /**
139
144
  * Pure. Resolve `raw`, written in the file at bundle-relative `from`, the way the graph does; `field`
140
- * applies the path-field rules (a `sources.resource` descriptor).
145
+ * applies the path-field rules (a `sources.resource` descriptor). `rule` (default `"declared"`) states which
146
+ * root-fallback rule applies; it is applied per call and never cached.
141
147
  */
142
- static resolve = (bundle, from, raw, field) => {
143
- const lookup = indexOf(bundle);
148
+ static resolve = (bundle, from, raw, field, rule = "declared") => {
149
+ const declared = indexOf(bundle);
150
+ const lookup = rule === "declared" ? declared : {
151
+ ...declared,
152
+ rootFallback: rule === "legacy"
153
+ };
144
154
  return field === void 0 ? resolveTarget(from, raw, lookup) : resolvePathField(from, field, raw, lookup);
145
155
  };
146
156
  /**
157
+ * Pure. The concept that replaces a deprecated concept (OKF 0.3 section 5.4): follow `superseded_by` from `id`
158
+ * through deprecated concepts to the first concept whose derived status is neither `deprecated` nor `unknown`
159
+ * (a `draft` or `stable` concept is current knowledge). `None` when `id` is not a deprecated concept, a link
160
+ * resolves to a non-concept or a missing target, a deprecated concept has no `superseded_by`, the chain ends at
161
+ * an `unknown`-status concept, or the chain revisits a concept (a cycle or a self-reference). Resolution is the
162
+ * one {@link Graph.resolve} performs, so a bare value in a v0.2 bundle resolves through the root fallback.
163
+ *
164
+ * @public
165
+ */
166
+ static replacement = (bundle, id) => {
167
+ const visited = /* @__PURE__ */ new Set();
168
+ let current = bundle.concepts.get(id);
169
+ while (current !== void 0) {
170
+ const status = Derive.status(current.frontmatter);
171
+ if (status !== "deprecated") return visited.size === 0 || status === "unknown" ? Option.none() : Option.some(current.id);
172
+ if (visited.has(current.id)) return Option.none();
173
+ visited.add(current.id);
174
+ const raw = current.frontmatter.superseded_by;
175
+ if (raw === void 0) return Option.none();
176
+ const resolved = Graph.resolve(bundle, current.path, raw, "superseded_by");
177
+ if (resolved._tag !== "node" || resolved.kind !== "concept") return Option.none();
178
+ const next = bundle.concepts.get(resolved.id);
179
+ if (next === void 0 || visited.has(next.id)) return Option.none();
180
+ current = next;
181
+ }
182
+ return Option.none();
183
+ };
184
+ /**
147
185
  * Pure. Body links come from `document.links`, path fields from the frontmatter (D-23, D-24).
148
186
  * Placeholder `missing` nodes are added before their edge because `Graph.addEdge` throws on an absent endpoint.
149
187
  */
150
188
  static fromBundle = (bundle) => {
151
- const lookup = {
152
- files: new Set(bundle.files),
153
- concepts: new Set(bundle.concepts.keys())
154
- };
189
+ const lookup = indexOf(bundle);
155
190
  const index = /* @__PURE__ */ new Map();
156
191
  const graph = Graph$1.directed((mutable) => {
157
192
  const node = (id, kind) => {
package/IndexDocument.js CHANGED
@@ -1,5 +1,5 @@
1
- import { DiagnosticRange } from "./Diagnostic.js";
2
1
  import { Schema } from "effect";
2
+ import { DiagnosticRange } from "./Diagnostic.js";
3
3
 
4
4
  // src/IndexDocument.ts
5
5
  /** One `index.md` list item. @public */
@@ -16,13 +16,20 @@ var IndexSection = class extends Schema.Class("IndexSection")({
16
16
  range: DiagnosticRange
17
17
  }) {};
18
18
  /**
19
- * A parsed `index.md` (D-21). `okfVersion` is present only on the bundle root.
19
+ * A parsed `index.md` (D-21). The metadata fields are present only on the bundle root (OKF 0.3 section 8.1):
20
+ * `okfVersion`, `title`, `description` and `license` are the typed reads, `metadata` is the whole decoded
21
+ * mapping (extension keys included) and `frontmatter` is the raw YAML text between the fences.
20
22
  * @public
21
23
  */
22
24
  var IndexDocument = class extends Schema.Class("IndexDocument")({
23
25
  path: Schema.String,
24
26
  dir: Schema.String,
25
27
  okfVersion: Schema.optionalKey(Schema.String),
28
+ title: Schema.optionalKey(Schema.String),
29
+ description: Schema.optionalKey(Schema.String),
30
+ license: Schema.optionalKey(Schema.String),
31
+ metadata: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),
32
+ frontmatter: Schema.optionalKey(Schema.String),
26
33
  sections: Schema.Array(IndexSection)
27
34
  }) {};
28
35