connore 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Abhinay
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,46 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # connore
2
+
3
+ Local context folder for AI coding agents. `.ctx/` is plain markdown and images. The agent reads `INDEX.md` and opens only the rows that match the task.
4
+
5
+ The command is `connore`. This package used to be published as `ctxfiles`.
6
+
7
+ ## Install
8
+
9
+ ```
10
+ npm install -g connore
11
+ connore init
12
+ ```
13
+
14
+ Or without installing:
15
+
16
+ ```
17
+ npx connore init
18
+ ```
19
+
20
+ Use a global install before `connore init --hooks`. The Claude Code hook runs `connore hook`, which has to be on the PATH.
21
+
22
+ ## Commands
23
+
24
+ ```
25
+ connore init [--tools all|claude,cursor,codex,copilot,windsurf,gemini] [--pack frontend] [--hooks] [--dry-run]
26
+ connore add <path> [--type t] [--tags a,b] [--dry-run]
27
+ connore update [--pack frontend] [--dry-run]
28
+ connore list
29
+ connore index [--dry-run]
30
+ connore hook
31
+ ```
32
+
33
+ `init` copies `packs/frontend` into `.ctx/library/`, creates `mine/` and `inbox/`, and patches instruction files. With no tool detected it writes `CLAUDE.md` and `AGENTS.md`.
34
+
35
+ `update` makes `library/` match the pack. It never changes `mine/` or `inbox/`.
36
+
37
+ ## Publish
38
+
39
+ From this repo, after `npm login`:
40
+
41
+ ```
42
+ npm test
43
+ npm publish --access public
44
+ ```
45
+
46
+ `prepublishOnly` runs the tests again. The tarball is the CLI and `packs/frontend` only. The local `.ctx/` screenshot library is not part of the package.
package/bin/ctxkit.js ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ import { run } from "../src/cli.js"
3
+
4
+ const code = await run(process.argv.slice(2))
5
+ process.exit(code)
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
- {
2
- "name": "connore",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "connore",
3
+ "version": "0.1.0",
4
+ "description": "Local context folder for AI coding agents",
5
+ "license": "MIT",
6
+ "author": "Abhinay",
7
+ "type": "module",
8
+ "bin": {
9
+ "connore": "./bin/ctxkit.js"
10
+ },
11
+ "files": [
12
+ "bin/ctxkit.js",
13
+ "src",
14
+ "packs",
15
+ "LICENSE",
16
+ "README.md"
17
+ ],
18
+ "engines": {
19
+ "node": ">=18"
20
+ },
21
+ "scripts": {
22
+ "test": "node --test",
23
+ "prepublishOnly": "node --test"
24
+ },
25
+ "keywords": [
26
+ "ai",
27
+ "claude",
28
+ "cursor",
29
+ "codex",
30
+ "context",
31
+ "cli"
32
+ ]
33
+ }
@@ -0,0 +1,25 @@
1
+ ---
2
+ title: Button
3
+ type: component
4
+ tags: [shadcn, button]
5
+ source: library
6
+ updated: 2026-11-19
7
+ description: Usage note for a button. Install the real component from shadcn.
8
+ ---
9
+
10
+ # Button
11
+
12
+ Install the code in the app. This pack does not vendor it.
13
+
14
+ ```
15
+ npx shadcn@latest add button
16
+ ```
17
+
18
+ ## Props
19
+ TODO. Read the generated file for variant and size.
20
+
21
+ ## When
22
+ The one primary action in a group. TODO: which variant is the default in this theme.
23
+
24
+ ## Example
25
+ TODO
@@ -0,0 +1,25 @@
1
+ ---
2
+ title: Card
3
+ type: component
4
+ tags: [shadcn, card]
5
+ source: library
6
+ updated: 2026-11-19
7
+ description: Usage note for a card. Install the real component from shadcn.
8
+ ---
9
+
10
+ # Card
11
+
12
+ Install the code in the app. This pack does not vendor it.
13
+
14
+ ```
15
+ npx shadcn@latest add card
16
+ ```
17
+
18
+ ## Props
19
+ TODO. Read the generated file for header, content, and footer slots.
20
+
21
+ ## When
22
+ A titled group of related content. TODO: radius and border for this theme.
23
+
24
+ ## Example
25
+ TODO
@@ -0,0 +1,25 @@
1
+ ---
2
+ title: Input
3
+ type: component
4
+ tags: [shadcn, input]
5
+ source: library
6
+ updated: 2026-11-19
7
+ description: Usage note for an input. Install the real component from shadcn.
8
+ ---
9
+
10
+ # Input
11
+
12
+ Install the code in the app. This pack does not vendor it.
13
+
14
+ ```
15
+ npx shadcn@latest add input
16
+ ```
17
+
18
+ ## Props
19
+ TODO. Read the generated file. Pair it with a label.
20
+
21
+ ## When
22
+ A single-line value. TODO: height, radius, and focus ring.
23
+
24
+ ## Example
25
+ TODO
@@ -0,0 +1,24 @@
1
+ ---
2
+ title: Design rules
3
+ type: rule
4
+ tags: [always, never]
5
+ source: library
6
+ updated: 2026-11-19
7
+ description: Five always rules and five never rules for the starter pack.
8
+ ---
9
+
10
+ # Rules
11
+
12
+ ## Always
13
+ 1. Always read the text spec before opening a screenshot.
14
+ 2. Always use the hex values in design/tokens.md. A TODO there means the value is unknown.
15
+ 3. Always use one accent color per screen.
16
+ 4. Always use the spacing scale in design/tokens.md.
17
+ 5. Always keep motion to the duration and easing in design/tokens.md.
18
+
19
+ ## Never
20
+ 1. Never invent a color, font, radius, or shadow that is still TODO.
21
+ 2. Never load the whole .ctx folder. Open only the index rows for the task.
22
+ 3. Never edit files in library/. Put your own notes in mine/.
23
+ 4. Never add a second accent hue on the same screen.
24
+ 5. Never skip a component's usage note and paste in an unstated variant.
@@ -0,0 +1,40 @@
1
+ ---
2
+ title: Design tokens
3
+ type: design-token
4
+ tags: [color, type, spacing, radius, shadow, motion]
5
+ source: library
6
+ updated: 2026-11-19
7
+ description: Placeholder color, type, spacing, radius, shadow, and motion tokens.
8
+ ---
9
+
10
+ # Tokens
11
+
12
+ Replace every TODO with a measured value. Do not invent one.
13
+
14
+ ## Colors
15
+ - background: TODO
16
+ - foreground: TODO
17
+ - muted: TODO
18
+ - accent: TODO
19
+ - destructive: TODO
20
+
21
+ ## Type
22
+ - sans: TODO
23
+ - mono: TODO
24
+ - body: TODO size
25
+ - heading: TODO size
26
+
27
+ ## Spacing
28
+ TODO scale. Example steps to fill in: 4, 8, 12, 16, 24, 32.
29
+
30
+ ## Radius
31
+ - sm: TODO
32
+ - md: TODO
33
+ - lg: TODO
34
+
35
+ ## Shadows
36
+ TODO. Write the full CSS value, including color and blur.
37
+
38
+ ## Motion
39
+ - duration: TODO
40
+ - easing: TODO
package/src/cli.js ADDED
@@ -0,0 +1,90 @@
1
+ import { add } from "./commands/add.js"
2
+ import { printIndex } from "./commands/hook.js"
3
+ import { init } from "./commands/init.js"
4
+ import { list } from "./commands/list.js"
5
+ import { reindex } from "./commands/reindex.js"
6
+ import { update } from "./commands/update.js"
7
+ import { createReport } from "./lib/report.js"
8
+
9
+ const USAGE = `connore <command> [options]
10
+
11
+ init [--tools all|claude,cursor,codex,copilot,windsurf,gemini] [--pack frontend] [--hooks] [--dry-run]
12
+ add <path> [--type t] [--tags a,b] [--dry-run]
13
+ update [--pack frontend] [--dry-run]
14
+ list
15
+ index [--dry-run]
16
+ hook
17
+ `
18
+
19
+ function parse(argv) {
20
+ const flags = { dryRun: false, hooks: false }
21
+ const positionals = []
22
+ for (let index = 0; index < argv.length; index += 1) {
23
+ const arg = argv[index]
24
+ if (arg === "--dry-run") flags.dryRun = true
25
+ else if (arg === "--hooks") flags.hooks = true
26
+ else if (arg === "--tools" || arg === "--pack" || arg === "--type" || arg === "--tags") {
27
+ const value = argv[index + 1]
28
+ if (!value || value.startsWith("--")) throw new Error(`Missing value for ${arg}.`)
29
+ flags[arg.slice(2)] = value
30
+ index += 1
31
+ } else if (arg.startsWith("--")) throw new Error(`Unknown flag ${arg}.`)
32
+ else positionals.push(arg)
33
+ }
34
+ return { command: positionals[0], args: positionals.slice(1), flags }
35
+ }
36
+
37
+ export async function run(argv, io = {}) {
38
+ const stdout = io.stdout || process.stdout
39
+ const stderr = io.stderr || process.stderr
40
+ const cwd = io.cwd || process.cwd()
41
+ try {
42
+ const { command, args, flags } = parse(argv)
43
+ if (!command) {
44
+ stdout.write(USAGE)
45
+ return 1
46
+ }
47
+ const report = createReport(flags.dryRun)
48
+ if (command === "init") {
49
+ if (args.length) throw new Error("init does not take a path. Run it inside the project.")
50
+ await init(cwd, flags, report)
51
+ report.print(stdout)
52
+ return 0
53
+ }
54
+ if (flags.hooks) throw new Error("--hooks is only valid with init.")
55
+ if (flags.tools) throw new Error("--tools is only valid with init.")
56
+ if (command === "add") {
57
+ if (flags.pack) throw new Error("--pack is only valid with init and update.")
58
+ if (args.length !== 1) throw new Error("Usage: connore add <path>.")
59
+ await add(cwd, args[0], flags, report)
60
+ report.print(stdout)
61
+ return 0
62
+ }
63
+ if (flags.type || flags.tags) throw new Error("--type and --tags are only valid with add.")
64
+ if (command === "update") {
65
+ if (args.length) throw new Error("update does not take a path.")
66
+ await update(cwd, flags, report)
67
+ report.print(stdout)
68
+ return 0
69
+ }
70
+ if (flags.pack) throw new Error("--pack is only valid with init and update.")
71
+ if (command === "list") {
72
+ await list(cwd, stdout)
73
+ if (flags.dryRun) report.print(stdout)
74
+ return 0
75
+ }
76
+ if (command === "index") {
77
+ await reindex(cwd, report)
78
+ report.print(stdout)
79
+ return 0
80
+ }
81
+ if (command === "hook") {
82
+ await printIndex(cwd, stdout)
83
+ return 0
84
+ }
85
+ throw new Error(`Unknown command "${command}".`)
86
+ } catch (error) {
87
+ stderr.write(`${error.message}\n`)
88
+ return 1
89
+ }
90
+ }
@@ -0,0 +1,57 @@
1
+ import { readFile, stat } from "node:fs/promises"
2
+ import { basename, join, relative, resolve } from "node:path"
3
+ import { readOptional, walkFiles, writeAtomic } from "../lib/fs-safe.js"
4
+ import { twinStub, today } from "../lib/frontmatter.js"
5
+ import { rebuildIndex } from "../lib/index.js"
6
+ import { ctxPath, fromRoot } from "../lib/paths.js"
7
+
8
+ const TYPES = new Set(["design-token", "component", "rule", "screenshot", "flow", "doc"])
9
+ const IMAGE = /\.(png|jpe?g|webp|gif|svg)$/i
10
+ const CODE = /\.(tsx|jsx|ts|js|mjs|cjs|css)$/i
11
+
12
+ function defaultType(name) {
13
+ if (IMAGE.test(name)) return "screenshot"
14
+ if (CODE.test(name)) return "component"
15
+ return null
16
+ }
17
+
18
+ async function placeFile(source, target, root, flags, report) {
19
+ const display = fromRoot(root, target)
20
+ if (await readOptional(target)) report.add("skipped", display)
21
+ else {
22
+ if (!report.dryRun) await writeAtomic(target, await readFile(source))
23
+ report.add("created", display)
24
+ }
25
+ const type = flags.type || defaultType(basename(target))
26
+ if (!type || target.endsWith(".md")) return
27
+ const twin = target.replace(/\.[^.]+$/, ".md")
28
+ const twinDisplay = fromRoot(root, twin)
29
+ if (await readOptional(twin)) {
30
+ report.add("skipped", twinDisplay)
31
+ return
32
+ }
33
+ const tags = flags.tags ? flags.tags.split(",").map((tag) => tag.trim()).filter(Boolean) : []
34
+ const body = twinStub({ title: basename(twin, ".md"), type, tags, date: today() })
35
+ if (!report.dryRun) await writeAtomic(twin, body)
36
+ report.add("created", twinDisplay)
37
+ }
38
+
39
+ export async function add(root, sourceArg, flags, report) {
40
+ if (flags.type && !TYPES.has(flags.type)) throw new Error(`Unknown type "${flags.type}".`)
41
+ if (!(await readOptional(join(root, ".ctx", "INDEX.md"))) && !(await readOptional(join(root, ".ctx", "PROCESS.md")))) {
42
+ throw new Error("No .ctx/ folder. Run connore init first.")
43
+ }
44
+ const source = resolve(root, sourceArg)
45
+ let info
46
+ try {
47
+ info = await stat(source)
48
+ } catch {
49
+ throw new Error(`Cannot read ${sourceArg}.`)
50
+ }
51
+ const mine = ctxPath(root, "mine")
52
+ if (info.isDirectory()) {
53
+ const files = await walkFiles(source)
54
+ for (const file of files) await placeFile(file, join(mine, basename(source), relative(source, file)), root, flags, report)
55
+ } else await placeFile(source, join(mine, basename(source)), root, flags, report)
56
+ await rebuildIndex(root, report)
57
+ }
@@ -0,0 +1,50 @@
1
+ import { join } from "node:path"
2
+ import { readOptional, writeAtomic } from "../lib/fs-safe.js"
3
+
4
+ export const HOOK_COMMAND = "connore hook"
5
+
6
+ export function mergeHookSettings(settings) {
7
+ const hooks = settings.hooks && typeof settings.hooks === "object" && !Array.isArray(settings.hooks) ? settings.hooks : {}
8
+ const session = Array.isArray(hooks.SessionStart) ? hooks.SessionStart : []
9
+ const present = session.some((group) => Array.isArray(group?.hooks) && group.hooks.some((hook) => hook?.command === HOOK_COMMAND))
10
+ if (present) return { changed: false, settings }
11
+ return {
12
+ changed: true,
13
+ settings: {
14
+ ...settings,
15
+ hooks: {
16
+ ...hooks,
17
+ SessionStart: [...session, { hooks: [{ type: "command", command: HOOK_COMMAND }] }],
18
+ },
19
+ },
20
+ }
21
+ }
22
+
23
+ export async function installHook(root, report) {
24
+ const file = join(root, ".claude", "settings.json")
25
+ const current = await readOptional(file)
26
+ let json = {}
27
+ if (current) {
28
+ try {
29
+ json = JSON.parse(current.toString("utf8"))
30
+ } catch {
31
+ throw new Error(".claude/settings.json is not valid JSON, so it was left untouched.")
32
+ }
33
+ if (!json || typeof json !== "object" || Array.isArray(json)) {
34
+ throw new Error(".claude/settings.json must be a JSON object.")
35
+ }
36
+ }
37
+ const merged = mergeHookSettings(json)
38
+ const display = ".claude/settings.json"
39
+ if (!merged.changed) {
40
+ report.add("skipped", display)
41
+ return
42
+ }
43
+ if (!report.dryRun) await writeAtomic(file, `${JSON.stringify(merged.settings, null, 2)}\n`)
44
+ report.add(current ? "changed" : "created", display)
45
+ }
46
+
47
+ export async function printIndex(root, stdout) {
48
+ const data = await readOptional(join(root, ".ctx", "INDEX.md"))
49
+ if (data) stdout.write(data)
50
+ }
@@ -0,0 +1,55 @@
1
+ import { join } from "node:path"
2
+ import { installHook } from "./hook.js"
3
+ import { readOptional, writeAtomic } from "../lib/fs-safe.js"
4
+ import { rebuildIndex } from "../lib/index.js"
5
+ import { packRoot } from "../lib/paths.js"
6
+ import { detectTools, parseTools, patchTools } from "../lib/pointers.js"
7
+ import { syncTree } from "../lib/sync.js"
8
+
9
+ export const PROCESS_MD = `---
10
+ title: Process the inbox
11
+ type: doc
12
+ tags: [inbox]
13
+ source: library
14
+ updated: 2026-11-19
15
+ description: How an agent turns raw inbox files into entries under mine/.
16
+ ---
17
+
18
+ # Process the inbox
19
+
20
+ When asked to process \`.ctx/inbox\`, write only inside \`.ctx/\`.
21
+
22
+ 1. List the inbox files before moving anything.
23
+ 2. Copy each finished entry into \`.ctx/mine/\`. Do not edit \`.ctx/library/\`.
24
+ 3. Every image or code file needs a same-name \`.md\` twin. Frontmatter: title, type, tags, source: user, updated, description.
25
+ 4. Spec the twin in concrete terms: hex colors, font and size, spacing, radius, shadow, animation, and components. Mark anything you cannot see as TODO.
26
+ 5. Leave the raw file in \`inbox/\` until the twin exists, then you may remove that inbox file.
27
+ 6. Rebuild the index with \`connore index\`.
28
+ 7. On later tasks, read \`INDEX.md\` and open only the relevant rows. Prefer the text spec over the image.
29
+ `
30
+
31
+ async function writeNew(file, contents, display, report) {
32
+ if (await readOptional(file)) {
33
+ report.add("skipped", display)
34
+ return
35
+ }
36
+ if (!report.dryRun) await writeAtomic(file, contents)
37
+ report.add("created", display)
38
+ }
39
+
40
+ export async function init(root, flags, report) {
41
+ const pack = flags.pack || "frontend"
42
+ const packDir = join(packRoot, "packs", pack)
43
+ if (!(await readOptional(join(packDir, "design", "tokens.md")))) {
44
+ throw new Error(`Unknown pack "${pack}".`)
45
+ }
46
+ const detected = await detectTools(root)
47
+ const tools = flags.tools ? parseTools(flags.tools) : detected.length ? detected : ["claude", "codex"]
48
+ await syncTree(packDir, join(root, ".ctx", "library"), root, { overwrite: false, report })
49
+ await writeNew(join(root, ".ctx", "inbox", ".gitkeep"), "", ".ctx/inbox/.gitkeep", report)
50
+ await writeNew(join(root, ".ctx", "mine", ".gitkeep"), "", ".ctx/mine/.gitkeep", report)
51
+ await writeNew(join(root, ".ctx", "PROCESS.md"), PROCESS_MD, ".ctx/PROCESS.md", report)
52
+ await patchTools(root, tools, report)
53
+ if (flags.hooks) await installHook(root, report)
54
+ await rebuildIndex(root, report)
55
+ }
@@ -0,0 +1,10 @@
1
+ import { join } from "node:path"
2
+ import { readOptional } from "../lib/fs-safe.js"
3
+ import { collectEntries } from "../lib/index.js"
4
+
5
+ export async function list(root, stdout) {
6
+ if (!(await readOptional(join(root, ".ctx", "PROCESS.md")))) throw new Error("No .ctx/ folder. Run connore init first.")
7
+ for (const entry of await collectEntries(root)) {
8
+ stdout.write(`${entry.type}\t${entry.path}\t${entry.description}\n`)
9
+ }
10
+ }
@@ -0,0 +1,8 @@
1
+ import { join } from "node:path"
2
+ import { readOptional } from "../lib/fs-safe.js"
3
+ import { rebuildIndex } from "../lib/index.js"
4
+
5
+ export async function reindex(root, report) {
6
+ if (!(await readOptional(join(root, ".ctx", "PROCESS.md")))) throw new Error("No .ctx/ folder. Run connore init first.")
7
+ await rebuildIndex(root, report)
8
+ }
@@ -0,0 +1,14 @@
1
+ import { join } from "node:path"
2
+ import { readOptional } from "../lib/fs-safe.js"
3
+ import { rebuildIndex } from "../lib/index.js"
4
+ import { packRoot } from "../lib/paths.js"
5
+ import { syncTree } from "../lib/sync.js"
6
+
7
+ export async function update(root, flags, report) {
8
+ if (!(await readOptional(join(root, ".ctx", "PROCESS.md")))) throw new Error("No .ctx/ folder. Run connore init first.")
9
+ const pack = flags.pack || "frontend"
10
+ const packDir = join(packRoot, "packs", pack)
11
+ if (!(await readOptional(join(packDir, "design", "tokens.md")))) throw new Error(`Unknown pack "${pack}".`)
12
+ await syncTree(packDir, join(root, ".ctx", "library"), root, { overwrite: true, report })
13
+ await rebuildIndex(root, report)
14
+ }
@@ -0,0 +1,70 @@
1
+ export function parseFrontmatter(text) {
2
+ const normalized = text.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n")
3
+ if (!normalized.startsWith("---")) return null
4
+ const end = normalized.indexOf("\n---", 3)
5
+ if (end === -1) return null
6
+ const block = normalized.slice(normalized.indexOf("\n") + 1, end)
7
+ const data = {}
8
+ for (const line of block.split(/\r?\n/)) {
9
+ const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line)
10
+ if (!match) continue
11
+ const value = match[2].trim()
12
+ if (value.startsWith("[") && value.endsWith("]")) {
13
+ data[match[1]] = value
14
+ .slice(1, -1)
15
+ .split(",")
16
+ .map((part) => part.trim())
17
+ .filter(Boolean)
18
+ } else data[match[1]] = value.replace(/^["']|["']$/g, "")
19
+ }
20
+ return data
21
+ }
22
+
23
+ export function today() {
24
+ const date = new Date()
25
+ const month = String(date.getMonth() + 1).padStart(2, "0")
26
+ const day = String(date.getDate()).padStart(2, "0")
27
+ return `${date.getFullYear()}-${month}-${day}`
28
+ }
29
+
30
+ export function twinStub({ title, type, tags, date }) {
31
+ const tagList = tags.length ? tags.join(", ") : "TODO"
32
+ return `---
33
+ title: ${title}
34
+ type: ${type}
35
+ tags: [${tagList}]
36
+ source: user
37
+ updated: ${date}
38
+ description: TODO
39
+ ---
40
+
41
+ # ${title}
42
+
43
+ ## Purpose
44
+ TODO
45
+
46
+ ## Layout
47
+ TODO
48
+
49
+ ## Colors
50
+ TODO hex values.
51
+
52
+ ## Type
53
+ TODO font and sizes.
54
+
55
+ ## Spacing
56
+ TODO
57
+
58
+ ## Radius
59
+ TODO
60
+
61
+ ## Shadows
62
+ TODO
63
+
64
+ ## Animation
65
+ TODO
66
+
67
+ ## Components
68
+ TODO
69
+ `
70
+ }
@@ -0,0 +1,62 @@
1
+ import { randomBytes } from "node:crypto"
2
+ import { mkdir, readdir, readFile, rename, rm, stat, unlink, writeFile } from "node:fs/promises"
3
+ import { basename, dirname, join } from "node:path"
4
+
5
+ export async function exists(filePath) {
6
+ try {
7
+ await stat(filePath)
8
+ return true
9
+ } catch (error) {
10
+ if (error.code === "ENOENT") return false
11
+ throw error
12
+ }
13
+ }
14
+
15
+ export async function readOptional(filePath) {
16
+ try {
17
+ return await readFile(filePath)
18
+ } catch (error) {
19
+ if (error.code === "ENOENT") return null
20
+ throw error
21
+ }
22
+ }
23
+
24
+ export async function writeAtomic(filePath, data) {
25
+ await mkdir(dirname(filePath), { recursive: true })
26
+ const tmp = join(dirname(filePath), `.${basename(filePath)}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`)
27
+ await writeFile(tmp, data)
28
+ try {
29
+ await rename(tmp, filePath)
30
+ } catch (error) {
31
+ if (error.code !== "EEXIST" && error.code !== "EPERM") {
32
+ await unlink(tmp).catch(() => {})
33
+ throw error
34
+ }
35
+ const backup = `${filePath}.${process.pid}.bak`
36
+ await rename(filePath, backup)
37
+ try {
38
+ await rename(tmp, filePath)
39
+ } catch (renameError) {
40
+ await rename(backup, filePath).catch(() => {})
41
+ throw renameError
42
+ }
43
+ await unlink(backup).catch(() => {})
44
+ }
45
+ }
46
+
47
+ export async function removeFile(filePath) {
48
+ await rm(filePath, { force: true })
49
+ }
50
+
51
+ export async function walkFiles(dir) {
52
+ if (!(await exists(dir))) return []
53
+ const entries = await readdir(dir, { withFileTypes: true })
54
+ entries.sort((a, b) => a.name.localeCompare(b.name))
55
+ const files = []
56
+ for (const entry of entries) {
57
+ const filePath = join(dir, entry.name)
58
+ if (entry.isDirectory()) files.push(...(await walkFiles(filePath)))
59
+ else if (entry.isFile()) files.push(filePath)
60
+ }
61
+ return files
62
+ }
@@ -0,0 +1,57 @@
1
+ import { readFile } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import { exists, readOptional, walkFiles, writeAtomic } from "./fs-safe.js"
4
+ import { parseFrontmatter } from "./frontmatter.js"
5
+ import { ctxPath, fromRoot } from "./paths.js"
6
+
7
+ export async function collectEntries(root) {
8
+ const files = []
9
+ for (const dir of [ctxPath(root, "library"), ctxPath(root, "mine")]) files.push(...(await walkFiles(dir)))
10
+ const processFile = ctxPath(root, "PROCESS.md")
11
+ if (await exists(processFile)) files.push(processFile)
12
+
13
+ const entries = []
14
+ for (const file of files) {
15
+ if (!file.endsWith(".md")) continue
16
+ const data = parseFrontmatter(await readFile(file, "utf8"))
17
+ if (!data) continue
18
+ entries.push({
19
+ path: fromRoot(root, file),
20
+ type: data.type || "",
21
+ tags: Array.isArray(data.tags) ? data.tags.join(", ") : data.tags || "",
22
+ description: data.description || "",
23
+ })
24
+ }
25
+ entries.sort((a, b) => a.path.localeCompare(b.path))
26
+ return entries
27
+ }
28
+
29
+ export function renderIndex(entries) {
30
+ const lines = [
31
+ "# Index",
32
+ "",
33
+ "Load only the entries relevant to the task. Prefer text specs over opening images.",
34
+ "",
35
+ "| Path | Type | Tags | Description |",
36
+ "| --- | --- | --- | --- |",
37
+ ]
38
+ for (const entry of entries) {
39
+ lines.push(`| \`${entry.path}\` | ${entry.type} | ${entry.tags} | ${entry.description} |`)
40
+ }
41
+ lines.push("")
42
+ return lines.join("\n")
43
+ }
44
+
45
+ export async function rebuildIndex(root, report) {
46
+ const file = join(root, ".ctx", "INDEX.md")
47
+ const next = renderIndex(await collectEntries(root))
48
+ const current = await readOptional(file)
49
+ const currentText = current ? current.toString("utf8") : null
50
+ if (currentText === next) {
51
+ report.add("skipped", ".ctx/INDEX.md")
52
+ return
53
+ }
54
+ const kind = currentText === null ? "created" : "changed"
55
+ if (!report.dryRun) await writeAtomic(file, next)
56
+ report.add(kind, ".ctx/INDEX.md")
57
+ }
@@ -0,0 +1,21 @@
1
+ import { dirname, relative, resolve, sep } from "node:path"
2
+ import { fileURLToPath } from "node:url"
3
+
4
+ export const packRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..")
5
+
6
+ export const TOOLS = ["claude", "cursor", "codex", "copilot", "windsurf", "gemini"]
7
+
8
+ export const POINTER =
9
+ "Before building UI or backend features, read .ctx/INDEX.md and load only the entries relevant to the task. Prefer text specs over opening images."
10
+
11
+ export function toPosix(filePath) {
12
+ return filePath.split(sep).join("/")
13
+ }
14
+
15
+ export function fromRoot(root, filePath) {
16
+ return toPosix(relative(root, filePath))
17
+ }
18
+
19
+ export function ctxPath(root, ...parts) {
20
+ return resolve(root, ".ctx", ...parts)
21
+ }
@@ -0,0 +1,76 @@
1
+ import { join, sep } from "node:path"
2
+ import { exists, readOptional, writeAtomic } from "./fs-safe.js"
3
+ import { POINTER } from "./paths.js"
4
+
5
+ const START = "<!-- ctx:start -->"
6
+ const END = "<!-- ctx:end -->"
7
+ const BLOCK = `${START}\n${POINTER}\n${END}\n`
8
+
9
+ const FILES = {
10
+ claude: { path: "CLAUDE.md" },
11
+ codex: { path: "AGENTS.md" },
12
+ copilot: { path: join(".github", "copilot-instructions.md") },
13
+ gemini: { path: "GEMINI.md" },
14
+ cursor: {
15
+ path: join(".cursor", "rules", "ctx.mdc"),
16
+ preface: "---\ndescription: Load the project context pack before building\nalwaysApply: true\n---\n\n",
17
+ },
18
+ windsurf: {
19
+ path: join(".windsurf", "rules", "ctx.md"),
20
+ preface: "---\ntrigger: always_on\n---\n\n",
21
+ },
22
+ }
23
+
24
+ export function parseTools(value) {
25
+ if (value === "all") return Object.keys(FILES)
26
+ const names = value.split(",").map((part) => part.trim()).filter(Boolean)
27
+ const unknown = names.filter((name) => !FILES[name])
28
+ if (names.length === 0 || unknown.length) {
29
+ throw new Error(`Unknown tool "${unknown[0] || value}". Use all or ${Object.keys(FILES).join(",")}.`)
30
+ }
31
+ return [...new Set(names)]
32
+ }
33
+
34
+ export async function detectTools(root) {
35
+ const found = []
36
+ if ((await exists(join(root, "CLAUDE.md"))) || (await exists(join(root, ".claude")))) found.push("claude")
37
+ if ((await exists(join(root, ".cursor"))) || (await exists(join(root, ".cursorrules")))) found.push("cursor")
38
+ if ((await exists(join(root, ".codex"))) || (await exists(join(root, "AGENTS.md")))) found.push("codex")
39
+ if (await exists(join(root, ".github", "copilot-instructions.md"))) found.push("copilot")
40
+ if ((await exists(join(root, ".windsurf"))) || (await exists(join(root, ".windsurfrules")))) found.push("windsurf")
41
+ if ((await exists(join(root, "GEMINI.md"))) || (await exists(join(root, ".gemini")))) found.push("gemini")
42
+ return found
43
+ }
44
+
45
+ export function pointerTargets(root, tools) {
46
+ return tools.map((tool) => ({
47
+ tool,
48
+ file: join(root, FILES[tool].path),
49
+ relative: FILES[tool].path.split(sep).join("/"),
50
+ preface: FILES[tool].preface || "",
51
+ }))
52
+ }
53
+
54
+ export async function patchPointer(file, preface, report, relative) {
55
+ const current = await readOptional(file)
56
+ const text = current ? current.toString("utf8") : null
57
+ let next
58
+ if (text === null) next = `${preface}${BLOCK}`
59
+ else if (text.includes(START) && text.includes(END)) next = text.replace(new RegExp(`${START}[\\s\\S]*?${END}\\n?`), BLOCK)
60
+ else if (text.includes(START) || text.includes(END)) {
61
+ throw new Error(`${relative} has a broken ctx marker. Fix the file by hand, then run init again.`)
62
+ } else next = `${text.replace(/\s*$/, "\n\n")}${BLOCK}`
63
+
64
+ if (text === next) {
65
+ report.add("skipped", relative)
66
+ return
67
+ }
68
+ if (!report.dryRun) await writeAtomic(file, next)
69
+ report.add(text === null ? "created" : "changed", relative)
70
+ }
71
+
72
+ export async function patchTools(root, tools, report) {
73
+ for (const target of pointerTargets(root, tools)) {
74
+ await patchPointer(target.file, target.preface, report, target.relative)
75
+ }
76
+ }
@@ -0,0 +1,17 @@
1
+ export function createReport(dryRun) {
2
+ const events = []
3
+ return {
4
+ dryRun,
5
+ add(kind, file) {
6
+ events.push({ kind, file })
7
+ },
8
+ print(stdout) {
9
+ for (const event of events) stdout.write(`${event.kind} ${event.file}\n`)
10
+ const count = (kind) => events.filter((event) => event.kind === kind).length
11
+ const mode = dryRun ? " (dry-run)" : ""
12
+ stdout.write(
13
+ `summary: ${count("created")} created, ${count("changed")} changed, ${count("skipped")} skipped, ${count("removed")} removed${mode}\n`,
14
+ )
15
+ },
16
+ }
17
+ }
@@ -0,0 +1,28 @@
1
+ import { readFile } from "node:fs/promises"
2
+ import { join, relative } from "node:path"
3
+ import { readOptional, removeFile, walkFiles, writeAtomic } from "./fs-safe.js"
4
+ import { fromRoot } from "./paths.js"
5
+
6
+ export async function syncTree(source, dest, root, { overwrite, report }) {
7
+ const expected = new Set()
8
+ for (const file of await walkFiles(source)) {
9
+ const rel = relative(source, file)
10
+ expected.add(rel)
11
+ const target = join(dest, rel)
12
+ const display = fromRoot(root, target)
13
+ const src = await readFile(file)
14
+ const current = await readOptional(target)
15
+ if (current && (!overwrite || current.equals(src))) {
16
+ report.add("skipped", display)
17
+ continue
18
+ }
19
+ if (!report.dryRun) await writeAtomic(target, src)
20
+ report.add(current ? "changed" : "created", display)
21
+ }
22
+ if (!overwrite) return
23
+ for (const file of await walkFiles(dest)) {
24
+ if (expected.has(relative(dest, file))) continue
25
+ if (!report.dryRun) await removeFile(file)
26
+ report.add("removed", fromRoot(root, file))
27
+ }
28
+ }