whywiki 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +183 -2
- package/assets/RULES.md +45 -0
- package/assets/house-rules.md +1 -0
- package/assets/index.md +13 -0
- package/assets/log.md +1 -0
- package/assets/templates/decision.md +18 -0
- package/assets/templates/dropped.md +11 -0
- package/assets/templates/open-loop.md +12 -0
- package/assets/templates/plan.md +12 -0
- package/assets/templates/topic.md +13 -0
- package/dist/bin.js +16 -0
- package/dist/cli.js +121 -0
- package/dist/errors.js +6 -0
- package/dist/frontmatter.js +27 -0
- package/dist/git.js +31 -0
- package/dist/init.js +107 -0
- package/dist/layout.js +28 -0
- package/dist/lock.js +36 -0
- package/dist/mcp.js +59 -0
- package/dist/ops.js +52 -0
- package/dist/remote.js +10 -0
- package/dist/wiki.js +284 -0
- package/package.json +50 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Aman Jaglan
|
|
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,184 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<picture>
|
|
4
|
+
<source media="(prefers-color-scheme: dark)" srcset=".github/logo-dark.svg">
|
|
5
|
+
<img src=".github/logo-light.svg" width="110" alt="whywiki logo: two question marks joined into one line">
|
|
6
|
+
</picture>
|
|
7
|
+
|
|
8
|
+
# whywiki
|
|
9
|
+
|
|
10
|
+
**Your AI forgets why. This doesn't.**
|
|
11
|
+
|
|
12
|
+
[](LICENSE)
|
|
13
|
+
[](https://nodejs.org)
|
|
14
|
+
[](#works-with)
|
|
15
|
+
|
|
16
|
+
</div>
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## Confession: yes, this is an AI memory tool.
|
|
21
|
+
|
|
22
|
+
Please don't close the tab.
|
|
23
|
+
|
|
24
|
+
There's no waitlist, no pricing page, and nobody here will call it your
|
|
25
|
+
"second brain." It's a folder of markdown files plus a short list of rules
|
|
26
|
+
your AI has to follow. No account, no server, no embeddings. Just notes in
|
|
27
|
+
git that every AI tool you use can read.
|
|
28
|
+
|
|
29
|
+
## Alright, let me pitch you the problem
|
|
30
|
+
|
|
31
|
+
*(Like you don't live it every day. Humor me.)*
|
|
32
|
+
|
|
33
|
+
**Monday, 2 pm.** You and your AI spend the afternoon on GraphQL. By 6 pm you
|
|
34
|
+
both agree it's overkill for a five-endpoint app, so you rip it out and go
|
|
35
|
+
back to REST. Lesson learned.
|
|
36
|
+
|
|
37
|
+
**Tuesday, 9 am.** New session. Your AI, bright-eyed:
|
|
38
|
+
|
|
39
|
+
> "This API would be a great fit for GraphQL! Want me to set it up?"
|
|
40
|
+
|
|
41
|
+
It also ran `npm install` in your pnpm project. For the fourteenth time.
|
|
42
|
+
|
|
43
|
+
Your AI has the memory of a goldfish with a very confident personality.
|
|
44
|
+
You're not pair programming. You're running a very expensive Groundhog Day.
|
|
45
|
+
|
|
46
|
+
## The fix
|
|
47
|
+
|
|
48
|
+
Give your AI a notebook. Make it read the notebook before every task. Make it
|
|
49
|
+
write in the notebook the moment something gets decided. That's the product.
|
|
50
|
+
|
|
51
|
+
The notebook is `~/wiki/`, and every AI tool you use shares the same one. The
|
|
52
|
+
AI writes when one of these happens:
|
|
53
|
+
|
|
54
|
+
| What happened | Where it goes |
|
|
55
|
+
|---|---|
|
|
56
|
+
| You picked one option over another | `decisions/` |
|
|
57
|
+
| You tried something and it flopped | `dropped/` (GraphQL rests here now 🪦) |
|
|
58
|
+
| You said "always…", "never…", "from now on…" | `house-rules.md` (hi, pnpm) |
|
|
59
|
+
| Work is stuck waiting on someone else | `open-loops/` |
|
|
60
|
+
| The wiki turned out to be wrong | the topic page gets fixed |
|
|
61
|
+
|
|
62
|
+
Nothing happened? Nothing gets written. You do zero bookkeeping.
|
|
63
|
+
|
|
64
|
+
### Why this one, when the others exist?
|
|
65
|
+
|
|
66
|
+
- **Others remember facts. This remembers decisions,** including what you
|
|
67
|
+
already tried and threw out.
|
|
68
|
+
- **Others live in one app. This lives on your disk.** Plan in ChatGPT, build
|
|
69
|
+
in Claude Code, and nobody starts from zero.
|
|
70
|
+
- **Others are a black box. This is a folder you can `cat`.** Every change is
|
|
71
|
+
a git commit, so you can see what the AI wrote and undo it.
|
|
72
|
+
- **Others hope the AI saves things. This makes it.** Fixed triggers, no vibes.
|
|
73
|
+
|
|
74
|
+
## Install
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
npx whywiki init
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
```
|
|
81
|
+
✓ Created ~/wiki
|
|
82
|
+
✓ Claude Code: updated ~/.claude/CLAUDE.md
|
|
83
|
+
✓ Codex: updated ~/.codex/AGENTS.md
|
|
84
|
+
✗ Cursor: Cursor keeps global rules in Settings → Rules. Add this to its instructions:
|
|
85
|
+
Before every task, read ~/wiki/RULES.md and follow it.
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Claude Code and Codex now load the rules at the start of every session.
|
|
89
|
+
Cursor gets a sticky note to paste. Sorry, Cursor.
|
|
90
|
+
|
|
91
|
+
Run it as often as you like. It never duplicates anything and never touches a
|
|
92
|
+
`~/wiki/` that isn't its own. You only need Node 20+. Git is built in.
|
|
93
|
+
|
|
94
|
+
## What's in the notebook
|
|
95
|
+
|
|
96
|
+
```
|
|
97
|
+
~/wiki/
|
|
98
|
+
├── RULES.md what the AI must do (40 lines, zero essays)
|
|
99
|
+
├── house-rules.md your pet peeves ("we use pnpm")
|
|
100
|
+
├── index.md map of every page
|
|
101
|
+
├── log.md one line per change
|
|
102
|
+
├── topics/ how things work right now
|
|
103
|
+
├── decisions/ "we picked X over Y, because Z"
|
|
104
|
+
├── dropped/ the idea graveyard 🪦
|
|
105
|
+
├── open-loops/ "legal still hasn't replied"
|
|
106
|
+
├── plans/ plans for one piece of work
|
|
107
|
+
└── projects/
|
|
108
|
+
└── your-app/ same folders, one set per code repo
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Inside a code repo, notes go in that repo's project folder. Anywhere else,
|
|
112
|
+
they go in the main wiki. Reading always searches everything.
|
|
113
|
+
|
|
114
|
+
Each topic page describes how things are **right now**. Old decisions aren't
|
|
115
|
+
deleted. They're stamped `superseded_by` and kept, so two pages never argue.
|
|
116
|
+
|
|
117
|
+
## Works with
|
|
118
|
+
|
|
119
|
+
| Tool | Setup |
|
|
120
|
+
|---|---|
|
|
121
|
+
| **Claude Code**, **Codex** | Done by `init`. You do nothing. |
|
|
122
|
+
| **Cursor** | Paste one line, or use MCP |
|
|
123
|
+
| **Claude desktop** | MCP |
|
|
124
|
+
| **ChatGPT** | MCP over HTTP |
|
|
125
|
+
|
|
126
|
+
`whywiki serve` gives chat apps the exact same powers as the CLI. Nobody gets
|
|
127
|
+
the budget version.
|
|
128
|
+
|
|
129
|
+
```json
|
|
130
|
+
{ "mcpServers": { "whywiki": { "command": "npx", "args": ["-y", "whywiki", "serve"] } } }
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
ChatGPT only talks to servers on the internet. Run the HTTP server, put it
|
|
134
|
+
behind an HTTPS tunnel you trust, and tell whywiki the tunnel's hostname:
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
npx -y whywiki serve --http --allow-host your-tunnel.example.com
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
It only listens on localhost and rejects requests for any other hostname.
|
|
141
|
+
|
|
142
|
+
> ⚠️ Anyone with the tunnel URL can read and write your wiki. Treat it like a password.
|
|
143
|
+
|
|
144
|
+
<details>
|
|
145
|
+
<summary><b>All commands</b> (mostly for the AI, which loves a good CLI)</summary>
|
|
146
|
+
|
|
147
|
+
```
|
|
148
|
+
whywiki <command> [--root <path>]
|
|
149
|
+
|
|
150
|
+
init create ~/wiki and wire Claude Code and Codex
|
|
151
|
+
serve [--http] [--port 3333] [--allow-host <host>]...
|
|
152
|
+
run the MCP server (stdio by default; --http
|
|
153
|
+
listens on localhost, --allow-host adds a tunnel host)
|
|
154
|
+
rules print the rules and house rules
|
|
155
|
+
projects list projects
|
|
156
|
+
find-project <remote> find the project for a git remote
|
|
157
|
+
create-project <name> [--description <text>] [--repo <remote>]...
|
|
158
|
+
search <query...> [--scope all|main|project:<name>]
|
|
159
|
+
read <path>
|
|
160
|
+
write --scope <scope> --type <type> --slug <slug> --summary <text> [--file <path>]
|
|
161
|
+
page content comes from --file or stdin
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
`--root` or `$WHYWIKI_ROOT` points at a wiki other than `~/wiki`.
|
|
165
|
+
|
|
166
|
+
</details>
|
|
167
|
+
|
|
168
|
+
## FAQ
|
|
169
|
+
|
|
170
|
+
**Can I edit it?** Read it, browse it, open it in Obsidian. To change it, ask
|
|
171
|
+
the AI, so the index, log and git history stay in sync.
|
|
172
|
+
|
|
173
|
+
**My AI ignored the wiki once.** AIs are AIs. If it keeps doing something,
|
|
174
|
+
say "from now on…" and it lands in `house-rules.md`.
|
|
175
|
+
|
|
176
|
+
**How do I uninstall?** Delete `~/wiki` and the marked `whywiki` block in your
|
|
177
|
+
agent's instructions file. A memory tool that's easy to forget. Ironic.
|
|
178
|
+
|
|
179
|
+
**What's the logo?** Two question marks holding hands. Every "why" gets an
|
|
180
|
+
answer, and every answer raises another "why."
|
|
181
|
+
|
|
182
|
+
## License
|
|
183
|
+
|
|
184
|
+
MIT. Do whatever you want. Just don't let the AI suggest GraphQL again.
|
package/assets/RULES.md
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# Wiki rules
|
|
2
|
+
|
|
3
|
+
Read before work. Write when a trigger fires. Never ask the user.
|
|
4
|
+
Wiki folder: `{{WIKI}}`. Paths below are relative to it. Commands: `npx -y whywiki <command>`, or the same tools over MCP.
|
|
5
|
+
|
|
6
|
+
## Where
|
|
7
|
+
- In a git repo: `find-project "$(git remote get-url origin)"`. None → `create-project <repo-name> --repo <remote> --description "<one line>"`. Scope `project:<name>`.
|
|
8
|
+
- Otherwise: scope `main`.
|
|
9
|
+
- Search everything.
|
|
10
|
+
|
|
11
|
+
## Before work
|
|
12
|
+
1. Read `house-rules.md`, `index.md`.
|
|
13
|
+
2. `search <task keywords>`.
|
|
14
|
+
3. Check `dropped/` and `open-loops/` hits. Never re-propose dropped items unless the user overrides.
|
|
15
|
+
4. Open loop's "Done when" is true → close it.
|
|
16
|
+
|
|
17
|
+
## Write when
|
|
18
|
+
- Choice made → `decision`
|
|
19
|
+
- Approach abandoned → `dropped`
|
|
20
|
+
- Rule set → `house-rules`
|
|
21
|
+
- Term defined → `topic`
|
|
22
|
+
- Wiki contradicted → update `topic`, supersede old page
|
|
23
|
+
- Blocked on outside condition → `open-loop`
|
|
24
|
+
|
|
25
|
+
Write in the same response. No trigger → write nothing.
|
|
26
|
+
|
|
27
|
+
## How
|
|
28
|
+
- Write only with `write` (MCP `write_page`). Never edit wiki files directly.
|
|
29
|
+
- Content follows `templates/<type>.md` with every `##` section.
|
|
30
|
+
- Update a dated page by passing its full dated slug.
|
|
31
|
+
- Topic page is current truth. Rewrite it whole. No changelog.
|
|
32
|
+
- Every `decision`, `dropped` or `open-loop` also updates its topic page and links it there.
|
|
33
|
+
- Replaced decision: set `superseded_by` or `superseded_in_part_by` on it. Never delete.
|
|
34
|
+
- Never leave two pages claiming current truth.
|
|
35
|
+
- Unproven → topic's Open questions.
|
|
36
|
+
- Closed open loop: `status: closed` + Resolution. Never delete.
|
|
37
|
+
- Plans are not current truth.
|
|
38
|
+
- `house-rules`: write the whole file, scope `main`.
|
|
39
|
+
|
|
40
|
+
## Format
|
|
41
|
+
- Slugs: lowercase-hyphenated. Dated types get `YYYY-MM-DD-` automatically.
|
|
42
|
+
- Links: `[[path]]` without `.md`.
|
|
43
|
+
|
|
44
|
+
## Never write
|
|
45
|
+
Secrets, credentials, transcripts.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# House rules
|
package/assets/index.md
ADDED
package/assets/log.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Wiki log
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
---
|
|
2
|
+
date: YYYY-MM-DD
|
|
3
|
+
type: decision
|
|
4
|
+
status: accepted
|
|
5
|
+
supersedes:
|
|
6
|
+
supersedes_in_part:
|
|
7
|
+
superseded_by:
|
|
8
|
+
superseded_in_part_by:
|
|
9
|
+
tags: []
|
|
10
|
+
---
|
|
11
|
+
# <Title>
|
|
12
|
+
## Context
|
|
13
|
+
## Evidence
|
|
14
|
+
## Options considered
|
|
15
|
+
## Decision
|
|
16
|
+
## What this changes
|
|
17
|
+
## Consequences
|
|
18
|
+
## Related
|
package/dist/bin.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import { run } from "./cli.js";
|
|
4
|
+
async function readStdin() {
|
|
5
|
+
const chunks = [];
|
|
6
|
+
for await (const chunk of process.stdin)
|
|
7
|
+
chunks.push(chunk);
|
|
8
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
9
|
+
}
|
|
10
|
+
process.exitCode = await run(process.argv.slice(2), {
|
|
11
|
+
stdout: (text) => process.stdout.write(`${text}\n`),
|
|
12
|
+
stderr: (text) => process.stderr.write(`${text}\n`),
|
|
13
|
+
readStdin,
|
|
14
|
+
env: process.env,
|
|
15
|
+
home: os.homedir(),
|
|
16
|
+
});
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
import { agentInstruction, displayPath, initWiki, wireAgents } from "./init.js";
|
|
5
|
+
import { defaultRoot } from "./layout.js";
|
|
6
|
+
import { serveHttp, serveStdio } from "./mcp.js";
|
|
7
|
+
import { callOperation } from "./ops.js";
|
|
8
|
+
import { Wiki } from "./wiki.js";
|
|
9
|
+
const USAGE = `Usage: whywiki <command> [--root <path>]
|
|
10
|
+
|
|
11
|
+
init create ~/wiki and wire Claude Code and Codex
|
|
12
|
+
serve [--http] [--port 3333] [--allow-host <host>]...
|
|
13
|
+
run the MCP server (stdio by default; --http
|
|
14
|
+
listens on localhost, --allow-host adds a tunnel host)
|
|
15
|
+
rules print the rules and house rules
|
|
16
|
+
projects list projects
|
|
17
|
+
find-project <remote> find the project for a git remote
|
|
18
|
+
create-project <name> [--description <text>] [--repo <remote>]...
|
|
19
|
+
search <query...> [--scope all|main|project:<name>]
|
|
20
|
+
read <path>
|
|
21
|
+
write --scope <scope> --type <type> --slug <slug> --summary <text> [--file <path>]
|
|
22
|
+
page content comes from --file or stdin`;
|
|
23
|
+
// Runs one CLI command and returns the exit code.
|
|
24
|
+
export async function run(argv, io) {
|
|
25
|
+
try {
|
|
26
|
+
const { values, positionals } = parseArgs({
|
|
27
|
+
args: argv,
|
|
28
|
+
allowPositionals: true,
|
|
29
|
+
options: {
|
|
30
|
+
root: { type: "string" },
|
|
31
|
+
http: { type: "boolean" },
|
|
32
|
+
port: { type: "string" },
|
|
33
|
+
"allow-host": { type: "string", multiple: true },
|
|
34
|
+
description: { type: "string" },
|
|
35
|
+
repo: { type: "string", multiple: true },
|
|
36
|
+
scope: { type: "string" },
|
|
37
|
+
type: { type: "string" },
|
|
38
|
+
slug: { type: "string" },
|
|
39
|
+
summary: { type: "string" },
|
|
40
|
+
file: { type: "string" },
|
|
41
|
+
help: { type: "boolean", short: "h" },
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
const [command, ...rest] = positionals;
|
|
45
|
+
if (values.help) {
|
|
46
|
+
io.stdout(USAGE);
|
|
47
|
+
return 0;
|
|
48
|
+
}
|
|
49
|
+
const root = values.root ? path.resolve(values.root) : defaultRoot(io.env, io.home);
|
|
50
|
+
if (command === "init")
|
|
51
|
+
return await init(root, io);
|
|
52
|
+
const wiki = new Wiki(root);
|
|
53
|
+
if (command === "serve")
|
|
54
|
+
return await serve(wiki, values, io);
|
|
55
|
+
const request = await toOperation(command, rest, values, io);
|
|
56
|
+
if (!request) {
|
|
57
|
+
io.stderr(USAGE);
|
|
58
|
+
return 1;
|
|
59
|
+
}
|
|
60
|
+
io.stdout(await callOperation(wiki, request.name, request.args));
|
|
61
|
+
return 0;
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
io.stderr(`error: ${error.message}`);
|
|
65
|
+
return 1;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
async function init(root, io) {
|
|
69
|
+
const shown = displayPath(root, io.home);
|
|
70
|
+
const status = await initWiki(root, io.home);
|
|
71
|
+
io.stdout(status === "created"
|
|
72
|
+
? `✓ Created ${shown}`
|
|
73
|
+
: `✓ ${shown} already set up${status === "updated" ? " (rules and templates refreshed)" : ""}`);
|
|
74
|
+
const instruction = agentInstruction(displayPath(path.join(root, "RULES.md"), io.home));
|
|
75
|
+
for (const r of wireAgents(root, io.home, io.env)) {
|
|
76
|
+
io.stdout(r.status === "manual"
|
|
77
|
+
? `✗ ${r.tool}: ${r.reason}. Add this to its instructions:\n ${instruction}`
|
|
78
|
+
: `✓ ${r.tool}: ${r.status} ${displayPath(r.path ?? "", io.home)}`);
|
|
79
|
+
}
|
|
80
|
+
io.stdout('\nChat apps (Claude desktop, Cursor, ChatGPT): add the MCP server "npx -y whywiki serve" (ChatGPT needs --http and a public URL).');
|
|
81
|
+
return 0;
|
|
82
|
+
}
|
|
83
|
+
async function serve(wiki, values, io) {
|
|
84
|
+
wiki.assertInitialized();
|
|
85
|
+
if (values.http) {
|
|
86
|
+
const port = Number(values.port ?? 3333);
|
|
87
|
+
const allowHosts = Array.isArray(values["allow-host"]) ? values["allow-host"] : [];
|
|
88
|
+
await serveHttp(wiki, port, allowHosts);
|
|
89
|
+
io.stderr(`whywiki MCP at http://localhost:${port}/mcp (wiki: ${wiki.root})`);
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
await serveStdio(wiki);
|
|
93
|
+
}
|
|
94
|
+
return 0;
|
|
95
|
+
}
|
|
96
|
+
async function toOperation(command, rest, values, io) {
|
|
97
|
+
const defined = (args) => Object.fromEntries(Object.entries(args).filter(([, v]) => v !== undefined));
|
|
98
|
+
switch (command) {
|
|
99
|
+
case "rules":
|
|
100
|
+
return { name: "read_rules", args: {} };
|
|
101
|
+
case "projects":
|
|
102
|
+
return { name: "list_projects", args: {} };
|
|
103
|
+
case "find-project":
|
|
104
|
+
return { name: "find_project", args: defined({ remote: rest[0] }) };
|
|
105
|
+
case "create-project":
|
|
106
|
+
return { name: "create_project", args: defined({ name: rest[0], description: values.description, repos: values.repo }) };
|
|
107
|
+
case "search":
|
|
108
|
+
return { name: "search", args: defined({ query: rest.join(" ") || undefined, scope: values.scope }) };
|
|
109
|
+
case "read":
|
|
110
|
+
return { name: "read_page", args: defined({ path: rest[0] }) };
|
|
111
|
+
case "write": {
|
|
112
|
+
const content = typeof values.file === "string" ? fs.readFileSync(values.file, "utf8") : await io.readStdin();
|
|
113
|
+
return {
|
|
114
|
+
name: "write_page",
|
|
115
|
+
args: defined({ scope: values.scope, type: values.type, slug: values.slug, summary: values.summary, content }),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
default:
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// Parses flat `key: value` and `key: [a, b]` frontmatter.
|
|
2
|
+
export function parseFrontmatter(source) {
|
|
3
|
+
const text = source.replace(/\r\n/g, "\n");
|
|
4
|
+
const match = /^---\n([\s\S]*?)\n---\n?/.exec(text);
|
|
5
|
+
if (!match)
|
|
6
|
+
return { data: {}, body: text };
|
|
7
|
+
const data = {};
|
|
8
|
+
for (const line of match[1].split("\n")) {
|
|
9
|
+
const kv = /^([A-Za-z_][\w-]*):\s*(.*)$/.exec(line);
|
|
10
|
+
if (!kv)
|
|
11
|
+
continue;
|
|
12
|
+
const raw = kv[2].trim();
|
|
13
|
+
data[kv[1]] =
|
|
14
|
+
raw.startsWith("[") && raw.endsWith("]")
|
|
15
|
+
? raw.slice(1, -1).split(",").map(unquote).filter(Boolean)
|
|
16
|
+
: unquote(raw);
|
|
17
|
+
}
|
|
18
|
+
return { data, body: text.slice(match[0].length) };
|
|
19
|
+
}
|
|
20
|
+
// Serializes flat frontmatter.
|
|
21
|
+
export function stringifyFrontmatter(data) {
|
|
22
|
+
const lines = Object.entries(data).map(([k, v]) => Array.isArray(v) ? `${k}: [${v.join(", ")}]` : `${k}: ${v}`);
|
|
23
|
+
return `---\n${lines.join("\n")}\n---\n`;
|
|
24
|
+
}
|
|
25
|
+
function unquote(s) {
|
|
26
|
+
return s.trim().replace(/^["']|["']$/g, "");
|
|
27
|
+
}
|
package/dist/git.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import * as git from "isomorphic-git";
|
|
4
|
+
const author = { name: "whywiki", email: "whywiki@localhost" };
|
|
5
|
+
// Creates a git repository with a main branch.
|
|
6
|
+
export async function gitInit(dir) {
|
|
7
|
+
await git.init({ fs, dir, defaultBranch: "main" });
|
|
8
|
+
}
|
|
9
|
+
// Stages every change in the working tree and commits it.
|
|
10
|
+
export async function commitAll(dir, message) {
|
|
11
|
+
for (const [filepath, head, workdir, stage] of await git.statusMatrix({ fs, dir })) {
|
|
12
|
+
if (workdir === 0) {
|
|
13
|
+
if (head !== 0 || stage !== 0)
|
|
14
|
+
await git.remove({ fs, dir, filepath });
|
|
15
|
+
}
|
|
16
|
+
else if (!(head === 1 && workdir === 1 && stage === 1)) {
|
|
17
|
+
await git.add({ fs, dir, filepath });
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return git.commit({ fs, dir, message, author });
|
|
21
|
+
}
|
|
22
|
+
// Stages only the given root-relative paths and commits them.
|
|
23
|
+
export async function commitFiles(dir, files, message) {
|
|
24
|
+
for (const filepath of files) {
|
|
25
|
+
if (fs.existsSync(path.join(dir, filepath)))
|
|
26
|
+
await git.add({ fs, dir, filepath });
|
|
27
|
+
else
|
|
28
|
+
await git.remove({ fs, dir, filepath });
|
|
29
|
+
}
|
|
30
|
+
return git.commit({ fs, dir, message, author });
|
|
31
|
+
}
|
package/dist/init.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { WikiError } from "./errors.js";
|
|
5
|
+
import { commitAll, commitFiles, gitInit } from "./git.js";
|
|
6
|
+
import { ASSETS_DIR, FOLDER, MARKER } from "./layout.js";
|
|
7
|
+
const START = "<!-- whywiki:start -->";
|
|
8
|
+
const END = "<!-- whywiki:end -->";
|
|
9
|
+
// Creates the wiki as a git repo, or refreshes whywiki's own files in an existing one.
|
|
10
|
+
export async function initWiki(root, home = os.homedir()) {
|
|
11
|
+
if (fs.existsSync(root)) {
|
|
12
|
+
if (!fs.existsSync(path.join(root, MARKER))) {
|
|
13
|
+
throw new WikiError(`${root} already exists and was not created by whywiki. Nothing was changed.`);
|
|
14
|
+
}
|
|
15
|
+
return refreshOwnedFiles(root, home);
|
|
16
|
+
}
|
|
17
|
+
try {
|
|
18
|
+
fs.cpSync(ASSETS_DIR, root, { recursive: true });
|
|
19
|
+
fs.writeFileSync(path.join(root, "RULES.md"), renderRules(root, home));
|
|
20
|
+
for (const folder of [...Object.values(FOLDER), "projects"]) {
|
|
21
|
+
fs.mkdirSync(path.join(root, folder), { recursive: true });
|
|
22
|
+
fs.writeFileSync(path.join(root, folder, ".gitkeep"), "");
|
|
23
|
+
}
|
|
24
|
+
fs.writeFileSync(path.join(root, MARKER), `${JSON.stringify({ version: 1 })}\n`);
|
|
25
|
+
await gitInit(root);
|
|
26
|
+
await commitAll(root, "init: whywiki");
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
fs.rmSync(root, { recursive: true, force: true });
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
return "created";
|
|
33
|
+
}
|
|
34
|
+
async function refreshOwnedFiles(root, home) {
|
|
35
|
+
const owned = [
|
|
36
|
+
["RULES.md", renderRules(root, home)],
|
|
37
|
+
...fs.readdirSync(path.join(ASSETS_DIR, "templates")).sort().map((f) => [
|
|
38
|
+
`templates/${f}`,
|
|
39
|
+
fs.readFileSync(path.join(ASSETS_DIR, "templates", f), "utf8"),
|
|
40
|
+
]),
|
|
41
|
+
];
|
|
42
|
+
const changed = owned.filter(([rel, content]) => {
|
|
43
|
+
const file = path.join(root, rel);
|
|
44
|
+
return !fs.existsSync(file) || fs.readFileSync(file, "utf8") !== content;
|
|
45
|
+
});
|
|
46
|
+
if (changed.length === 0)
|
|
47
|
+
return "unchanged";
|
|
48
|
+
for (const [rel, content] of changed)
|
|
49
|
+
fs.writeFileSync(path.join(root, rel), content);
|
|
50
|
+
const files = changed.map(([rel]) => rel);
|
|
51
|
+
await commitFiles(root, files, `update: ${files.join(", ")}`);
|
|
52
|
+
return "updated";
|
|
53
|
+
}
|
|
54
|
+
// The line to paste into tools whose instructions whywiki cannot edit.
|
|
55
|
+
export function agentInstruction(rulesPath) {
|
|
56
|
+
return `Before every task, read ${rulesPath} and follow it.`;
|
|
57
|
+
}
|
|
58
|
+
// Loads the rules into each installed agent's global instructions file.
|
|
59
|
+
export function wireAgents(root, home, env) {
|
|
60
|
+
const shown = (file) => displayPath(path.join(root, file), home);
|
|
61
|
+
const targets = [
|
|
62
|
+
{
|
|
63
|
+
tool: "Claude Code",
|
|
64
|
+
dir: env.CLAUDE_CONFIG_DIR ?? path.join(home, ".claude"),
|
|
65
|
+
file: "CLAUDE.md",
|
|
66
|
+
body: `@${shown("RULES.md")}\n@${shown("house-rules.md")}`,
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
tool: "Codex",
|
|
70
|
+
dir: env.CODEX_HOME ?? path.join(home, ".codex"),
|
|
71
|
+
file: "AGENTS.md",
|
|
72
|
+
body: fs.readFileSync(path.join(root, "RULES.md"), "utf8").trimEnd(),
|
|
73
|
+
},
|
|
74
|
+
];
|
|
75
|
+
const results = targets.map(({ tool, dir, file, body }) => {
|
|
76
|
+
if (!fs.existsSync(dir)) {
|
|
77
|
+
return { tool, status: "manual", reason: `${displayPath(dir, home)} not found (${tool} may not be installed)` };
|
|
78
|
+
}
|
|
79
|
+
const target = path.join(dir, file);
|
|
80
|
+
return { tool, status: upsertBlock(target, `${START}\n${body}\n${END}`), path: target };
|
|
81
|
+
});
|
|
82
|
+
results.push({ tool: "Cursor", status: "manual", reason: "Cursor keeps global rules in Settings → Rules" });
|
|
83
|
+
return results;
|
|
84
|
+
}
|
|
85
|
+
// Shows paths under the home folder as ~/...
|
|
86
|
+
export function displayPath(p, home) {
|
|
87
|
+
return p === home || p.startsWith(home + path.sep) ? `~${p.slice(home.length)}` : p;
|
|
88
|
+
}
|
|
89
|
+
function renderRules(root, home) {
|
|
90
|
+
return fs.readFileSync(path.join(ASSETS_DIR, "RULES.md"), "utf8").replaceAll("{{WIKI}}", displayPath(root, home));
|
|
91
|
+
}
|
|
92
|
+
function upsertBlock(file, block) {
|
|
93
|
+
if (!fs.existsSync(file)) {
|
|
94
|
+
fs.writeFileSync(file, `${block}\n`);
|
|
95
|
+
return "created";
|
|
96
|
+
}
|
|
97
|
+
const current = fs.readFileSync(file, "utf8");
|
|
98
|
+
const pattern = new RegExp(`${START}[\\s\\S]*?${END}`);
|
|
99
|
+
const trimmed = current.trimEnd();
|
|
100
|
+
const next = pattern.test(current)
|
|
101
|
+
? current.replace(pattern, () => block)
|
|
102
|
+
: `${trimmed ? `${trimmed}\n\n` : ""}${block}\n`;
|
|
103
|
+
if (next === current)
|
|
104
|
+
return "unchanged";
|
|
105
|
+
fs.writeFileSync(file, next);
|
|
106
|
+
return "updated";
|
|
107
|
+
}
|
package/dist/layout.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
export const PAGE_TYPES = ["topic", "decision", "dropped", "open-loop", "plan"];
|
|
6
|
+
export const FOLDER = {
|
|
7
|
+
topic: "topics",
|
|
8
|
+
decision: "decisions",
|
|
9
|
+
dropped: "dropped",
|
|
10
|
+
"open-loop": "open-loops",
|
|
11
|
+
plan: "plans",
|
|
12
|
+
};
|
|
13
|
+
export const INDEX_SECTION = {
|
|
14
|
+
topic: "Topics",
|
|
15
|
+
decision: "Decisions",
|
|
16
|
+
dropped: "Dropped",
|
|
17
|
+
"open-loop": "Open loops",
|
|
18
|
+
plan: "Plans",
|
|
19
|
+
};
|
|
20
|
+
export const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
21
|
+
export const DATED = /^\d{4}-\d{2}-\d{2}-/;
|
|
22
|
+
export const MARKER = ".whywiki";
|
|
23
|
+
export const ASSETS_DIR = fileURLToPath(new URL("../assets/", import.meta.url));
|
|
24
|
+
export const VERSION = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
25
|
+
// Resolves the wiki folder from $WHYWIKI_ROOT or ~/wiki.
|
|
26
|
+
export function defaultRoot(env, home = os.homedir()) {
|
|
27
|
+
return env.WHYWIKI_ROOT ? path.resolve(env.WHYWIKI_ROOT) : path.join(home, "wiki");
|
|
28
|
+
}
|
package/dist/lock.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
4
|
+
import { WikiError } from "./errors.js";
|
|
5
|
+
export const LOCK = ".whywiki.lock";
|
|
6
|
+
const STALE_MS = 30_000;
|
|
7
|
+
const WAIT_MS = 10_000;
|
|
8
|
+
// Runs a task while holding a lock file shared by every process using the wiki.
|
|
9
|
+
export async function withLock(root, task) {
|
|
10
|
+
const file = path.join(root, LOCK);
|
|
11
|
+
const deadline = Date.now() + WAIT_MS;
|
|
12
|
+
for (;;) {
|
|
13
|
+
try {
|
|
14
|
+
fs.writeFileSync(file, String(process.pid), { flag: "wx" });
|
|
15
|
+
break;
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
if (error.code !== "EEXIST")
|
|
19
|
+
throw error;
|
|
20
|
+
const held = fs.statSync(file, { throwIfNoEntry: false });
|
|
21
|
+
if (held && Date.now() - held.mtimeMs > STALE_MS) {
|
|
22
|
+
fs.rmSync(file, { force: true });
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
if (Date.now() > deadline)
|
|
26
|
+
throw new WikiError("The wiki is busy with another write. Try again.");
|
|
27
|
+
await sleep(25);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
try {
|
|
31
|
+
return await task();
|
|
32
|
+
}
|
|
33
|
+
finally {
|
|
34
|
+
fs.rmSync(file, { force: true });
|
|
35
|
+
}
|
|
36
|
+
}
|
package/dist/mcp.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
5
|
+
import { WikiError } from "./errors.js";
|
|
6
|
+
import { VERSION } from "./layout.js";
|
|
7
|
+
import { OPERATIONS, callOperation } from "./ops.js";
|
|
8
|
+
// Builds an MCP server exposing every operation as a tool.
|
|
9
|
+
export function createServer(wiki) {
|
|
10
|
+
const server = new McpServer({ name: "whywiki", version: VERSION }, { instructions: "Call read_rules before every task and follow it." });
|
|
11
|
+
for (const [name, op] of Object.entries(OPERATIONS)) {
|
|
12
|
+
server.registerTool(name, { description: op.description, inputSchema: op.input }, async (args) => {
|
|
13
|
+
try {
|
|
14
|
+
return { content: [{ type: "text", text: await callOperation(wiki, name, args) }] };
|
|
15
|
+
}
|
|
16
|
+
catch (error) {
|
|
17
|
+
return { content: [{ type: "text", text: error.message }], isError: true };
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
return server;
|
|
22
|
+
}
|
|
23
|
+
// Serves MCP over stdin/stdout.
|
|
24
|
+
export async function serveStdio(wiki) {
|
|
25
|
+
await createServer(wiki).connect(new StdioServerTransport());
|
|
26
|
+
}
|
|
27
|
+
// Serves stateless streamable HTTP MCP at /mcp on localhost, accepting only known Host headers.
|
|
28
|
+
export function serveHttp(wiki, port, allowHosts = []) {
|
|
29
|
+
const httpServer = http.createServer(async (req, res) => {
|
|
30
|
+
try {
|
|
31
|
+
if (!req.url?.startsWith("/mcp")) {
|
|
32
|
+
res.writeHead(404).end();
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
const { port: bound } = httpServer.address();
|
|
36
|
+
const server = createServer(wiki);
|
|
37
|
+
const transport = new StreamableHTTPServerTransport({
|
|
38
|
+
sessionIdGenerator: undefined,
|
|
39
|
+
enableDnsRebindingProtection: true,
|
|
40
|
+
allowedHosts: [`localhost:${bound}`, `127.0.0.1:${bound}`, ...allowHosts],
|
|
41
|
+
});
|
|
42
|
+
res.on("close", () => {
|
|
43
|
+
void transport.close();
|
|
44
|
+
void server.close();
|
|
45
|
+
});
|
|
46
|
+
await server.connect(transport);
|
|
47
|
+
await transport.handleRequest(req, res);
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
if (!res.headersSent)
|
|
51
|
+
res.writeHead(500, { "content-type": "text/plain" });
|
|
52
|
+
res.end(error.message);
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
return new Promise((resolve, reject) => {
|
|
56
|
+
httpServer.once("error", (error) => reject(error.code === "EADDRINUSE" ? new WikiError(`Port ${port} is already in use. Pick another with --port.`) : error));
|
|
57
|
+
httpServer.listen(port, "127.0.0.1", () => resolve(httpServer));
|
|
58
|
+
});
|
|
59
|
+
}
|
package/dist/ops.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { WikiError } from "./errors.js";
|
|
3
|
+
export const OPERATIONS = {
|
|
4
|
+
read_rules: {
|
|
5
|
+
description: "Read the wiki rules and house rules. Call before every task.",
|
|
6
|
+
input: {},
|
|
7
|
+
run: (w) => w.readRules(),
|
|
8
|
+
},
|
|
9
|
+
list_projects: {
|
|
10
|
+
description: "List projects with description and repos.",
|
|
11
|
+
input: {},
|
|
12
|
+
run: (w) => w.listProjects(),
|
|
13
|
+
},
|
|
14
|
+
find_project: {
|
|
15
|
+
description: "Find the project that lists a git remote URL. Returns null when none does.",
|
|
16
|
+
input: { remote: z.string() },
|
|
17
|
+
run: (w, a) => w.findProject(a.remote),
|
|
18
|
+
},
|
|
19
|
+
create_project: {
|
|
20
|
+
description: "Create a project folder for a repo.",
|
|
21
|
+
input: { name: z.string(), description: z.string().optional(), repos: z.array(z.string()).optional() },
|
|
22
|
+
run: (w, a) => w.createProject(a),
|
|
23
|
+
},
|
|
24
|
+
search: {
|
|
25
|
+
description: "Search pages by keywords. scope: all (default), main, or project:<name>.",
|
|
26
|
+
input: { query: z.string(), scope: z.string().optional() },
|
|
27
|
+
run: (w, a) => w.search(a.query, a.scope),
|
|
28
|
+
},
|
|
29
|
+
read_page: {
|
|
30
|
+
description: "Read a page by path relative to the wiki root, e.g. decisions/2026-10-31-use-git.",
|
|
31
|
+
input: { path: z.string() },
|
|
32
|
+
run: (w, a) => w.readPage(a.path),
|
|
33
|
+
},
|
|
34
|
+
write_page: {
|
|
35
|
+
description: "Write a page following templates/<type>.md; updates index and log and commits. type: topic, decision, dropped, open-loop, plan, house-rules. scope: main or project:<name>.",
|
|
36
|
+
input: { scope: z.string(), type: z.string(), slug: z.string(), summary: z.string(), content: z.string() },
|
|
37
|
+
run: (w, a) => w.writePage(a),
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
// Validates input, runs one operation, and formats its result as text.
|
|
41
|
+
export async function callOperation(wiki, name, args) {
|
|
42
|
+
const op = OPERATIONS[name];
|
|
43
|
+
if (!op)
|
|
44
|
+
throw new WikiError(`Unknown operation "${name}".`);
|
|
45
|
+
wiki.assertInitialized();
|
|
46
|
+
const parsed = z.object(op.input).strict().safeParse(args ?? {});
|
|
47
|
+
if (!parsed.success) {
|
|
48
|
+
throw new WikiError(parsed.error.issues.map((i) => `${i.path.join(".") || "input"}: ${i.message}`).join("; "));
|
|
49
|
+
}
|
|
50
|
+
const result = await op.run(wiki, parsed.data);
|
|
51
|
+
return typeof result === "string" ? result : JSON.stringify(result, null, 2);
|
|
52
|
+
}
|
package/dist/remote.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Normalizes https, ssh and scp-style git remotes to host/path.
|
|
2
|
+
export function normalizeRemote(url) {
|
|
3
|
+
let s = url.trim().toLowerCase();
|
|
4
|
+
const scp = /^(?:[^@/]+@)?([^:/]+):(?!\/)(.+)$/.exec(s);
|
|
5
|
+
if (!s.includes("://") && scp)
|
|
6
|
+
s = `${scp[1]}/${scp[2]}`;
|
|
7
|
+
else
|
|
8
|
+
s = s.replace(/^[a-z+]+:\/\//, "").replace(/^[^@/]+@/, "");
|
|
9
|
+
return s.replace(/\/+$/, "").replace(/\.git$/, "");
|
|
10
|
+
}
|
package/dist/wiki.js
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { WikiError } from "./errors.js";
|
|
4
|
+
import { parseFrontmatter, stringifyFrontmatter } from "./frontmatter.js";
|
|
5
|
+
import { commitFiles } from "./git.js";
|
|
6
|
+
import { DATED, FOLDER, INDEX_SECTION, MARKER, PAGE_TYPES, SLUG } from "./layout.js";
|
|
7
|
+
import { withLock } from "./lock.js";
|
|
8
|
+
import { normalizeRemote } from "./remote.js";
|
|
9
|
+
export class Wiki {
|
|
10
|
+
root;
|
|
11
|
+
now;
|
|
12
|
+
commit;
|
|
13
|
+
queue = Promise.resolve();
|
|
14
|
+
constructor(root, options = {}) {
|
|
15
|
+
this.root = root;
|
|
16
|
+
this.now = options.now ?? (() => new Date());
|
|
17
|
+
this.commit = options.commit ?? commitFiles;
|
|
18
|
+
}
|
|
19
|
+
// Throws unless the root was created by whywiki.
|
|
20
|
+
assertInitialized() {
|
|
21
|
+
if (!fs.existsSync(path.join(this.root, MARKER))) {
|
|
22
|
+
throw new WikiError(`No wiki at ${this.root}. Run "npx whywiki init" first.`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
// Returns RULES.md followed by house-rules.md.
|
|
26
|
+
readRules() {
|
|
27
|
+
return `${this.read("RULES.md").trimEnd()}\n\n${this.read("house-rules.md")}`;
|
|
28
|
+
}
|
|
29
|
+
// Lists projects sorted by name.
|
|
30
|
+
listProjects() {
|
|
31
|
+
const dir = path.join(this.root, "projects");
|
|
32
|
+
if (!fs.existsSync(dir))
|
|
33
|
+
return [];
|
|
34
|
+
return fs
|
|
35
|
+
.readdirSync(dir, { withFileTypes: true })
|
|
36
|
+
.filter((e) => e.isDirectory() && SLUG.test(e.name) && fs.existsSync(path.join(dir, e.name, "index.md")))
|
|
37
|
+
.map((e) => this.project(e.name))
|
|
38
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
39
|
+
}
|
|
40
|
+
// Returns the project listing the given git remote, or null.
|
|
41
|
+
findProject(remote) {
|
|
42
|
+
const wanted = normalizeRemote(remote);
|
|
43
|
+
return this.listProjects().find((p) => p.repos.some((r) => normalizeRemote(r) === wanted)) ?? null;
|
|
44
|
+
}
|
|
45
|
+
// Creates projects/<name>/ with the standard layout.
|
|
46
|
+
createProject(input) {
|
|
47
|
+
return this.exclusive(async () => {
|
|
48
|
+
const { name } = input;
|
|
49
|
+
if (!SLUG.test(name)) {
|
|
50
|
+
throw new WikiError(`Invalid project name "${name}". Use lowercase letters, digits and hyphens.`);
|
|
51
|
+
}
|
|
52
|
+
const dir = path.join(this.root, "projects", name);
|
|
53
|
+
if (fs.existsSync(dir))
|
|
54
|
+
throw new WikiError(`Project "${name}" already exists.`);
|
|
55
|
+
const project = { name, description: oneLine(input.description ?? "") || name, repos: input.repos ?? [] };
|
|
56
|
+
const mainIndex = this.abs("index.md");
|
|
57
|
+
const mainLog = this.abs("log.md");
|
|
58
|
+
const keeps = Object.values(FOLDER).map((folder) => path.join(dir, folder, ".gitkeep"));
|
|
59
|
+
const projectIndexFile = path.join(dir, "index.md");
|
|
60
|
+
const projectLog = path.join(dir, "log.md");
|
|
61
|
+
await this.transaction([mainIndex, mainLog, projectIndexFile, projectLog, ...keeps], `project: ${name} — created`, () => {
|
|
62
|
+
for (const keep of keeps) {
|
|
63
|
+
fs.mkdirSync(path.dirname(keep), { recursive: true });
|
|
64
|
+
fs.writeFileSync(keep, "");
|
|
65
|
+
}
|
|
66
|
+
fs.writeFileSync(projectIndexFile, projectIndex(project));
|
|
67
|
+
fs.writeFileSync(projectLog, `# ${name} log\n`);
|
|
68
|
+
upsertIndexLine(mainIndex, "Projects", `projects/${name}/index`, project.description);
|
|
69
|
+
this.appendLog(mainLog, "project", name, "created");
|
|
70
|
+
}, dir);
|
|
71
|
+
return project;
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
// Searches pages by keywords; scope is all, main or project:<name>.
|
|
75
|
+
search(query, scope = "all") {
|
|
76
|
+
const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
|
|
77
|
+
if (terms.length === 0)
|
|
78
|
+
throw new WikiError("Search query is empty.");
|
|
79
|
+
const scored = this.scopeFiles(scope).flatMap((rel) => {
|
|
80
|
+
const text = this.read(rel);
|
|
81
|
+
const lower = text.toLowerCase();
|
|
82
|
+
const found = terms.filter((t) => lower.includes(t));
|
|
83
|
+
if (found.length === 0)
|
|
84
|
+
return [];
|
|
85
|
+
const occurrences = found.reduce((n, t) => n + lower.split(t).length - 1, 0);
|
|
86
|
+
const line = text.split("\n").find((l) => found.some((t) => l.toLowerCase().includes(t))) ?? "";
|
|
87
|
+
return [{ score: found.length * 1000 + occurrences, hit: { path: rel, title: title(text, rel), excerpt: line.trim().slice(0, 200) } }];
|
|
88
|
+
});
|
|
89
|
+
return scored
|
|
90
|
+
.sort((a, b) => b.score - a.score || a.hit.path.localeCompare(b.hit.path))
|
|
91
|
+
.slice(0, 20)
|
|
92
|
+
.map((s) => s.hit);
|
|
93
|
+
}
|
|
94
|
+
// Returns a page's content by path relative to the root.
|
|
95
|
+
readPage(page) {
|
|
96
|
+
const rel = `${page.trim().replace(/^\[\[|\]\]$/g, "").replace(/^\/+/, "").replace(/\.md$/, "")}.md`;
|
|
97
|
+
const inside = path.relative(this.root, path.resolve(this.root, rel));
|
|
98
|
+
if (rel.split(/[\\/]/).some((part) => part === "" || part === ".." || part.startsWith(".")) ||
|
|
99
|
+
inside.startsWith("..") ||
|
|
100
|
+
path.isAbsolute(inside)) {
|
|
101
|
+
throw new WikiError(`Invalid page path "${page}".`);
|
|
102
|
+
}
|
|
103
|
+
if (!fs.existsSync(this.abs(rel)))
|
|
104
|
+
throw new WikiError(`Page "${rel}" not found.`);
|
|
105
|
+
return this.read(rel);
|
|
106
|
+
}
|
|
107
|
+
// Validates and writes a page, updates index and log, and commits.
|
|
108
|
+
writePage(input) {
|
|
109
|
+
return this.exclusive(async () => {
|
|
110
|
+
const prefix = this.scopePrefix(input.scope);
|
|
111
|
+
const summary = oneLine(input.summary);
|
|
112
|
+
if (!summary)
|
|
113
|
+
throw new WikiError("Summary is required.");
|
|
114
|
+
const logFile = this.abs(`${prefix}log.md`);
|
|
115
|
+
if (input.type === "house-rules") {
|
|
116
|
+
if (prefix !== "")
|
|
117
|
+
throw new WikiError('house-rules is main-only. Use scope "main".');
|
|
118
|
+
const file = this.abs("house-rules.md");
|
|
119
|
+
await this.transaction([file, logFile], `house-rules: ${summary}`, () => {
|
|
120
|
+
fs.writeFileSync(file, withNewline(input.content));
|
|
121
|
+
this.appendLog(logFile, "house-rules", "house-rules", summary);
|
|
122
|
+
});
|
|
123
|
+
return { path: "house-rules.md" };
|
|
124
|
+
}
|
|
125
|
+
if (!isPageType(input.type)) {
|
|
126
|
+
throw new WikiError(`Unknown type "${input.type}". Use one of: ${[...PAGE_TYPES, "house-rules"].join(", ")}.`);
|
|
127
|
+
}
|
|
128
|
+
const type = input.type;
|
|
129
|
+
if (!SLUG.test(input.slug.replace(DATED, ""))) {
|
|
130
|
+
throw new WikiError(`Invalid slug "${input.slug}". Use lowercase letters, digits and hyphens.`);
|
|
131
|
+
}
|
|
132
|
+
const name = this.pageName(type, prefix, input.slug);
|
|
133
|
+
const missing = this.requiredSections(type).filter((s) => !hasHeading(input.content, s));
|
|
134
|
+
if (missing.length > 0) {
|
|
135
|
+
throw new WikiError(`Missing sections for ${type}: ${missing.map((s) => `## ${s}`).join(", ")}.`);
|
|
136
|
+
}
|
|
137
|
+
const rel = `${prefix}${FOLDER[type]}/${name}.md`;
|
|
138
|
+
const file = this.abs(rel);
|
|
139
|
+
const indexFile = this.abs(`${prefix}index.md`);
|
|
140
|
+
await this.transaction([file, indexFile, logFile], `${type}: ${name} — ${summary}`, () => {
|
|
141
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
142
|
+
fs.writeFileSync(file, withNewline(input.content));
|
|
143
|
+
upsertIndexLine(indexFile, INDEX_SECTION[type], rel.replace(/\.md$/, ""), summary);
|
|
144
|
+
this.appendLog(logFile, type, name, summary);
|
|
145
|
+
});
|
|
146
|
+
return { path: rel };
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
pageName(type, prefix, slug) {
|
|
150
|
+
if (type === "topic" || DATED.test(slug))
|
|
151
|
+
return slug;
|
|
152
|
+
const dir = this.abs(`${prefix}${FOLDER[type]}`);
|
|
153
|
+
const existing = fs.existsSync(dir)
|
|
154
|
+
? fs.readdirSync(dir).find((f) => DATED.test(f) && f.replace(DATED, "") === `${slug}.md`)
|
|
155
|
+
: undefined;
|
|
156
|
+
if (existing) {
|
|
157
|
+
const dated = existing.replace(/\.md$/, "");
|
|
158
|
+
throw new WikiError(`A ${type} "${slug}" already exists at ${prefix}${FOLDER[type]}/${existing}. Pass slug "${dated}" to update it, or pick a new slug.`);
|
|
159
|
+
}
|
|
160
|
+
return `${this.today()}-${slug}`;
|
|
161
|
+
}
|
|
162
|
+
project(name) {
|
|
163
|
+
const { data } = parseFrontmatter(this.read(`projects/${name}/index.md`));
|
|
164
|
+
const repos = data.repos ?? [];
|
|
165
|
+
return {
|
|
166
|
+
name,
|
|
167
|
+
description: typeof data.description === "string" ? data.description : name,
|
|
168
|
+
repos: Array.isArray(repos) ? repos : [repos],
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
scopePrefix(scope) {
|
|
172
|
+
if (scope === "main")
|
|
173
|
+
return "";
|
|
174
|
+
const match = /^project:(.+)$/.exec(scope);
|
|
175
|
+
if (!match)
|
|
176
|
+
throw new WikiError(`Invalid scope "${scope}". Use "main" or "project:<name>".`);
|
|
177
|
+
const name = match[1];
|
|
178
|
+
if (!SLUG.test(name) || !fs.existsSync(this.abs(`projects/${name}/index.md`))) {
|
|
179
|
+
throw new WikiError(`Unknown project "${name}".`);
|
|
180
|
+
}
|
|
181
|
+
return `projects/${name}/`;
|
|
182
|
+
}
|
|
183
|
+
scopeFiles(scope) {
|
|
184
|
+
if (scope === "all") {
|
|
185
|
+
return [
|
|
186
|
+
...this.scopeFiles("main"),
|
|
187
|
+
...this.listProjects().flatMap((p) => this.scopeFiles(`project:${p.name}`)),
|
|
188
|
+
];
|
|
189
|
+
}
|
|
190
|
+
const prefix = this.scopePrefix(scope);
|
|
191
|
+
const top = prefix === "" ? ["index.md", "house-rules.md"] : ["index.md"];
|
|
192
|
+
const files = top.map((f) => `${prefix}${f}`).filter((rel) => fs.existsSync(this.abs(rel)));
|
|
193
|
+
for (const folder of Object.values(FOLDER)) {
|
|
194
|
+
const dir = this.abs(`${prefix}${folder}`);
|
|
195
|
+
if (!fs.existsSync(dir))
|
|
196
|
+
continue;
|
|
197
|
+
for (const f of fs.readdirSync(dir).filter((n) => n.endsWith(".md")).sort()) {
|
|
198
|
+
files.push(`${prefix}${folder}/${f}`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return files;
|
|
202
|
+
}
|
|
203
|
+
requiredSections(type) {
|
|
204
|
+
return this.read(`templates/${type}.md`)
|
|
205
|
+
.split("\n")
|
|
206
|
+
.map((l) => /^## (.+?)\s*$/.exec(l)?.[1])
|
|
207
|
+
.filter((s) => Boolean(s));
|
|
208
|
+
}
|
|
209
|
+
async transaction(files, message, change, createdDir) {
|
|
210
|
+
const before = files.map((f) => (fs.existsSync(f) ? fs.readFileSync(f, "utf8") : null));
|
|
211
|
+
try {
|
|
212
|
+
change();
|
|
213
|
+
await this.commit(this.root, files.map((f) => path.relative(this.root, f).split(path.sep).join("/")), message);
|
|
214
|
+
}
|
|
215
|
+
catch (error) {
|
|
216
|
+
files.forEach((f, i) => {
|
|
217
|
+
const old = before[i];
|
|
218
|
+
if (old === null)
|
|
219
|
+
fs.rmSync(f, { force: true });
|
|
220
|
+
else
|
|
221
|
+
fs.writeFileSync(f, old);
|
|
222
|
+
});
|
|
223
|
+
if (createdDir)
|
|
224
|
+
fs.rmSync(createdDir, { recursive: true, force: true });
|
|
225
|
+
throw error;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
exclusive(task) {
|
|
229
|
+
const locked = () => withLock(this.root, task);
|
|
230
|
+
const run = this.queue.then(locked, locked);
|
|
231
|
+
this.queue = run.catch(() => undefined);
|
|
232
|
+
return run;
|
|
233
|
+
}
|
|
234
|
+
appendLog(file, type, slug, summary) {
|
|
235
|
+
const current = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
|
|
236
|
+
fs.writeFileSync(file, `${current.trimEnd()}\n\n## [${this.today()}] ${type} | ${slug} — ${summary}\n`);
|
|
237
|
+
}
|
|
238
|
+
today() {
|
|
239
|
+
const d = this.now();
|
|
240
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
|
241
|
+
}
|
|
242
|
+
abs(rel) {
|
|
243
|
+
return path.join(this.root, ...rel.split("/"));
|
|
244
|
+
}
|
|
245
|
+
read(rel) {
|
|
246
|
+
return fs.readFileSync(this.abs(rel), "utf8");
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
function isPageType(type) {
|
|
250
|
+
return PAGE_TYPES.includes(type);
|
|
251
|
+
}
|
|
252
|
+
function hasHeading(content, section) {
|
|
253
|
+
return content.split("\n").some((l) => l.trim() === `## ${section}`);
|
|
254
|
+
}
|
|
255
|
+
function oneLine(text) {
|
|
256
|
+
return text.replace(/\s+/g, " ").trim();
|
|
257
|
+
}
|
|
258
|
+
function withNewline(text) {
|
|
259
|
+
return text.endsWith("\n") ? text : `${text}\n`;
|
|
260
|
+
}
|
|
261
|
+
function title(text, rel) {
|
|
262
|
+
return /^# (.+)$/m.exec(text)?.[1].trim() ?? rel;
|
|
263
|
+
}
|
|
264
|
+
function projectIndex(p) {
|
|
265
|
+
const sections = Object.values(INDEX_SECTION).map((s) => `## ${s}\n`).join("\n");
|
|
266
|
+
return `${stringifyFrontmatter({ project: p.name, description: p.description, repos: p.repos })}\n# ${p.name}\n\n${sections}`;
|
|
267
|
+
}
|
|
268
|
+
function upsertIndexLine(file, section, target, summary) {
|
|
269
|
+
const line = `- [[${target}]] — ${summary}`;
|
|
270
|
+
const lines = fs.readFileSync(file, "utf8").split("\n");
|
|
271
|
+
const existing = lines.findIndex((l) => l.startsWith(`- [[${target}]]`));
|
|
272
|
+
if (existing >= 0) {
|
|
273
|
+
lines[existing] = line;
|
|
274
|
+
}
|
|
275
|
+
else {
|
|
276
|
+
let heading = lines.findIndex((l) => l.trim() === `## ${section}`);
|
|
277
|
+
if (heading < 0) {
|
|
278
|
+
lines.push("", `## ${section}`);
|
|
279
|
+
heading = lines.length - 1;
|
|
280
|
+
}
|
|
281
|
+
lines.splice(heading + 1, 0, line);
|
|
282
|
+
}
|
|
283
|
+
fs.writeFileSync(file, lines.join("\n"));
|
|
284
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "whywiki",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A plain-markdown wiki that AI agents read before working and write when decisions happen",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"whywiki": "dist/bin.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist",
|
|
12
|
+
"assets"
|
|
13
|
+
],
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=20"
|
|
16
|
+
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsc -p tsconfig.json",
|
|
19
|
+
"test": "vitest run",
|
|
20
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
21
|
+
"prepublishOnly": "rm -rf dist && npm run build && npm test"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@modelcontextprotocol/sdk": "1.32.1",
|
|
25
|
+
"isomorphic-git": "1.44.2",
|
|
26
|
+
"zod": "4.6.7"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@types/node": "26.6.5",
|
|
30
|
+
"typescript": "7.0.2",
|
|
31
|
+
"vitest": "4.1.12"
|
|
32
|
+
},
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+https://github.com/aman-jaglan/whywiki.git"
|
|
36
|
+
},
|
|
37
|
+
"keywords": [
|
|
38
|
+
"ai",
|
|
39
|
+
"agents",
|
|
40
|
+
"wiki",
|
|
41
|
+
"mcp",
|
|
42
|
+
"claude",
|
|
43
|
+
"codex",
|
|
44
|
+
"chatgpt",
|
|
45
|
+
"decisions"
|
|
46
|
+
],
|
|
47
|
+
"homepage": "https://github.com/aman-jaglan/whywiki#readme",
|
|
48
|
+
"bugs": {
|
|
49
|
+
"url": "https://github.com/aman-jaglan/whywiki/issues"
|
|
50
|
+
},
|
|
51
|
+
"author": "Aman Jaglan"
|
|
52
|
+
}
|