@ldclabs/kip-lang 0.3.1 → 2.0.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.
Files changed (64) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/LICENSE +21 -0
  3. package/README.md +133 -44
  4. package/dist/ast.d.ts +519 -144
  5. package/dist/ast.d.ts.map +1 -1
  6. package/dist/budget.d.ts +37 -0
  7. package/dist/budget.d.ts.map +1 -0
  8. package/dist/budget.js +105 -0
  9. package/dist/budget.js.map +1 -0
  10. package/dist/diagnostics.d.ts +8 -2
  11. package/dist/diagnostics.d.ts.map +1 -1
  12. package/dist/diagnostics.js +32 -3
  13. package/dist/diagnostics.js.map +1 -1
  14. package/dist/errors.d.ts +29 -0
  15. package/dist/errors.d.ts.map +1 -0
  16. package/dist/errors.js +27 -0
  17. package/dist/errors.js.map +1 -0
  18. package/dist/exec-ast.d.ts +679 -0
  19. package/dist/exec-ast.d.ts.map +1 -0
  20. package/dist/exec-ast.js +24 -0
  21. package/dist/exec-ast.js.map +1 -0
  22. package/dist/formatter.d.ts.map +1 -1
  23. package/dist/formatter.js +870 -479
  24. package/dist/formatter.js.map +1 -1
  25. package/dist/index.d.ts +9 -3
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +6 -2
  28. package/dist/index.js.map +1 -1
  29. package/dist/lexer.d.ts.map +1 -1
  30. package/dist/lexer.js +46 -33
  31. package/dist/lexer.js.map +1 -1
  32. package/dist/lower.d.ts +17 -0
  33. package/dist/lower.d.ts.map +1 -0
  34. package/dist/lower.js +1566 -0
  35. package/dist/lower.js.map +1 -0
  36. package/dist/parser.d.ts.map +1 -1
  37. package/dist/parser.js +2476 -1152
  38. package/dist/parser.js.map +1 -1
  39. package/dist/semantics.d.ts +11 -7
  40. package/dist/semantics.d.ts.map +1 -1
  41. package/dist/semantics.js +295 -180
  42. package/dist/semantics.js.map +1 -1
  43. package/dist/token.d.ts +130 -40
  44. package/dist/token.d.ts.map +1 -1
  45. package/dist/token.js +264 -83
  46. package/dist/token.js.map +1 -1
  47. package/dist/version.d.ts +13 -0
  48. package/dist/version.d.ts.map +1 -0
  49. package/dist/version.js +13 -0
  50. package/dist/version.js.map +1 -0
  51. package/package.json +36 -6
  52. package/src/ast.ts +914 -0
  53. package/src/budget.ts +108 -0
  54. package/src/diagnostics.ts +182 -0
  55. package/src/errors.ts +42 -0
  56. package/src/exec-ast.ts +614 -0
  57. package/src/formatter.ts +1339 -0
  58. package/src/index.ts +226 -0
  59. package/src/lexer.ts +459 -0
  60. package/src/lower.ts +2011 -0
  61. package/src/parser.ts +3506 -0
  62. package/src/semantics.ts +392 -0
  63. package/src/token.ts +408 -0
  64. package/src/version.ts +13 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,53 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@ldclabs/kip-lang` are documented here.
4
+
5
+ ## 2.0.0
6
+
7
+ Targets KIP specification revision `2.0-draft`. This is a rewrite of the
8
+ language surface, not an increment: KIP 2.0 command text is not backward
9
+ compatible with the 1.0 grammar the 0.x line implemented.
10
+
11
+ ### Added
12
+
13
+ - **Executable AST.** `lower` / `lowerAll` / `lowerStatement` turn a syntax
14
+ tree into the closed `Command` AST an engine runs, rejecting what the
15
+ grammar admits but the language does not with a KIP error code.
16
+ - **KQL 2.0**: the five Core element patterns (`CONCEPT`, `PROPOSITION`,
17
+ `ASSERTION`, `EVIDENCE`, `ACTIVITY`), `STRUCTURAL` topology patterns,
18
+ `BELIEF` / `BELIEF SLOT` projection patterns, the independent `AS OF`
19
+ (`SEQ` / `TX`) and `FOR TIME` axes, `WITH EPISTEMIC`, multi-key `ORDER BY`,
20
+ and `CURSOR` paging.
21
+ - **KML 2.0**: `MUTATE` transactions, `CREATE`/`UPSERT CONCEPT`,
22
+ `ENSURE PROPOSITION`, the `ASSERT` sugar with `SUPERSEDING`,
23
+ `CREATE EVIDENCE | ASSERTION | ACTIVITY`, generic `UPDATE`, the
24
+ `RETRACT` / `SUPERSEDE` / `CORRECT` / `TRANSITION` lifecycle,
25
+ `SET RETENTION`, `ARCHIVE`, `TOMBSTONE`, `PURGE ... CONFIRM "PURGE"`, and
26
+ `MERGE CONCEPT`, with `EXPECT VERSION` / `EXPECT STATE` preconditions.
27
+ - **`UNSET STRUCTURAL`**, so every `SET` clause has its removal counterpart.
28
+ - **META 2.0**: every `DESCRIBE`, `LIST`, `SEARCH`, `VERIFY`, `VALIDATE`,
29
+ `PREVIEW`, `HISTORY`, `CHANGES`, `SNAPSHOT` and `EXPORT CAPSULE` target.
30
+ - **`validateExecutable(program)`**, chained into `diagnose`, so the editor
31
+ reports any statement that parses but cannot lower.
32
+ - **`checkBudget` / `checkBatchBudget`** (`KIP_4002`) matching `anda_kip`'s
33
+ ceilings, so a command one engine refuses on size is refused by all.
34
+ - `KipSyntaxError` carrying KIP error codes; `PARSER_VERSION` and
35
+ `KIP_SPEC_REVISION` exports.
36
+ - `src/` ships alongside `dist/`, so published source maps resolve.
37
+
38
+ ### Changed
39
+
40
+ - Keywords are ASCII case-insensitive and **contextual, not reserved** — `by`,
41
+ `mode`, `type`, `status` remain usable as object keys and dot-path steps.
42
+ - The parser enforces the canonical KQL trailing-clause order (`AS OF`,
43
+ `FOR TIME`, `WITH EPISTEMIC`, `ORDER BY`, `LIMIT`, `CURSOR`) while still
44
+ recovering from a mistake.
45
+ - Proposition subjects lower as Element references only; KML predicates and
46
+ structural edges take an exact quoted name or a `:parameter`, never a
47
+ `?variable`.
48
+ - Unbound `MUTATE` references (`KIP_2102`) are errors, not warnings.
49
+ - The formatter keeps a comment attached to the body clause it annotates.
50
+
51
+ ## 0.4.0 and earlier
52
+
53
+ Implemented the KIP 1.0 command-text surface. See the git history.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 LDC Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,16 +1,51 @@
1
1
  # @ldclabs/kip-lang
2
2
 
3
- TypeScript toolkit for **KIP** (Knowledge Interaction Protocol) — a structured query language for knowledge graphs.
4
-
5
- Provides a full-featured **lexer → parser → AST → formatter / diagnostics** pipeline for `.kip` files.
6
-
7
- The parser targets the KIP v1.0-RC9 command-text syntax, including `:parameter`
8
- placeholders in full value positions, JSON-compatible object literals with
9
- unquoted identifier keys, predicate variables, multi-key `ORDER BY`, `SEARCH`
10
- retrieval modes and thresholds, `EXPECT VERSION`, `UPDATE`, `MERGE`, `EXPORT`,
11
- and batch-friendly multi-command source text. The `execute_kip` request envelope
12
- (`command`, `commands`, `parameters`, `dry_run`) is JSON outside the `.kip`
13
- language and should be validated by the caller.
3
+ TypeScript toolkit for **KIP** (Knowledge Interaction Protocol) — the cognitive
4
+ state protocol between an agent and a persistent Cognitive Nexus.
5
+
6
+ Provides a full-featured **lexer → parser → AST → formatter / diagnostics**
7
+ pipeline for `.kip` files, plus **`lower`**, which turns a syntax tree into the
8
+ executable AST a KIP engine runs.
9
+
10
+ This package targets the normative **KIP 2.0 draft** command-text surface. It
11
+ implements the KQL, KML, and META syntax surfaces, but it does not claim a
12
+ complete KIP conformance profile by itself: Schema resolution, Governance,
13
+ transactions, persistence, projection, history, Capsules, and runtime
14
+ envelopes remain engine responsibilities.
15
+
16
+ The parser targets the KIP 2.0 command-text syntax — all three languages:
17
+ **KQL** (`FIND`) to read, **KML** (`ASSERT`, `MUTATE`, `CREATE`, `UPSERT`,
18
+ `UPDATE`, and the retract/supersede/archive/tombstone/purge lifecycle) to
19
+ change cognition, and **META** (`DESCRIBE`, `LIST`, `SEARCH`, `VERIFY`,
20
+ `VALIDATE`, `PREVIEW`, `HISTORY`, `CHANGES`, `SNAPSHOT`, `EXPORT CAPSULE`) to
21
+ ground and introspect. That includes the five Core element kinds (Concept,
22
+ Proposition, Assertion, Evidence, Activity), `BELIEF` / `BELIEF SLOT`
23
+ projection patterns, `STRUCTURAL` topology patterns, facets, the independent
24
+ `AS OF` / `FOR TIME` time axes, `:parameter` placeholders in full value
25
+ positions, ASCII case-insensitive keywords, JSON-compatible object literals
26
+ with unquoted identifier keys, and batch-friendly multi-command source text.
27
+ The request envelope (`kip`, `request_id`, `space`, `execution`, `ingest`,
28
+ `operations`) is JSON outside the `.kip` language and should be validated by
29
+ the caller.
30
+
31
+ ## Two trees, two audiences
32
+
33
+ `parse` returns a **syntax tree**: ranges, comments, quoting style, raw number
34
+ text — everything a formatter or an editor needs to reproduce the source, and
35
+ error recovery that keeps producing a tree after a mistake.
36
+
37
+ `lower` returns the **executable AST**: every construct collapsed to the one
38
+ shape it means, with the open-ended parts of the grammar closed. The `ASSERT`
39
+ sugar desugars to exactly the `ENSURE PROPOSITION` + `CREATE ASSERTION`
40
+ (+ `SUPERSEDE`) it stands for, and nothing more; a filter becomes a
41
+ comparison, a logical node, a negation, or a call to a registered function; a
42
+ variable becomes a name and a dot path. Anything the syntax admits but the
43
+ language does not — an unknown filter function, an `UPSERT` identified by name
44
+ alone, an `UPDATE` that reaches into Assertion epistemic payload — is rejected
45
+ here, with a KIP error code.
46
+
47
+ That split is why the two exist: an editor wants the loosest tree it can get,
48
+ an engine wants the tightest.
14
49
 
15
50
  ## Installation
16
51
 
@@ -29,16 +64,20 @@ const tokens = tokenize('FIND(?x.name) WHERE { ?x {type: "Person"} }')
29
64
  // Token[] with type, value, line, column, offset
30
65
  ```
31
66
 
67
+ Keywords are ASCII case-insensitive, so `find` and `FIND` produce the same
68
+ token type; schema symbols and string values keep their own case-sensitive
69
+ contracts.
70
+
32
71
  ### Parse
33
72
 
34
73
  ```ts
35
74
  import { parse } from '@ldclabs/kip-lang'
36
75
 
37
76
  const { ast, diagnostics } = parse(`
38
- FIND(?drug.name)
77
+ FIND(?belief.status, ?tz)
39
78
  WHERE {
40
- ?drug {type: "Drug"}
41
- (?drug, "treats", {name: "Headache"})
79
+ ?person {type: "Person", name: "Alice"}
80
+ ?belief BELIEF (?person, "timezone", ?tz)
42
81
  }
43
82
  LIMIT 10
44
83
  `)
@@ -52,35 +91,35 @@ console.log(diagnostics) // [] (no errors)
52
91
  ```ts
53
92
  import { format } from '@ldclabs/kip-lang'
54
93
 
55
- const source = `UPSERT { CONCEPT ?x { {type: "Drug", name: "Aspirin"} SET ATTRIBUTES { risk_level: 2 } } }`
94
+ const source = `CREATE CONCEPT ?exp { TYPE "Experience" NAME "Deploy v2 failure" SET ATTRIBUTES { goal: :goal, outcome_status: "failure" } }`
56
95
 
57
96
  const formatted = format(source, {
58
- indentSize: 4, // default: 4
59
- sortAttributes: true // default: true
97
+ indentSize: 4, // default: 4
98
+ sortAttributes: false // default: false — author key order is preserved
60
99
  })
61
100
  ```
62
101
 
63
102
  Output:
64
103
 
65
104
  ```kip
66
- UPSERT {
67
- CONCEPT ?x {
68
- {type: "Drug", name: "Aspirin"}
69
- SET ATTRIBUTES { risk_level: 2 }
70
- }
105
+ CREATE CONCEPT ?exp {
106
+ TYPE "Experience"
107
+ NAME "Deploy v2 failure"
108
+ SET ATTRIBUTES {goal: :goal, outcome_status: "failure"}
71
109
  }
72
110
  ```
73
111
 
74
- The formatter preserves comments and quoted/unquoted key styles from the original source.
75
-
76
- A lighter alternative `formatPreservingComments()` is also available it normalizes indentation at the line level without AST reconstruction.
112
+ The formatter preserves comments and quoted/unquoted key styles from the
113
+ original source. `sortAttributes` alphabetizes `SET ATTRIBUTES` keys, and skips
114
+ any block holding a comment, since reordering would detach the comment from
115
+ its key.
77
116
 
78
117
  ### Diagnose
79
118
 
80
119
  ```ts
81
120
  import { diagnose } from '@ldclabs/kip-lang'
82
121
 
83
- const diagnostics = diagnose('UPSERT { CONCEPT ?x { {type: "Drug"} }')
122
+ const diagnostics = diagnose('CREATE CONCEPT ?x { TYPE "Experience"')
84
123
  // [{ severity: "error", message: "Unclosed '{'", ... }]
85
124
  ```
86
125
 
@@ -90,35 +129,85 @@ Diagnostics cover:
90
129
  - Bracket matching (unclosed / mismatched braces, brackets, parentheses)
91
130
  - Parser errors (unexpected tokens, missing clauses)
92
131
 
132
+ ### Lower to the executable AST
133
+
134
+ ```ts
135
+ import { parse, lower, checkBudget } from '@ldclabs/kip-lang'
136
+
137
+ function command(source: string) {
138
+ checkBudget(source) // KIP_4002 before parsing recurses
139
+ const { ast, diagnostics } = parse(source)
140
+ const fatal = diagnostics.find((d) => d.severity === 'error')
141
+ if (fatal) throw new Error(`${fatal.code} ${fatal.message}`)
142
+ return lower(ast) // throws KipSyntaxError
143
+ }
144
+
145
+ command('FIND(?e.name) WHERE { ?e {type: "Experience"} } LIMIT 10')
146
+ // → the executable Command AST
147
+ ```
148
+
149
+ `lower` requires the program to hold exactly one command. In KML that means
150
+ one statement — `MUTATE { ... }` is how several mutations become one
151
+ all-or-nothing cognitive transition, so a transaction is still one command.
152
+ Use `lowerAll` for source text that is genuinely a sequence of commands.
153
+
154
+ The `diagnostics` check above is not decoration. `parse` recovers from a
155
+ malformed string or an unquoted value by reading it leniently, and `lower`
156
+ receives only the tree — so skipping the check lowers `"a\xb"` to `axb` and
157
+ `{a: bare}` to `{a: "bare"}` without a word of complaint.
158
+
159
+ `checkBudget` is not optional for a server. `parse` is recursive descent, so
160
+ without a depth ceiling a hostile `[[[[…` overflows the JavaScript stack — and
161
+ in a runtime that shares one stack across requests, that takes down more than
162
+ the one request. The budgets match `anda_kip`'s, so a command one KIP engine
163
+ refuses on size is refused by every other engine too.
164
+
93
165
  ## API Reference
94
166
 
95
- | Export | Description |
96
- | -------------------------------------------- | -------------------------------------------------------- |
97
- | `tokenize(source)` | Tokenize KIP source into `Token[]` |
98
- | `parse(source)` | Parse into `{ ast: Program, diagnostics: Diagnostic[] }` |
99
- | `format(source, options?)` | AST-based formatting with comment preservation |
100
- | `formatPreservingComments(source, options?)` | Line-level indent normalization |
101
- | `diagnose(source)` | Return `Diagnostic[]` (lexer + bracket + parser errors) |
102
- | `TokenType` | Enum of all token types |
103
- | `KEYWORDS` / `FUNCTIONS` | Maps of KIP keywords and built-in functions |
167
+ | Export | Description |
168
+ | ---------------------------------- | -------------------------------------------------------- |
169
+ | `tokenize(source)` | Tokenize KIP source into `Token[]` |
170
+ | `parse(source)` | Parse into `{ ast: Program, diagnostics: Diagnostic[] }` |
171
+ | `format(source, options?)` | AST-based formatting with comment preservation |
172
+ | `diagnose(source)` | Return syntax, static-semantic, and executable diagnostics |
173
+ | `validateExecutable(program)` | Check every parsed statement can lower to executable AST |
174
+ | `analyzeSemantics(program)` | Spec SHOULD/MUST checks decidable without a live schema |
175
+ | `lower(program)` | Lower one command to the executable `Command` AST |
176
+ | `lowerAll(program)` | Lower every command in a multi-statement program |
177
+ | `lowerStatement(statement)` | Lower a single statement |
178
+ | `checkBudget(source)` | Enforce length and nesting ceilings (`KIP_4002`) |
179
+ | `checkBatchBudget(count)` | Enforce the command-count ceiling (`KIP_4002`) |
180
+ | `KipSyntaxError` | Thrown by `lower` / `checkBudget`, carries a KIP code |
181
+ | `TokenType` | Enum of all token types |
182
+ | `KEYWORDS` / `FUNCTIONS` | Keyword map and built-in function set |
183
+ | `PARSER_VERSION` / `KIP_SPEC_REVISION` | Grammar version and the spec revision it targets |
104
184
 
105
185
  ### AST Node Types
106
186
 
107
187
  All AST types are exported for downstream consumption:
108
188
 
109
- - **Statements**: `FindStatement`, `UpsertStatement`, `UpdateStatement`, `MergeStatement`, `DeleteStatement`, `DescribeStatement`, `SearchStatement`, `ExportStatement`
110
- - **Blocks**: `ConceptBlock`, `PropositionBlock`, `SetAttributes`, `SetMetadata`, `SetPropositions`, `WithMetadata`, `ExpectVersion`
111
- - **Patterns**: `ConceptPattern`, `PropositionPattern`, `FilterClause`, `NotClause`, `OptionalClause`, `UnionClause`
112
- - **Expressions**: `ObjectLiteral`, `ArrayLiteral`, `ObjectEntry`, `Expression`
189
+ - **KQL**: `FindStatement`, with `AsOfClause`, `ForTimeClause`, `EpistemicClause`, `OrderByClause`, `LimitClause`, `CursorClause`
190
+ - **KML**: `MutateStatement` plus every `MutationClause` — `CreateConceptStatement`, `UpsertConceptStatement`, `EnsurePropositionStatement`, `AssertStatement`, `CreateEvidenceStatement`, `CreateAssertionStatement`, `CreateActivityStatement`, `UpdateStatement`, `RetractAssertionStatement`, `SupersedeAssertionStatement`, `CorrectEvidenceStatement`, `TransitionActivityStatement`, `SetRetentionStatement`, `ArchiveStatement`, `TombstoneStatement`, `PurgeStatement`, `MergeConceptStatement`
191
+ - **META**: `DescribeStatement`, `ListStatement`, `SearchStatement`, `VerifyStatement`, `ValidateStatement`, `PreviewStatement`, `HistoryStatement`, `ChangesStatement`, `SnapshotStatement`, `ExportCapsuleStatement`
192
+ - **Clauses**: `TypeClause`, `ClientKeyClause`, `NameClause`, `MatchClause`, `SetFieldsClause`, `SetAttributesClause`, `SetFacetClause`, `UnsetAttributesClause`, `UnsetFacetClause`, `SetStructuralClause`, `UnsetStructuralClause`, `ExpectVersionClause`, `ExpectStateClause`
193
+ - **Patterns**: `ConceptPattern`, `PropositionPattern`, `AssertionPattern`, `EvidencePattern`, `ActivityPattern`, `StructuralPattern`, `BeliefPattern`, `BeliefSlotPattern`, `FilterClause`, `NotClause`, `OptionalClause`, `UnionClause`
194
+ - **Expressions**: `Expression`, `FieldAccess`, `AggregateExpr`, `FunctionCallExpr`, `ObjectLiteral`, `ObjectPattern`, `ArrayLiteral`, `ObjectEntry`
195
+
196
+ The executable AST is exported separately, and names that collide with a
197
+ syntax-tree node carry an `Exec` prefix.
113
198
 
114
- String-or-parameter statement fields such as `SearchStatement.termValue`,
115
- `SearchStatement.withTypeValue`, `SearchStatement.modeValue`, and
116
- `DescribeStatement.typeNameValue` preserve whether the original source used a
117
- quoted string or a `:parameter` placeholder.
199
+ String-or-parameter operands stay `ScalarValue` nodes `SearchStatement.term`,
200
+ `SearchStatement.withType`, `DescribeStatement.value`, `ClientKeyClause.value`
201
+ so the tree still says whether the source wrote a quoted string or a
202
+ `:parameter` placeholder.
118
203
 
119
204
  ## KIP Language
120
205
 
121
- KIP is a structured query and mutation language for knowledge graphs. See the [KIP Specification](../../SPECIFICATION.md) for full syntax details.
206
+ KIP 2.0 is the cognitive state protocol between an agent and a persistent
207
+ Cognitive Nexus: you read with KQL, change cognition with KML, and ground or
208
+ introspect with META. See the [KIP 2.0 Specification](https://github.com/ldclabs/KIP/blob/main/v2/KIP-2.0-SPECIFICATION.md)
209
+ for full syntax details, or the [syntax card](https://github.com/ldclabs/KIP/blob/main/v2/KIPSyntax.md) for a
210
+ condensed reference.
122
211
 
123
212
  ## License
124
213