Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
149 changes: 149 additions & 0 deletions .claude/skills/kdbx-modules/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
---
name: kdbx-modules
description: >
Writing, loading and converting KDB-X modules: the `export` dictionary,
`use`, the module-local namespace, `.z.m` / `.z.M`, QPATH and `.Q.m.SP`
search paths, module hierarchy (`.child`, `..sibling`), module-relative
`::` paths, binary modules with `kexport`, and converting a legacy q or C
library to a module. Use when q code calls `use` or defines `export`, or the
user asks to create a module or turn a library into one.
---

# KDB-X Modules

Source: [KX module framework quickstart](https://code.kx.com/kdb-x/modules/module-framework/quickstart.html). The examples follow the KX page and use `//` comments. **In this repo, `style.md` and `consistency.md` take precedence** (`/ ` comments, required injected deps, `VERSION`). For turning TorQ code into a module, use the `torq-module-extraction` skill.

**Key difference from legacy/TorQ q:** inside a module, do *not* use absolute names (`.foo.f`) or `\d .foo`. Code runs in a module-private namespace; write bare names, and use `.z.m` / `.z.M` only where a bare name won't work (see below).

## Minimum module

A module is a file on the search path that defines `export`, a dictionary of its public interface:

```q
// $QHOME/mod/foo/init.q
export:([f:{x+1};g:{x*2}])

// user
q)foo:use`foo
q)foo.f 10
11
```

`use` returns the module's `export`. Other forms of `export`:

```q
f:{x+1}
g:{x*2}
export:([f;g]) // keys taken from the variable names
export:{([f;g])} // or a function returning the dictionary
export:.z.m // simple module with nothing private: export everything
```

## Encapsulation

Names defined during load go in the module's own namespace and stay private unless exported:

```q
MULT:2 // private value
f:{x+1} // private function
g:{f[x]*MULT}
getMult:{MULT}
setMult:{.z.m.MULT:x} // .z.m.x: to assign the module global from inside a function
export:([g;getMult;setMult])
```

Exporting a variable gives the user a **copy**, not a reference. Expose state through getter/setter functions.

## `.z.m` and `.z.M`

- `.z.m`: the current module's namespace. `.z.M`: its name as a symbol; `.z.M.name` builds the symbolic global name of a member.
- Inside functions they keep the module they were *defined* in. Outside any module both refer to `.`.

Use them when:
- **The name is reserved** (`log`, `use`, `parse`, …): define it as `.z.m.log:{...}` and call `.z.m.log`.
- **A q-sql statement calls a module function**: `select .z.m.f a from t`. A bare `f` there resolves in the *caller's* namespace.
- **A legacy API needs a global name as a symbol**: `.timer.addTimer[.z.M.cleanup;01:00]`. To replace a member: `.z.M.log set(::)`.
- **A local and a global share a name**: refer to the global as `.z.M.name`. Renaming one of them is often clearer.
- **You need a child namespace inside the module**: prefix each definition explicitly - `.z.m.foo.a:1`, `.z.m.foo.f:{...}`. Never `\d .z.m.foo`: the conventional `\d .` that follows returns to *root*, not to the module, so every later definition - including `export` - lands at root and `use` fails with `no export`. There is no acceptable form of `\d` in a module.
- **Merging another module's exports into this one**: `.z.m,:use`foo`.

```q
.z.m.log:{-1 string[.z.P]," ",x}
disableLog:{.z.M.log set(::);}
f:{x+1}
upd:{.z.m.log"updating";select .z.m.f a from ([]a:1 2 3)}
export:([disableLog;upd])
```

## Search path and file names

Search path: `$QPATH` (colon-separated, like `PATH`), or `.Q.m.SP` (string list) at run time; default `$QHOME/mod`. For module `foo`, each path entry is tried in this order before moving to the next entry:

```
foo.k foo.q foo.k_ foo.q_ foo.$PLATFORM.so
foo/init.k foo/init.q foo/init.k_ foo/init.q_ foo/init.$PLATFORM.so
```

`$PLATFORM` = OS (`w`/`l`/`m`) + arch (`i`/`a`) + word size, e.g. `li64`. A dotted module name maps to directories: `use`parent.child2` loads `parent/child2.q` or `parent/child2/init.q`.

## Module hierarchy

Relative `use` from inside a module:
- `` use`.child ``: child of the current module
- `` use`..sibling ``: sibling
- `` use`...name ``: parent's sibling, and so on; deeper paths like `` `.a.b `` also work

## `use` behaviour

- Exported functions come back as **aliases** (type `104h`). If the module later redefines the function, the alias follows the change. Don't rely on the generated alias name. To get the definition: `value first value f`.
- Loads are **deduplicated**: a module used in several places loads once, and later calls return the cached value.
- `use` is an ordinary function, so it can be called inside functions, e.g. `{use[`parent.child1][`f]x}`. A context without permission to load (e.g. inside `peach`) can only fetch modules that are already loaded.
- Destructure on import: `([f]):use`foo`.

## Module-relative paths

A path starting with `::` is relative to the current module's file, so a path symbol has three colons. It resolves **only during load**; to use it in a function, resolve it at load time with `.Q.rp`:

```q
// foo/init.q
\l ::bar.q
export:([f])

// foo/bar.q
data:.Q.rp`:::bar.txt
f:{read0 data}
```

## Converting a legacy q library

1. Convert external dependencies to modules first, then replace their imports with `use`.
2. Remove absolute namespace prefixes (`.lib.func` → `func`) in assignments **and** in global references inside functions. Remove every `\d`, including one that spans the whole file; to keep a grouping, prefix each definition explicitly (`.z.m.foo.a:1`).
3. If dropping a prefix makes a local and a global collide, refer to the global as `.z.M.name`, or rename one of them.
4. Inside functions, change global assignments from `:` to `.z.m.x:` - the house convention (`style.md`). `.lib.x:1` set a global; `x:1` would now create a local. `x::1` also works, but `style.md` says to avoid `::`.
5. Prefix names that clash with reserved words (`use`, `log`, `parse`, …) with `.z.m`.
6. Prefix functions called from q-sql with `.z.m`.
7. Convert relative paths to `::` paths, resolving them with `.Q.rp` at load time if functions use them.
8. Add `export` at the end of the file: the public interface, or `export:.z.m` if nothing is private.
9. Rename the file to a lookup name: `m.q` or `m/init.q`.
10. In user code, put the module's directory on `$QPATH` and replace `\l`/import with `use`.

Check after converting: grep the file for leftover `\.lib\.` prefixes, `\d`, and function-body assignments to globals that still use a single `:`.

## Converting a binary (C) library

1. Add a `kexport` function (not `export`, which is reserved in C++) that returns the interface dictionary, using `dl` to wrap each function:

```c
K kexport(K x) {
K names = ktn(KS,2);
kS(names)[0] = ss("foo");
kS(names)[1] = ss("bar");
K fns = ktn(0,2);
kK(fns)[0] = dl((void*)k_foo, 1);
kK(fns)[1] = dl((void*)k_bar, 1);
return xD(names, fns);
}
```

2. Rename the library to a lookup name, e.g. `m.li64.so` or `m/init.li64.so`.
3. Put its directory on `$QPATH` and load it with `use`.
192 changes: 192 additions & 0 deletions .claude/skills/torq-module-extraction/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
---
name: torq-module-extraction
description: >
Extract a piece of TorQ (a code/common/*.q file, a handler, or logic inside
a process such as gateway.q) into a standalone Data Intellect KDB-X module
under di/ in kdbx-modules: analyse the source, design the export and init
API, inject or `use` dependencies, write init.q / implementation / .md docs
/ k4unit test.csv / VERSION, and verify with k4unit.moduletest. Use for
"extract", "port", "convert" or "modularise" a TorQ file, or when reviewing
such a module against consistency.md.
---

# TorQ → KDB-X Module Extraction

The job is to turn TorQ code into a `di.<name>` module that does **what the original did, no more**, and follows this repo's rules.

**Authority order:** `consistency.md` and `style.md` in this repo come first, then existing modules (`di/dbwrite`, `di/eodtime`, `di/subscriptions`), then this skill. Read both guides before writing code. They change, and they beat anything here. For module mechanics (`export`, `.z.m`/`.z.M`, `::` paths, `use`), see the `kdbx-modules` skill. For reading TorQ source, see the TorQ repo's `torq-developer` skill.

## Step 1: Analyse the source (before writing anything)

Read the TorQ file(s) and give the user this summary:
- **Functions:** what each does. Mark each **public** (called from other TorQ files or by clients; grep the TorQ tree for its callers) or **internal**.
- **External namespaces it touches:** `.lg`, `.timer`, `.servers`, `.dotz`/`.z.*`, `.proc`, `.ps`, `.sub`, `.os`, `.api`, other module namespaces.
- **Config:** every `@[value;`var;default]` and what sets it (settings files, command line).
- **Handler assignments:** any `.z.*` set directly or through `.dotz.set`.
- **Code to strip:** FinSpace (`.finspace.*`, `.aws.*`, `.awscust.*`) and dead code.

Check the public/internal split with the user. Don't decide it alone: left alone, you'd tend to export everything.

## Step 2: Design the API

- **`export`:** only the functions external callers need. Helpers stay private.
- **`init` signature:**
- Library module: `init[deps]`.
- Framework/process module (anything `di.torq` orchestrates): `init[config;deps]`.
- Read config with a presence check: ``$[`k in key config;config`k;default]``. This replaces `@[value;`var;default]`.
- **Settings sections don't deep-merge.** `di.torq.config`'s `cascade` joins tiers with `,`, and a `[section]` is one key holding a dict - so a proctype or procname tier that sets one key of a section replaces the whole section. Give every section key a code-side default (``opt[`k;default]``, as `di.torq`'s `initquerylog` does) rather than relying on defaults that live in a lower-tier file.
- **Each dependency is either injected or `use`d:**

| TorQ call | Becomes | Contract |
|---|---|---|
| `.lg.o/.lg.w/.lg.e` | injected `log` | `` `info`warn`error `` each `{[ctx;msg]}` |
| `.timer.repeat/.once/.rep` | injected `timer` | `` `addjob`deletejobs`enablejobs`disablejobs`getactivejobs `` |
| `.dotz.set` / `.z.*` assignment | injected `handlers` | `` `register`remove`list `` |
| `.servers.*` | injected `servers` | `` `startup`getservers`gethandlebytype`waitfortype `` |
| a stateless library (`dbwrite`, `pubsub`, `subscriptions`, `dataaccess`, `tplog`, …) | `x:use`di.x` at the top of `init.q` | its export |

Rule of thumb: inject cross-cutting singletons, and `use` libraries. Use `use` by default; inject only where there's shared state, a single lifecycle, or a seam for substitution.
- **Name:** new framework/process modules go under `di.torq.*` / `di.torq.proc.*`, and standalone utilities under `di.util.*`. Library modules stay flat (`di.<name>`). Don't rename existing flat modules: that migration is a separate coordinated change.

Confirm the export list and the inject/`use` split with the user before Step 3.

## Step 3: Layout

```
di/<name>/
init.q / loads the implementation, sets version, defines export
<name>.q / implementation
<name>.md / documentation
test.csv / k4unit tests
VERSION / semver, e.g. 0.1.0
deps.toml / optional: minimum versions of modules it uses
```

`init.q` follows `di/dbwrite/init.q`:

```q
/ <one-line purpose>

\l ::<name>.q

version:first read0`:::VERSION

export:([init;func1;func2;version])
```

`version` can be published as the `VERSION` file alone, without the `export` entry - `di.torq.depcheck` reads the file pre-load and falls back to it post-load. Do that when a `getapimeta` contract test asserts the exact export set (`di.torq.config`, `di.torq.servers`, `di.util.toml`). The `VERSION` file is required either way.

## Step 4: Convert the code

Apply every rule below. These are the mistakes you're most likely to make when converting from TorQ source, so check each one:

1. **No `\d`.** Module code runs in its own private namespace, so write bare names. Use `.z.m.x` / `.z.M` only for reserved-word clashes, functions called from q-sql, or names passed as symbols to legacy APIs.
2. **Strip every absolute `.oldns.` prefix,** in definitions *and* inside function bodies.
3. **Assigning a module global inside a function:** use `.z.m.x:value` (the existing modules' idiom). Avoid `::` (style.md).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kdbx-modules/SKILL.md uses :: to assign a module global from inside a function (line 51’s MULT::x, and the “Converting a legacy q library” step that says to change : to ::). torq-module-extraction/SKILL.md rule 3 says the opposite — use .z.m.x: and avoid ::, matching style.md. Both work mechanically, but an agent following one skill then the other will flip conventions depending on which it read last. Suggest fixing kdbx-modules to use .z.m.x: throughout, matching style.md and the other skill, and adding a one-line note here that .z.m.x: is the house convention.

4. **Dependencies are required.** `init` validates the deps dict and errors immediately, with a message naming the module and what to pass. There's no silent fallback, and no default logger. (The exercise brief says "sensible defaults"; `consistency.md` overrides it.) Pattern:

```q
init:{[deps]
/ deps - `log!(logdict) where logdict is `info`warn`error!({[c;m]};{[c;m]};{[c;m]})
if[99h<>type deps;'"di.<name>: deps must be a dict with a `log key"];
if[not `log in key deps;'"di.<name>: log dependency is required; pass `info`warn`error functions keyed on `log"];
if[not all `info`warn`error in key deps`log;'"di.<name>: log dict must have `info`warn`error keys"];
.z.m.loginfo:deps[`log]`info;
.z.m.logwarn:deps[`log]`warn;
.z.m.logerr:deps[`log]`error;
};
```

Always call injected functions through `.z.m` (`.z.m.loginfo[`<name>;"msg"]`). You can store each function separately or the whole dict (`.z.m.log[`info][...]`), but pick one per module.
5. **Make `init` idempotent** if it registers anything (handlers, timer jobs): guard the registration with a `registered` flag.
6. **Handlers:** never assign `.z.*` directly. Go through the injected `handlers` dependency.
7. **Root state and root IPC entry points:** what decides where a name resolves is bare-vs-symbol, not read-vs-write. Bare names inside module functions refer only to the module: reading a root-only name signals (`{count trade}` → `'trade`), and writing one (`trade,:x`, `x::v`) quietly creates a private copy, leaving root untouched. Symbols do reach root: `value t`, `exec … from t`, `t insert x`, `t upsert x`, `t set v`, and ``@[`.;t;…]``. To maintain a root table or publish a root function (`upd`, a `reload` peers call by name):

```q
@[`.;`upd;:;updfn];
@[`.;t;{[tab;d] tab upsert d}[;x]]; / root upsert; also works under -11! replay
set[`.hdb.reload;reloadfn];
```

A subscriber `upd` that isn't published at root is never found: live updates are dropped with only an `'upd` in the subscriber's log (the tickerplant publishes async, so it never sees the error), and `-11!` replay signals `'upd` and replays nothing.
8. **Paths:** module-local paths use `::`: `\l ::file.q`, `` get`:::data/file ``. Resolve them with `.Q.rp` at load time if a function needs them later.
9. **Remove FinSpace code** entirely.
10. **No `show`, `0N!`, `-1`, `-2`.** Log through the injected logger, or not at all.
11. **Reserved names break at load time:** `log`, `ss`, `sv`, `string`, `cut`, `tables` as locals or parameters can throw while the file loads. Use distinct names (`srv`, `lg`).
12. **Don't simulate polymorphism.** Use dictionaries of functions keyed by mode (as in `di/timer` `nextstart`), and avoid big `$[...]` blocks.
13. **Style** (style.md):
- Comments are `/ ` plus lowercase text, not `//`, despite the exercise brief. A multi-line function's description comment goes on the line *after* the declaration.
- Lowercase names: no camelCase, no underscores.
- 2-space indent, `;` at the end of every line including the closing `}`.
- No `do`/`while`/`for`.
- Timestamps, not datetime.
- Lines of 150 characters or fewer.
- Multi-line formatting for complex q-sql; functional form only when unavoidable, with the q-sql in a comment.
14. **Don't add features.** Same behaviour as the TorQ original. Put any improvements you'd suggest in a list for the user rather than in the code.

## Step 5: Tests (`test.csv`)

The header is exactly:

```
action,ms,bytes,lang,code,repeat,minver,comment
```

- Actions:
- `before` / `after`: per-file setup and teardown
- `run`: execute, checking time against `ms`
- `true`: must return `1b`
- `fail`: must signal
- `comment`
- The first `before` row loads the module under the name the tests use: ``before,0,0,q,mymod:use`di.mymod,1,,load module``.
- Quote any `code` field containing commas, and double its inner quotes (see `di/dbwrite/test.csv`).
- Every exported function gets at least one test. Also cover edge cases: empty input, nulls, wrong types (`fail`), and `init` rejecting missing or malformed deps.
- Mock dependencies:
- A no-op logger: ``mylog:`info`warn`error!({[c;m]};{[c;m]};{[c;m]})``.
- A capturing logger that upserts into a `caplog` table, to assert the module logged.
- Clean up any files the tests write.

## Step 6: Documentation (`<name>.md`)

Follow an existing module's `.md`. Include:
- the purpose in one or two sentences
- how to load and initialise it (with a `di.util.log` example)
- each export with its signature and description
- config keys and their defaults
- dependencies, both injected and `use`d
- a short usage example

## Step 7: Verify

From the repo root (QPATH must include it):

```q
q)mymod:use`di.mymod
q)logging:use`di.util.log
q)mymod.init logging.logdict / or mymod.init[config;deps] for framework modules
q)k4unit:use`di.k4unit
q)k4unit.moduletest`di.mymod
```

**One `moduletest` per q process.** `KUT`/`KUTR` accumulate, so a second call in the same session re-runs the first module's suite and the pass/fail summary covers both. Test several modules with one process each, with a `runner.q` that does a single `moduletest` and exits:

```sh
for m in di.mymod di.other; do q runner.q -q $m; done
```

Several suites also spawn child processes and mutate real process state, so a failure seen in a combined run is unverified until it reproduces in a fresh process.

Report the k4unit results honestly, including any failures. Also check that the module loads in a fresh session **without** `di.torq`.

## Definition of done

- [ ] `init.q` loads cleanly; `export` holds only the public API plus `version`
- [ ] No `\d`, and no leftover absolute TorQ namespace prefixes
- [ ] All dependencies arrive through `init`, are validated, and fail clearly when missing; `init` is idempotent if it registers anything
- [ ] No direct `.z.*` assignment, no FinSpace code, no `show`/`0N!`/`-1`/`-2`
- [ ] Root writes use `@[`.;…]` / `set` where root state or root IPC functions are needed
- [ ] `test.csv` covers every export, and `k4unit.moduletest` passes
- [ ] `<name>.md` written; `VERSION` present; `deps.toml` if it `use`s versioned modules
- [ ] Follows style.md (`/ ` comments, lowercase, `;` line ends, no loops, ≤150 chars)
- [ ] Behaviour matches the TorQ original, with suggested extras listed separately for the user
- [ ] Loads standalone in a fresh q session

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True for library modules but wrong for proc modules, which depend on root .servers./.sub. names published by other modules. Scope the check to library modules only.