@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.
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,17 +1,20 @@
1
- import { FrontmatterDecodeError, MarkdownDocument, YamlFrontmatter } from "@effected/markdown";
2
- import { DescendError, PosixPath } from "@effected/walker";
1
+ import { FrontmatterDecodeError, MarkdownDocument, MarkdownVisitor, YamlFrontmatter } from "@effected/markdown";
2
+ import { DescendError, PosixPath, confineReal } from "@effected/walker";
3
3
  import { YamlParseError } from "@effected/yaml";
4
4
  import { Effect, FileSystem, Option, Path, Result, Schema } from "effect";
5
5
  import { Concept } from "./Concept.js";
6
6
  import { ConceptId } from "./ConceptId.js";
7
+ import { readConfinedString } from "./ConfinedRead.js";
7
8
  import { Diagnostic, DiagnosticRange } from "./Diagnostic.js";
8
9
  import { IndexDocument } from "./IndexDocument.js";
9
10
  import { detectFence } from "./internal/fence.js";
10
11
  import { decodeConcept } from "./internal/frontmatter.js";
12
+ import { COULD_NOT_RESOLVE, RESOLVES_OUTSIDE, scanLinks } from "./internal/linkScan.js";
11
13
  import { toFileOffset } from "./internal/position.js";
12
14
  import { OPTIONS, parseIndex, parseLog } from "./internal/reserved.js";
13
15
  import { DEFAULT_PRUNE, walk } from "./internal/walk.js";
14
16
  import { LogDocument } from "./LogDocument.js";
17
+ import { OkfVersion } from "./OkfVersion.js";
15
18
 
16
19
  // src/Bundle.ts
17
20
  /**
@@ -58,7 +61,14 @@ var BundleDepthExceededError = class extends Schema.TaggedError()("BundleDepthEx
58
61
  };
59
62
  /**
60
63
  * One concept file after loading: typed frontmatter, the parsed body, and the
61
- * `# Computation` section body when present (D-20).
64
+ * inline computation when present.
65
+ *
66
+ * @remarks
67
+ * `computationBody` is the inline form only. 0.3 or later: the code of the first fenced block in
68
+ * the first `Computation` section at any heading level (an empty fence yields an empty string; no
69
+ * fence is `None`). 0.2 or undeclared: the body of the depth-1 `Computation` section. When
70
+ * `attested.computation` is set, the file that path names is the computation (OKF 0.3 10.3 rule 1)
71
+ * and this field is not authoritative; core does not read that file.
62
72
  *
63
73
  * @public
64
74
  */
@@ -97,6 +107,32 @@ const diagnostic = (file, code, severity, message, range) => Diagnostic.make(ran
97
107
  message,
98
108
  range
99
109
  });
110
+ /** CommonMark: a fence opens with three backticks or tildes after at most three spaces; four or more is indented code. */
111
+ const FENCE_OPENING = /^ {0,3}(```|~~~)/;
112
+ /**
113
+ * OKF 0.3 10.3: the code of the first fenced block in the first `Computation` section, in source order.
114
+ *
115
+ * @remarks
116
+ * Blocks nested in a list item or block quote count (R17): the section's blocks are walked depth first.
117
+ * A deeper sub-heading does not end the section (`sectionByHeading` keeps its subsections), and the first
118
+ * fenced block wins even when it sits in a list item before a root-level fence. A code node's position starts
119
+ * at the fence character when it is fenced and at its indentation when it is an indented block, so the fence
120
+ * test reads from the node's own start; its `value` already has the container's indentation and `> ` markers
121
+ * removed and the inner relative indentation kept.
122
+ */
123
+ const fencedComputation = (document) => Option.flatMapNullishOr(document.sectionByHeading("Computation"), (section) => {
124
+ const first = section.children[0];
125
+ const last = section.children[section.children.length - 1];
126
+ if (first === void 0 || last === void 0) return void 0;
127
+ const from = first.position.start.offset;
128
+ const to = last.position.end.offset;
129
+ for (const event of MarkdownVisitor.walk(document.root)) {
130
+ if (event._tag !== "Enter" || event.node.type !== "code") continue;
131
+ const offset = event.node.position.start.offset;
132
+ if (offset < from || offset >= to) continue;
133
+ if (FENCE_OPENING.test(document.source.slice(offset, offset + 6))) return event.node.value;
134
+ }
135
+ });
100
136
  const blockRange = (text, node) => DiagnosticRange.fromOffset(text, node.position.start.offset, node.position.end.offset - node.position.start.offset);
101
137
  /** Group A's `dirname` returns `"."` for a bundle-root file; `LoadedBundle` keys the root `""`. */
102
138
  const directoryKey = (relativePath) => {
@@ -121,8 +157,8 @@ const loadMarkdown = (file, text) => Effect.gen(function* () {
121
157
  const reserved = ConceptId.isReservedFile(file);
122
158
  const fence = detectFence(text);
123
159
  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);
160
+ if (fence === "absent" && !reserved) return { diagnostics: [diagnostic(file, "frontmatter-missing", "warning", "no frontmatter, so this file is not a concept and is skipped")] };
161
+ const parsed = Bundle.parseDocument(text);
126
162
  if (Result.isFailure(parsed)) {
127
163
  const d = parsed.failure.diagnostic;
128
164
  return { diagnostics: [diagnostic(file, "frontmatter-unparseable", "error", d.message, DiagnosticRange.fromOffset(text, d.offset, d.length))] };
@@ -166,7 +202,6 @@ const loadMarkdown = (file, text) => Effect.gen(function* () {
166
202
  const diagnostics = [...decoded.diagnostics, ...result.diagnostics];
167
203
  const id = ConceptId.fromPath(file);
168
204
  if (Option.isNone(result.concept) || Option.isNone(id)) return { diagnostics };
169
- const computation = document.sectionByHeading("Computation", { depth: 1 });
170
205
  return {
171
206
  diagnostics,
172
207
  concept: LoadedConcept.make({
@@ -174,7 +209,7 @@ const loadMarkdown = (file, text) => Effect.gen(function* () {
174
209
  path: file,
175
210
  frontmatter: result.concept.value,
176
211
  document,
177
- computationBody: Option.map(computation, (section) => section.body)
212
+ computationBody: Bundle.inlineComputation(document, "legacy")
178
213
  })
179
214
  };
180
215
  });
@@ -184,13 +219,36 @@ const loadMarkdown = (file, text) => Effect.gen(function* () {
184
219
  *
185
220
  * @public
186
221
  */
187
- var Bundle = class {
222
+ var Bundle = class Bundle {
188
223
  constructor() {}
189
224
  /**
225
+ * Parse Markdown text exactly as `Bundle.load` parses every bundle file (frontmatter on), so a tool that
226
+ * scans a file the loader did not keep as a concept reads its body the way a concept's is read.
227
+ */
228
+ static parseDocument = (text) => MarkdownDocument.parseResult(text, OPTIONS);
229
+ /**
230
+ * Pure. The inline computation of `document` under one reading of the spec: `"legacy"` (OKF 0.2) is the body
231
+ * of the depth-1 `Computation` section, `"current"` (OKF 0.3 section 10.3) is the first fenced block of the
232
+ * first `Computation` section at any heading level. `None` when the reading finds nothing. `Bundle.load` calls
233
+ * this for the reading its bundle's declared version selects; a tool comparing the two readings calls it twice.
234
+ *
235
+ * @public
236
+ */
237
+ static inlineComputation = (document, reading) => reading === "legacy" ? Option.map(document.sectionByHeading("Computation", { depth: 1 }), (section) => section.body) : fencedComputation(document);
238
+ /**
190
239
  * Load the bundle at `options.root` (D-8, D-9, D-11 to D-14, D-21). Content never
191
240
  * fails: every bad file becomes a diagnostic and loading continues (spec 8). A walk
192
241
  * that descends past `options.maxDepth` fails typed with `BundleDepthExceededError`
193
242
  * (W-1) rather than being silently truncated.
243
+ *
244
+ * A symbolic link is never followed out of the bundle (OKF 0.3 section 3.2 rule 5). A file link that leaves
245
+ * it, a directory link that leaves it (nothing under it is read), and a link of either kind whose resolution
246
+ * fails (dangling, a loop, an unreadable target) each record a `symlink-escape` warning at their own path
247
+ * (a pruned name, `node_modules` by default, is silent for a file link and a directory link alike and the link is never read; hidden names are checked only under `includeHidden`); a directory link that stays inside is never walked and
248
+ * records nothing. Each Markdown file is read confined (`readConfinedString`): a file that becomes a link out of
249
+ * the bundle between the link check and the read is refused as `symlink-escape`, and one that changed under the
250
+ * read (`changed`) is recorded `read-changed` ("try again") and left out of that load. A race through a directory above
251
+ * the file can still win (spencerbeggs/okfit#524).
194
252
  */
195
253
  static load = Effect.fn("Bundle.load")(function* (options) {
196
254
  const fs = yield* FileSystem.FileSystem;
@@ -219,25 +277,57 @@ var Bundle = class {
219
277
  cause: error
220
278
  });
221
279
  };
280
+ const prune = new Set(options.prune ?? DEFAULT_PRUNE);
222
281
  const walked = yield* walk({
223
282
  root,
224
283
  includeHidden: options.includeHidden ?? false,
225
284
  maxDepth,
226
- prune: new Set(options.prune ?? DEFAULT_PRUNE)
285
+ prune
227
286
  }).pipe(Effect.mapError(toLoadError));
228
287
  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`));
288
+ const files = [];
289
+ for (const file of walked.files) {
290
+ if ((yield* fs.lstat(path.join(root, file)).pipe(Effect.mapError((cause) => new BundleReadError({
291
+ root,
292
+ path: file,
293
+ cause
294
+ })))).type === "SymbolicLink") {
295
+ if (prune.has(file.slice(file.lastIndexOf("/") + 1))) continue;
296
+ const refused = yield* confineReal(root, path.join(root, file)).pipe(Effect.match({
297
+ onFailure: (error) => error,
298
+ onSuccess: () => void 0
299
+ }));
300
+ if (refused !== void 0) {
301
+ const why = refused.reason === "outside" ? RESOLVES_OUTSIDE : COULD_NOT_RESOLVE;
302
+ diagnostics.push(diagnostic(file, "symlink-escape", "warning", `symbolic link ${why}; it is not read and not part of the bundle`));
303
+ continue;
304
+ }
305
+ }
306
+ files.push(file);
307
+ }
308
+ const links = yield* scanLinks(root, walked.links, {
309
+ includeHidden: options.includeHidden ?? false,
310
+ prune
311
+ });
312
+ for (const link of links) diagnostics.push(diagnostic(link.file, "symlink-escape", "warning", link.message));
229
313
  const concepts = /* @__PURE__ */ new Map();
230
314
  const indexes = /* @__PURE__ */ new Map();
231
315
  const logs = /* @__PURE__ */ new Map();
232
316
  const directories = /* @__PURE__ */ new Set();
233
- for (const file of walked.files) {
317
+ const refusedAtRead = /* @__PURE__ */ new Set();
318
+ for (const file of files) {
234
319
  if (!file.endsWith(".md")) continue;
235
- const text = yield* fs.readFileString(path.join(root, file)).pipe(Effect.mapError((cause) => new BundleReadError({
320
+ const read = yield* readConfinedString(root, path.join(root, file)).pipe(Effect.map((text) => ({ text })), Effect.catchTag("ConfinementError", (error) => Effect.succeed({ refused: error.reason })), Effect.mapError((cause) => new BundleReadError({
236
321
  root,
237
322
  path: file,
238
323
  cause
239
324
  })));
240
- const outcome = yield* loadMarkdown(file, text);
325
+ if ("refused" in read) {
326
+ refusedAtRead.add(file);
327
+ diagnostics.push(read.refused === "changed" ? diagnostic(file, "read-changed", "warning", `file "${file}" changed while it was read; try again. It is not part of this load`) : diagnostic(file, "symlink-escape", "warning", `symbolic link ${read.refused === "outside" ? RESOLVES_OUTSIDE : COULD_NOT_RESOLVE}; it is not read and not part of the bundle`));
328
+ continue;
329
+ }
330
+ const outcome = yield* loadMarkdown(file, read.text);
241
331
  diagnostics.push(...outcome.diagnostics);
242
332
  if (outcome.concept !== void 0) {
243
333
  concepts.set(outcome.concept.id, outcome.concept);
@@ -246,15 +336,25 @@ var Bundle = class {
246
336
  if (outcome.index !== void 0) indexes.set(outcome.index.dir, outcome.index);
247
337
  if (outcome.log !== void 0) logs.set(outcome.log.dir, outcome.log);
248
338
  }
249
- return LoadedBundle.make({
339
+ const bundle = LoadedBundle.make({
250
340
  root,
251
- files: walked.files,
341
+ files: refusedAtRead.size === 0 ? files : files.filter((file) => !refusedAtRead.has(file)),
252
342
  directories: [...directories].sort(),
253
343
  concepts,
254
344
  indexes,
255
345
  logs,
256
346
  diagnostics
257
347
  });
348
+ if (OkfVersion.legacyFallbacks(bundle)) return bundle;
349
+ const located = /* @__PURE__ */ new Map();
350
+ for (const [conceptId, concept] of concepts) located.set(conceptId, LoadedConcept.make({
351
+ ...concept,
352
+ computationBody: Bundle.inlineComputation(concept.document, "current")
353
+ }));
354
+ return LoadedBundle.make({
355
+ ...bundle,
356
+ concepts: located
357
+ });
258
358
  });
259
359
  };
260
360
 
package/Concept.js CHANGED
@@ -13,6 +13,21 @@ import { Verification } from "./Verification.js";
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,33 @@ 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
+ /**
72
+ * OKF 0.3 §11.2 rule 1: `undefined`, `null`, an empty string and an empty list read as absent.
73
+ *
74
+ * @remarks
75
+ * A mapping, `{}` included, is not absent. A family the decoder ignores (a `generated` without a readable
76
+ * `by`) reads as absent through the decoded `Concept`, not through this predicate.
77
+ */
78
+ static isAbsent(value) {
79
+ return value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0;
80
+ }
81
+ };
44
82
 
45
- export { ATTESTED_COMPUTATION_TYPE, Concept };
83
+ export { ATTESTED_COMPUTATION_TYPE, Concept, EntryPaths };
@@ -0,0 +1,113 @@
1
+ import { confineReal } from "@effected/walker";
2
+ import { Effect, FileSystem, Option, Schema } from "effect";
3
+
4
+ // src/ConfinedRead.ts
5
+ /**
6
+ * The transient wording every surface uses for a file that changed under a read: the quoted `subject` (a path or
7
+ * a concept file name) followed by `changed while it was read; try again`. One spelling, so the CLI, the MCP server
8
+ * and `ConfinementError` never drift. It is never an escape verdict.
9
+ *
10
+ * @public
11
+ */
12
+ const changedWhileRead = (subject) => `"${subject}" changed while it was read; try again`;
13
+ /**
14
+ * A file read was refused (OKF 0.3 section 3.2).
15
+ *
16
+ * `reason` says why: `outside` (a link on the path resolves outside the root), `unresolvable` (a link on the path
17
+ * dangles or cannot be resolved) or `changed` (the path no longer names the file that was opened, or what it names
18
+ * could not be compared: it was swapped, replaced or removed while it was read, so reading again may succeed). Only
19
+ * `outside` and `unresolvable` mean the path leaves the bundle; `changed` is transient and never an escape verdict.
20
+ *
21
+ * @public
22
+ */
23
+ var ConfinementError = class extends Schema.TaggedError()("ConfinementError", {
24
+ root: Schema.String,
25
+ /** The path that was read, as it was given. */
26
+ path: Schema.String,
27
+ reason: Schema.Literals([
28
+ "outside",
29
+ "unresolvable",
30
+ "changed"
31
+ ])
32
+ }) {
33
+ get message() {
34
+ return this.reason === "outside" ? `"${this.path}" resolves outside the bundle root "${this.root}"` : this.reason === "unresolvable" ? `"${this.path}" could not be resolved, so it cannot be shown to stay inside the bundle root "${this.root}"` : changedWhileRead(this.path);
35
+ }
36
+ };
37
+ const CHUNK = 65536;
38
+ /**
39
+ * Read the file `target` (an absolute path) under `root` confined to it, so a link swapped in after a check is not
40
+ * read: open the file, resolve the path with `confineReal` (every link on it, at the file or at a directory above
41
+ * it), require that the path still exists (`realPath`), then require that the open file is the file the resolved
42
+ * path names (`dev` and `ino` of the open file's `stat` against `lstat` of the real path, which must itself be a
43
+ * file and not a link). The bytes come from the open file, never from a second open of the path.
44
+ *
45
+ * The guarantee is exact about one case: a link at the file itself, swapped in at any moment during the read, is
46
+ * refused. A race through a directory above the file can still win, because the open and the resolution are
47
+ * separate steps on the path (spencerbeggs/okfit#524); there is no retry, which would only widen that window.
48
+ *
49
+ * It fails with {@link ConfinementError} (`outside` or `unresolvable` when a link on the path leaves the root or
50
+ * dangles; `changed` when the path no longer names the file that was opened, or either stat lacks an `ino`), and
51
+ * with the `PlatformError` of the open or the read otherwise. A missing file is that `PlatformError` (`NotFound`)
52
+ * unless a link on its path escapes or dangles. A hard link to a file under the root is a file under the root
53
+ * (OKF 0.3 section 3.2) and is read.
54
+ *
55
+ * Only reads are confined this way. A write stays a check followed by `writeAtomic`.
56
+ *
57
+ * @public
58
+ */
59
+ const readConfinedBytes = Effect.fn("okfit/ConfinedRead/readConfinedBytes")(function* (root, target) {
60
+ const fs = yield* FileSystem.FileSystem;
61
+ const refuse = (reason) => new ConfinementError({
62
+ root,
63
+ path: target,
64
+ reason
65
+ });
66
+ return yield* Effect.scoped(Effect.gen(function* () {
67
+ const opened = yield* Effect.result(fs.open(target));
68
+ if (opened._tag === "Failure") {
69
+ const refused = yield* confineReal(root, target).pipe(Effect.match({
70
+ onFailure: (error) => error.reason,
71
+ onSuccess: () => void 0
72
+ }));
73
+ if (refused !== void 0) return yield* refuse(refused === "outside" ? "outside" : "unresolvable");
74
+ return yield* Effect.fail(opened.failure);
75
+ }
76
+ const file = opened.success;
77
+ const real = yield* confineReal(root, target).pipe(Effect.mapError((error) => refuse(error.reason === "outside" ? "outside" : "unresolvable")));
78
+ if ((yield* fs.realPath(target).pipe(Effect.mapError(() => refuse("changed")))) !== real) return yield* refuse("changed");
79
+ const held = yield* file.stat;
80
+ const named = yield* fs.lstat(real).pipe(Effect.mapError(() => refuse("changed")));
81
+ if (named.type !== "File") return yield* refuse("changed");
82
+ if (held.dev !== named.dev || !Option.isSome(held.ino) || !Option.isSome(named.ino)) return yield* refuse("changed");
83
+ if (held.ino.value !== named.ino.value) return yield* refuse("changed");
84
+ const chunks = [];
85
+ let length = 0;
86
+ for (;;) {
87
+ const chunk = yield* file.readAlloc(CHUNK);
88
+ if (Option.isNone(chunk)) break;
89
+ chunks.push(chunk.value);
90
+ length += chunk.value.length;
91
+ }
92
+ const bytes = new Uint8Array(length);
93
+ let offset = 0;
94
+ for (const chunk of chunks) {
95
+ bytes.set(chunk, offset);
96
+ offset += chunk.length;
97
+ }
98
+ return bytes;
99
+ }));
100
+ });
101
+ /**
102
+ * {@link readConfinedBytes} decoded as UTF-8. A leading byte-order mark is dropped, as Effect's
103
+ * `FileSystem.readFileString` (a `TextDecoder`) drops it, so the loader reads a BOM file as it always did and a
104
+ * writer gives the BOM back.
105
+ *
106
+ * @public
107
+ */
108
+ const readConfinedString = Effect.fn("okfit/ConfinedRead/readConfinedString")(function* (root, target) {
109
+ const bytes = yield* readConfinedBytes(root, target);
110
+ return new TextDecoder("utf-8").decode(bytes);
111
+ });
112
+
113
+ export { ConfinementError, changedWhileRead, readConfinedBytes, readConfinedString };
package/Derive.js CHANGED
@@ -1,21 +1,30 @@
1
1
  import { PosixPath } from "@effected/walker";
2
2
  import { DateTime, Schema } from "effect";
3
- import { Actor } from "./Actor.js";
3
+ import { Concept } from "./Concept.js";
4
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 && !Concept.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";
73
+ };
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 (Concept.isAbsent(value)) return void 0;
78
+ return typeof value === "string" ? value : JSON.stringify(value);
35
79
  };
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`. */
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
1
  import { LineIndex } from "@effected/source";
2
2
  import { Option, Schema } from "effect";
3
- import { frontmatterPathSpan } from "./internal/yamlPathSpan.js";
3
+ import { findFrontmatterKeySpan, 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,8 +35,10 @@ 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
+ "read-changed",
41
42
  "generated-at-drift",
42
43
  "status-missing",
43
44
  "source-resource-missing",
@@ -49,7 +50,20 @@ const LintCode = Schema.Literals([
49
50
  "actor-email",
50
51
  "verified-actor-unknown",
51
52
  "resource-ignored",
52
- "resource-untracked"
53
+ "resource-untracked",
54
+ "resource-outside-project",
55
+ "superseded-by-orphan",
56
+ "superseded-by-unresolved",
57
+ "index-metadata-invalid",
58
+ "entry-ignored",
59
+ "value-malformed",
60
+ "value-unknown",
61
+ "frontmatter-missing",
62
+ "type-missing",
63
+ "symlink-escape",
64
+ "non-concept-unlisted",
65
+ "computation-missing",
66
+ "generated-at-future"
53
67
  ]);
54
68
  /** @public */
55
69
  const DiagnosticCode = Schema.Union([ConformanceCode, LintCode]);
@@ -92,6 +106,19 @@ var DiagnosticRange = class DiagnosticRange extends Schema.Class("DiagnosticRang
92
106
  const span = frontmatterPathSpan(document.source, node, path);
93
107
  return DiagnosticRange.fromOffset(document.source, span.offset, span.length);
94
108
  };
109
+ /**
110
+ * Maps a frontmatter YAML path to the range of its last segment's own key inside `document.source`, or `undefined`
111
+ * when the document has no frontmatter block, the path does not end in a written mapping key, or the key is not
112
+ * there. For a caller that edits a key whose value has no text of its own (a bare `body:` or `body: !!null`, which
113
+ * {@link DiagnosticRange.forFrontmatterPath} reports as the whole block), so it can still find where the value goes.
114
+ *
115
+ * @public
116
+ */
117
+ static forFrontmatterKey = (document, path) => {
118
+ const node = Option.getOrUndefined(document.frontmatter);
119
+ const span = node === void 0 ? void 0 : findFrontmatterKeySpan(document.source, node, path);
120
+ return span === void 0 ? void 0 : DiagnosticRange.fromOffset(document.source, span.offset, span.length);
121
+ };
95
122
  };
96
123
  const CONFORMANCE_CODES = new Set(ConformanceCode.literals);
97
124
  /**
package/Generated.js CHANGED
@@ -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
  }) {