whywiki 0.0.0-stage → 0.2.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 +137 -2
- package/assets/RULES.md +49 -0
- package/assets/house-rules.md +1 -0
- package/assets/index.md +15 -0
- package/assets/log.md +1 -0
- package/assets/templates/decision.md +18 -0
- package/assets/templates/dropped.md +11 -0
- package/assets/templates/meeting.md +13 -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 +30 -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 +286 -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,138 @@
|
|
|
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
|
+
**The logbook of all your work. No matter what you do.**
|
|
11
|
+
|
|
12
|
+
[](https://www.npmjs.com/package/whywiki)
|
|
13
|
+
[](LICENSE)
|
|
14
|
+
[](https://nodejs.org)
|
|
15
|
+
|
|
16
|
+
</div>
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
Code, meetings, trip plans, the pricing call you made in the shower. You do
|
|
21
|
+
the work. Your AI writes it down.
|
|
22
|
+
|
|
23
|
+
One folder of plain markdown at `~/wiki`, shared by every AI tool you use.
|
|
24
|
+
No account, no server, no app to open.
|
|
25
|
+
|
|
26
|
+
## Why
|
|
27
|
+
|
|
28
|
+
Agents now work alongside us. But the tools we use to log work were built for
|
|
29
|
+
humans, not for them.
|
|
30
|
+
|
|
31
|
+
The AI isn't bad. We are just bad at giving it the tools it needs to store its
|
|
32
|
+
own decisions. It can't remember its last ten sessions until someone builds
|
|
33
|
+
the place to keep them.
|
|
34
|
+
|
|
35
|
+
This is that place.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
npx whywiki init
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Done. Claude Code and Codex now read the logbook before every task and write
|
|
44
|
+
in it the moment something happens. Already have one? `npx whywiki@latest init`
|
|
45
|
+
upgrades it.
|
|
46
|
+
|
|
47
|
+
## What gets logged
|
|
48
|
+
|
|
49
|
+
| What happened | Where it goes |
|
|
50
|
+
|---|---|
|
|
51
|
+
| You picked one thing over another | `decisions/` |
|
|
52
|
+
| You tried it and it flopped | `dropped/` 🪦 |
|
|
53
|
+
| You said "always…", "never…", "from now on…" | `house-rules.md` |
|
|
54
|
+
| You're waiting on someone | `open-loops/` |
|
|
55
|
+
| You had a meeting | `meetings/` |
|
|
56
|
+
| How a thing works right now | `topics/` |
|
|
57
|
+
| A plan for one piece of work | `plans/` |
|
|
58
|
+
|
|
59
|
+
Nothing happened? Nothing gets written. You do zero bookkeeping.
|
|
60
|
+
|
|
61
|
+
Inside a code repo, pages go in that repo's own folder under `projects/`.
|
|
62
|
+
Anywhere else, they go in the main logbook. Search always covers everything,
|
|
63
|
+
and every change is a git commit you can read and undo.
|
|
64
|
+
|
|
65
|
+
## Meetings land here too
|
|
66
|
+
|
|
67
|
+
Connect your notes tool to your AI: Granola, Notion, Claude, Fireflies, Otter,
|
|
68
|
+
anything it can reach over MCP. Before each task, the AI fetches the meetings
|
|
69
|
+
it hasn't logged yet and files a short page for each one: summary, decisions,
|
|
70
|
+
action items, who was there.
|
|
71
|
+
|
|
72
|
+
A decision made in the room also becomes its own decision page. So the coding
|
|
73
|
+
session the next morning already knows what the meeting agreed.
|
|
74
|
+
|
|
75
|
+
Summaries only. Transcripts never go in.
|
|
76
|
+
|
|
77
|
+
## Works with
|
|
78
|
+
|
|
79
|
+
| Tool | Setup |
|
|
80
|
+
|---|---|
|
|
81
|
+
| **Claude Code**, **Codex** | Done by `init` |
|
|
82
|
+
| **Cursor** | Paste the one line `init` prints, or use MCP |
|
|
83
|
+
| **Claude desktop** | MCP |
|
|
84
|
+
| **ChatGPT** | MCP over HTTP |
|
|
85
|
+
|
|
86
|
+
```json
|
|
87
|
+
{ "mcpServers": { "whywiki": { "command": "npx", "args": ["-y", "whywiki", "serve"] } } }
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
ChatGPT only talks to servers on the internet. Run the HTTP server behind an
|
|
91
|
+
HTTPS tunnel you trust and pass the tunnel's hostname:
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
npx -y whywiki serve --http --allow-host your-tunnel.example.com
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
It listens on localhost only and rejects every other hostname.
|
|
98
|
+
|
|
99
|
+
> ⚠️ Anyone with the tunnel URL can read and write your logbook. Treat it like a password.
|
|
100
|
+
|
|
101
|
+
<details>
|
|
102
|
+
<summary><b>All commands</b> (mostly for the AI)</summary>
|
|
103
|
+
|
|
104
|
+
```
|
|
105
|
+
whywiki <command> [--root <path>]
|
|
106
|
+
|
|
107
|
+
init create ~/wiki and wire Claude Code and Codex
|
|
108
|
+
serve [--http] [--port 3333] [--allow-host <host>]...
|
|
109
|
+
run the MCP server (stdio by default; --http
|
|
110
|
+
listens on localhost, --allow-host adds a tunnel host)
|
|
111
|
+
rules print the rules and house rules
|
|
112
|
+
projects list projects
|
|
113
|
+
find-project <remote> find the project for a git remote
|
|
114
|
+
create-project <name> [--description <text>] [--repo <remote>]...
|
|
115
|
+
search <query...> [--scope all|main|project:<name>]
|
|
116
|
+
read <path>
|
|
117
|
+
write --scope <scope> --type <type> --slug <slug> --summary <text> [--file <path>]
|
|
118
|
+
page content comes from --file or stdin
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
`--root` or `$WHYWIKI_ROOT` points at a logbook other than `~/wiki`.
|
|
122
|
+
|
|
123
|
+
</details>
|
|
124
|
+
|
|
125
|
+
## FAQ
|
|
126
|
+
|
|
127
|
+
**Can I edit it?** Read it, browse it, open it in Obsidian. To change it, ask
|
|
128
|
+
the AI, so the index, log and git history stay in sync.
|
|
129
|
+
|
|
130
|
+
**My AI skipped the logbook once.** AIs are AIs. If it keeps happening, say
|
|
131
|
+
"from now on…" and it lands in `house-rules.md`.
|
|
132
|
+
|
|
133
|
+
**How do I uninstall?** Delete `~/wiki` and the marked `whywiki` block in your
|
|
134
|
+
agent's instructions file.
|
|
135
|
+
|
|
136
|
+
## License
|
|
137
|
+
|
|
138
|
+
MIT.
|
package/assets/RULES.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
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
|
+
5. Meeting-notes tool connected (Granola, Notion, Claude, Fireflies, Otter, any other) → fetch meetings newer than the newest `meetings/` line in `index.md`; none yet → last 7 days. Write each as a `meeting`.
|
|
17
|
+
|
|
18
|
+
## Write when
|
|
19
|
+
- Choice made → `decision`
|
|
20
|
+
- Approach abandoned → `dropped`
|
|
21
|
+
- Rule set → `house-rules`
|
|
22
|
+
- Term defined → `topic`
|
|
23
|
+
- Wiki contradicted → update `topic`, supersede old page
|
|
24
|
+
- Blocked on outside condition → `open-loop`
|
|
25
|
+
- Meeting held or meeting notes shared → `meeting`
|
|
26
|
+
|
|
27
|
+
Write in the same response. No trigger → write nothing.
|
|
28
|
+
|
|
29
|
+
## How
|
|
30
|
+
- Write only with `write` (MCP `write_page`). Never edit wiki files directly.
|
|
31
|
+
- Content follows `templates/<type>.md` with every `##` section.
|
|
32
|
+
- Update a dated page by passing its full dated slug.
|
|
33
|
+
- Topic page is current truth. Rewrite it whole. No changelog.
|
|
34
|
+
- Every `decision`, `dropped` or `open-loop` also updates its topic page and links it there.
|
|
35
|
+
- Replaced decision: set `superseded_by` or `superseded_in_part_by` on it. Never delete.
|
|
36
|
+
- Never leave two pages claiming current truth.
|
|
37
|
+
- Unproven → topic's Open questions.
|
|
38
|
+
- Closed open loop: `status: closed` + Resolution. Never delete.
|
|
39
|
+
- Plans are not current truth.
|
|
40
|
+
- `meeting`: scope `main`, slug `<meeting-date>-<title>`. Summarize; record `source` and `attendees`.
|
|
41
|
+
- Every choice, abandoned approach or blocker in a meeting also gets its own page in the project it is about, else `main`, linked from the meeting.
|
|
42
|
+
- `house-rules`: write the whole file, scope `main`.
|
|
43
|
+
|
|
44
|
+
## Format
|
|
45
|
+
- Slugs: lowercase-hyphenated. Dated types get `YYYY-MM-DD-` automatically.
|
|
46
|
+
- Links: `[[path]]` without `.md`.
|
|
47
|
+
|
|
48
|
+
## Never write
|
|
49
|
+
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,30 @@
|
|
|
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", "meeting"];
|
|
6
|
+
export const FOLDER = {
|
|
7
|
+
topic: "topics",
|
|
8
|
+
decision: "decisions",
|
|
9
|
+
dropped: "dropped",
|
|
10
|
+
"open-loop": "open-loops",
|
|
11
|
+
plan: "plans",
|
|
12
|
+
meeting: "meetings",
|
|
13
|
+
};
|
|
14
|
+
export const INDEX_SECTION = {
|
|
15
|
+
topic: "Topics",
|
|
16
|
+
decision: "Decisions",
|
|
17
|
+
dropped: "Dropped",
|
|
18
|
+
"open-loop": "Open loops",
|
|
19
|
+
plan: "Plans",
|
|
20
|
+
meeting: "Meetings",
|
|
21
|
+
};
|
|
22
|
+
export const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
23
|
+
export const DATED = /^\d{4}-\d{2}-\d{2}-/;
|
|
24
|
+
export const MARKER = ".whywiki";
|
|
25
|
+
export const ASSETS_DIR = fileURLToPath(new URL("../assets/", import.meta.url));
|
|
26
|
+
export const VERSION = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
27
|
+
// Resolves the wiki folder from $WHYWIKI_ROOT or ~/wiki.
|
|
28
|
+
export function defaultRoot(env, home = os.homedir()) {
|
|
29
|
+
return env.WHYWIKI_ROOT ? path.resolve(env.WHYWIKI_ROOT) : path.join(home, "wiki");
|
|
30
|
+
}
|
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, meeting, 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,286 @@
|
|
|
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 (type === "meeting" && prefix !== "")
|
|
130
|
+
throw new WikiError('meeting is main-only. Use scope "main".');
|
|
131
|
+
if (!SLUG.test(input.slug.replace(DATED, ""))) {
|
|
132
|
+
throw new WikiError(`Invalid slug "${input.slug}". Use lowercase letters, digits and hyphens.`);
|
|
133
|
+
}
|
|
134
|
+
const name = this.pageName(type, prefix, input.slug);
|
|
135
|
+
const missing = this.requiredSections(type).filter((s) => !hasHeading(input.content, s));
|
|
136
|
+
if (missing.length > 0) {
|
|
137
|
+
throw new WikiError(`Missing sections for ${type}: ${missing.map((s) => `## ${s}`).join(", ")}.`);
|
|
138
|
+
}
|
|
139
|
+
const rel = `${prefix}${FOLDER[type]}/${name}.md`;
|
|
140
|
+
const file = this.abs(rel);
|
|
141
|
+
const indexFile = this.abs(`${prefix}index.md`);
|
|
142
|
+
await this.transaction([file, indexFile, logFile], `${type}: ${name} — ${summary}`, () => {
|
|
143
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
144
|
+
fs.writeFileSync(file, withNewline(input.content));
|
|
145
|
+
upsertIndexLine(indexFile, INDEX_SECTION[type], rel.replace(/\.md$/, ""), summary);
|
|
146
|
+
this.appendLog(logFile, type, name, summary);
|
|
147
|
+
});
|
|
148
|
+
return { path: rel };
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
pageName(type, prefix, slug) {
|
|
152
|
+
if (type === "topic" || DATED.test(slug))
|
|
153
|
+
return slug;
|
|
154
|
+
const dir = this.abs(`${prefix}${FOLDER[type]}`);
|
|
155
|
+
const existing = fs.existsSync(dir)
|
|
156
|
+
? fs.readdirSync(dir).find((f) => DATED.test(f) && f.replace(DATED, "") === `${slug}.md`)
|
|
157
|
+
: undefined;
|
|
158
|
+
if (existing) {
|
|
159
|
+
const dated = existing.replace(/\.md$/, "");
|
|
160
|
+
throw new WikiError(`A ${type} "${slug}" already exists at ${prefix}${FOLDER[type]}/${existing}. Pass slug "${dated}" to update it, or pick a new slug.`);
|
|
161
|
+
}
|
|
162
|
+
return `${this.today()}-${slug}`;
|
|
163
|
+
}
|
|
164
|
+
project(name) {
|
|
165
|
+
const { data } = parseFrontmatter(this.read(`projects/${name}/index.md`));
|
|
166
|
+
const repos = data.repos ?? [];
|
|
167
|
+
return {
|
|
168
|
+
name,
|
|
169
|
+
description: typeof data.description === "string" ? data.description : name,
|
|
170
|
+
repos: Array.isArray(repos) ? repos : [repos],
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
scopePrefix(scope) {
|
|
174
|
+
if (scope === "main")
|
|
175
|
+
return "";
|
|
176
|
+
const match = /^project:(.+)$/.exec(scope);
|
|
177
|
+
if (!match)
|
|
178
|
+
throw new WikiError(`Invalid scope "${scope}". Use "main" or "project:<name>".`);
|
|
179
|
+
const name = match[1];
|
|
180
|
+
if (!SLUG.test(name) || !fs.existsSync(this.abs(`projects/${name}/index.md`))) {
|
|
181
|
+
throw new WikiError(`Unknown project "${name}".`);
|
|
182
|
+
}
|
|
183
|
+
return `projects/${name}/`;
|
|
184
|
+
}
|
|
185
|
+
scopeFiles(scope) {
|
|
186
|
+
if (scope === "all") {
|
|
187
|
+
return [
|
|
188
|
+
...this.scopeFiles("main"),
|
|
189
|
+
...this.listProjects().flatMap((p) => this.scopeFiles(`project:${p.name}`)),
|
|
190
|
+
];
|
|
191
|
+
}
|
|
192
|
+
const prefix = this.scopePrefix(scope);
|
|
193
|
+
const top = prefix === "" ? ["index.md", "house-rules.md"] : ["index.md"];
|
|
194
|
+
const files = top.map((f) => `${prefix}${f}`).filter((rel) => fs.existsSync(this.abs(rel)));
|
|
195
|
+
for (const folder of Object.values(FOLDER)) {
|
|
196
|
+
const dir = this.abs(`${prefix}${folder}`);
|
|
197
|
+
if (!fs.existsSync(dir))
|
|
198
|
+
continue;
|
|
199
|
+
for (const f of fs.readdirSync(dir).filter((n) => n.endsWith(".md")).sort()) {
|
|
200
|
+
files.push(`${prefix}${folder}/${f}`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return files;
|
|
204
|
+
}
|
|
205
|
+
requiredSections(type) {
|
|
206
|
+
return this.read(`templates/${type}.md`)
|
|
207
|
+
.split("\n")
|
|
208
|
+
.map((l) => /^## (.+?)\s*$/.exec(l)?.[1])
|
|
209
|
+
.filter((s) => Boolean(s));
|
|
210
|
+
}
|
|
211
|
+
async transaction(files, message, change, createdDir) {
|
|
212
|
+
const before = files.map((f) => (fs.existsSync(f) ? fs.readFileSync(f, "utf8") : null));
|
|
213
|
+
try {
|
|
214
|
+
change();
|
|
215
|
+
await this.commit(this.root, files.map((f) => path.relative(this.root, f).split(path.sep).join("/")), message);
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
files.forEach((f, i) => {
|
|
219
|
+
const old = before[i];
|
|
220
|
+
if (old === null)
|
|
221
|
+
fs.rmSync(f, { force: true });
|
|
222
|
+
else
|
|
223
|
+
fs.writeFileSync(f, old);
|
|
224
|
+
});
|
|
225
|
+
if (createdDir)
|
|
226
|
+
fs.rmSync(createdDir, { recursive: true, force: true });
|
|
227
|
+
throw error;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
exclusive(task) {
|
|
231
|
+
const locked = () => withLock(this.root, task);
|
|
232
|
+
const run = this.queue.then(locked, locked);
|
|
233
|
+
this.queue = run.catch(() => undefined);
|
|
234
|
+
return run;
|
|
235
|
+
}
|
|
236
|
+
appendLog(file, type, slug, summary) {
|
|
237
|
+
const current = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
|
|
238
|
+
fs.writeFileSync(file, `${current.trimEnd()}\n\n## [${this.today()}] ${type} | ${slug} — ${summary}\n`);
|
|
239
|
+
}
|
|
240
|
+
today() {
|
|
241
|
+
const d = this.now();
|
|
242
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
|
243
|
+
}
|
|
244
|
+
abs(rel) {
|
|
245
|
+
return path.join(this.root, ...rel.split("/"));
|
|
246
|
+
}
|
|
247
|
+
read(rel) {
|
|
248
|
+
return fs.readFileSync(this.abs(rel), "utf8");
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
function isPageType(type) {
|
|
252
|
+
return PAGE_TYPES.includes(type);
|
|
253
|
+
}
|
|
254
|
+
function hasHeading(content, section) {
|
|
255
|
+
return content.split("\n").some((l) => l.trim() === `## ${section}`);
|
|
256
|
+
}
|
|
257
|
+
function oneLine(text) {
|
|
258
|
+
return text.replace(/\s+/g, " ").trim();
|
|
259
|
+
}
|
|
260
|
+
function withNewline(text) {
|
|
261
|
+
return text.endsWith("\n") ? text : `${text}\n`;
|
|
262
|
+
}
|
|
263
|
+
function title(text, rel) {
|
|
264
|
+
return /^# (.+)$/m.exec(text)?.[1].trim() ?? rel;
|
|
265
|
+
}
|
|
266
|
+
function projectIndex(p) {
|
|
267
|
+
const sections = Object.values(INDEX_SECTION).map((s) => `## ${s}\n`).join("\n");
|
|
268
|
+
return `${stringifyFrontmatter({ project: p.name, description: p.description, repos: p.repos })}\n# ${p.name}\n\n${sections}`;
|
|
269
|
+
}
|
|
270
|
+
function upsertIndexLine(file, section, target, summary) {
|
|
271
|
+
const line = `- [[${target}]] — ${summary}`;
|
|
272
|
+
const lines = fs.readFileSync(file, "utf8").split("\n");
|
|
273
|
+
const existing = lines.findIndex((l) => l.startsWith(`- [[${target}]]`));
|
|
274
|
+
if (existing >= 0) {
|
|
275
|
+
lines[existing] = line;
|
|
276
|
+
}
|
|
277
|
+
else {
|
|
278
|
+
let heading = lines.findIndex((l) => l.trim() === `## ${section}`);
|
|
279
|
+
if (heading < 0) {
|
|
280
|
+
lines.push("", `## ${section}`);
|
|
281
|
+
heading = lines.length - 1;
|
|
282
|
+
}
|
|
283
|
+
lines.splice(heading + 1, 0, line);
|
|
284
|
+
}
|
|
285
|
+
fs.writeFileSync(file, lines.join("\n"));
|
|
286
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "whywiki",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "The logbook of all your work: plain markdown that AI agents read before working and write as things 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
|
+
}
|