agent-wisdom 0.0.0-stage → 0.1.1
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/CHANGELOG.md +51 -0
- package/LICENSE +21 -0
- package/README.md +103 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +4 -0
- package/dist/wisdom.d.ts +63 -0
- package/dist/wisdom.js +547 -0
- package/examples/README.md +21 -0
- package/examples/hooks/claude-code/wisdom-pretooluse.mjs +220 -0
- package/examples/store/core/w-report-what-you-ran.md +18 -0
- package/examples/store/precedents/p-narrow-vs-full-before-commit.md +14 -0
- package/examples/store/techniques/w-full-suite-first.md +21 -0
- package/examples/store/techniques/w-narrow-test-first.md +21 -0
- package/examples/store/techniques/w-read-your-diff-before-pr.md +20 -0
- package/examples/store/techniques/w-reproduce-before-fix.md +20 -0
- package/examples/store/techniques/w-small-focused-commits.md +20 -0
- package/examples/store/values/w-prefer-reversible-steps.md +20 -0
- package/package.json +61 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
Version headings are bracketed and linked once a release is tagged; untagged
|
|
8
|
+
versions are listed plainly.
|
|
9
|
+
|
|
10
|
+
## [Unreleased]
|
|
11
|
+
|
|
12
|
+
## [0.1.1] - 2026-11-29
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
|
|
16
|
+
- **The example Claude Code hook reads unusual file names as themselves.** It now lists staged paths with `git diff --cached --name-only -z`. Before, git quoted names with non-ASCII characters or quotes, so they were queried and logged as escaped text (`"r\303\251sum\303\251.md"`, stray quotes and backslashes), and a non-ASCII word such as `résumé` could not match as a whole word. Quote characters are also dropped when a name is split into words.
|
|
17
|
+
- **A large staged set no longer empties the query.** The hook gives git a 16 MiB output buffer. Before, more than 1 MiB of names killed git and the query fell back to the fixed words only.
|
|
18
|
+
- **The hook always exits 0.** Reading the hook input now sits inside the same error guard as everything else, so a broken input stream can never fail the hook.
|
|
19
|
+
|
|
20
|
+
### Changed
|
|
21
|
+
|
|
22
|
+
- This is the first release published from CI through npm Trusted Publishing, with provenance. No change to the `wisdom` command.
|
|
23
|
+
|
|
24
|
+
## [0.1.0] - 2026-11-29
|
|
25
|
+
|
|
26
|
+
First release. `wisdom` is a read-only command over a directory of conditional entries; it started as a read-path prototype inside a larger agent orchestrator and is now a standalone package.
|
|
27
|
+
|
|
28
|
+
### Added
|
|
29
|
+
|
|
30
|
+
- **The `wisdom` CLI.** `wisdom validate [--strict] [--json]`, `wisdom list [--layer L] [--status S] [--json]`, `wisdom show <id> [--json]` and `wisdom lookup "<situation>" [--point P] [--limit N] [--role R] [--task T] [--repo R] [--json] [--no-log]`. Exit codes: `0` success (including "no match"), `1` a validation error or an unknown id, `2` a usage error. See [FR-CLI-001](docs/requirements.md#fr-cli-001).
|
|
31
|
+
- **The store and entry format.** A directory of Markdown files with YAML frontmatter in four layers (`core/`, `values/`, `techniques/`, `precedents/`). Every entry states a claim, `applies_when`, `fails_when`, and an opposite with the cue that picks between the two, plus triggers, tags, sources and a status. Ids are chosen, stable, and equal to the filename. See [entry-format.md](docs/entry-format.md).
|
|
32
|
+
- **A deterministic, offline lookup.** Keyword match over `claim`, `applies_when` and tags, at most 3 results, possibly none; no model, no embeddings, no network ([DP-3](docs/requirements.md#dp-3), [DP-4](docs/requirements.md#dp-4)).
|
|
33
|
+
- **A lookup log.** Each lookup appends one JSON line to `<store>/lookups.jsonl`, labelled with `task` (`--task` or `$WISDOM_TASK`), `repo` (`--repo` or `$WISDOM_REPO`) and `role` (`--role`). It fails open and `--no-log` turns it off.
|
|
34
|
+
- **Source independence.** `validate` warns when an active technique or value has fewer than 3 sources or sources from fewer than 2 tasks; `--strict` makes that an error ([DP-9](docs/requirements.md#dp-9)).
|
|
35
|
+
- **`WISDOM_DIR` pointing at a regular file** is a `validate` error (exit 1) and a stderr note for `list` and `lookup`, which still answer with no entry and exit 0 ([FR-STORE-006](docs/requirements.md#fr-store-006)).
|
|
36
|
+
- **A library entry point** (`import { loadStore, lookupEntries, resolveStoreDir, runWisdomCli, ... } from 'agent-wisdom'`) with types.
|
|
37
|
+
- **Documentation and examples:** a requirements document, a getting-started guide, the entry format, harness setup for Claude Code and Codex (with an example `PreToolUse` hook that never blocks and never sends text from the command: its query is the decision point's fixed words plus words from git state, namely staged file paths for a commit and the branch name for a pull request), a rationale, a synthetic example store passing `validate --strict`, and three Claude Code skills (`agent-wisdom-explain`, `agent-wisdom-setup`, `agent-wisdom-write-entry`).
|
|
38
|
+
|
|
39
|
+
### Changed (relative to the prototype this package was extracted from)
|
|
40
|
+
|
|
41
|
+
- **One runtime dependency, `yaml`, now in `dependencies`.** The prototype listed it as a dev dependency, so an install without dev dependencies could not start. Recorded as a design principle with its rationale ([DP-7](docs/requirements.md#dp-7)); nothing else may be added without changing it.
|
|
42
|
+
- **Generic names.** The store is `$WISDOM_DIR`, else `~/.agent-wisdom` (trimmed, a leading `~` expanded against the `HOME` of the environment passed in). The log labels come from `$WISDOM_TASK` and `$WISDOM_REPO`. No harness-specific variable is read.
|
|
43
|
+
- **`lookup` skips entries that fail validation** and prints one stderr note with the count, pointing to `wisdom validate`. `validate` still reports them ([FR-LOOKUP-001](docs/requirements.md#fr-lookup-001)).
|
|
44
|
+
- **Tags match case-insensitively, and a hyphenated tag matches when all of its parts are among the query words**, so `code-review` matches "code review". Tag parts follow the query's 3-character minimum. `validate` warns on a tag that can never match ([FR-LOOKUP-004](docs/requirements.md#fr-lookup-004), [FR-VALIDATE-005](docs/requirements.md#fr-validate-005)).
|
|
45
|
+
- **Sources are de-duplicated by (kind, ref, task)** before counting; all `wisdom-kb` sources together still count as one source with at most one task ([FR-VALIDATE-004](docs/requirements.md#fr-validate-004)).
|
|
46
|
+
- **A layer path that is not a directory is a `validate` error** and is skipped by the other commands, instead of crashing with `ENOTDIR` ([FR-STORE-004](docs/requirements.md#fr-store-004)).
|
|
47
|
+
- **A UTF-8 byte order mark before the frontmatter is tolerated** ([FR-STORE-002](docs/requirements.md#fr-store-002)).
|
|
48
|
+
- **YAML warnings never print during lookup**; `validate` reports them ([FR-STORE-005](docs/requirements.md#fr-store-005)).
|
|
49
|
+
- **The "N file(s) checked" count includes files that failed to parse** ([FR-VALIDATE-002](docs/requirements.md#fr-validate-002)).
|
|
50
|
+
- **In `show --json`, the computed `layer` and `body` win over frontmatter keys of the same name** ([FR-SHOW-002](docs/requirements.md#fr-show-002)).
|
|
51
|
+
- **The documentation states that `list` cuts claims to 100 characters** ([FR-LIST-002](docs/requirements.md#fr-list-002)).
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jean Ibarz
|
|
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,3 +1,104 @@
|
|
|
1
|
-
#
|
|
1
|
+
# agent-wisdom
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Conditional wisdom for AI agents: advice that says when it applies, when it fails, and what the opposite advice is.**
|
|
4
|
+
|
|
5
|
+
`agent-wisdom` is a small read-only command, `wisdom`, over a folder of Markdown files. Each file is one *entry*: a claim, the situation where it holds, the situation where it fails, and the opposite advice with the observable cue that chooses between the two. An agent about to commit, open a pull request or merge runs `wisdom lookup "<situation>"` and gets back at most three entries, or none. The match is plain keywords: no model, no embeddings, no network, the same answer every time. It has one runtime dependency, `yaml`.
|
|
6
|
+
|
|
7
|
+
## Why it exists
|
|
8
|
+
|
|
9
|
+
Agents record plenty of concrete lessons ("this repo's tests need a build step first"), but almost none of that becomes judgment they can apply to a *new* situation. And advice without conditions is a trap: "test first" and "ship fast" are both good advice, and an agent that has only read one of them cannot tell when it is wrong. A conditional entry makes the agent check fit before it acts, and "no match" is a first-class answer, so the store never pads a bad guess into the context.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
npm install -g agent-wisdom # Node 18 or newer
|
|
15
|
+
wisdom --help
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## 60-second quickstart
|
|
19
|
+
|
|
20
|
+
The repository ships a small synthetic store in `examples/store`. From a clone (or from the installed package's `examples/` folder):
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
export WISDOM_DIR=examples/store
|
|
24
|
+
|
|
25
|
+
wisdom validate --strict
|
|
26
|
+
# 8 file(s) checked: 0 error(s), 0 warning(s)
|
|
27
|
+
|
|
28
|
+
wisdom lookup "about to commit a change to one module" --point commit --no-log
|
|
29
|
+
# w-narrow-test-first [technique, score 5] Run the narrow test before the full suite
|
|
30
|
+
# applies: a change touches one module and its own tests are quick to run
|
|
31
|
+
# fails: the change alters shared fixtures, build configuration, or a public interface other modules use
|
|
32
|
+
# opposite: Run the full suite first (w-full-suite-first)
|
|
33
|
+
# cue: shared fixtures or build configuration changed
|
|
34
|
+
#
|
|
35
|
+
# w-small-focused-commits [technique, score 5] Keep each commit to one logical change
|
|
36
|
+
# ...
|
|
37
|
+
|
|
38
|
+
wisdom lookup "quantum chromodynamics" --no-log
|
|
39
|
+
# no matching entry
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Read the first result the way an agent should: does `applies` describe my situation? Does `fails` describe it instead? If the `cue` holds, follow the opposite. Then start your own store: create `~/.agent-wisdom/techniques/w-my-first.md` (see below) and run `wisdom validate`.
|
|
43
|
+
|
|
44
|
+
## The entry format
|
|
45
|
+
|
|
46
|
+
One Markdown file per entry, `<layer>/<id>.md`. The layer is `core/`, `values/`, `techniques/` or `precedents/`.
|
|
47
|
+
|
|
48
|
+
```markdown
|
|
49
|
+
---
|
|
50
|
+
id: w-narrow-test-first
|
|
51
|
+
kind: technique
|
|
52
|
+
claim: Run the narrow test before the full suite
|
|
53
|
+
applies_when: a change touches one module and its own tests are quick to run
|
|
54
|
+
fails_when: the change alters shared fixtures, build configuration, or a public interface other modules use
|
|
55
|
+
opposite:
|
|
56
|
+
text: Run the full suite first
|
|
57
|
+
cue: shared fixtures or build configuration changed
|
|
58
|
+
entry: w-full-suite-first
|
|
59
|
+
triggers: [commit, review]
|
|
60
|
+
tags: [testing, commit]
|
|
61
|
+
sources:
|
|
62
|
+
- { kind: lesson, ref: example-lesson-3, task: example-task-1 }
|
|
63
|
+
- { kind: notebook, ref: example-shelf-3, task: example-task-2 }
|
|
64
|
+
- { kind: correction, ref: example-review-3, task: example-task-3 }
|
|
65
|
+
status: active
|
|
66
|
+
created: 2026-01-10
|
|
67
|
+
updated: 2026-01-10
|
|
68
|
+
---
|
|
69
|
+
Optional prose: the reasoning, an example.
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
An *active* technique or value should have at least 3 sources from at least 2 different tasks; `validate` warns when it does not, and `--strict` makes that an error. The full schema is in [docs/entry-format.md](docs/entry-format.md).
|
|
73
|
+
|
|
74
|
+
## Commands
|
|
75
|
+
|
|
76
|
+
| Command | What it does |
|
|
77
|
+
|---|---|
|
|
78
|
+
| `wisdom validate [--strict] [--json]` | Checks every entry. Exit 1 on errors; `--strict` makes warnings errors. |
|
|
79
|
+
| `wisdom list [--layer L] [--status S] [--json]` | One line per entry. The claim is cut to 100 characters (`--json` is not). |
|
|
80
|
+
| `wisdom show <id> [--json]` | One entry in full. Exit 1 on an unknown id. |
|
|
81
|
+
| `wisdom lookup "<situation>" [--point P] [--limit N] [--role R] [--task T] [--repo R] [--json] [--no-log]` | Keyword match over active entries and all core entries. At most 3 results, possibly none. Skips entries that fail validation and says so on stderr. |
|
|
82
|
+
|
|
83
|
+
The store is `$WISDOM_DIR`, else `~/.agent-wisdom`. `lookup` appends one line to `<store>/lookups.jsonl` (task from `--task` or `$WISDOM_TASK`, repo from `--repo` or `$WISDOM_REPO`); it fails open and `--no-log` turns it off. Nothing else is ever written. Exit codes: `0` success (including no match), `1` a validation error or unknown id, `2` a usage error.
|
|
84
|
+
|
|
85
|
+
## How this differs from agent-notebook
|
|
86
|
+
|
|
87
|
+
[agent-notebook](https://github.com/jeanibarz/agent-notebook) is the sibling project: a bounded memory of **one-line lessons ranked by votes**. It answers "what did we learn that I might forget?" and it surfaces lessons by listing them. `agent-wisdom` answers a different question, "what general judgment applies at this decision, and when does it not?". Its entries are **conditional** (claim, applies, fails, opposite with a cue), they are **not voted** (quality is argued through conditions, precedents and independent sources), and they are **looked up** at decision points. They are complementary: a notebook lesson is a good *source* for a wisdom entry.
|
|
88
|
+
|
|
89
|
+
## Using it from an agent harness
|
|
90
|
+
|
|
91
|
+
Put the contract in [AGENTS.md](AGENTS.md) in front of your agent, and optionally run the lookup from a hook at `git commit` and `gh pr create`. See [docs/harness-setup.md](docs/harness-setup.md) (Claude Code and Codex, with Kookr as one worked example).
|
|
92
|
+
|
|
93
|
+
## Documentation
|
|
94
|
+
|
|
95
|
+
- [Getting started](docs/getting-started.md) — the plain-language guide.
|
|
96
|
+
- [Entry format](docs/entry-format.md) — every field, with examples.
|
|
97
|
+
- [Harness setup](docs/harness-setup.md) — wiring `lookup` into Claude Code and Codex.
|
|
98
|
+
- [Rationale](docs/rationale.md) — why not a vector database, a knowledge graph, or agent-notebook's format.
|
|
99
|
+
- [Requirements](docs/requirements.md) — the specification, design principles and non-goals.
|
|
100
|
+
- [AGENTS.md](AGENTS.md) — the operating contract for agents; [CONTRIBUTING.md](CONTRIBUTING.md); [SECURITY.md](SECURITY.md); [CHANGELOG.md](CHANGELOG.md).
|
|
101
|
+
|
|
102
|
+
## License
|
|
103
|
+
|
|
104
|
+
MIT. See [LICENSE](LICENSE).
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
package/dist/wisdom.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
export declare const LAYERS: readonly ['core', 'values', 'techniques', 'precedents'];
|
|
2
|
+
export type Layer = (typeof LAYERS)[number];
|
|
3
|
+
export declare const TRIGGERS: string[];
|
|
4
|
+
export declare const SOURCE_KINDS: string[];
|
|
5
|
+
export declare const ROLES: string[];
|
|
6
|
+
export declare const MAX_LIMIT = 3;
|
|
7
|
+
export interface Entry {
|
|
8
|
+
layer: Layer;
|
|
9
|
+
file: string;
|
|
10
|
+
id: string;
|
|
11
|
+
fm: Record<string, any>;
|
|
12
|
+
body: string;
|
|
13
|
+
}
|
|
14
|
+
export interface Issue {
|
|
15
|
+
level: 'error' | 'warning';
|
|
16
|
+
file: string;
|
|
17
|
+
message: string;
|
|
18
|
+
}
|
|
19
|
+
export interface Store {
|
|
20
|
+
dir: string;
|
|
21
|
+
exists: boolean;
|
|
22
|
+
/** True when `dir` exists but is not a directory (for example `WISDOM_DIR` names a regular file). */
|
|
23
|
+
notDirectory: boolean;
|
|
24
|
+
/** Number of `.md` files read, including the ones that failed to parse. */
|
|
25
|
+
checked: number;
|
|
26
|
+
entries: Entry[];
|
|
27
|
+
precedents: Entry[];
|
|
28
|
+
issues: Issue[];
|
|
29
|
+
/** Files of core/values/techniques entries that have at least one error. Lookup does not serve them. */
|
|
30
|
+
invalid: string[];
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The store directory: `$WISDOM_DIR` (trimmed, a leading `~` expanded), else
|
|
34
|
+
* `~/.agent-wisdom`. `~` resolves against the HOME of the env passed in, so a
|
|
35
|
+
* caller (or a test) that injects an env never reads the real home directory.
|
|
36
|
+
*/
|
|
37
|
+
export declare function resolveStoreDir(env: NodeJS.ProcessEnv): string;
|
|
38
|
+
/** The words of a tag that can match a query: the same tokens a query is split into. */
|
|
39
|
+
export declare function tagTokens(tag: string): string[];
|
|
40
|
+
/**
|
|
41
|
+
* Effective source count. Sources are de-duplicated by (kind, ref, task) first;
|
|
42
|
+
* then all `wisdom-kb` sources together count as one source and add at most one task.
|
|
43
|
+
*/
|
|
44
|
+
export declare function effectiveSources(sources: any[]): {
|
|
45
|
+
count: number;
|
|
46
|
+
tasks: number;
|
|
47
|
+
};
|
|
48
|
+
export declare function loadStore(dir: string): Store;
|
|
49
|
+
export declare function tokenize(text: string): string[];
|
|
50
|
+
export interface Scored {
|
|
51
|
+
entry: Entry;
|
|
52
|
+
score: number;
|
|
53
|
+
}
|
|
54
|
+
export declare function lookupEntries(store: Store, query: string, point?: string): Scored[];
|
|
55
|
+
export interface Io {
|
|
56
|
+
out: (s: string) => void;
|
|
57
|
+
err: (s: string) => void;
|
|
58
|
+
}
|
|
59
|
+
export declare function runWisdomCli(argv: string[], opts?: {
|
|
60
|
+
env?: NodeJS.ProcessEnv;
|
|
61
|
+
io?: Io;
|
|
62
|
+
now?: () => Date;
|
|
63
|
+
}): number;
|
package/dist/wisdom.js
ADDED
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
// agent-wisdom: a read-only, deterministic store of conditional wisdom for AI
|
|
2
|
+
// agents. This module is the library: load a directory of Markdown entry files,
|
|
3
|
+
// validate them, list/show them, and look entries up for a situation. It makes
|
|
4
|
+
// no model call and no network call. The only write it ever does is one append
|
|
5
|
+
// to the lookup log, and that write fails open. See docs/requirements.md.
|
|
6
|
+
import { appendFileSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
7
|
+
import { homedir } from 'node:os';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { parseDocument } from 'yaml';
|
|
10
|
+
export const LAYERS = ['core', 'values', 'techniques', 'precedents'];
|
|
11
|
+
const LAYER_KIND = { core: 'core', values: 'value', techniques: 'technique' };
|
|
12
|
+
export const TRIGGERS = ['commit', 'pr-create', 'merge', 'reply', 'plan', 'triage', 'review', 'any'];
|
|
13
|
+
export const SOURCE_KINDS = ['lesson', 'notebook', 'correction', 'wisdom-kb', 'citation', 'operator', 'research'];
|
|
14
|
+
const STATUSES = ['candidate', 'active', 'retired'];
|
|
15
|
+
export const ROLES = ['critic', 'debate', 'hook', 'human'];
|
|
16
|
+
export const MAX_LIMIT = 3;
|
|
17
|
+
const MIN_TOKEN = 3;
|
|
18
|
+
const STOPWORDS = new Set([
|
|
19
|
+
'the', 'and', 'for', 'with', 'that', 'this', 'from', 'are', 'was', 'were', 'has', 'have', 'had',
|
|
20
|
+
'not', 'but', 'you', 'your', 'our', 'its', 'into', 'about', 'when', 'what', 'which', 'who', 'how',
|
|
21
|
+
'why', 'can', 'will', 'should', 'would', 'could', 'then', 'than', 'there', 'their', 'them', 'they',
|
|
22
|
+
]);
|
|
23
|
+
/**
|
|
24
|
+
* The store directory: `$WISDOM_DIR` (trimmed, a leading `~` expanded), else
|
|
25
|
+
* `~/.agent-wisdom`. `~` resolves against the HOME of the env passed in, so a
|
|
26
|
+
* caller (or a test) that injects an env never reads the real home directory.
|
|
27
|
+
*/
|
|
28
|
+
export function resolveStoreDir(env) {
|
|
29
|
+
const home = env.HOME || env.USERPROFILE || homedir();
|
|
30
|
+
const raw = env.WISDOM_DIR?.trim();
|
|
31
|
+
if (!raw)
|
|
32
|
+
return join(home, '.agent-wisdom');
|
|
33
|
+
if (raw === '~')
|
|
34
|
+
return home;
|
|
35
|
+
if (raw.startsWith('~/') || raw.startsWith('~\\'))
|
|
36
|
+
return join(home, raw.slice(2));
|
|
37
|
+
return raw;
|
|
38
|
+
}
|
|
39
|
+
function splitFrontmatter(text) {
|
|
40
|
+
const m = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n([\s\S]*))?$/.exec(text);
|
|
41
|
+
return m ? { yaml: m[1], body: (m[2] ?? '').trim() } : null;
|
|
42
|
+
}
|
|
43
|
+
const isStr = (v) => typeof v === 'string' && v.trim() !== '';
|
|
44
|
+
const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
45
|
+
/** `YYYY-MM-DD`, optionally followed by a time, that names a real calendar day. */
|
|
46
|
+
function isIsoDate(v) {
|
|
47
|
+
if (typeof v !== 'string' || !/^\d{4}-\d{2}-\d{2}(T[\w:.+-]+Z?)?$/.test(v))
|
|
48
|
+
return false;
|
|
49
|
+
const day = v.slice(0, 10);
|
|
50
|
+
return !Number.isNaN(Date.parse(v)) && new Date(day).toISOString().slice(0, 10) === day;
|
|
51
|
+
}
|
|
52
|
+
/** The words of a tag that can match a query: the same tokens a query is split into. */
|
|
53
|
+
export function tagTokens(tag) {
|
|
54
|
+
return tokenize(tag);
|
|
55
|
+
}
|
|
56
|
+
function validateSources(fm, err, required) {
|
|
57
|
+
if (fm.sources === undefined) {
|
|
58
|
+
if (required)
|
|
59
|
+
err('sources is required');
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
if (!Array.isArray(fm.sources)) {
|
|
63
|
+
err('sources must be a list');
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
fm.sources.forEach((s, i) => {
|
|
67
|
+
if (!isObj(s))
|
|
68
|
+
return err(`sources[${i}] must be an object`);
|
|
69
|
+
if (!SOURCE_KINDS.includes(s.kind))
|
|
70
|
+
err(`sources[${i}].kind must be one of ${SOURCE_KINDS.join('|')}`);
|
|
71
|
+
if (!isStr(s.ref))
|
|
72
|
+
err(`sources[${i}].ref is required`);
|
|
73
|
+
if (s.task !== undefined && !isStr(s.task))
|
|
74
|
+
err(`sources[${i}].task must be a string`);
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
/** Schema checks that need no other entry. Returns error messages. */
|
|
78
|
+
function schemaErrors(e) {
|
|
79
|
+
const out = [];
|
|
80
|
+
const err = (m) => out.push(m);
|
|
81
|
+
const fm = e.fm;
|
|
82
|
+
const idRe = e.layer === 'precedents' ? /^p-[a-z0-9][a-z0-9-]*$/ : /^w-[a-z0-9][a-z0-9-]*$/;
|
|
83
|
+
if (!isStr(fm.id))
|
|
84
|
+
err('id is required');
|
|
85
|
+
else {
|
|
86
|
+
if (!idRe.test(fm.id))
|
|
87
|
+
err(`id "${fm.id}" must match ${idRe.source}`);
|
|
88
|
+
if (fm.id !== e.id)
|
|
89
|
+
err(`id "${fm.id}" does not match filename stem "${e.id}"`);
|
|
90
|
+
}
|
|
91
|
+
if (!isIsoDate(fm.created))
|
|
92
|
+
err('created must be an ISO date');
|
|
93
|
+
if (e.layer === 'precedents') {
|
|
94
|
+
if (!isStr(fm.situation))
|
|
95
|
+
err('situation is required');
|
|
96
|
+
if (!['win', 'draw', 'open'].includes(fm.ruling))
|
|
97
|
+
err('ruling must be one of win|draw|open');
|
|
98
|
+
if (fm.ruling === 'win') {
|
|
99
|
+
if (!isStr(fm.winner))
|
|
100
|
+
err('winner is required when ruling is win');
|
|
101
|
+
if (!isStr(fm.loser))
|
|
102
|
+
err('loser is required when ruling is win');
|
|
103
|
+
}
|
|
104
|
+
if (!isStr(fm.cue))
|
|
105
|
+
err('cue is required');
|
|
106
|
+
validateSources(fm, err, true);
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
if (!isStr(fm.kind) || !['core', 'value', 'technique'].includes(fm.kind))
|
|
110
|
+
err('kind must be one of core|value|technique');
|
|
111
|
+
else if (fm.kind !== LAYER_KIND[e.layer])
|
|
112
|
+
err(`kind "${fm.kind}" does not match layer ${e.layer}/ (expected "${LAYER_KIND[e.layer]}")`);
|
|
113
|
+
if (!isStr(fm.claim))
|
|
114
|
+
err('claim is required');
|
|
115
|
+
else if (fm.claim.length > 300)
|
|
116
|
+
err(`claim is ${fm.claim.length} characters (max 300)`);
|
|
117
|
+
if (!isStr(fm.applies_when))
|
|
118
|
+
err('applies_when is required');
|
|
119
|
+
if (!isStr(fm.fails_when))
|
|
120
|
+
err('fails_when is required');
|
|
121
|
+
const needOpp = fm.kind !== 'core';
|
|
122
|
+
if (fm.opposite === undefined) {
|
|
123
|
+
if (needOpp)
|
|
124
|
+
err('opposite is required');
|
|
125
|
+
}
|
|
126
|
+
else if (!isObj(fm.opposite))
|
|
127
|
+
err('opposite must be an object');
|
|
128
|
+
else {
|
|
129
|
+
if (needOpp && !isStr(fm.opposite.text))
|
|
130
|
+
err('opposite.text is required');
|
|
131
|
+
if (needOpp && !isStr(fm.opposite.cue))
|
|
132
|
+
err('opposite.cue is required');
|
|
133
|
+
if (fm.opposite.entry !== undefined && !isStr(fm.opposite.entry))
|
|
134
|
+
err('opposite.entry must be a string id');
|
|
135
|
+
}
|
|
136
|
+
if (!Array.isArray(fm.triggers) || fm.triggers.length === 0)
|
|
137
|
+
err('triggers must be a non-empty list');
|
|
138
|
+
else
|
|
139
|
+
for (const t of fm.triggers)
|
|
140
|
+
if (!TRIGGERS.includes(t))
|
|
141
|
+
err(`trigger "${t}" must be one of ${TRIGGERS.join('|')}`);
|
|
142
|
+
if (!Array.isArray(fm.tags) || !fm.tags.every((t) => typeof t === 'string'))
|
|
143
|
+
err('tags must be a list of strings');
|
|
144
|
+
validateSources(fm, err, true);
|
|
145
|
+
if (!STATUSES.includes(fm.status))
|
|
146
|
+
err('status must be one of candidate|active|retired');
|
|
147
|
+
if (!isIsoDate(fm.updated))
|
|
148
|
+
err('updated must be an ISO date');
|
|
149
|
+
return out;
|
|
150
|
+
}
|
|
151
|
+
/** Warnings about an entry that is valid but probably not doing what its author hopes. */
|
|
152
|
+
function tagWarnings(fm) {
|
|
153
|
+
if (!Array.isArray(fm.tags))
|
|
154
|
+
return [];
|
|
155
|
+
return fm.tags
|
|
156
|
+
.filter((t) => typeof t === 'string' && tagTokens(t).length === 0)
|
|
157
|
+
.map((t) => `tag "${t}" can never match a query: it has no word of ${MIN_TOKEN}+ letters or digits (other than a stopword)`);
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Effective source count. Sources are de-duplicated by (kind, ref, task) first;
|
|
161
|
+
* then all `wisdom-kb` sources together count as one source and add at most one task.
|
|
162
|
+
*/
|
|
163
|
+
export function effectiveSources(sources) {
|
|
164
|
+
const seen = new Set();
|
|
165
|
+
const unique = sources.filter((s) => {
|
|
166
|
+
const key = JSON.stringify([s?.kind ?? null, s?.ref ?? null, s?.task ?? null]);
|
|
167
|
+
if (seen.has(key))
|
|
168
|
+
return false;
|
|
169
|
+
seen.add(key);
|
|
170
|
+
return true;
|
|
171
|
+
});
|
|
172
|
+
const real = unique.filter((s) => s?.kind !== 'wisdom-kb');
|
|
173
|
+
const kb = unique.filter((s) => s?.kind === 'wisdom-kb');
|
|
174
|
+
const tasks = new Set(real.map((s) => s?.task).filter(isStr));
|
|
175
|
+
const kbTask = kb.map((s) => s?.task).find(isStr);
|
|
176
|
+
if (kbTask)
|
|
177
|
+
tasks.add(kbTask);
|
|
178
|
+
return { count: real.length + (kb.length ? 1 : 0), tasks: tasks.size };
|
|
179
|
+
}
|
|
180
|
+
export function loadStore(dir) {
|
|
181
|
+
const store = { dir, exists: false, notDirectory: false, checked: 0, entries: [], precedents: [], issues: [], invalid: [] };
|
|
182
|
+
try {
|
|
183
|
+
const st = statSync(dir);
|
|
184
|
+
store.exists = st.isDirectory();
|
|
185
|
+
store.notDirectory = !st.isDirectory();
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
store.exists = false;
|
|
189
|
+
}
|
|
190
|
+
if (!store.exists)
|
|
191
|
+
return store;
|
|
192
|
+
const add = (level, file, message) => store.issues.push({ level, file, message });
|
|
193
|
+
const seen = new Map();
|
|
194
|
+
for (const layer of LAYERS) {
|
|
195
|
+
const ldir = join(dir, layer);
|
|
196
|
+
let names;
|
|
197
|
+
try {
|
|
198
|
+
if (!statSync(ldir).isDirectory()) {
|
|
199
|
+
add('error', `${layer}/`, `${layer} exists but is not a directory`);
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
names = readdirSync(ldir).filter((n) => n.endsWith('.md')).sort();
|
|
203
|
+
}
|
|
204
|
+
catch (e) {
|
|
205
|
+
if (e.code !== 'ENOENT')
|
|
206
|
+
add('error', `${layer}/`, `unreadable: ${e.message}`);
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
for (const name of names) {
|
|
210
|
+
const file = `${layer}/${name}`;
|
|
211
|
+
store.checked++;
|
|
212
|
+
let text;
|
|
213
|
+
try {
|
|
214
|
+
text = readFileSync(join(ldir, name), 'utf-8');
|
|
215
|
+
}
|
|
216
|
+
catch (e) {
|
|
217
|
+
add('error', file, `unreadable: ${e.message}`);
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
const parts = splitFrontmatter(text.replace(/^\uFEFF/, ''));
|
|
221
|
+
if (!parts) {
|
|
222
|
+
add('error', file, 'missing YAML frontmatter (--- block)');
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
// logLevel 'error' keeps the yaml library from printing warnings; they are reported as issues instead.
|
|
226
|
+
const doc = parseDocument(parts.yaml, { logLevel: 'error' });
|
|
227
|
+
if (doc.errors.length) {
|
|
228
|
+
add('error', file, `unparseable YAML: ${doc.errors[0].message.split('\n')[0]}`);
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
for (const w of doc.warnings)
|
|
232
|
+
add('warning', file, `YAML warning: ${w.message.split('\n')[0]}`);
|
|
233
|
+
const fm = doc.toJS();
|
|
234
|
+
if (!isObj(fm)) {
|
|
235
|
+
add('error', file, 'frontmatter must be a YAML mapping');
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
const entry = { layer, file, id: name.slice(0, -3), fm, body: parts.body };
|
|
239
|
+
for (const m of schemaErrors(entry))
|
|
240
|
+
add('error', file, m);
|
|
241
|
+
if (layer !== 'precedents')
|
|
242
|
+
for (const m of tagWarnings(fm))
|
|
243
|
+
add('warning', file, m);
|
|
244
|
+
const key = isStr(fm.id) ? fm.id : entry.id;
|
|
245
|
+
const prev = seen.get(key);
|
|
246
|
+
if (prev)
|
|
247
|
+
add('error', file, `duplicate id "${key}" (also in ${prev})`);
|
|
248
|
+
else
|
|
249
|
+
seen.set(key, file);
|
|
250
|
+
(layer === 'precedents' ? store.precedents : store.entries).push(entry);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
const ids = new Set(store.entries.map((e) => e.fm.id));
|
|
254
|
+
for (const e of store.entries) {
|
|
255
|
+
const ref = e.fm.opposite?.entry;
|
|
256
|
+
if (isStr(ref) && !ids.has(ref))
|
|
257
|
+
add('error', e.file, `opposite.entry "${ref}" does not exist`);
|
|
258
|
+
if (e.fm.status === 'active' && (e.fm.kind === 'technique' || e.fm.kind === 'value') && Array.isArray(e.fm.sources)) {
|
|
259
|
+
const eff = effectiveSources(e.fm.sources);
|
|
260
|
+
if (eff.count < 3)
|
|
261
|
+
add('warning', e.file, `active ${e.fm.kind} has ${eff.count} source(s) (need 3; wisdom-kb counts as one in total)`);
|
|
262
|
+
if (eff.tasks < 2)
|
|
263
|
+
add('warning', e.file, `active ${e.fm.kind} has sources from ${eff.tasks} distinct task(s) (need 2)`);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
for (const p of store.precedents) {
|
|
267
|
+
for (const k of ['winner', 'loser']) {
|
|
268
|
+
if (isStr(p.fm[k]) && !ids.has(p.fm[k]))
|
|
269
|
+
add('error', p.file, `${k} "${p.fm[k]}" does not exist`);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
const bad = new Set(store.issues.filter((i) => i.level === 'error' && !i.file.startsWith('precedents/') && i.file.endsWith('.md')).map((i) => i.file));
|
|
273
|
+
store.invalid = [...bad];
|
|
274
|
+
return store;
|
|
275
|
+
}
|
|
276
|
+
export function tokenize(text) {
|
|
277
|
+
const out = new Set();
|
|
278
|
+
for (const t of text.toLowerCase().split(/[^a-z0-9]+/))
|
|
279
|
+
if (t.length >= MIN_TOKEN && !STOPWORDS.has(t))
|
|
280
|
+
out.add(t);
|
|
281
|
+
return [...out];
|
|
282
|
+
}
|
|
283
|
+
/** A tag matches when it has at least one word and every one of its words is a query token. */
|
|
284
|
+
function tagMatches(tag, queryTokens) {
|
|
285
|
+
const parts = tagTokens(tag);
|
|
286
|
+
return parts.length > 0 && parts.every((p) => queryTokens.has(p));
|
|
287
|
+
}
|
|
288
|
+
export function lookupEntries(store, query, point) {
|
|
289
|
+
const qt = tokenize(query);
|
|
290
|
+
const qset = new Set(qt);
|
|
291
|
+
const invalid = new Set(store.invalid);
|
|
292
|
+
const out = [];
|
|
293
|
+
for (const e of store.entries) {
|
|
294
|
+
const fm = e.fm;
|
|
295
|
+
if (invalid.has(e.file))
|
|
296
|
+
continue;
|
|
297
|
+
if (!(fm.status === 'active' || e.layer === 'core'))
|
|
298
|
+
continue;
|
|
299
|
+
if (point && !(Array.isArray(fm.triggers) && (fm.triggers.includes(point) || fm.triggers.includes('any'))))
|
|
300
|
+
continue;
|
|
301
|
+
const text = new Set(tokenize(`${fm.claim ?? ''} ${fm.applies_when ?? ''}`));
|
|
302
|
+
const tags = new Set((Array.isArray(fm.tags) ? fm.tags : []).filter((t) => typeof t === 'string').map((t) => t.toLowerCase().trim()));
|
|
303
|
+
let score = 0;
|
|
304
|
+
for (const t of qt)
|
|
305
|
+
if (text.has(t))
|
|
306
|
+
score += 1;
|
|
307
|
+
for (const tag of tags)
|
|
308
|
+
if (tagMatches(tag, qset))
|
|
309
|
+
score += 2;
|
|
310
|
+
if (score >= 1)
|
|
311
|
+
out.push({ entry: e, score });
|
|
312
|
+
}
|
|
313
|
+
return out.sort((a, b) => b.score - a.score || (a.entry.id < b.entry.id ? -1 : a.entry.id > b.entry.id ? 1 : 0));
|
|
314
|
+
}
|
|
315
|
+
const HELP = `wisdom - read-only CLI over a store of conditional wisdom entries
|
|
316
|
+
|
|
317
|
+
Store: $WISDOM_DIR (trimmed, a leading ~ expanded), else ~/.agent-wisdom.
|
|
318
|
+
Layout: <layer>/<id>.md with layers core/, values/, techniques/, precedents/.
|
|
319
|
+
|
|
320
|
+
Usage:
|
|
321
|
+
wisdom validate [--strict] [--json]
|
|
322
|
+
Check every entry. Exit 1 on errors. --strict turns warnings into errors.
|
|
323
|
+
A missing store directory is a note, exit 0.
|
|
324
|
+
wisdom list [--layer core|values|techniques|precedents] [--status S] [--json]
|
|
325
|
+
One line per entry; the claim is cut to 100 characters.
|
|
326
|
+
wisdom show <id> [--json]
|
|
327
|
+
Print one entry or precedent. Exit 1 if the id is unknown.
|
|
328
|
+
wisdom lookup "<situation>" [--point <trigger>] [--limit N] [--role critic|debate|hook|human]
|
|
329
|
+
[--task <id>] [--repo <name>] [--json] [--no-log]
|
|
330
|
+
Deterministic keyword match over active entries plus all core entries.
|
|
331
|
+
Entries that fail validation are skipped (see wisdom validate).
|
|
332
|
+
Returns at most 3 entries (--limit is clamped to 3), or none.
|
|
333
|
+
--point: commit|pr-create|merge|reply|plan|triage|review|any
|
|
334
|
+
Appends one JSON line to <store>/lookups.jsonl unless --no-log.
|
|
335
|
+
wisdom --help
|
|
336
|
+
|
|
337
|
+
Env: WISDOM_DIR, WISDOM_TASK, WISDOM_REPO (the last two label the lookup log; --task and --repo override them).
|
|
338
|
+
`;
|
|
339
|
+
const VALUE_FLAGS = new Set(['layer', 'status', 'point', 'limit', 'role', 'task', 'repo']);
|
|
340
|
+
const BOOL_FLAGS = new Set(['strict', 'json', 'no-log', 'help']);
|
|
341
|
+
function parseArgs(argv) {
|
|
342
|
+
const pos = [];
|
|
343
|
+
const flags = {};
|
|
344
|
+
for (let i = 0; i < argv.length; i++) {
|
|
345
|
+
const a = argv[i];
|
|
346
|
+
if (!a.startsWith('--')) {
|
|
347
|
+
pos.push(a);
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
const [name, inline] = a.slice(2).split(/=(.*)/s, 2);
|
|
351
|
+
if (BOOL_FLAGS.has(name))
|
|
352
|
+
flags[name] = true;
|
|
353
|
+
else if (VALUE_FLAGS.has(name)) {
|
|
354
|
+
const v = inline !== undefined ? inline : argv[++i];
|
|
355
|
+
if (v === undefined)
|
|
356
|
+
return `--${name} needs a value`;
|
|
357
|
+
flags[name] = v;
|
|
358
|
+
}
|
|
359
|
+
else
|
|
360
|
+
return `unknown option --${name}`;
|
|
361
|
+
}
|
|
362
|
+
return { pos, flags };
|
|
363
|
+
}
|
|
364
|
+
function oneLine(s) { return String(s ?? '').replace(/\s+/g, ' ').trim(); }
|
|
365
|
+
function summary(e) {
|
|
366
|
+
const fm = e.fm;
|
|
367
|
+
return { id: fm.id ?? e.id, layer: e.layer, kind: fm.kind ?? null, status: fm.status ?? null, claim: fm.claim ?? fm.situation ?? null };
|
|
368
|
+
}
|
|
369
|
+
function renderEntry(e, score) {
|
|
370
|
+
const fm = e.fm;
|
|
371
|
+
if (e.layer === 'precedents') {
|
|
372
|
+
const lines = [`${fm.id} [precedent, ${fm.ruling}]${fm.winner ? ` ${fm.winner} beats ${fm.loser}` : ''}`, ` situation: ${oneLine(fm.situation)}`, ` cue: ${oneLine(fm.cue)}`];
|
|
373
|
+
return lines.join('\n');
|
|
374
|
+
}
|
|
375
|
+
const lines = [`${fm.id} [${fm.kind}${score !== undefined ? `, score ${score}` : ''}] ${oneLine(fm.claim)}`,
|
|
376
|
+
` applies: ${oneLine(fm.applies_when)}`, ` fails: ${oneLine(fm.fails_when)}`];
|
|
377
|
+
if (fm.opposite?.text)
|
|
378
|
+
lines.push(` opposite: ${oneLine(fm.opposite.text)}${fm.opposite.entry ? ` (${fm.opposite.entry})` : ''}`);
|
|
379
|
+
if (fm.opposite?.cue)
|
|
380
|
+
lines.push(` cue: ${oneLine(fm.opposite.cue)}`);
|
|
381
|
+
return lines.join('\n');
|
|
382
|
+
}
|
|
383
|
+
const nonEmpty = (v) => (typeof v === 'string' && v.trim() !== '' ? v.trim() : null);
|
|
384
|
+
export function runWisdomCli(argv, opts = {}) {
|
|
385
|
+
const env = opts.env ?? process.env;
|
|
386
|
+
const io = opts.io ?? { out: (s) => process.stdout.write(s + '\n'), err: (s) => process.stderr.write(s + '\n') };
|
|
387
|
+
const [cmd, ...rest] = argv;
|
|
388
|
+
if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') {
|
|
389
|
+
io.out(HELP.trimEnd());
|
|
390
|
+
return cmd ? 0 : 2;
|
|
391
|
+
}
|
|
392
|
+
const parsed = parseArgs(rest);
|
|
393
|
+
if (typeof parsed === 'string') {
|
|
394
|
+
io.err(`wisdom: ${parsed}`);
|
|
395
|
+
return 2;
|
|
396
|
+
}
|
|
397
|
+
const { pos, flags } = parsed;
|
|
398
|
+
if (flags.help) {
|
|
399
|
+
io.out(HELP.trimEnd());
|
|
400
|
+
return 0;
|
|
401
|
+
}
|
|
402
|
+
const json = flags.json === true;
|
|
403
|
+
const dir = resolveStoreDir(env);
|
|
404
|
+
const store = loadStore(dir);
|
|
405
|
+
const noStore = store.notDirectory
|
|
406
|
+
? `wisdom: note: WISDOM_DIR ${dir} is not a directory (nothing to read)`
|
|
407
|
+
: `wisdom: note: store directory ${dir} does not exist (nothing to read)`;
|
|
408
|
+
const printJson = (v) => io.out(JSON.stringify(v, null, 2));
|
|
409
|
+
switch (cmd) {
|
|
410
|
+
case 'validate': {
|
|
411
|
+
if (store.notDirectory) {
|
|
412
|
+
const message = `WISDOM_DIR ${dir} is not a directory`;
|
|
413
|
+
if (json)
|
|
414
|
+
printJson({ ok: false, store: dir, exists: false, checked: 0, errors: [{ file: '.', message }], warnings: [] });
|
|
415
|
+
else
|
|
416
|
+
io.out(`error: ${message}`);
|
|
417
|
+
return 1;
|
|
418
|
+
}
|
|
419
|
+
if (!store.exists) {
|
|
420
|
+
if (json)
|
|
421
|
+
printJson({ ok: true, store: dir, exists: false, checked: 0, errors: [], warnings: [] });
|
|
422
|
+
else
|
|
423
|
+
io.err(noStore);
|
|
424
|
+
return 0;
|
|
425
|
+
}
|
|
426
|
+
const strict = flags.strict === true;
|
|
427
|
+
const errors = store.issues.filter((i) => i.level === 'error' || strict);
|
|
428
|
+
const warnings = store.issues.filter((i) => i.level === 'warning' && !strict);
|
|
429
|
+
const fmt = (i) => ({ file: i.file, message: i.message });
|
|
430
|
+
const n = store.checked;
|
|
431
|
+
if (json)
|
|
432
|
+
printJson({ ok: errors.length === 0, store: dir, exists: true, checked: n, errors: errors.map(fmt), warnings: warnings.map(fmt) });
|
|
433
|
+
else {
|
|
434
|
+
for (const i of errors)
|
|
435
|
+
io.out(`error: ${i.file}: ${i.message}`);
|
|
436
|
+
for (const i of warnings)
|
|
437
|
+
io.out(`warning: ${i.file}: ${i.message}`);
|
|
438
|
+
io.out(`${n} file(s) checked: ${errors.length} error(s), ${warnings.length} warning(s)`);
|
|
439
|
+
}
|
|
440
|
+
return errors.length ? 1 : 0;
|
|
441
|
+
}
|
|
442
|
+
case 'list': {
|
|
443
|
+
const layer = flags.layer;
|
|
444
|
+
if (layer !== undefined && !LAYERS.includes(layer)) {
|
|
445
|
+
io.err(`wisdom: --layer must be one of ${LAYERS.join('|')}`);
|
|
446
|
+
return 2;
|
|
447
|
+
}
|
|
448
|
+
if (!store.exists) {
|
|
449
|
+
io.err(noStore);
|
|
450
|
+
if (json)
|
|
451
|
+
printJson([]);
|
|
452
|
+
return 0;
|
|
453
|
+
}
|
|
454
|
+
let all = [...store.entries, ...store.precedents];
|
|
455
|
+
if (layer)
|
|
456
|
+
all = all.filter((e) => e.layer === layer);
|
|
457
|
+
if (typeof flags.status === 'string')
|
|
458
|
+
all = all.filter((e) => e.fm.status === flags.status);
|
|
459
|
+
if (json)
|
|
460
|
+
printJson(all.map(summary));
|
|
461
|
+
else if (!all.length)
|
|
462
|
+
io.out('no entries');
|
|
463
|
+
else
|
|
464
|
+
for (const e of all) {
|
|
465
|
+
const s = summary(e);
|
|
466
|
+
io.out(`${s.id}\t${e.layer}\t${s.kind ?? '-'}\t${s.status ?? '-'}\t${oneLine(s.claim).slice(0, 100)}`);
|
|
467
|
+
}
|
|
468
|
+
return 0;
|
|
469
|
+
}
|
|
470
|
+
case 'show': {
|
|
471
|
+
const id = pos[0];
|
|
472
|
+
if (!id) {
|
|
473
|
+
io.err('wisdom: show needs an <id>');
|
|
474
|
+
return 2;
|
|
475
|
+
}
|
|
476
|
+
const e = [...store.entries, ...store.precedents].find((x) => x.fm.id === id);
|
|
477
|
+
if (!e) {
|
|
478
|
+
io.err(`wisdom: no entry with id "${id}"`);
|
|
479
|
+
return 1;
|
|
480
|
+
}
|
|
481
|
+
if (json)
|
|
482
|
+
printJson({ ...e.fm, layer: e.layer, body: e.body });
|
|
483
|
+
else {
|
|
484
|
+
io.out(renderEntry(e));
|
|
485
|
+
if (e.layer !== 'precedents')
|
|
486
|
+
io.out(` triggers: ${(e.fm.triggers ?? []).join(', ')}\n tags: ${(e.fm.tags ?? []).join(', ')}\n status: ${e.fm.status}`);
|
|
487
|
+
if (e.body)
|
|
488
|
+
io.out(`\n${e.body}`);
|
|
489
|
+
}
|
|
490
|
+
return 0;
|
|
491
|
+
}
|
|
492
|
+
case 'lookup': {
|
|
493
|
+
const query = pos.join(' ').trim();
|
|
494
|
+
if (!query) {
|
|
495
|
+
io.err('wisdom: lookup needs a "<situation>" string');
|
|
496
|
+
return 2;
|
|
497
|
+
}
|
|
498
|
+
const point = typeof flags.point === 'string' ? flags.point : undefined;
|
|
499
|
+
if (point && !TRIGGERS.includes(point)) {
|
|
500
|
+
io.err(`wisdom: --point must be one of ${TRIGGERS.join('|')}`);
|
|
501
|
+
return 2;
|
|
502
|
+
}
|
|
503
|
+
const role = typeof flags.role === 'string' ? flags.role : undefined;
|
|
504
|
+
if (role && !ROLES.includes(role)) {
|
|
505
|
+
io.err(`wisdom: --role must be one of ${ROLES.join('|')}`);
|
|
506
|
+
return 2;
|
|
507
|
+
}
|
|
508
|
+
let limit = MAX_LIMIT;
|
|
509
|
+
if (flags.limit !== undefined) {
|
|
510
|
+
limit = Number(flags.limit);
|
|
511
|
+
if (!Number.isInteger(limit) || limit < 1) {
|
|
512
|
+
io.err('wisdom: --limit must be a positive integer');
|
|
513
|
+
return 2;
|
|
514
|
+
}
|
|
515
|
+
limit = Math.min(limit, MAX_LIMIT);
|
|
516
|
+
}
|
|
517
|
+
if (store.invalid.length) {
|
|
518
|
+
io.err(`wisdom: note: ${store.invalid.length} entr${store.invalid.length === 1 ? 'y' : 'ies'} failed validation and ${store.invalid.length === 1 ? 'was' : 'were'} skipped; run \`wisdom validate\``);
|
|
519
|
+
}
|
|
520
|
+
if (store.notDirectory)
|
|
521
|
+
io.err(noStore);
|
|
522
|
+
const hits = lookupEntries(store, query, point).slice(0, limit);
|
|
523
|
+
if (flags['no-log'] !== true && store.exists) {
|
|
524
|
+
try {
|
|
525
|
+
const line = {
|
|
526
|
+
ts: (opts.now ?? (() => new Date()))().toISOString(),
|
|
527
|
+
task: nonEmpty(flags.task) ?? nonEmpty(env.WISDOM_TASK), repo: nonEmpty(flags.repo) ?? nonEmpty(env.WISDOM_REPO),
|
|
528
|
+
role: role ?? null, point: point ?? null, query: query.slice(0, 400),
|
|
529
|
+
returned: hits.map((h) => ({ id: h.entry.fm.id, score: h.score })),
|
|
530
|
+
};
|
|
531
|
+
appendFileSync(join(dir, 'lookups.jsonl'), JSON.stringify(line) + '\n');
|
|
532
|
+
}
|
|
533
|
+
catch { /* fail open: logging never fails the lookup */ }
|
|
534
|
+
}
|
|
535
|
+
if (json)
|
|
536
|
+
printJson(hits.map((h) => ({ ...summary(h.entry), score: h.score, applies_when: h.entry.fm.applies_when, fails_when: h.entry.fm.fails_when, opposite: h.entry.fm.opposite ?? null })));
|
|
537
|
+
else if (!hits.length)
|
|
538
|
+
io.out('no matching entry');
|
|
539
|
+
else
|
|
540
|
+
io.out(hits.map((h) => renderEntry(h.entry, h.score)).join('\n\n'));
|
|
541
|
+
return 0;
|
|
542
|
+
}
|
|
543
|
+
default:
|
|
544
|
+
io.err(`wisdom: unknown command "${cmd}" (try wisdom --help)`);
|
|
545
|
+
return 2;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Examples
|
|
2
|
+
|
|
3
|
+
## `store/` — a synthetic example store
|
|
4
|
+
|
|
5
|
+
A small wisdom store you can point `wisdom` at:
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
export WISDOM_DIR=examples/store
|
|
9
|
+
wisdom validate --strict # 8 files, 0 errors, 0 warnings
|
|
10
|
+
wisdom list
|
|
11
|
+
wisdom lookup "about to commit a change to one module" --point commit --no-log
|
|
12
|
+
wisdom show w-narrow-test-first
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
It holds seven entries (one core, one value, five techniques) and one precedent. Every entry is **synthetic**: generic software-engineering advice with neutral example values (`example-task-1`, `example-lesson-3`) in the `sources` lists. None of it comes from a real store, and it is not meant to be good advice for your team. Its job is to show the format and to give the quickstart something to answer.
|
|
16
|
+
|
|
17
|
+
The two entries `w-narrow-test-first` and `w-full-suite-first` are each other's opposite (`opposite.entry`), and `precedents/p-narrow-vs-full-before-commit.md` records which one wins and the cue that decides.
|
|
18
|
+
|
|
19
|
+
Use `--no-log` when you look up against this store, so no `lookups.jsonl` is written into the repository. To start your own store, copy the layout (not the content) to `~/.agent-wisdom` and write entries with the `agent-wisdom-write-entry` skill or by hand ([docs/entry-format.md](../docs/entry-format.md)).
|
|
20
|
+
|
|
21
|
+
A test (`src/cli.test.ts`) keeps this store passing `wisdom validate --strict`.
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Claude Code PreToolUse hook: when the agent is about to run `git commit`,
|
|
3
|
+
// `gh pr create` or `gh pr merge`, look up wisdom for that decision point and add
|
|
4
|
+
// the result to the agent's context. It NEVER blocks: it always exits 0, prints
|
|
5
|
+
// nothing when there is no match, and swallows every error.
|
|
6
|
+
//
|
|
7
|
+
// PRIVACY RULE: no text taken from the Bash command ever reaches `wisdom` or the
|
|
8
|
+
// lookup log. A shell command can carry secrets and cannot be parsed safely
|
|
9
|
+
// enough to pick a "safe" part of it, so the command is scanned only to decide
|
|
10
|
+
// WHETHER and WHICH decision point this is. The lookup query is built from:
|
|
11
|
+
// 1. the decision point's fixed words ("commit", "open pull request",
|
|
12
|
+
// "merge pull request"), and
|
|
13
|
+
// 2. facts read from git state in the hook's working directory, with git run
|
|
14
|
+
// without a shell: for a commit, the staged file paths (at most 20); for
|
|
15
|
+
// a pull request, the current branch name. Both are split into words.
|
|
16
|
+
// The query is at most 200 characters. If git is unavailable, slow (2 s) or this
|
|
17
|
+
// is not a repository, the query is just the fixed words.
|
|
18
|
+
//
|
|
19
|
+
// Settings (see docs/harness-setup.md):
|
|
20
|
+
// { "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [
|
|
21
|
+
// { "type": "command", "command": "node /ABSOLUTE/PATH/wisdom-pretooluse.mjs" } ] } ] } }
|
|
22
|
+
//
|
|
23
|
+
// Env: WISDOM_BIN (default `wisdom`), WISDOM_DIR, WISDOM_TASK, WISDOM_REPO as for the CLI.
|
|
24
|
+
// WISDOM_HOOK_OFF=1 turns the hook off.
|
|
25
|
+
import { spawnSync } from 'node:child_process';
|
|
26
|
+
import { realpathSync } from 'node:fs';
|
|
27
|
+
import { fileURLToPath } from 'node:url';
|
|
28
|
+
|
|
29
|
+
const MAX_QUERY = 200;
|
|
30
|
+
const MAX_PATHS = 20;
|
|
31
|
+
const PREFIX = { commit: 'commit', 'pr-create': 'open pull request', merge: 'merge pull request' };
|
|
32
|
+
const SEP = '\0';
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Split a shell command into words for DETECTION only. Every unquoted newline,
|
|
36
|
+
* `;`, `|`, `&`, `(`, `)` and backtick separates commands (over-splitting only
|
|
37
|
+
* makes detection stricter). A backslash outside quotes makes the next
|
|
38
|
+
* character literal, `$'...'` is an escaped quote, a `#` that starts a word
|
|
39
|
+
* begins a comment, and heredoc bodies are skipped. Returns null when unsure
|
|
40
|
+
* (an unterminated quote), and the caller then does nothing.
|
|
41
|
+
*/
|
|
42
|
+
function tokenize(command) {
|
|
43
|
+
const tokens = [];
|
|
44
|
+
const heredocs = []; // pending { delim, strip } to consume after the current line
|
|
45
|
+
let cur = null;
|
|
46
|
+
let quote = '';
|
|
47
|
+
const push = () => { if (cur !== null) tokens.push(cur); cur = null; };
|
|
48
|
+
const n = command.length;
|
|
49
|
+
for (let i = 0; i < n; i++) {
|
|
50
|
+
const c = command[i];
|
|
51
|
+
if (quote) {
|
|
52
|
+
if (c === (quote === "$'" ? "'" : quote)) quote = '';
|
|
53
|
+
else if (c === '\\' && (quote === '"' || quote === "$'") && i + 1 < n) cur += command[++i];
|
|
54
|
+
else cur += c;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (c === '\\') { if (i + 1 < n) { cur = (cur ?? '') + command[++i]; } continue; }
|
|
58
|
+
if (c === '"') { quote = '"'; cur ??= ''; continue; }
|
|
59
|
+
if (c === "'") { quote = "'"; cur ??= ''; continue; }
|
|
60
|
+
if (c === '$' && command[i + 1] === "'") { quote = "$'"; cur ??= ''; i++; continue; }
|
|
61
|
+
if (c === '#' && cur === null) { while (i + 1 < n && command[i + 1] !== '\n') i++; continue; }
|
|
62
|
+
if (c === '<' && command[i + 1] === '<' && command[i + 2] !== '<') {
|
|
63
|
+
let j = i + 2;
|
|
64
|
+
const strip = command[j] === '-';
|
|
65
|
+
if (strip) j++;
|
|
66
|
+
while (command[j] === ' ' || command[j] === '\t') j++;
|
|
67
|
+
let delim = '';
|
|
68
|
+
let q = '';
|
|
69
|
+
for (; j < n; j++) {
|
|
70
|
+
const d = command[j];
|
|
71
|
+
if (q) { if (d === q) q = ''; else delim += d; }
|
|
72
|
+
else if (d === '"' || d === "'") q = d;
|
|
73
|
+
else if (d === '\\') { if (j + 1 < n) delim += command[++j]; }
|
|
74
|
+
else if (/[\s;|&()<>`]/.test(d)) break;
|
|
75
|
+
else delim += d;
|
|
76
|
+
}
|
|
77
|
+
if (delim) heredocs.push({ delim, strip });
|
|
78
|
+
push();
|
|
79
|
+
tokens.push(SEP);
|
|
80
|
+
i = j - 1;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (c === '\n') {
|
|
84
|
+
push();
|
|
85
|
+
tokens.push(SEP);
|
|
86
|
+
// Skip the body of every heredoc opened on the line that just ended.
|
|
87
|
+
let pos = i + 1;
|
|
88
|
+
for (const h of heredocs.splice(0)) {
|
|
89
|
+
while (pos < n) {
|
|
90
|
+
let end = command.indexOf('\n', pos);
|
|
91
|
+
if (end < 0) end = n;
|
|
92
|
+
const line = command.slice(pos, end);
|
|
93
|
+
pos = end + 1;
|
|
94
|
+
if ((h.strip ? line.replace(/^\t+/, '') : line) === h.delim) break;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
i = pos - 1;
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (/\s/.test(c)) { push(); continue; }
|
|
101
|
+
if (c === ';' || c === '|' || c === '&' || c === '(' || c === ')' || c === '`') { push(); tokens.push(SEP); continue; }
|
|
102
|
+
cur = (cur ?? '') + c;
|
|
103
|
+
}
|
|
104
|
+
if (quote) return null;
|
|
105
|
+
push();
|
|
106
|
+
return tokens;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const GIT_VALUE_OPTS = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace']);
|
|
110
|
+
|
|
111
|
+
/** The decision point of one command segment, or null. */
|
|
112
|
+
function decisionOf(seg) {
|
|
113
|
+
let i = 0;
|
|
114
|
+
while (i < seg.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(seg[i])) i++; // leading VAR=value
|
|
115
|
+
if (seg[i] === 'git') {
|
|
116
|
+
i++;
|
|
117
|
+
while (i < seg.length && seg[i].startsWith('-')) i += GIT_VALUE_OPTS.has(seg[i]) ? 2 : 1;
|
|
118
|
+
if (seg[i] === 'commit') return 'commit';
|
|
119
|
+
} else if (seg[i] === 'gh' && seg[i + 1] === 'pr') {
|
|
120
|
+
if (seg[i + 2] === 'create') return 'pr-create';
|
|
121
|
+
if (seg[i + 2] === 'merge') return 'merge';
|
|
122
|
+
}
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The decision point a shell command is at (`commit`, `pr-create`, `merge`), or
|
|
128
|
+
* null. Used only to decide whether and which; nothing from the command is
|
|
129
|
+
* ever used afterwards. `echo git commit` and `git merge` are not decision points.
|
|
130
|
+
*/
|
|
131
|
+
export function pointFor(command) {
|
|
132
|
+
const tokens = tokenize(command);
|
|
133
|
+
if (!tokens) return null;
|
|
134
|
+
const seg = [];
|
|
135
|
+
for (const t of [...tokens, SEP]) {
|
|
136
|
+
if (t !== SEP) { seg.push(t); continue; }
|
|
137
|
+
const point = decisionOf(seg);
|
|
138
|
+
seg.length = 0;
|
|
139
|
+
if (point) return point;
|
|
140
|
+
}
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Run git without a shell; returns raw stdout (callers trim or split it), or '' on any failure. */
|
|
145
|
+
function git(args, cwd, env) {
|
|
146
|
+
try {
|
|
147
|
+
// maxBuffer: a large staged set must not kill git and drop every path word.
|
|
148
|
+
const r = spawnSync('git', args, { cwd, env, encoding: 'utf8', timeout: 2000, maxBuffer: 16 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
149
|
+
return r.status === 0 ? (r.stdout ?? '') : '';
|
|
150
|
+
} catch {
|
|
151
|
+
return '';
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Words of a path or branch name: split on `/`, `.`, `-`, `_`, whitespace and quote characters. */
|
|
156
|
+
function wordsOf(text) {
|
|
157
|
+
return text.split(/[\/._\-\s"'`]+/).filter(Boolean);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* The lookup query for a decision point: its fixed words plus words from git
|
|
162
|
+
* state in `cwd` (staged paths for a commit, the branch for a pull request),
|
|
163
|
+
* at most 200 characters. It never contains any text from the command.
|
|
164
|
+
*/
|
|
165
|
+
export function queryFor(point, cwd = process.cwd(), env = process.env) {
|
|
166
|
+
const words = [];
|
|
167
|
+
if (point === 'commit') {
|
|
168
|
+
// -z: NUL-separated, unquoted names, so unusual characters arrive as themselves.
|
|
169
|
+
const paths = git(['diff', '--cached', '--name-only', '-z'], cwd, env).split('\0').filter(Boolean).slice(0, MAX_PATHS);
|
|
170
|
+
for (const p of paths) words.push(...wordsOf(p));
|
|
171
|
+
} else {
|
|
172
|
+
const branch = git(['rev-parse', '--abbrev-ref', 'HEAD'], cwd, env).trim();
|
|
173
|
+
if (branch && branch !== 'HEAD') words.push(...wordsOf(branch));
|
|
174
|
+
}
|
|
175
|
+
const unique = [...new Set(words)];
|
|
176
|
+
return `${PREFIX[point]} ${unique.join(' ')}`.trim().slice(0, MAX_QUERY);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** The hook's stdout for one PreToolUse payload (an object), or '' to add nothing. */
|
|
180
|
+
export function contextFor(payload, env = process.env) {
|
|
181
|
+
if (env.WISDOM_HOOK_OFF === '1') return '';
|
|
182
|
+
const command = payload?.tool_input?.command;
|
|
183
|
+
if (payload?.tool_name !== 'Bash' || typeof command !== 'string') return '';
|
|
184
|
+
const point = pointFor(command);
|
|
185
|
+
if (!point) return '';
|
|
186
|
+
const cwd = typeof payload.cwd === 'string' && payload.cwd ? payload.cwd : process.cwd();
|
|
187
|
+
const r = spawnSync(env.WISDOM_BIN || 'wisdom', ['lookup', queryFor(point, cwd, env), '--point', point, '--role', 'hook'], {
|
|
188
|
+
env, encoding: 'utf8', timeout: 5000,
|
|
189
|
+
});
|
|
190
|
+
const text = (r.stdout ?? '').trim();
|
|
191
|
+
if (r.status !== 0 || !text || text === 'no matching entry') return '';
|
|
192
|
+
return JSON.stringify({
|
|
193
|
+
hookSpecificOutput: {
|
|
194
|
+
hookEventName: 'PreToolUse',
|
|
195
|
+
additionalContext:
|
|
196
|
+
`Wisdom for this ${point} (check applies/fails, use the cue to choose between an entry and its opposite; name the id you applied):\n${text}`,
|
|
197
|
+
},
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function main() {
|
|
202
|
+
try {
|
|
203
|
+
let raw = '';
|
|
204
|
+
for await (const chunk of process.stdin) raw += chunk;
|
|
205
|
+
const out = contextFor(JSON.parse(raw));
|
|
206
|
+
if (out) process.stdout.write(out + '\n');
|
|
207
|
+
} catch { /* fail open: a hook must never break the agent */ }
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// Run only as the entry point. Compare real paths: when the script is reached
|
|
211
|
+
// through a symlink, argv[1] keeps the link path while import.meta.url is real.
|
|
212
|
+
function isMainModule() {
|
|
213
|
+
try {
|
|
214
|
+
return Boolean(process.argv[1]) && realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
|
|
215
|
+
} catch {
|
|
216
|
+
return false;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (isMainModule()) await main();
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: w-report-what-you-ran
|
|
3
|
+
kind: core
|
|
4
|
+
claim: Report only the checks you actually ran, and say which ones you skipped
|
|
5
|
+
applies_when: you summarize the result of a task, a test run, or a review
|
|
6
|
+
fails_when: the reader asked only for a plan and no checks were run on purpose
|
|
7
|
+
triggers: [any]
|
|
8
|
+
tags: [reporting, honesty]
|
|
9
|
+
sources:
|
|
10
|
+
- { kind: lesson, ref: example-lesson-1, task: example-task-1 }
|
|
11
|
+
- { kind: notebook, ref: example-shelf-1, task: example-task-2 }
|
|
12
|
+
- { kind: correction, ref: example-review-1, task: example-task-3 }
|
|
13
|
+
status: active
|
|
14
|
+
created: 2026-01-10
|
|
15
|
+
updated: 2026-01-10
|
|
16
|
+
---
|
|
17
|
+
A core entry has no opposite: it is a line the store holds fixed. A claim like
|
|
18
|
+
"all tests pass" is only worth reading if it names the command that produced it.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: p-narrow-vs-full-before-commit
|
|
3
|
+
situation: choosing between the narrow test and the full suite before a commit
|
|
4
|
+
ruling: win
|
|
5
|
+
winner: w-narrow-test-first
|
|
6
|
+
loser: w-full-suite-first
|
|
7
|
+
cue: no shared fixture, build configuration or public interface changed
|
|
8
|
+
created: 2026-01-10
|
|
9
|
+
sources:
|
|
10
|
+
- { kind: lesson, ref: example-ruling-1, task: example-task-1 }
|
|
11
|
+
- { kind: notebook, ref: example-ruling-2, task: example-task-2 }
|
|
12
|
+
---
|
|
13
|
+
When the cue holds, the narrow test wins. When it does not, the full suite wins,
|
|
14
|
+
and the precedent does not apply.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: w-full-suite-first
|
|
3
|
+
kind: technique
|
|
4
|
+
claim: Run the full test suite before trusting a change to shared code
|
|
5
|
+
applies_when: a change alters shared fixtures, build configuration, or an interface many modules use
|
|
6
|
+
fails_when: the suite takes so long that the change is abandoned half tested, or only one isolated module changed
|
|
7
|
+
opposite:
|
|
8
|
+
text: Run only the narrow test first
|
|
9
|
+
cue: the change stays inside one module
|
|
10
|
+
entry: w-narrow-test-first
|
|
11
|
+
triggers: [commit, merge]
|
|
12
|
+
tags: [testing, shared-code, regression]
|
|
13
|
+
sources:
|
|
14
|
+
- { kind: lesson, ref: example-lesson-4, task: example-task-1 }
|
|
15
|
+
- { kind: notebook, ref: example-shelf-4, task: example-task-2 }
|
|
16
|
+
- { kind: correction, ref: example-review-4, task: example-task-3 }
|
|
17
|
+
status: active
|
|
18
|
+
created: 2026-01-10
|
|
19
|
+
updated: 2026-01-10
|
|
20
|
+
---
|
|
21
|
+
A narrow test cannot see a breakage that lives in a different module.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: w-narrow-test-first
|
|
3
|
+
kind: technique
|
|
4
|
+
claim: Run the narrow test before the full suite
|
|
5
|
+
applies_when: a change touches one module and its own tests are quick to run
|
|
6
|
+
fails_when: the change alters shared fixtures, build configuration, or a public interface other modules use
|
|
7
|
+
opposite:
|
|
8
|
+
text: Run the full suite first
|
|
9
|
+
cue: shared fixtures or build configuration changed
|
|
10
|
+
entry: w-full-suite-first
|
|
11
|
+
triggers: [commit, review]
|
|
12
|
+
tags: [testing, commit]
|
|
13
|
+
sources:
|
|
14
|
+
- { kind: lesson, ref: example-lesson-3, task: example-task-1 }
|
|
15
|
+
- { kind: notebook, ref: example-shelf-3, task: example-task-2 }
|
|
16
|
+
- { kind: correction, ref: example-review-3, task: example-task-3 }
|
|
17
|
+
status: active
|
|
18
|
+
created: 2026-01-10
|
|
19
|
+
updated: 2026-01-10
|
|
20
|
+
---
|
|
21
|
+
A fast, narrow signal first saves minutes per iteration. The full suite still runs before merge.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: w-read-your-diff-before-pr
|
|
3
|
+
kind: technique
|
|
4
|
+
claim: Read your own complete diff before opening a pull request
|
|
5
|
+
applies_when: you are about to open a pull request for a change you wrote yourself
|
|
6
|
+
fails_when: the diff is a mechanical rename produced by a tool and verified by the compiler
|
|
7
|
+
opposite:
|
|
8
|
+
text: Open a draft pull request early and review it there
|
|
9
|
+
cue: you want feedback on the direction before the details are settled
|
|
10
|
+
triggers: [pr-create, review]
|
|
11
|
+
tags: [pull-request, review, code-review]
|
|
12
|
+
sources:
|
|
13
|
+
- { kind: lesson, ref: example-lesson-7, task: example-task-1 }
|
|
14
|
+
- { kind: notebook, ref: example-shelf-7, task: example-task-2 }
|
|
15
|
+
- { kind: correction, ref: example-review-7, task: example-task-3 }
|
|
16
|
+
status: active
|
|
17
|
+
created: 2026-01-10
|
|
18
|
+
updated: 2026-01-10
|
|
19
|
+
---
|
|
20
|
+
Stray debug lines and unrelated edits are cheapest to catch before a second person sees them.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: w-reproduce-before-fix
|
|
3
|
+
kind: technique
|
|
4
|
+
claim: Reproduce a bug with a failing test before you change any code
|
|
5
|
+
applies_when: a bug report describes behaviour you have not yet seen fail yourself
|
|
6
|
+
fails_when: the failure appears only under production conditions that cannot be scripted locally
|
|
7
|
+
opposite:
|
|
8
|
+
text: Start from the code and form a hypothesis first
|
|
9
|
+
cue: the report already includes a stack trace that points at one line
|
|
10
|
+
triggers: [plan, triage]
|
|
11
|
+
tags: [debugging, bug-fix, regression]
|
|
12
|
+
sources:
|
|
13
|
+
- { kind: lesson, ref: example-lesson-6, task: example-task-1 }
|
|
14
|
+
- { kind: notebook, ref: example-shelf-6, task: example-task-2 }
|
|
15
|
+
- { kind: correction, ref: example-review-6, task: example-task-3 }
|
|
16
|
+
status: active
|
|
17
|
+
created: 2026-01-10
|
|
18
|
+
updated: 2026-01-10
|
|
19
|
+
---
|
|
20
|
+
A fix without a failing test first proves nothing: you cannot tell it from a coincidence.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: w-small-focused-commits
|
|
3
|
+
kind: technique
|
|
4
|
+
claim: Keep each commit to one logical change
|
|
5
|
+
applies_when: you are about to commit a change that mixes a fix, a rename, and a formatting pass
|
|
6
|
+
fails_when: a refactor does not compile unless it lands in a single commit
|
|
7
|
+
opposite:
|
|
8
|
+
text: Commit the whole working state at once
|
|
9
|
+
cue: the branch is a throwaway that will be squashed before review
|
|
10
|
+
triggers: [commit]
|
|
11
|
+
tags: [commit, git-history, review]
|
|
12
|
+
sources:
|
|
13
|
+
- { kind: lesson, ref: example-lesson-5, task: example-task-1 }
|
|
14
|
+
- { kind: notebook, ref: example-shelf-5, task: example-task-2 }
|
|
15
|
+
- { kind: correction, ref: example-review-5, task: example-task-3 }
|
|
16
|
+
status: active
|
|
17
|
+
created: 2026-01-10
|
|
18
|
+
updated: 2026-01-10
|
|
19
|
+
---
|
|
20
|
+
One concern per commit makes review, revert, and bisect cheap.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: w-prefer-reversible-steps
|
|
3
|
+
kind: value
|
|
4
|
+
claim: Prefer a small step that can be undone over a large step that cannot
|
|
5
|
+
applies_when: you plan a change to a shared system and more than one route reaches the goal
|
|
6
|
+
fails_when: keeping the old and the new path alive at once costs more than the risk it removes
|
|
7
|
+
opposite:
|
|
8
|
+
text: Make one decisive change and accept that it cannot be rolled back
|
|
9
|
+
cue: the old path is already broken and a half-migrated state is worse than either end
|
|
10
|
+
triggers: [plan, merge]
|
|
11
|
+
tags: [risk, planning, rollback]
|
|
12
|
+
sources:
|
|
13
|
+
- { kind: lesson, ref: example-lesson-2, task: example-task-1 }
|
|
14
|
+
- { kind: notebook, ref: example-shelf-2, task: example-task-2 }
|
|
15
|
+
- { kind: correction, ref: example-review-2, task: example-task-3 }
|
|
16
|
+
status: active
|
|
17
|
+
created: 2026-01-10
|
|
18
|
+
updated: 2026-01-10
|
|
19
|
+
---
|
|
20
|
+
Reversibility is a value, not a rule: weigh it against the cost of carrying two paths.
|
package/package.json
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-wisdom",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "A read-only, deterministic store of conditional wisdom for AI agents: entries that say when they apply, when they fail, and what the opposite advice is. One dependency (yaml), no embeddings, no network.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Jean Ibarz",
|
|
7
|
+
"homepage": "https://github.com/jeanibarz/agent-wisdom",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/jeanibarz/agent-wisdom.git"
|
|
11
|
+
},
|
|
12
|
+
"bugs": "https://github.com/jeanibarz/agent-wisdom/issues",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"ai-agents",
|
|
15
|
+
"llm",
|
|
16
|
+
"agent-memory",
|
|
17
|
+
"wisdom",
|
|
18
|
+
"cli"
|
|
19
|
+
],
|
|
20
|
+
"type": "module",
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=18"
|
|
23
|
+
},
|
|
24
|
+
"bin": {
|
|
25
|
+
"wisdom": "dist/cli.js"
|
|
26
|
+
},
|
|
27
|
+
"main": "dist/wisdom.js",
|
|
28
|
+
"types": "dist/wisdom.d.ts",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/wisdom.d.ts",
|
|
32
|
+
"default": "./dist/wisdom.js"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"files": [
|
|
36
|
+
"dist",
|
|
37
|
+
"examples",
|
|
38
|
+
"!examples/store/lookups.jsonl",
|
|
39
|
+
"README.md",
|
|
40
|
+
"CHANGELOG.md",
|
|
41
|
+
"LICENSE"
|
|
42
|
+
],
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "tsc && chmod +x dist/cli.js",
|
|
45
|
+
"typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
|
|
46
|
+
"pretest": "npm run build",
|
|
47
|
+
"pretest:coverage": "npm run build",
|
|
48
|
+
"test": "node scripts/check-node-for-tests.mjs && vitest run",
|
|
49
|
+
"test:coverage": "node scripts/check-node-for-tests.mjs && vitest run --coverage",
|
|
50
|
+
"test:fast": "node scripts/check-node-for-tests.mjs && vitest run --config vitest.fast.config.ts",
|
|
51
|
+
"test:watch": "vitest",
|
|
52
|
+
"prepublishOnly": "npm run build && npm test"
|
|
53
|
+
},
|
|
54
|
+
"dependencies": {
|
|
55
|
+
"yaml": "^2.9.1"
|
|
56
|
+
},
|
|
57
|
+
"devDependencies": {
|
|
58
|
+
"@types/node": "^26.6.6",
|
|
59
|
+
"@vitest/coverage-v8": "^5.1.0",
|
|
60
|
+
"typescript": "^7.0.2",
|
|
61
|
+
"vitest": "^5.0.5"
|
|
62
|
+
}
|
|
63
|
+
}
|