@sigloch/graph-api-core 5.11.2 → 6.1.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/dist/audit.d.ts CHANGED
@@ -1,81 +1,133 @@
1
- import type { FormatEDiff } from './types.js';
2
- import type { RuleViolation } from './rule-engine.js';
3
- import type { MutateCommand } from '@sigloch/contracts/harness';
4
- export interface AuditEntry {
5
- id: string;
6
- timestamp: string;
7
- consumerId: string;
8
- consumerType: 'frontend' | 'agent' | 'automation';
9
- operation: 'mutate' | 'batch' | 'validate' | 'export';
10
- diff?: FormatEDiff;
11
- /**
12
- * The mutate commands that produced this entry (CR-207, formerly the graphcode-
13
- * local `GraphcodeAuditEntry.commands`). Optional: a `validate`/`export` entry
14
- * carries none, and pre-CR-207 records predate the field. Replay-merge reads
15
- * these in log order; without them replay is impossible.
16
- */
17
- commands?: MutateCommand[];
18
- result: 'applied' | 'rejected' | 'partial';
19
- violations?: RuleViolation[];
20
- graphVersion: number;
21
- /**
22
- * The POSITIVE half of the finding (CR-GC-314): rule IDs that were evaluated for this
23
- * mutation and returned nothing.
24
- *
25
- * `violations` records only what went wrong, so an accepted mutation leaves an empty
26
- * field — and "rule R-18 checked this edit and passed it" is not recoverable from
27
- * "no violation". A later learning mechanism can learn from the first statement and
28
- * nothing at all from the second; that asymmetry is the whole reason this field exists.
29
- *
30
- * Rule IDs only, never rule text (REQ-A04). Optional and purely additive: an entry
31
- * written before this field means "not recorded", NOT "passed nothing" — a consumer
32
- * must not read absence as an empty pass set (REQ-A05). Old records are deliberately
33
- * not back-filled: reconstructing them would evaluate against a rule version that did
34
- * not hold at mutation time, which is itself a provenance violation.
35
- */
36
- rulesPassed?: string[];
37
- /**
38
- * Version of the rule set this mutation was evaluated against (REQ-A02) — read from
39
- * the loaded package, never from config, so a rule-set change is visible in the trail
40
- * at exactly the records it affected.
41
- */
42
- rulesetVersion?: string;
43
- /**
44
- * PROVENANCE (CR-GC-354) — the four fields that make a record answer the base question
45
- * of an audit trail: WHO, with WHICH PROMPT, reached WHICH RESULT. The result half was
46
- * always there; these are the other two.
47
- *
48
- * All four are DERIVED at the recording site, never self-declared by the consumer.
49
- * `consumerId` is the counter-example that motivated this: it IS a self-declared field
50
- * and 40% of the records carry its anonymous default. A prompt a model writes about
51
- * itself is a paraphrase — it already contains the interpretation a later consumer
52
- * would want to predict — so it is worthless as provenance.
53
- *
54
- * Session this record was written in — groups the records of ONE conversation.
55
- * Assigned by the recording host, not accepted from the caller.
56
- */
57
- sessionId?: string;
58
- /**
59
- * The LLM that emitted the commands (e.g. the executor's configured model). The
60
- * dimension rule calibration breaks down by ("R-01 dominated rejections: Haiku 26/29,
61
- * Opus 17/18, devstral 10/23") and the one a client-side transcript cannot supply for
62
- * a local or third-party model, because no transcript exists there.
63
- */
64
- model?: string;
65
- /**
66
- * The triggering prompt VERBATIM, truncated by the recording host's policy (the
67
- * contract states that it is truncated, the host states where).
68
- *
69
- * Same absence asymmetry as `rulesPassed`: a missing field means NOT RECORDED, never
70
- * "empty prompt". A consumer must not read absence as "no prompt was given".
71
- */
72
- intent?: string;
73
- /**
74
- * `true` when `intent` was truncated. Present only in that case — no silent cut, and
75
- * no `false` noise on the overwhelming majority of records that fit.
76
- */
77
- intentTruncated?: boolean;
78
- }
1
+ import { z } from 'zod/v4';
2
+ /**
3
+ * Der Vertrag eines Log-Eintrags (CR-SM-456). Typ per `z.infer`; die Felder, die spaeter dazukamen,
4
+ * bleiben optional, damit aeltere Zeilen weiter lesbar sind — die Kommentare je Feld sagen warum.
5
+ * Untertypen kommen aus den vorhandenen Schemas (FormatEDiff hier, MutateCommand und RuleViolation
6
+ * aus contracts), nichts davon ist nachgebaut.
7
+ */
8
+ export declare const AuditEntrySchema: z.ZodObject<{
9
+ id: z.ZodString;
10
+ timestamp: z.ZodString;
11
+ consumerId: z.ZodString;
12
+ consumerType: z.ZodEnum<{
13
+ frontend: "frontend";
14
+ agent: "agent";
15
+ automation: "automation";
16
+ }>;
17
+ operation: z.ZodEnum<{
18
+ mutate: "mutate";
19
+ batch: "batch";
20
+ validate: "validate";
21
+ export: "export";
22
+ }>;
23
+ diff: z.ZodOptional<z.ZodObject<{
24
+ operations: z.ZodArray<z.ZodObject<{
25
+ type: z.ZodEnum<{
26
+ add_node: "add_node";
27
+ remove_node: "remove_node";
28
+ update_node: "update_node";
29
+ add_edge: "add_edge";
30
+ remove_edge: "remove_edge";
31
+ update_edge: "update_edge";
32
+ strict_add_node: "strict_add_node";
33
+ strict_add_edge: "strict_add_edge";
34
+ merge_nodes: "merge_nodes";
35
+ }>;
36
+ semanticId: z.ZodString;
37
+ elementType: z.ZodOptional<z.ZodString>;
38
+ description: z.ZodOptional<z.ZodString>;
39
+ attributes: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
40
+ sourceId: z.ZodOptional<z.ZodString>;
41
+ targetId: z.ZodOptional<z.ZodString>;
42
+ edgeType: z.ZodOptional<z.ZodString>;
43
+ sourceIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
44
+ set: z.ZodOptional<z.ZodObject<{
45
+ edgeType: z.ZodOptional<z.ZodString>;
46
+ flip: z.ZodOptional<z.ZodBoolean>;
47
+ attributes: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
48
+ }, z.core.$strip>>;
49
+ }, z.core.$strip>>;
50
+ errors: z.ZodArray<z.ZodString>;
51
+ }, z.core.$strip>>;
52
+ commands: z.ZodOptional<z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
53
+ op: z.ZodLiteral<"add-node">;
54
+ node: z.ZodObject<{
55
+ uid: z.ZodString;
56
+ type: z.ZodString;
57
+ name: z.ZodString;
58
+ description: z.ZodOptional<z.ZodString>;
59
+ attributes: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
60
+ }, z.core.$strip>;
61
+ }, z.core.$strip>, z.ZodObject<{
62
+ op: z.ZodLiteral<"update-node">;
63
+ node: z.ZodObject<{
64
+ uid: z.ZodString;
65
+ type: z.ZodOptional<z.ZodString>;
66
+ name: z.ZodOptional<z.ZodString>;
67
+ description: z.ZodOptional<z.ZodString>;
68
+ attributes: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
69
+ }, z.core.$strip>;
70
+ }, z.core.$strip>, z.ZodObject<{
71
+ op: z.ZodLiteral<"delete-node">;
72
+ uid: z.ZodString;
73
+ }, z.core.$strip>, z.ZodObject<{
74
+ op: z.ZodLiteral<"add-edge">;
75
+ edge: z.ZodObject<{
76
+ sourceId: z.ZodString;
77
+ targetId: z.ZodString;
78
+ edgeType: z.ZodString;
79
+ attributes: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
80
+ }, z.core.$strip>;
81
+ }, z.core.$strip>, z.ZodObject<{
82
+ op: z.ZodLiteral<"delete-edge">;
83
+ edge: z.ZodObject<{
84
+ sourceId: z.ZodString;
85
+ targetId: z.ZodString;
86
+ edgeType: z.ZodString;
87
+ }, z.core.$strip>;
88
+ }, z.core.$strip>, z.ZodObject<{
89
+ op: z.ZodLiteral<"update-edge">;
90
+ edge: z.ZodObject<{
91
+ sourceId: z.ZodString;
92
+ targetId: z.ZodString;
93
+ edgeType: z.ZodString;
94
+ }, z.core.$strip>;
95
+ set: z.ZodObject<{
96
+ edgeType: z.ZodOptional<z.ZodString>;
97
+ flip: z.ZodOptional<z.ZodBoolean>;
98
+ attributes: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
99
+ }, z.core.$strip>;
100
+ }, z.core.$strip>, z.ZodObject<{
101
+ op: z.ZodLiteral<"merge-nodes">;
102
+ sourceUid: z.ZodString;
103
+ targetUid: z.ZodString;
104
+ }, z.core.$strip>], "op">>>;
105
+ result: z.ZodEnum<{
106
+ applied: "applied";
107
+ rejected: "rejected";
108
+ partial: "partial";
109
+ }>;
110
+ violations: z.ZodOptional<z.ZodArray<z.ZodObject<{
111
+ ruleId: z.ZodString;
112
+ severity: z.ZodEnum<{
113
+ error: "error";
114
+ info: "info";
115
+ warning: "warning";
116
+ }>;
117
+ message: z.ZodString;
118
+ elementId: z.ZodOptional<z.ZodString>;
119
+ fixHint: z.ZodOptional<z.ZodString>;
120
+ context: z.ZodOptional<z.ZodUnknown>;
121
+ }, z.core.$strip>>>;
122
+ graphVersion: z.ZodNumber;
123
+ rulesPassed: z.ZodOptional<z.ZodArray<z.ZodString>>;
124
+ rulesetVersion: z.ZodOptional<z.ZodString>;
125
+ sessionId: z.ZodOptional<z.ZodString>;
126
+ model: z.ZodOptional<z.ZodString>;
127
+ intent: z.ZodOptional<z.ZodString>;
128
+ intentTruncated: z.ZodOptional<z.ZodBoolean>;
129
+ }, z.core.$strip>;
130
+ export type AuditEntry = z.infer<typeof AuditEntrySchema>;
79
131
  /** The read horizon of a query (CR-GC-349). */
80
132
  export interface AuditQueryFilter {
81
133
  consumerId?: string;
@@ -168,7 +220,7 @@ export declare class FileOperationsLog implements OperationsLog {
168
220
  checkpointVersion: number;
169
221
  };
170
222
  private maybeCompact;
171
- /** Read all parseable lines; skip a torn tail (crash mid-append) with a warning. */
223
+ /** Read the active log: see {@link readLogFile}. */
172
224
  private readLines;
173
225
  private readEntries;
174
226
  /**
package/dist/audit.js CHANGED
@@ -18,6 +18,90 @@
18
18
  */
19
19
  import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
20
20
  import { dirname, join } from 'node:path';
21
+ import { z } from 'zod/v4';
22
+ import { MutateCommandSchema, RuleViolationSchema } from '@sigloch/contracts/harness';
23
+ import { FormatEDiffSchema } from './schemas.js';
24
+ /**
25
+ * Der Vertrag eines Log-Eintrags (CR-SM-456). Typ per `z.infer`; die Felder, die spaeter dazukamen,
26
+ * bleiben optional, damit aeltere Zeilen weiter lesbar sind — die Kommentare je Feld sagen warum.
27
+ * Untertypen kommen aus den vorhandenen Schemas (FormatEDiff hier, MutateCommand und RuleViolation
28
+ * aus contracts), nichts davon ist nachgebaut.
29
+ */
30
+ export const AuditEntrySchema = z.object({
31
+ id: z.string(),
32
+ timestamp: z.string(),
33
+ consumerId: z.string(),
34
+ consumerType: z.enum(['frontend', 'agent', 'automation']),
35
+ operation: z.enum(['mutate', 'batch', 'validate', 'export']),
36
+ diff: FormatEDiffSchema.optional(),
37
+ /**
38
+ * The mutate commands that produced this entry (CR-207, formerly the graphcode-
39
+ * local `GraphcodeAuditEntry.commands`). Optional: a `validate`/`export` entry
40
+ * carries none, and pre-CR-207 records predate the field. Replay-merge reads
41
+ * these in log order; without them replay is impossible.
42
+ */
43
+ commands: z.array(MutateCommandSchema).optional(),
44
+ result: z.enum(['applied', 'rejected', 'partial']),
45
+ violations: z.array(RuleViolationSchema).optional(),
46
+ graphVersion: z.number(),
47
+ /**
48
+ * The POSITIVE half of the finding (CR-GC-314): rule IDs that were evaluated for this
49
+ * mutation and returned nothing.
50
+ *
51
+ * `violations` records only what went wrong, so an accepted mutation leaves an empty
52
+ * field — and "rule R-18 checked this edit and passed it" is not recoverable from
53
+ * "no violation". A later learning mechanism can learn from the first statement and
54
+ * nothing at all from the second; that asymmetry is the whole reason this field exists.
55
+ *
56
+ * Rule IDs only, never rule text (REQ-A04). Optional and purely additive: an entry
57
+ * written before this field means "not recorded", NOT "passed nothing" — a consumer
58
+ * must not read absence as an empty pass set (REQ-A05). Old records are deliberately
59
+ * not back-filled: reconstructing them would evaluate against a rule version that did
60
+ * not hold at mutation time, which is itself a provenance violation.
61
+ */
62
+ rulesPassed: z.array(z.string()).optional(),
63
+ /**
64
+ * Version of the rule set this mutation was evaluated against (REQ-A02) — read from
65
+ * the loaded package, never from config, so a rule-set change is visible in the trail
66
+ * at exactly the records it affected.
67
+ */
68
+ rulesetVersion: z.string().optional(),
69
+ /**
70
+ * PROVENANCE (CR-GC-354) — the four fields that make a record answer the base question
71
+ * of an audit trail: WHO, with WHICH PROMPT, reached WHICH RESULT. The result half was
72
+ * always there; these are the other two.
73
+ *
74
+ * All four are DERIVED at the recording site, never self-declared by the consumer.
75
+ * `consumerId` is the counter-example that motivated this: it IS a self-declared field
76
+ * and 40% of the records carry its anonymous default. A prompt a model writes about
77
+ * itself is a paraphrase — it already contains the interpretation a later consumer
78
+ * would want to predict — so it is worthless as provenance.
79
+ *
80
+ * Session this record was written in — groups the records of ONE conversation.
81
+ * Assigned by the recording host, not accepted from the caller.
82
+ */
83
+ sessionId: z.string().optional(),
84
+ /**
85
+ * The LLM that emitted the commands (e.g. the executor's configured model). The
86
+ * dimension rule calibration breaks down by ("R-01 dominated rejections: Haiku 26/29,
87
+ * Opus 17/18, devstral 10/23") and the one a client-side transcript cannot supply for
88
+ * a local or third-party model, because no transcript exists there.
89
+ */
90
+ model: z.string().optional(),
91
+ /**
92
+ * The triggering prompt VERBATIM, truncated by the recording host's policy (the
93
+ * contract states that it is truncated, the host states where).
94
+ *
95
+ * Same absence asymmetry as `rulesPassed`: a missing field means NOT RECORDED, never
96
+ * "empty prompt". A consumer must not read absence as "no prompt was given".
97
+ */
98
+ intent: z.string().optional(),
99
+ /**
100
+ * `true` when `intent` was truncated. Present only in that case — no silent cut, and
101
+ * no `false` noise on the overwhelming majority of records that fit.
102
+ */
103
+ intentTruncated: z.boolean().optional(),
104
+ });
21
105
  export class InMemoryAuditLog {
22
106
  entries = [];
23
107
  async record(entry) {
@@ -37,6 +121,20 @@ export class InMemoryAuditLog {
37
121
  return result;
38
122
  }
39
123
  }
124
+ // ---------------------------------------------------------------------------
125
+ // FileOperationsLog — durable append-only JSONL (lifted from graphcode's
126
+ // FileAuditLog, CR-GC-232 → CR-207). One file per store at `<storeDir>/audit.jsonl`
127
+ // (per store, never per repo — a temp-store harness must not write into the live
128
+ // store's log). Single-writer by design; the consumer's store-ownership lock
129
+ // guarantees one writer, so appendFileSync needs no cross-process coordination.
130
+ // ---------------------------------------------------------------------------
131
+ /** First line of a compacted log — the version anchor that survives compaction. */
132
+ const CheckpointLineSchema = z.object({
133
+ checkpoint: z.literal(true),
134
+ version: z.number(),
135
+ timestamp: z.string(),
136
+ reason: z.string(),
137
+ });
40
138
  const isCheckpoint = (l) => l.checkpoint === true;
41
139
  /** Auto-compaction size threshold (bytes). */
42
140
  export const DEFAULT_COMPACT_BYTES = 10 * 1024 * 1024;
@@ -44,6 +142,53 @@ export const DEFAULT_COMPACT_BYTES = 10 * 1024 * 1024;
44
142
  export const AUDIT_BASENAME = 'audit.jsonl';
45
143
  /** Standard-layout location relative to the repo root (store dir = `.graphcode`). */
46
144
  export const AUDIT_FILE = join('.graphcode', AUDIT_BASENAME);
145
+ /**
146
+ * Read one JSONL file line by line; each line is parsed against its contract (CR-SM-456): a
147
+ * checkpoint line against `CheckpointLineSchema`, every other line against `AuditEntrySchema`.
148
+ *
149
+ * A line that is not JSON (torn tail after a crash) or does not satisfy the contract is SKIPPED,
150
+ * not fatal, and the skip is stated on stderr with the reason of the first such line. Skipping was
151
+ * already the rule for torn lines; a line that is valid JSON but breaks the contract used to pass
152
+ * through unchecked and now follows the same rule. The returned value is the parsed original, not
153
+ * the schema's copy, so fields the contract does not name survive the read.
154
+ */
155
+ function readLogFile(path) {
156
+ const lines = [];
157
+ let unparseable = 0;
158
+ let invalid = 0;
159
+ let firstInvalid = '';
160
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
161
+ if (!line.trim())
162
+ continue;
163
+ let json;
164
+ try {
165
+ json = JSON.parse(line);
166
+ }
167
+ catch {
168
+ unparseable += 1;
169
+ continue;
170
+ }
171
+ const isCp = typeof json === 'object' && json !== null && json.checkpoint === true;
172
+ const verdict = isCp ? CheckpointLineSchema.safeParse(json) : AuditEntrySchema.safeParse(json);
173
+ if (verdict.success) {
174
+ lines.push(json);
175
+ }
176
+ else {
177
+ invalid += 1;
178
+ if (!firstInvalid) {
179
+ const issue = verdict.error.issues[0];
180
+ firstInvalid = `${issue.path.join('.') || '(line)'}: ${issue.message}`;
181
+ }
182
+ }
183
+ }
184
+ if (unparseable > 0) {
185
+ process.stderr.write(`[graph-api-core] WARN: ${path}: skipped ${unparseable} unparseable line(s) (torn tail after a crash?).\n`);
186
+ }
187
+ if (invalid > 0) {
188
+ process.stderr.write(`[graph-api-core] WARN: ${path}: skipped ${invalid} line(s) that break the AuditEntry contract; first: ${firstInvalid}.\n`);
189
+ }
190
+ return lines;
191
+ }
47
192
  export class FileOperationsLog {
48
193
  path;
49
194
  maxBytes;
@@ -126,27 +271,9 @@ export class FileOperationsLog {
126
271
  // A stat/rename race only defers compaction to the next bind — never fatal.
127
272
  }
128
273
  }
129
- /** Read all parseable lines; skip a torn tail (crash mid-append) with a warning. */
274
+ /** Read the active log: see {@link readLogFile}. */
130
275
  readLines() {
131
- if (!existsSync(this.path))
132
- return [];
133
- const raw = readFileSync(this.path, 'utf8');
134
- const lines = [];
135
- let skipped = 0;
136
- for (const line of raw.split('\n')) {
137
- if (!line.trim())
138
- continue;
139
- try {
140
- lines.push(JSON.parse(line));
141
- }
142
- catch {
143
- skipped += 1;
144
- }
145
- }
146
- if (skipped > 0) {
147
- process.stderr.write(`[graph-api-core] WARN: ${this.path}: skipped ${skipped} unparseable line(s) (torn tail after a crash?).\n`);
148
- }
149
- return lines;
276
+ return existsSync(this.path) ? readLogFile(this.path) : [];
150
277
  }
151
278
  readEntries() {
152
279
  return this.readLines().filter((l) => !isCheckpoint(l));
@@ -188,18 +315,7 @@ export class FileOperationsLog {
188
315
  const out = [];
189
316
  for (const archive of this.archives()) {
190
317
  try {
191
- for (const line of readFileSync(archive, 'utf8').split('\n')) {
192
- if (!line.trim())
193
- continue;
194
- try {
195
- const parsed = JSON.parse(line);
196
- if (!isCheckpoint(parsed))
197
- out.push(parsed);
198
- }
199
- catch {
200
- // torn line in an archive — skip, same as the active log
201
- }
202
- }
318
+ out.push(...readLogFile(archive).filter((l) => !isCheckpoint(l)));
203
319
  }
204
320
  catch {
205
321
  // unreadable archive — skip the segment, keep the answer
@@ -22,6 +22,17 @@ const MERGE_RE = /^M\s+(.+)$/;
22
22
  const FORMAT_E_FENCE = /```format-e\s*\n([\s\S]*?)```/;
23
23
  /** Inline attribute block: [key:value,key:value] */
24
24
  const INLINE_ATTRS_RE = /\[([^\]]+)\]$/;
25
+ /**
26
+ * CR-SM-446 — ein Block am Ende einer KNOTENZEILE ist nur dann ein Attributblock, wenn JEDES
27
+ * Glied die Form `schluessel:wert` hat. Vorher zaehlte jede eckige Klammer am Zeilenende: aus der
28
+ * Beschreibung „… höchstens [limit ≤ 100]" wurde „… höchstens", ohne Fehler. Eine Beschreibung
29
+ * darf eckige Klammern tragen (Parameter in der Anforderung, CR-GC-979 in graphcode).
30
+ *
31
+ * Mehrdeutig bleibt ein Text, der selbst mit `[wort:wert]` endet; er wird weiter als
32
+ * Attributblock gelesen (benannter Preis der Variante A, CR-SM-445).
33
+ */
34
+ const ATTR_PAIR_RE = /^\s*[A-Za-z_]\w*\s*:/;
35
+ const isAttrBlock = (raw) => raw.split(',').every(pair => ATTR_PAIR_RE.test(pair));
25
36
  /**
26
37
  * CR-SM-332 (ITEM-2026-183) — Format E ist ZEILENBASIERT, also darf kein Feld eine Zeile
27
38
  * beenden koennen. `serialize` schrieb `|${description}` roh hinaus; eine Beschreibung mit
@@ -298,7 +309,7 @@ export class FormatECodec {
298
309
  let mainPart = rest;
299
310
  let inlineAttrs;
300
311
  const attrMatch = INLINE_ATTRS_RE.exec(rest);
301
- if (attrMatch) {
312
+ if (attrMatch && isAttrBlock(attrMatch[1])) {
302
313
  mainPart = rest.slice(0, attrMatch.index).trim();
303
314
  inlineAttrs = this.parseInlineAttrs(attrMatch[1], nodeType);
304
315
  }
@@ -6,15 +6,15 @@
6
6
  * hierher und nicht in eine Anwendung — CR-GC-641 hatte sie in graphcode gebaut, und damit hatte
7
7
  * ein Konsument den Vertrag eines anderen definiert.
8
8
  *
9
- * Die Tuer ist ein Zod-Schema, kein Typ: zur Laufzeit pruefbar, und als Konstante zaehlt die Regel
10
- * RC-09 (contracts) jeden, der sie parst, gegen das Modell des Konsumenten. Ein zweiter Leser
11
- * desselben Textes ist damit ein Befund, keine Stilfrage (Spike CR-GC-637).
9
+ * Die Tuer hat zwei Teile (CR-SM-450/451): das Zod-Schema `FormatEInputSchema` ist reine Struktur und
10
+ * wird vom Konsumenten geparst, die Funktion `leseFormatE` liest die geparste Eingabe ueber den Codec. Ein Vertrag traegt keine frei programmierte Pruefung
11
+ * (FAQ vertrag-ohne-refine-custom); der Codec ist keine Schema-Pruefung, sondern ein Leser.
12
12
  *
13
13
  * @author andreas@siglochconsulting
14
14
  */
15
15
  import { z } from 'zod/v4';
16
16
  import { FormatECodec } from './format-e-codec.js';
17
- import type { Graph } from './types.js';
17
+ import type { FormatEDiff } from './types.js';
18
18
  /**
19
19
  * Die EINE SE-Instanz des Codecs. `FormatECodec` traegt keinen Zustand ueber den Aufruf hinaus —
20
20
  * eine zweite Instanz waere kein Fehler, aber eine zweite Stelle, an der jemand einen anderen
@@ -22,16 +22,44 @@ import type { Graph } from './types.js';
22
22
  */
23
23
  export declare const SE_FORMAT_E_CODEC: FormatECodec;
24
24
  /**
25
- * Format-E-Text → Operations-Diff, ueber den SE-Codec.
26
- *
27
- * Eingabe ist `{ text, bestand }`: der Parser typisiert uids, die der Text nicht deklariert, aus
28
- * dem Bestand — ein reiner Kanten-Batch zwischen bestehenden Knoten braucht keine
29
- * `### <TYPE>`-Sektion. Jeder Codec-Fehler wird ein Zod-Issue, wortgleich.
25
+ * Eingabe der Tuer: `{ text, bestand }`. Der Parser typisiert uids, die der Text nicht deklariert,
26
+ * aus dem Bestand — ein reiner Kanten-Batch zwischen bestehenden Knoten braucht keine
27
+ * `### <TYPE>`-Sektion. Reine Struktur (CR-SM-450): der Vertrag traegt keine eigene Pruefung, der
28
+ * Bestand ist ein ganzer `GraphSchema` (Knoten UND Kanten).
30
29
  */
31
- export declare const FormatEInputSchema: z.ZodPipe<z.ZodObject<{
30
+ export declare const FormatEInputSchema: z.ZodObject<{
32
31
  text: z.ZodString;
33
- bestand: z.ZodCustom<Graph, Graph>;
34
- }, z.core.$strip>, z.ZodTransform<import("./types.js").FormatEDiff, {
35
- text: string;
36
- bestand: Graph;
37
- }>>;
32
+ bestand: z.ZodObject<{
33
+ nodes: z.ZodArray<z.ZodObject<{
34
+ uid: z.ZodString;
35
+ type: z.ZodString;
36
+ name: z.ZodString;
37
+ description: z.ZodOptional<z.ZodString>;
38
+ attributes: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
39
+ createdAt: z.ZodOptional<z.ZodString>;
40
+ updatedAt: z.ZodOptional<z.ZodString>;
41
+ }, z.core.$strip>>;
42
+ edges: z.ZodArray<z.ZodObject<{
43
+ sourceId: z.ZodString;
44
+ targetId: z.ZodString;
45
+ edgeType: z.ZodString;
46
+ attributes: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
47
+ }, z.core.$strip>>;
48
+ }, z.core.$strip>;
49
+ }, z.core.$strip>;
50
+ /** Die geparste Eingabe der Tuer. */
51
+ export type FormatEInput = z.infer<typeof FormatEInputSchema>;
52
+ /** Ergebnis von `leseFormatE`: der Diff, oder die Meldungen des Codecs (wortgleich). */
53
+ export type FormatELesung = {
54
+ ok: true;
55
+ diff: FormatEDiff;
56
+ } | {
57
+ ok: false;
58
+ messages: string[];
59
+ };
60
+ /**
61
+ * Format-E-Text → Operations-Diff, ueber den SE-Codec. Nimmt die schon GEPARSTE Eingabe: wer liest,
62
+ * parst den Vertrag `FormatEInputSchema` an seiner Grenze selbst (Strukturfehler sind dort ein
63
+ * ZodError, CR-SM-451) und reicht das Ergebnis hierher. Wirft nicht.
64
+ */
65
+ export declare function leseFormatE(eingabe: FormatEInput): FormatELesung;
@@ -6,15 +6,16 @@
6
6
  * hierher und nicht in eine Anwendung — CR-GC-641 hatte sie in graphcode gebaut, und damit hatte
7
7
  * ein Konsument den Vertrag eines anderen definiert.
8
8
  *
9
- * Die Tuer ist ein Zod-Schema, kein Typ: zur Laufzeit pruefbar, und als Konstante zaehlt die Regel
10
- * RC-09 (contracts) jeden, der sie parst, gegen das Modell des Konsumenten. Ein zweiter Leser
11
- * desselben Textes ist damit ein Befund, keine Stilfrage (Spike CR-GC-637).
9
+ * Die Tuer hat zwei Teile (CR-SM-450/451): das Zod-Schema `FormatEInputSchema` ist reine Struktur und
10
+ * wird vom Konsumenten geparst, die Funktion `leseFormatE` liest die geparste Eingabe ueber den Codec. Ein Vertrag traegt keine frei programmierte Pruefung
11
+ * (FAQ vertrag-ohne-refine-custom); der Codec ist keine Schema-Pruefung, sondern ein Leser.
12
12
  *
13
13
  * @author andreas@siglochconsulting
14
14
  */
15
15
  import { z } from 'zod/v4';
16
16
  import { FormatECodec } from './format-e-codec.js';
17
17
  import { SE_DESCRIPTOR } from './se-descriptor.js';
18
+ import { GraphSchema } from './schemas.js';
18
19
  /**
19
20
  * Die EINE SE-Instanz des Codecs. `FormatECodec` traegt keinen Zustand ueber den Aufruf hinaus —
20
21
  * eine zweite Instanz waere kein Fehler, aber eine zweite Stelle, an der jemand einen anderen
@@ -22,21 +23,25 @@ import { SE_DESCRIPTOR } from './se-descriptor.js';
22
23
  */
23
24
  export const SE_FORMAT_E_CODEC = new FormatECodec(SE_DESCRIPTOR);
24
25
  /**
25
- * Format-E-Text → Operations-Diff, ueber den SE-Codec.
26
- *
27
- * Eingabe ist `{ text, bestand }`: der Parser typisiert uids, die der Text nicht deklariert, aus
28
- * dem Bestand — ein reiner Kanten-Batch zwischen bestehenden Knoten braucht keine
29
- * `### <TYPE>`-Sektion. Jeder Codec-Fehler wird ein Zod-Issue, wortgleich.
26
+ * Eingabe der Tuer: `{ text, bestand }`. Der Parser typisiert uids, die der Text nicht deklariert,
27
+ * aus dem Bestand — ein reiner Kanten-Batch zwischen bestehenden Knoten braucht keine
28
+ * `### <TYPE>`-Sektion. Reine Struktur (CR-SM-450): der Vertrag traegt keine eigene Pruefung, der
29
+ * Bestand ist ein ganzer `GraphSchema` (Knoten UND Kanten).
30
30
  */
31
- export const FormatEInputSchema = z
32
- .object({
31
+ export const FormatEInputSchema = z.object({
33
32
  text: z.string(),
34
- bestand: z.custom((g) => typeof g === 'object' && g !== null && Array.isArray(g.nodes)),
35
- })
36
- .transform(({ text, bestand }, ctx) => {
33
+ bestand: GraphSchema,
34
+ });
35
+ /**
36
+ * Format-E-Text → Operations-Diff, ueber den SE-Codec. Nimmt die schon GEPARSTE Eingabe: wer liest,
37
+ * parst den Vertrag `FormatEInputSchema` an seiner Grenze selbst (Strukturfehler sind dort ein
38
+ * ZodError, CR-SM-451) und reicht das Ergebnis hierher. Wirft nicht.
39
+ */
40
+ export function leseFormatE(eingabe) {
41
+ const { text, bestand } = eingabe;
37
42
  const typeIndex = new Map(bestand.nodes.map((n) => [n.uid, n.type]));
38
43
  const diff = SE_FORMAT_E_CODEC.parse(text, { resolveType: (uid) => typeIndex.get(uid) });
39
- for (const message of diff.errors)
40
- ctx.addIssue({ code: 'custom', message });
41
- return diff;
42
- });
44
+ if (diff.errors.length > 0)
45
+ return { ok: false, messages: diff.errors };
46
+ return { ok: true, diff };
47
+ }
package/dist/index.d.ts CHANGED
@@ -10,17 +10,18 @@ export type { OntologyDescriptor, NodeTypeDescriptor, EdgeTypeDescriptor, TraceP
10
10
  export { isValidTrace, tracePatternsOf } from './types.js';
11
11
  export type { GraphScope, GraphQuery, MutationResult, BatchResult, HealthStatus } from './types.js';
12
12
  export type { FormatEOperation, FormatEDiff } from './types.js';
13
- export { GraphNodeSchema, GraphEdgeSchema, GraphSchema, GraphScopeSchema, GraphQuerySchema, MutationResultSchema, HealthStatusSchema, } from './schemas.js';
13
+ export { GraphNodeSchema, GraphEdgeSchema, GraphSchema, GraphScopeSchema, GraphQuerySchema, MutationResultSchema, HealthStatusSchema, FormatEOperationSchema, FormatEDiffSchema, } from './schemas.js';
14
14
  export { GraphService } from './graph-service.js';
15
15
  export { FormatECodec } from './format-e-codec.js';
16
- export { SE_FORMAT_E_CODEC, FormatEInputSchema } from './format-e-door.js';
16
+ export { SE_FORMAT_E_CODEC, FormatEInputSchema, leseFormatE } from './format-e-door.js';
17
+ export type { FormatEInput, FormatELesung } from './format-e-door.js';
17
18
  export { commandsToFormatE } from './format-e-commands.js';
18
19
  export { applyDelta, deltaToFormatE, edgeToTrace, formatEToDelta, formatEToExportedGraph, graphToFormatE, nodeToElement, toExportedGraph } from './graph-delta.js';
19
20
  export type { ExportedElement, ExportedGraph, ExportedTrace, GraphDelta } from './graph-delta.js';
20
21
  export type { Rule, RuleViolation, RuleEngine } from './rule-engine.js';
21
22
  export { DefaultRuleEngine } from './rule-engine.js';
22
23
  export type { AuditEntry, AuditLog, OperationsLog } from './audit.js';
23
- export { InMemoryAuditLog, FileOperationsLog, AUDIT_FILE, AUDIT_BASENAME, DEFAULT_COMPACT_BYTES } from './audit.js';
24
+ export { AuditEntrySchema, InMemoryAuditLog, FileOperationsLog, AUDIT_FILE, AUDIT_BASENAME, DEFAULT_COMPACT_BYTES } from './audit.js';
24
25
  export type { StorageAdapter } from './storage-adapter.js';
25
26
  export { MemoryAdapter } from './memory-adapter.js';
26
27
  export type { TransportAdapter, TransportConfig } from './transport-adapter.js';
package/dist/index.js CHANGED
@@ -8,17 +8,17 @@
8
8
  // Trace legality — the ONE checker (CR-GC-247). validPairs is menu-only now.
9
9
  export { isValidTrace, tracePatternsOf } from './types.js';
10
10
  // Schemas (Zod)
11
- export { GraphNodeSchema, GraphEdgeSchema, GraphSchema, GraphScopeSchema, GraphQuerySchema, MutationResultSchema, HealthStatusSchema, } from './schemas.js';
11
+ export { GraphNodeSchema, GraphEdgeSchema, GraphSchema, GraphScopeSchema, GraphQuerySchema, MutationResultSchema, HealthStatusSchema, FormatEOperationSchema, FormatEDiffSchema, } from './schemas.js';
12
12
  // Service
13
13
  export { GraphService } from './graph-service.js';
14
14
  // Format E Codec
15
15
  export { FormatECodec } from './format-e-codec.js';
16
16
  // CR-SM-359: die Tuer des Format-E-Vertrags und die eine SE-Codec-Instanz — Konsumenten bauen keine eigene.
17
- export { SE_FORMAT_E_CODEC, FormatEInputSchema } from './format-e-door.js';
17
+ export { SE_FORMAT_E_CODEC, FormatEInputSchema, leseFormatE } from './format-e-door.js';
18
18
  export { commandsToFormatE } from './format-e-commands.js';
19
19
  export { applyDelta, deltaToFormatE, edgeToTrace, formatEToDelta, formatEToExportedGraph, graphToFormatE, nodeToElement, toExportedGraph } from './graph-delta.js';
20
20
  export { DefaultRuleEngine } from './rule-engine.js';
21
- export { InMemoryAuditLog, FileOperationsLog, AUDIT_FILE, AUDIT_BASENAME, DEFAULT_COMPACT_BYTES } from './audit.js';
21
+ export { AuditEntrySchema, InMemoryAuditLog, FileOperationsLog, AUDIT_FILE, AUDIT_BASENAME, DEFAULT_COMPACT_BYTES } from './audit.js';
22
22
  export { MemoryAdapter } from './memory-adapter.js';
23
23
  // Factory
24
24
  export { createGraphApi } from './factory.js';
package/dist/schemas.d.ts CHANGED
@@ -40,8 +40,8 @@ export declare const GraphScopeSchema: z.ZodObject<{
40
40
  }, z.core.$strip>;
41
41
  export declare const GraphQuerySchema: z.ZodObject<{
42
42
  type: z.ZodEnum<{
43
- elements: "elements";
44
43
  edges: "edges";
44
+ elements: "elements";
45
45
  subgraph: "subgraph";
46
46
  view: "view";
47
47
  }>;
@@ -95,3 +95,60 @@ export declare const HealthStatusSchema: z.ZodObject<{
95
95
  edgeCount: z.ZodNumber;
96
96
  violationCount: z.ZodNumber;
97
97
  }, z.core.$strip>;
98
+ export declare const FormatEOperationSchema: z.ZodObject<{
99
+ type: z.ZodEnum<{
100
+ add_node: "add_node";
101
+ remove_node: "remove_node";
102
+ update_node: "update_node";
103
+ add_edge: "add_edge";
104
+ remove_edge: "remove_edge";
105
+ update_edge: "update_edge";
106
+ strict_add_node: "strict_add_node";
107
+ strict_add_edge: "strict_add_edge";
108
+ merge_nodes: "merge_nodes";
109
+ }>;
110
+ semanticId: z.ZodString;
111
+ elementType: z.ZodOptional<z.ZodString>;
112
+ description: z.ZodOptional<z.ZodString>;
113
+ attributes: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
114
+ sourceId: z.ZodOptional<z.ZodString>;
115
+ targetId: z.ZodOptional<z.ZodString>;
116
+ edgeType: z.ZodOptional<z.ZodString>;
117
+ sourceIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
118
+ set: z.ZodOptional<z.ZodObject<{
119
+ edgeType: z.ZodOptional<z.ZodString>;
120
+ flip: z.ZodOptional<z.ZodBoolean>;
121
+ attributes: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
122
+ }, z.core.$strip>>;
123
+ }, z.core.$strip>;
124
+ export type FormatEOperation = z.infer<typeof FormatEOperationSchema>;
125
+ export declare const FormatEDiffSchema: z.ZodObject<{
126
+ operations: z.ZodArray<z.ZodObject<{
127
+ type: z.ZodEnum<{
128
+ add_node: "add_node";
129
+ remove_node: "remove_node";
130
+ update_node: "update_node";
131
+ add_edge: "add_edge";
132
+ remove_edge: "remove_edge";
133
+ update_edge: "update_edge";
134
+ strict_add_node: "strict_add_node";
135
+ strict_add_edge: "strict_add_edge";
136
+ merge_nodes: "merge_nodes";
137
+ }>;
138
+ semanticId: z.ZodString;
139
+ elementType: z.ZodOptional<z.ZodString>;
140
+ description: z.ZodOptional<z.ZodString>;
141
+ attributes: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
142
+ sourceId: z.ZodOptional<z.ZodString>;
143
+ targetId: z.ZodOptional<z.ZodString>;
144
+ edgeType: z.ZodOptional<z.ZodString>;
145
+ sourceIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
146
+ set: z.ZodOptional<z.ZodObject<{
147
+ edgeType: z.ZodOptional<z.ZodString>;
148
+ flip: z.ZodOptional<z.ZodBoolean>;
149
+ attributes: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
150
+ }, z.core.$strip>>;
151
+ }, z.core.$strip>>;
152
+ errors: z.ZodArray<z.ZodString>;
153
+ }, z.core.$strip>;
154
+ export type FormatEDiff = z.infer<typeof FormatEDiffSchema>;
package/dist/schemas.js CHANGED
@@ -56,3 +56,36 @@ export const HealthStatusSchema = z.object({
56
56
  edgeCount: z.number(),
57
57
  violationCount: z.number(),
58
58
  });
59
+ // ---------------------------------------------------------------------------
60
+ // Format E (CR-SM-456) — der Vertrag, den das Audit-Log im Feld `diff` traegt.
61
+ // ---------------------------------------------------------------------------
62
+ export const FormatEOperationSchema = z.object({
63
+ type: z.enum([
64
+ 'add_node', 'remove_node', 'update_node',
65
+ 'add_edge', 'remove_edge', 'update_edge',
66
+ 'strict_add_node', 'strict_add_edge',
67
+ 'merge_nodes',
68
+ ]),
69
+ /** Node uid or edge key (source->target). */
70
+ semanticId: z.string(),
71
+ /** CR-SM-216: the node type of the `### <TYPE>` section; set on every node-creating operation. */
72
+ elementType: z.string().optional(),
73
+ description: z.string().optional(),
74
+ /** BOK-CR-026: `unknown` — object-valued bindings (`realRef`, `testRefs`) must survive as objects. */
75
+ attributes: z.record(z.string(), z.unknown()).optional(),
76
+ sourceId: z.string().optional(),
77
+ targetId: z.string().optional(),
78
+ edgeType: z.string().optional(),
79
+ /** Merge operation: source node IDs to merge. */
80
+ sourceIds: z.array(z.string()).optional(),
81
+ /** update_edge (CR-198): identity is sourceId/targetId/edgeType; this is the change. */
82
+ set: z.object({
83
+ edgeType: z.string().optional(),
84
+ flip: z.boolean().optional(),
85
+ attributes: z.record(z.string(), z.unknown()).optional(),
86
+ }).optional(),
87
+ });
88
+ export const FormatEDiffSchema = z.object({
89
+ operations: z.array(FormatEOperationSchema),
90
+ errors: z.array(z.string()),
91
+ });
@@ -34,7 +34,25 @@ export declare function readFixture(name: FixtureName): string;
34
34
  *
35
35
  * Throws if the parse produces validation errors.
36
36
  */
37
- export declare function loadFixture(name: FixtureName, codec?: FormatECodec): import("./types.js").FormatEDiff;
37
+ export declare function loadFixture(name: FixtureName, codec?: FormatECodec): {
38
+ operations: {
39
+ type: "add_node" | "remove_node" | "update_node" | "add_edge" | "remove_edge" | "update_edge" | "strict_add_node" | "strict_add_edge" | "merge_nodes";
40
+ semanticId: string;
41
+ elementType?: string | undefined;
42
+ description?: string | undefined;
43
+ attributes?: Record<string, unknown> | undefined;
44
+ sourceId?: string | undefined;
45
+ targetId?: string | undefined;
46
+ edgeType?: string | undefined;
47
+ sourceIds?: string[] | undefined;
48
+ set?: {
49
+ edgeType?: string | undefined;
50
+ flip?: boolean | undefined;
51
+ attributes?: Record<string, unknown> | undefined;
52
+ } | undefined;
53
+ }[];
54
+ errors: string[];
55
+ };
38
56
  /**
39
57
  * Absolute path to the fixtures directory — useful for consumers using
40
58
  * Vite's `?raw` import, esbuild's loader, or their own glob.
package/dist/types.d.ts CHANGED
@@ -95,41 +95,7 @@ export interface HealthStatus {
95
95
  edgeCount: number;
96
96
  violationCount: number;
97
97
  }
98
- export interface FormatEOperation {
99
- type: 'add_node' | 'remove_node' | 'update_node' | 'add_edge' | 'remove_edge' | 'update_edge' | 'strict_add_node' | 'strict_add_edge' | 'merge_nodes';
100
- /** Node uid or edge key (source->target). */
101
- semanticId: string;
102
- /**
103
- * CR-SM-216: the node type, taken from the `### <TYPE>` section the node was declared
104
- * under. Set on every node-creating operation. Consumers must read this instead of
105
- * re-deriving a type from the uid — uid conventions differ per repo, and guessing
106
- * from the spelling fails silently on the ones it does not recognise.
107
- */
108
- elementType?: string;
109
- description?: string;
110
- /**
111
- * BOK-CR-026: `unknown`, not `string` — object-valued bindings (`realRef`,
112
- * `testRefs`) must survive a Format-E mutation as objects/arrays, or the element reads as
113
- * unbound. GraphService already handled them as unknown internally; this is the
114
- * public type catching up (a plain `@key value` line still yields a string).
115
- */
116
- attributes?: Record<string, unknown>;
117
- sourceId?: string;
118
- targetId?: string;
119
- edgeType?: string;
120
- /** Merge operation: source node IDs to merge. */
121
- sourceIds?: string[];
122
- /** update_edge: identity is sourceId/targetId/edgeType above; this is the change (CR-198). */
123
- set?: {
124
- edgeType?: string;
125
- flip?: boolean;
126
- attributes?: Record<string, unknown>;
127
- };
128
- }
129
- export interface FormatEDiff {
130
- operations: FormatEOperation[];
131
- errors: string[];
132
- }
98
+ export type { FormatEOperation, FormatEDiff } from './schemas.js';
133
99
  /**
134
100
  * Trace legality for any ontology, decided by contracts' `isValidTrace` — the routine R-18
135
101
  * runs. No logic of its own: `label` and endpoint `kinds` are part of the rule exactly as
@@ -150,4 +116,3 @@ export declare function isValidTrace(trace: {
150
116
  * ontologies that declare only pairs keep working.
151
117
  */
152
118
  export declare function tracePatternsOf(ontology: OntologyDescriptor): TracePattern[];
153
- export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sigloch/graph-api-core",
3
- "version": "5.11.2",
3
+ "version": "6.1.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",