@okfit/core 0.15.0 → 0.17.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/index.js CHANGED
@@ -3,17 +3,21 @@ import { AttestedComputation, ComputationAttester, ComputationExecutor, Computat
3
3
  import { Bundle, BundleDepthExceededError, BundleReadError, BundleRootNotFoundError, LoadedBundle, LoadedConcept } from "./Bundle.js";
4
4
  import { ATTESTED_COMPUTATION_TYPE, Concept, EntryPaths } from "./Concept.js";
5
5
  import { ConceptId } from "./ConceptId.js";
6
+ import { ConfinementError, changedWhileRead, readConfinedBytes, readConfinedString } from "./ConfinedRead.js";
6
7
  import { Derive, Staleness, TrustTier } from "./Derive.js";
7
8
  import { ConformanceCode, Diagnostic, DiagnosticCode, DiagnosticRange, DiagnosticSeverity, LintCode } from "./Diagnostic.js";
8
9
  import { Generated } from "./Generated.js";
9
- import { GENERATED_AT_TOLERANCE, generatedAtIsFuture, verificationBlockingRestamp } from "./GeneratedAtFuture.js";
10
+ import { GENERATED_AT_TOLERANCE, GENERATED_AT_TOLERANCE_TEXT, generatedAtIsFuture, verificationBlockingRestamp } from "./GeneratedAtFuture.js";
10
11
  import { Graph, GraphNodeKind, LinkGraph } from "./Graph.js";
11
12
  import { IndexDocument, IndexEntry, IndexSection } from "./IndexDocument.js";
12
13
  import { Digest, INTEGRITY_KEY, Integrity, IntegrityGenerated, IntegrityVerified, OKFIT_KEY_PREFIX } from "./Integrity.js";
13
14
  import { LogDocument, LogGroup, LogItem } from "./LogDocument.js";
14
- import { CONFIG_SCHEMA_VERSION, FieldDeclaration, LintLevel, LintTable, OkfitConfig, OkfitConfigFile, SCHEMA_DIRECTIVE, StaleAfterDuration, TagDeclaration, TypeDeclaration, okfitConfigDocumentFields, okfitConfigSchemaHost } from "./OkfitConfig.js";
15
+ import { Access, CONFIG_SCHEMA_VERSION, FieldDeclaration, OkfitConfig, OkfitConfigFile, SCHEMA_DIRECTIVE, StaleAfterDuration, TagDeclaration, TypeDeclaration, okfitConfigDocumentFields, okfitConfigSchemaHost } from "./OkfitConfig.js";
15
16
  import { OkfVersion } from "./OkfVersion.js";
17
+ import { Reference } from "./Reference.js";
18
+ import { RepoIdentity } from "./RepoIdentity.js";
16
19
  import { Source, UsageWindow } from "./Source.js";
20
+ import { LintLevel, LintTable } from "./LintTable.js";
17
21
  import { DerivedStatus, Status } from "./Status.js";
18
22
  import { Timestamp } from "./Timestamp.js";
19
23
  import { Validate } from "./Validate.js";
@@ -27,4 +31,4 @@ import { Verification } from "./Verification.js";
27
31
  */
28
32
  const OKF_SPEC_VERSION = "0.3";
29
33
 
30
- export { ATTESTED_COMPUTATION_TYPE, Actor, ActorPattern, AttestedComputation, Bundle, BundleDepthExceededError, BundleReadError, BundleRootNotFoundError, CONFIG_SCHEMA_VERSION, ComputationAttester, ComputationExecutor, ComputationParameter, Concept, ConceptId, ConformanceCode, Derive, DerivedStatus, Diagnostic, DiagnosticCode, DiagnosticRange, DiagnosticSeverity, Digest, EntryPaths, FieldDeclaration, GENERATED_AT_TOLERANCE, Generated, Graph, GraphNodeKind, INTEGRITY_KEY, IndexDocument, IndexEntry, IndexSection, Integrity, IntegrityGenerated, IntegrityVerified, LinkGraph, LintCode, LintLevel, LintTable, LoadedBundle, LoadedConcept, LogDocument, LogGroup, LogItem, OKFIT_KEY_PREFIX, OKF_SPEC_VERSION, OkfVersion, OkfitConfig, OkfitConfigFile, SCHEMA_DIRECTIVE, Source, StaleAfterDuration, Staleness, Status, TagDeclaration, Timestamp, TrustTier, TypeDeclaration, UsageWindow, Validate, Verification, generatedAtIsFuture, okfitConfigDocumentFields, okfitConfigSchemaHost, verificationBlockingRestamp };
34
+ export { ATTESTED_COMPUTATION_TYPE, Access, Actor, ActorPattern, AttestedComputation, Bundle, BundleDepthExceededError, BundleReadError, BundleRootNotFoundError, CONFIG_SCHEMA_VERSION, ComputationAttester, ComputationExecutor, ComputationParameter, Concept, ConceptId, ConfinementError, ConformanceCode, Derive, DerivedStatus, Diagnostic, DiagnosticCode, DiagnosticRange, DiagnosticSeverity, Digest, EntryPaths, FieldDeclaration, GENERATED_AT_TOLERANCE, GENERATED_AT_TOLERANCE_TEXT, Generated, Graph, GraphNodeKind, INTEGRITY_KEY, IndexDocument, IndexEntry, IndexSection, Integrity, IntegrityGenerated, IntegrityVerified, LinkGraph, LintCode, LintLevel, LintTable, LoadedBundle, LoadedConcept, LogDocument, LogGroup, LogItem, OKFIT_KEY_PREFIX, OKF_SPEC_VERSION, OkfVersion, OkfitConfig, OkfitConfigFile, Reference, RepoIdentity, SCHEMA_DIRECTIVE, Source, StaleAfterDuration, Staleness, Status, TagDeclaration, Timestamp, TrustTier, TypeDeclaration, UsageWindow, Validate, Verification, changedWhileRead, generatedAtIsFuture, okfitConfigDocumentFields, okfitConfigSchemaHost, readConfinedBytes, readConfinedString, verificationBlockingRestamp };
@@ -30,12 +30,6 @@ const SCALAR_SCHEMAS = {
30
30
  const PARSE_OPTIONS = { errors: "all" };
31
31
  const formatIssue = SchemaIssue.makeFormatterStandardSchemaV1();
32
32
  const isMapping = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
33
- /**
34
- * OKF 0.3 11.2 rule 1: `null`, an empty string and an empty list read as absent.
35
- *
36
- * @internal
37
- */
38
- const isAbsent = (value) => value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0;
39
33
  const leafMessages = (failure) => formatIssue(failure.issue).issues.map((leaf) => ({
40
34
  path: (leaf.path ?? []).filter((segment) => typeof segment !== "symbol"),
41
35
  message: leaf.message
@@ -55,11 +49,14 @@ const decodeFamily = (schema, family, prefix, value, issues, code = "value-malfo
55
49
  * Decode a mapping key by key against a class's declared fields (OKF 0.3 11.2 rule 3). Each
56
50
  * declared key is decoded alone: a REQUIRED key that is missing or unreadable ignores the whole
57
51
  * mapping (`entry-ignored`, returns `undefined`); any other key that is unreadable is dropped
58
- * alone (`value-malformed` at `[...path, key]`). Keys the class does not declare are never read.
52
+ * alone (`value-malformed` at `[...path, key]`). Keys the class does not declare are never read, so
53
+ * an unknown key never keeps a mapping present (see {@link decodeNested}). A key listed in `nested`
54
+ * is itself a declared mapping and is decoded key by key at `[...path, key]`, so one bad key inside
55
+ * it drops that key alone.
59
56
  *
60
57
  * @internal
61
58
  */
62
- const decodeMapping = (fields, required, value, path, family, issues) => {
59
+ const decodeMapping = (fields, required, value, path, family, issues, nested = {}) => {
63
60
  if (!isMapping(value)) {
64
61
  issues.push({
65
62
  code: required.length > 0 ? "entry-ignored" : "value-malformed",
@@ -81,8 +78,15 @@ const decodeMapping = (fields, required, value, path, family, issues) => {
81
78
  };
82
79
  for (const key of Object.keys(fields)) {
83
80
  const isRequired = required.includes(key);
84
- const present = Object.hasOwn(value, key) && !isAbsent(value[key]);
81
+ const present = Object.hasOwn(value, key) && !Concept.isAbsent(value[key]);
85
82
  if (isRequired && !present) return ignore(`\`${key}\` is required`);
83
+ const inner = Object.hasOwn(nested, key) ? nested[key] : void 0;
84
+ if (inner !== void 0) {
85
+ if (!present) continue;
86
+ const kept = decodeNested(inner.cls, inner.required, value[key], [...path, key], family, dropped);
87
+ if (kept !== void 0) out[key] = kept;
88
+ continue;
89
+ }
86
90
  const schema = Schema.Struct({ [key]: fields[key] });
87
91
  const result = Schema.decodeUnknownResult(schema, PARSE_OPTIONS)(present ? { [key]: value[key] } : {});
88
92
  if (Result.isSuccess(result)) {
@@ -131,11 +135,11 @@ const itemsOf = (key, value) => Array.isArray(value) ? value.map((item, index) =
131
135
  path: [key]
132
136
  }];
133
137
  /** Decode a list family of mappings; returns the kept values with their YAML paths, or `undefined` when none survive. */
134
- const decodeMappingList = (key, family, value, cls, required, issues) => {
138
+ const decodeMappingList = (key, family, value, cls, required, issues, nested = {}) => {
135
139
  const values = [];
136
140
  const paths = [];
137
141
  for (const { item, path } of itemsOf(key, value)) {
138
- const decoded = decodeMapping(cls.fields, required, item, path, family, issues);
142
+ const decoded = decodeMapping(cls.fields, required, item, path, family, issues, nested);
139
143
  if (decoded === void 0) continue;
140
144
  const built = build(cls, decoded, path, family, issues);
141
145
  if (built === void 0) continue;
@@ -147,24 +151,32 @@ const decodeMappingList = (key, family, value, cls, required, issues) => {
147
151
  paths
148
152
  };
149
153
  };
150
- /** Decode one single-mapping key; absent (rule 1) or unreadable reads as `undefined`. */
151
- const decodeSingle = (key, family, raw, cls, required, issues) => {
152
- if (isAbsent(raw[key])) return void 0;
154
+ /**
155
+ * Decode one mapping value key by key (a top-level family, or a declared mapping nested in another).
156
+ *
157
+ * "Emptied by dropped keys" counts only the class's declared keys: a mapping with at least one
158
+ * dropped key and no kept declared key reads as absent, whatever unknown keys it also has. A mapping
159
+ * with no dropped key is kept, even when it holds nothing but unknown keys (`{ x: 1 }`, like `{}`).
160
+ * Unknown keys stay in `raw` and are never read (OKF 0.3 11.2: never rejected).
161
+ */
162
+ const decodeNested = (cls, required, value, path, family, issues) => {
153
163
  const before = issues.length;
154
- const decoded = decodeMapping(cls.fields, required, raw[key], [key], family, issues);
164
+ const decoded = decodeMapping(cls.fields, required, value, path, family, issues);
155
165
  if (decoded === void 0) return void 0;
156
166
  if (Object.keys(decoded).length === 0 && issues.length > before) return void 0;
157
- return build(cls, decoded, [key], family, issues);
167
+ return build(cls, decoded, path, family, issues);
158
168
  };
169
+ /** Decode one single-mapping key; absent (rule 1) or unreadable reads as `undefined`. */
170
+ const decodeSingle = (key, family, raw, cls, required, issues) => Concept.isAbsent(raw[key]) ? void 0 : decodeNested(cls, required, raw[key], [key], family, issues);
159
171
  /** Decode the computation keys independently (a bad `executor` no longer drops `runtime`). */
160
172
  const decodeAttested = (raw, issues, entries) => {
161
173
  const input = { parameters: [] };
162
174
  for (const key of ["runtime", "computation"]) {
163
- if (isAbsent(raw[key])) continue;
175
+ if (Concept.isAbsent(raw[key])) continue;
164
176
  const decoded = decodeFamily(Schema.String, "attested", [key], raw[key], issues);
165
177
  if (decoded !== void 0) input[key] = decoded;
166
178
  }
167
- if (!isAbsent(raw.parameters)) {
179
+ if (!Concept.isAbsent(raw.parameters)) {
168
180
  const list = decodeMappingList("parameters", "attested", raw.parameters, ComputationParameter, ["name", "type"], issues);
169
181
  if (list !== void 0) {
170
182
  input.parameters = list.values;
@@ -221,7 +233,7 @@ const decodeConcept = (value) => {
221
233
  };
222
234
  const out = fields;
223
235
  const entries = {};
224
- const present = (key) => key in raw && !isAbsent(raw[key]);
236
+ const present = (key) => key in raw && !Concept.isAbsent(raw[key]);
225
237
  const scalar = (key) => {
226
238
  if (!present(key)) return;
227
239
  const decoded = decodeFamily(SCALAR_SCHEMAS[key], key, [key], raw[key], issues);
@@ -254,7 +266,10 @@ const decodeConcept = (value) => {
254
266
  }
255
267
  }
256
268
  if (present("sources")) {
257
- const list = decodeMappingList("sources", "sources", raw.sources, Source, ["resource"], issues);
269
+ const list = decodeMappingList("sources", "sources", raw.sources, Source, ["resource"], issues, { usage_window: {
270
+ cls: UsageWindow,
271
+ required: []
272
+ } });
258
273
  if (list !== void 0) {
259
274
  out.sources = list.values;
260
275
  entries.sources = list.paths;
@@ -318,4 +333,4 @@ const decodeConcept = (value) => {
318
333
  };
319
334
  };
320
335
 
321
- export { COMPUTATION_KEYS, decodeConcept, decodeMapping, isAbsent };
336
+ export { COMPUTATION_KEYS, decodeConcept, decodeMapping };
@@ -1,7 +1,7 @@
1
1
  import { Option } from "effect";
2
2
  import { Diagnostic, DiagnosticRange } from "../Diagnostic.js";
3
3
  import { decodeConcept as decodeConcept$1 } from "./conceptDecode.js";
4
- import { frontmatterPathSpan } from "./yamlPathSpan.js";
4
+ import { frontmatterAnchorSpan } from "./yamlPathSpan.js";
5
5
 
6
6
  // src/internal/frontmatter.ts
7
7
  /** D-34 default severities for a `FamilyIssue`'s lint code. */
@@ -14,7 +14,7 @@ const FAMILY_ISSUE_SEVERITY = {
14
14
  "value-unknown": "warning"
15
15
  };
16
16
  const spanToRange = (text, path, node) => {
17
- const span = frontmatterPathSpan(text, node, path);
17
+ const span = frontmatterAnchorSpan(text, node, path);
18
18
  return DiagnosticRange.fromOffset(text, span.offset, span.length);
19
19
  };
20
20
  /**
@@ -0,0 +1,57 @@
1
+ import { confineReal } from "@effected/walker";
2
+ import { Effect, Path } from "effect";
3
+
4
+ // src/internal/linkScan.ts
5
+ /** The words a `symlink-escape` message uses for a link that leaves the bundle root; one spelling for every site. */
6
+ const RESOLVES_OUTSIDE = "resolves outside the bundle root";
7
+ /** The words a `symlink-escape` message uses for a link that cannot be resolved (dangling, a loop, unreadable). */
8
+ const COULD_NOT_RESOLVE = "could not be resolved, so it cannot be shown to stay inside the bundle root";
9
+ const byPath = (a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : 0;
10
+ /**
11
+ * The walker's `links` report as `symlink-escape` findings: a link to a directory that resolves outside the bundle (the
12
+ * walker never enters one, wherever it points), and a link that does not resolve (dangling, whether it named a file or
13
+ * a directory). A directory link is decided on its REAL path with `confineReal`, so a link inside the bundle that points
14
+ * at a link leaving it is refused too; one that stays inside (or is the bundle root itself) is silent and never walked.
15
+ * Directory findings come first, then the unresolvable ones, each sorted by path.
16
+ *
17
+ * @remarks
18
+ * The walker reports links only from directories it reads, so a pruned directory, a hidden one and anything under them
19
+ * are never seen. It reports a dangling link whatever its own name, so a pruned or (without `includeHidden`) hidden name
20
+ * is dropped here to keep Q8: a pruned directory name is fully silent, and a hidden name is reported only with
21
+ * `includeHidden`. A file link with a pruned name is a file match, not a skipped link; `Bundle.load` drops it
22
+ * silently too (never read, never reported), so the prune list silences a name for files and directories alike.
23
+ *
24
+ * @internal
25
+ */
26
+ const scanLinks = (root, links, options) => Effect.gen(function* () {
27
+ const path = yield* Path.Path;
28
+ const silent = (link) => {
29
+ const name = link.slice(link.lastIndexOf("/") + 1);
30
+ return options.prune.has(name) || !options.includeHidden && name.startsWith(".");
31
+ };
32
+ const directories = [];
33
+ const unresolvable = [];
34
+ for (const link of links) {
35
+ if (silent(link.path)) continue;
36
+ if (link.kind === "special") continue;
37
+ if (link.kind === "dangling") {
38
+ unresolvable.push({
39
+ file: link.path,
40
+ message: `symbolic link ${COULD_NOT_RESOLVE}; it is not read and not part of the bundle`
41
+ });
42
+ continue;
43
+ }
44
+ const reason = yield* confineReal(root, path.join(root, link.path), { allowBase: true }).pipe(Effect.match({
45
+ onFailure: (error) => error.reason,
46
+ onSuccess: () => void 0
47
+ }));
48
+ if (reason === void 0) continue;
49
+ directories.push({
50
+ file: link.path,
51
+ message: `symbolic link to a directory ${reason === "outside" ? RESOLVES_OUTSIDE : COULD_NOT_RESOLVE}; nothing under it is read or part of the bundle`
52
+ });
53
+ }
54
+ return [...directories.sort(byPath), ...unresolvable.sort(byPath)];
55
+ });
56
+
57
+ export { COULD_NOT_RESOLVE, RESOLVES_OUTSIDE, scanLinks };
@@ -5,18 +5,19 @@ import { Actor } from "../Actor.js";
5
5
  import { Concept } from "../Concept.js";
6
6
  import { Derive } from "../Derive.js";
7
7
  import { Diagnostic, DiagnosticRange } from "../Diagnostic.js";
8
- import { generatedAtIsFuture, verificationBlockingRestamp } from "../GeneratedAtFuture.js";
8
+ import { Generated } from "../Generated.js";
9
+ import { GENERATED_AT_TOLERANCE_TEXT, generatedAtIsFuture, verificationBlockingRestamp } from "../GeneratedAtFuture.js";
9
10
  import { Graph as Graph$1 } from "../Graph.js";
10
11
  import { INTEGRITY_KEY } from "../Integrity.js";
11
12
  import { OkfVersion } from "../OkfVersion.js";
12
13
  import { Timestamp } from "../Timestamp.js";
13
- import { isAbsent } from "./conceptDecode.js";
14
14
  import { frontmatterPathRange } from "./frontmatter.js";
15
15
  import { tierOf } from "./tier.js";
16
+ import { isReplaceableNull } from "./yamlPathSpan.js";
16
17
 
17
18
  // src/internal/lintRules.ts
18
19
  /** OKF 0.3 §11.2 rule 1: a key holding null, the empty string or the empty list is absent. */
19
- const present = (raw, key) => Object.hasOwn(raw, key) && !isAbsent(raw[key]);
20
+ const present = (raw, key) => Object.hasOwn(raw, key) && !Concept.isAbsent(raw[key]);
20
21
  const diagnostic = (file, code, severity, message, range) => Diagnostic.make({
21
22
  file,
22
23
  code,
@@ -57,16 +58,17 @@ const configOkfVersionStale = rule("config-okf-version-stale", (context, severit
57
58
  });
58
59
  /**
59
60
  * #471: a `generated.at` later than now counts for no verification (OKF 0.3 §5.3) and `okfit verify` refuses it;
60
- * `okfit sync` re-stamps it, except when a verification would then count (`verificationBlockingRestamp`).
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`).
61
63
  */
62
64
  const generatedAtFuture = perConcept("generated-at-future", (concept, context) => {
63
65
  const at = concept.frontmatter.generated?.at;
64
66
  const { now } = context;
65
67
  if (at === void 0 || now === void 0 || !generatedAtIsFuture(at, now)) return [];
66
- const head = `generated.at ${instant(at)} is more than 5 minutes later than now (${instant(now)}), so no verification can count yet (OKF 0.3 §5.3) and okfit verify refuses this concept`;
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`;
67
69
  const blocking = verificationBlockingRestamp((concept.frontmatter.verified ?? []).map((entry) => entry.at), at, now);
68
70
  return [{
69
- 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`,
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)`,
70
72
  path: ["generated", "at"]
71
73
  }];
72
74
  });
@@ -83,8 +85,10 @@ const requiredKeyMissing = perConcept("required-key-missing", (concept, context)
83
85
  path: [key]
84
86
  }));
85
87
  });
88
+ /** The declaration of concept type `type`, an own entry of `types` only (a type named `constructor` is not `Object`). */
89
+ const typeSpec = (config, type) => config.types !== void 0 && Object.hasOwn(config.types, type) ? config.types[type] : void 0;
86
90
  const fieldValueUnknown = perConcept("field-value-unknown", (concept, context) => {
87
- const fields = context.config.types?.[concept.frontmatter.type]?.fields ?? {};
91
+ const fields = typeSpec(context.config, concept.frontmatter.type)?.fields ?? {};
88
92
  const out = [];
89
93
  for (const [key, declaration] of Object.entries(fields)) {
90
94
  if (declaration.values === void 0 || !present(concept.frontmatter.raw, key)) continue;
@@ -96,7 +100,7 @@ const fieldValueUnknown = perConcept("field-value-unknown", (concept, context) =
96
100
  }
97
101
  return out;
98
102
  });
99
- 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 ? [{
103
+ const requireVerifiedUnmet = perConcept("require-verified-unmet", (concept, context) => typeSpec(context.config, concept.frontmatter.type)?.require_verified === true && concept.frontmatter.status !== "draft" && (concept.frontmatter.verified ?? []).length === 0 ? [{
100
104
  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`,
101
105
  path: ["status"]
102
106
  }] : []);
@@ -143,7 +147,21 @@ const nonConceptUnlisted = rule("non-concept-unlisted", (context, severity) => {
143
147
  });
144
148
  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));
145
149
  });
146
- 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`] : []);
150
+ const generatedMissing = perConcept("generated-missing", (concept, context) => {
151
+ const agent = context.config.actors?.agent;
152
+ if (agent === void 0) return [];
153
+ const frontmatter = concept.frontmatter;
154
+ if (frontmatter.generated !== void 0) return !Concept.isAbsent(frontmatter.raw.generated) || frontmatter.generated.by !== Generated.LEGACY_BY ? [] : [{
155
+ path: ["timestamp"],
156
+ 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"
157
+ }];
158
+ const document = Option.getOrUndefined(concept.document.frontmatter);
159
+ if (document !== void 0 && Object.hasOwn(frontmatter.raw, "generated") && !isReplaceableNull(document, "generated")) return [{
160
+ path: ["generated"],
161
+ 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"
162
+ }];
163
+ 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`];
164
+ });
147
165
  /**
148
166
  * OKF 0.3 §10.3: an Attested Computation with neither a `computation` key nor an inline computation is not
149
167
  * attestable. `computationBody` is already the bundle's declared reading (fenced block under 0.3, the depth-1
@@ -310,19 +328,22 @@ const brokenLinks = rule("broken-links", (context, severity) => {
310
328
  slugCache.set(id, slugs);
311
329
  return slugs;
312
330
  };
313
- const check = (file, raw, targetId, target, position) => {
331
+ const check = (file, raw, targetId, target, position, label = "Link target") => {
314
332
  const fragment = fragmentOf(raw);
315
333
  if (fragment === void 0 || fragment === "") return;
316
334
  const slugs = slugsOf(targetId, target);
317
335
  if (slugs.includes(fragment)) return;
318
- const message = `Link target "${raw}" exists but has no heading "#${fragment}"; ${candidateHint(fragment, slugs)}`;
336
+ const message = `${label} "${raw}" exists but has no heading "#${fragment}"; ${candidateHint(fragment, slugs)}`;
319
337
  anchors.push(diagnostic(file, "broken-links", severity, message, position));
320
338
  };
321
339
  for (const link of context.graph.edges) {
322
- if (link.data.source !== "body") continue;
340
+ const { field } = link.data;
341
+ if (link.data.source !== "body" && field === void 0) continue;
342
+ if (field === "superseded_by" && link.to === link.from) continue;
323
343
  const target = byId.get(link.to);
324
344
  if (target === void 0) continue;
325
- check(fileOf(link.from), link.data.raw, link.to, target, link.data.position);
345
+ const label = field === void 0 ? void 0 : field === "sources.resource" ? "sources[].resource" : field;
346
+ check(fileOf(link.from), link.data.raw, link.to, target, link.data.position, label);
326
347
  }
327
348
  for (const concept of context.bundle.concepts.values()) for (const link of concept.document.links) {
328
349
  if (link.url === void 0 || !link.url.startsWith("#") || link.node.type === "linkReference") continue;
@@ -346,7 +367,7 @@ const supersededByUnresolved = perConcept("superseded-by-unresolved", (concept,
346
367
  path: ["superseded_by"]
347
368
  }];
348
369
  });
349
- const missingIndex = rule("missing-index", (context, severity) => Derive.indexDirectories(context.bundle).filter((dir) => !context.bundle.indexes.has(dir)).map((dir) => {
370
+ 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) => {
350
371
  const message = `Directory "${dir === "" ? "." : dir}" has no index.md`;
351
372
  return diagnostic(dir === "" ? "index.md" : `${dir}/index.md`, "missing-index", severity, message, void 0);
352
373
  }));
@@ -3,10 +3,10 @@ import { FrontmatterSource } from "@effected/markdown";
3
3
  // src/internal/position.ts
4
4
  /**
5
5
  * Map a `YamlDiagnostic.offset` or `YamlNode.offset` inside the frontmatter value to a whole-file
6
- * offset. Only meaningful when `text` opens a closed frontmatter block.
6
+ * offset. Only meaningful when `text` opens a closed frontmatter block; a leading BOM is stepped over and counted.
7
7
  *
8
8
  * @public
9
9
  */
10
- const toFileOffset = (text, yamlOffset) => (FrontmatterSource.split(text).frontmatter?.valueStart ?? 0) + yamlOffset;
10
+ const toFileOffset = (text, yamlOffset) => (FrontmatterSource.split(text, { bom: "skip" }).frontmatter?.valueStart ?? 0) + yamlOffset;
11
11
 
12
12
  export { toFileOffset };
@@ -4,9 +4,18 @@ 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
6
  import { OkfVersion } from "../OkfVersion.js";
7
+ import { findFrontmatterScalarSource } from "./yamlPathSpan.js";
7
8
 
8
9
  // src/internal/reserved.ts
9
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
+ /**
10
19
  * The one parse configuration every OKF file uses: GFM with frontmatter capture
11
20
  * (effected-markdown.md section 1; `Markdown.ts:60-62`).
12
21
  *
@@ -81,9 +90,15 @@ const parseIndex = (input) => {
81
90
  metadata.okfVersion = version;
82
91
  if (Option.isNone(OkfVersion.parse(version))) warn("okf_version", `okf_version "${version}" is not a <major>.<minor> version`);
83
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));
84
99
  } else if (version !== null && version !== void 0) {
85
- metadata.okfVersion = typeof version === "number" ? String(version) : JSON.stringify(version);
86
- warn("okf_version", typeof version === "number" ? `okf_version ${String(version)} is an unquoted number; quote it as "<major>.<minor>"` : "okf_version must be a quoted <major>.<minor> string");
100
+ metadata.okfVersion = JSON.stringify(version);
101
+ warn("okf_version", "okf_version must be a quoted <major>.<minor> string");
87
102
  }
88
103
  for (const key of [
89
104
  "title",
@@ -136,7 +151,8 @@ const parseIndex = (input) => {
136
151
  const fields = {
137
152
  path: file,
138
153
  dir,
139
- sections
154
+ sections,
155
+ source: text
140
156
  };
141
157
  return {
142
158
  document: IndexDocument.make({
@@ -214,7 +230,8 @@ const parseLog = (input) => {
214
230
  const fields = {
215
231
  path: file,
216
232
  dir,
217
- groups
233
+ groups,
234
+ source: text
218
235
  };
219
236
  return {
220
237
  document: LogDocument.make(title === void 0 ? fields : {
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,6 +1,6 @@
1
1
  {
2
2
  "name": "@okfit/core",
3
- "version": "0.15.0",
3
+ "version": "0.17.0",
4
4
  "private": false,
5
5
  "description": "Spec-level Open Knowledge Format (OKF) v0.3 schemas, bundle loading, graph, derivation, and validation for Effect.",
6
6
  "keywords": [
@@ -37,15 +37,17 @@
37
37
  "./package.json": "./package.json"
38
38
  },
39
39
  "peerDependencies": {
40
- "@effected/config-file": "^0.29.0",
40
+ "@effected/config-file": "^0.34.0",
41
+ "@effected/git": "^0.36.0",
41
42
  "@effected/glob": "^0.23.0",
42
43
  "@effected/jsonc": "^0.25.0",
43
- "@effected/markdown": "^0.30.0",
44
- "@effected/schemastore": "^0.33.0",
44
+ "@effected/kit": "^0.15.0",
45
+ "@effected/markdown": "^0.34.0",
46
+ "@effected/schemastore": "^0.35.0",
45
47
  "@effected/source": "^0.5.0",
46
- "@effected/toml": "^0.20.0",
47
- "@effected/walker": "^0.30.0",
48
- "@effected/yaml": "^0.30.0",
48
+ "@effected/toml": "^0.21.0",
49
+ "@effected/walker": "^0.33.0",
50
+ "@effected/yaml": "^0.31.0",
49
51
  "effect": "~4.1.0"
50
52
  },
51
53
  "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
  }