connore 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/README.md +53 -46
  2. package/package.json +35 -33
  3. package/packs/CONTRIBUTING.md +32 -0
  4. package/packs/base/catalog/README.md +24 -0
  5. package/packs/base/catalog/api.md +46 -0
  6. package/packs/base/catalog/auth.md +46 -0
  7. package/packs/base/catalog/backend.md +46 -0
  8. package/packs/base/catalog/blueprints.md +46 -0
  9. package/packs/base/catalog/components.md +46 -0
  10. package/packs/base/catalog/database.md +46 -0
  11. package/packs/base/catalog/docs.md +46 -0
  12. package/packs/base/catalog/github.md +46 -0
  13. package/packs/base/catalog/golden.md +46 -0
  14. package/packs/base/catalog/motion.md +46 -0
  15. package/packs/base/catalog/plan.md +46 -0
  16. package/packs/base/catalog/screenshots.md +46 -0
  17. package/packs/base/catalog/skills.md +46 -0
  18. package/packs/base/catalog/tokens.md +47 -0
  19. package/packs/base/planning/START.md +28 -0
  20. package/packs/base/planning/blueprint-template.md +46 -0
  21. package/packs/base/planning/plan-template.md +45 -0
  22. package/packs/base/rules/anti-patterns.md +43 -0
  23. package/packs/base/rules/code-style.md +43 -0
  24. package/packs/base/rules/definition-of-done.md +47 -0
  25. package/packs/base/rules/dependency-policy.md +43 -0
  26. package/packs/base/rules/error-handling.md +43 -0
  27. package/packs/base/rules/security-baseline.md +43 -0
  28. package/packs/base/templates/bug-report.md +43 -0
  29. package/packs/base/templates/feature-spec.md +43 -0
  30. package/packs/base/templates/handoff.md +43 -0
  31. package/packs/base/templates/project-brief.md +43 -0
  32. package/packs/base/workflow/build-loop.md +48 -0
  33. package/packs/base/workflow/code-review.md +43 -0
  34. package/packs/base/workflow/debugging.md +43 -0
  35. package/packs/base/workflow/git-and-commits.md +43 -0
  36. package/packs/base/workflow/idea-to-spec.md +43 -0
  37. package/packs/base/workflow/session-handoff.md +43 -0
  38. package/packs/base/workflow/spec-to-plan.md +43 -0
  39. package/packs/nextjs-fullstack/backend/api-conventions.md +48 -0
  40. package/packs/nextjs-fullstack/backend/auth-and-roles.md +43 -0
  41. package/packs/nextjs-fullstack/backend/background-jobs.md +43 -0
  42. package/packs/nextjs-fullstack/backend/caching.md +43 -0
  43. package/packs/nextjs-fullstack/backend/database.md +43 -0
  44. package/packs/nextjs-fullstack/backend/file-uploads.md +43 -0
  45. package/packs/nextjs-fullstack/backend/logging.md +43 -0
  46. package/packs/nextjs-fullstack/backend/migrations.md +43 -0
  47. package/packs/nextjs-fullstack/backend/rate-limiting.md +43 -0
  48. package/packs/nextjs-fullstack/backend/secrets-and-env.md +43 -0
  49. package/packs/nextjs-fullstack/backend/validation.md +43 -0
  50. package/packs/nextjs-fullstack/blueprints/ai-app.md +84 -0
  51. package/packs/nextjs-fullstack/blueprints/internal-tool.md +83 -0
  52. package/packs/nextjs-fullstack/blueprints/saas-app.md +83 -0
  53. package/packs/nextjs-fullstack/build-deploy/ci.md +43 -0
  54. package/packs/nextjs-fullstack/build-deploy/deploy.md +43 -0
  55. package/packs/nextjs-fullstack/build-deploy/monitoring.md +43 -0
  56. package/packs/nextjs-fullstack/build-deploy/performance.md +43 -0
  57. package/packs/nextjs-fullstack/build-deploy/project-structure.md +43 -0
  58. package/packs/nextjs-fullstack/build-deploy/release-checklist.md +43 -0
  59. package/packs/nextjs-fullstack/build-deploy/testing.md +43 -0
  60. package/packs/nextjs-fullstack/evals/README.md +43 -0
  61. package/packs/nextjs-fullstack/examples/golden-app/README.md +43 -0
  62. package/packs/nextjs-fullstack/frontend/accessibility.md +43 -0
  63. package/packs/nextjs-fullstack/frontend/components.md +43 -0
  64. package/packs/nextjs-fullstack/frontend/forms.md +43 -0
  65. package/packs/nextjs-fullstack/frontend/layout.md +43 -0
  66. package/packs/nextjs-fullstack/frontend/loading-empty-error.md +43 -0
  67. package/packs/nextjs-fullstack/frontend/motion.md +43 -0
  68. package/packs/nextjs-fullstack/frontend/responsive.md +43 -0
  69. package/packs/nextjs-fullstack/frontend/seo.md +43 -0
  70. package/packs/nextjs-fullstack/frontend/tables.md +43 -0
  71. package/packs/nextjs-fullstack/frontend/tokens.md +43 -0
  72. package/packs/nextjs-fullstack/integrations/analytics.md +43 -0
  73. package/packs/nextjs-fullstack/integrations/email.md +43 -0
  74. package/packs/nextjs-fullstack/integrations/llm-apis.md +43 -0
  75. package/packs/nextjs-fullstack/integrations/oauth.md +43 -0
  76. package/packs/nextjs-fullstack/integrations/object-storage.md +43 -0
  77. package/packs/nextjs-fullstack/integrations/payments.md +43 -0
  78. package/packs/nextjs-fullstack/integrations/queues.md +43 -0
  79. package/packs/nextjs-fullstack/integrations/search.md +43 -0
  80. package/packs/nextjs-fullstack/integrations/webhooks.md +43 -0
  81. package/packs/nextjs-fullstack/playbooks/add-ai-feature.md +43 -0
  82. package/packs/nextjs-fullstack/playbooks/add-auth.md +43 -0
  83. package/packs/nextjs-fullstack/playbooks/add-billing.md +50 -0
  84. package/packs/nextjs-fullstack/playbooks/add-crud.md +43 -0
  85. package/packs/nextjs-fullstack/playbooks/add-email.md +43 -0
  86. package/packs/nextjs-fullstack/playbooks/add-file-upload.md +43 -0
  87. package/packs/nextjs-fullstack/playbooks/add-webhook.md +43 -0
  88. package/packs/nextjs-fullstack/playbooks/ship-to-prod.md +43 -0
  89. package/src/cli.js +288 -90
  90. package/src/commands/add.js +61 -57
  91. package/src/commands/catalog.js +21 -0
  92. package/src/commands/doctor.js +42 -0
  93. package/src/commands/hook.js +67 -50
  94. package/src/commands/init.js +69 -55
  95. package/src/commands/learn.js +39 -0
  96. package/src/commands/lint.js +5 -0
  97. package/src/commands/list.js +10 -10
  98. package/src/commands/log.js +25 -0
  99. package/src/commands/memory.js +14 -0
  100. package/src/commands/plan.js +41 -0
  101. package/src/commands/reindex.js +8 -8
  102. package/src/commands/review.js +31 -0
  103. package/src/commands/search.js +21 -0
  104. package/src/commands/stats.js +35 -0
  105. package/src/commands/undo.js +7 -0
  106. package/src/commands/update.js +16 -14
  107. package/src/lib/catalog.js +32 -0
  108. package/src/lib/config.js +64 -0
  109. package/src/lib/fs-safe.js +36 -11
  110. package/src/lib/gitlog.js +75 -0
  111. package/src/lib/ignore.js +47 -0
  112. package/src/lib/index.js +27 -12
  113. package/src/lib/lessons.js +173 -0
  114. package/src/lib/lint.js +67 -0
  115. package/src/lib/lock.js +47 -0
  116. package/src/lib/memory.js +49 -0
  117. package/src/lib/mutate.js +24 -0
  118. package/src/lib/packs.js +10 -0
  119. package/src/lib/paths.js +6 -2
  120. package/src/lib/plan.js +156 -0
  121. package/src/lib/pointers.js +3 -3
  122. package/src/lib/provider.js +27 -0
  123. package/src/lib/report.js +20 -4
  124. package/src/lib/run.js +73 -0
  125. package/src/lib/search.js +40 -0
  126. package/src/lib/secrets.js +25 -0
  127. package/src/lib/signals.js +55 -0
  128. package/src/lib/sync.js +20 -12
@@ -0,0 +1,49 @@
1
+ import { join } from "node:path"
2
+ import { readOptional } from "./fs-safe.js"
3
+ import { commitWrite } from "./mutate.js"
4
+ import { redactSecrets } from "./secrets.js"
5
+
6
+ export const MEMORIES = [
7
+ { id: "project", file: "project.md", title: "Project memory", description: "Notes saved with connore memory project." },
8
+ { id: "architecture", file: "architecture.md", title: "Architecture memory", description: "Notes saved with connore memory architecture." },
9
+ { id: "decision", file: "decision.md", title: "Decision memory", description: "Notes saved with connore memory decision." },
10
+ { id: "agent", file: "agent.md", title: "Agent memory", description: "Notes saved with connore memory agent." },
11
+ { id: "preferences", file: "preferences.md", title: "Developer preferences", description: "Notes saved with connore memory preferences." },
12
+ { id: "task", file: "task.md", title: "Task context", description: "Notes saved with connore memory task." },
13
+ { id: "knowledge", file: "knowledge.md", title: "Knowledge library", description: "Notes saved with connore memory knowledge." },
14
+ ]
15
+
16
+ export function memoryById(id) {
17
+ return MEMORIES.find((memory) => memory.id === id)
18
+ }
19
+
20
+ export function renderMemory(memory) {
21
+ return `---
22
+ title: ${memory.title}
23
+ type: memory
24
+ tags: [memory, ${memory.id}]
25
+ source: user
26
+ description: ${memory.description}
27
+ ---
28
+
29
+ # ${memory.title}
30
+ `
31
+ }
32
+
33
+ export async function appendMemory(root, id, text, report) {
34
+ const memory = memoryById(id)
35
+ if (!memory) {
36
+ throw Object.assign(new Error(`Unknown memory "${id}". Use: ${MEMORIES.map((item) => item.id).join(", ")}.`), { exitCode: 2 })
37
+ }
38
+ const note = redactSecrets(String(text || "").trim())
39
+ if (!note) throw Object.assign(new Error(`Usage: connore memory ${id} "text".`), { exitCode: 2 })
40
+ if (!(await readOptional(join(root, ".ctx", "PROCESS.md")))) throw new Error("No .ctx/ folder. Run connore init first.")
41
+ const display = `.ctx/memory/${memory.file}`
42
+ const file = join(root, ".ctx", "memory", memory.file)
43
+ const current = await readOptional(file)
44
+ const base = current ? current.toString("utf8") : renderMemory(memory)
45
+ const stamp = new Date().toISOString().slice(0, 10)
46
+ const next = `${base.replace(/\s*$/, "")}\n\n## ${stamp}\n\n${note}\n`
47
+ await commitWrite(file, next, report, display)
48
+ return memory
49
+ }
@@ -0,0 +1,24 @@
1
+ import { readOptional, removeFile, writeAtomic } from "./fs-safe.js"
2
+
3
+ function asBuffer(data) {
4
+ return Buffer.isBuffer(data) ? data : Buffer.from(data)
5
+ }
6
+
7
+ export async function commitWrite(file, data, report, display) {
8
+ const previous = await readOptional(file)
9
+ const buf = asBuffer(data)
10
+ if (previous && previous.equals(buf)) {
11
+ report.add("skipped", display)
12
+ return
13
+ }
14
+ const kind = previous ? "changed" : "created"
15
+ if (!report.dryRun) await writeAtomic(file, buf)
16
+ report.add(kind, display, { previous })
17
+ }
18
+
19
+ export async function commitRemove(file, report, display) {
20
+ const previous = await readOptional(file)
21
+ if (!previous) return
22
+ if (!report.dryRun) await removeFile(file)
23
+ report.add("removed", display, { previous })
24
+ }
@@ -0,0 +1,10 @@
1
+ import { join } from "node:path"
2
+ import { walkFiles } from "./fs-safe.js"
3
+ import { packRoot } from "./paths.js"
4
+
5
+ export async function packDir(name) {
6
+ const dir = join(packRoot, "packs", name)
7
+ const files = await walkFiles(dir)
8
+ if (!files.some((file) => file.endsWith(".md"))) throw new Error(`Unknown pack "${name}".`)
9
+ return dir
10
+ }
package/src/lib/paths.js CHANGED
@@ -1,4 +1,4 @@
1
- import { dirname, relative, resolve, sep } from "node:path"
1
+ import { dirname, join, relative, resolve, sep } from "node:path"
2
2
  import { fileURLToPath } from "node:url"
3
3
 
4
4
  export const packRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..")
@@ -6,7 +6,7 @@ export const packRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "
6
6
  export const TOOLS = ["claude", "cursor", "codex", "copilot", "windsurf", "gemini"]
7
7
 
8
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."
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. Before new work, read .ctx/START.md. When a decision is made, record it with connore log decision."
10
10
 
11
11
  export function toPosix(filePath) {
12
12
  return filePath.split(sep).join("/")
@@ -19,3 +19,7 @@ export function fromRoot(root, filePath) {
19
19
  export function ctxPath(root, ...parts) {
20
20
  return resolve(root, ".ctx", ...parts)
21
21
  }
22
+
23
+ export function absFromPosix(root, posixPath) {
24
+ return join(root, ...posixPath.split("/"))
25
+ }
@@ -0,0 +1,156 @@
1
+ import { join } from "node:path"
2
+ import { readOptional } from "./fs-safe.js"
3
+ import { parseFrontmatter } from "./frontmatter.js"
4
+ import { packRoot } from "./paths.js"
5
+
6
+ const BLUEPRINT_DIRS = [
7
+ join(packRoot, "packs", "nextjs-fullstack", "blueprints"),
8
+ join(packRoot, "packs", "base", "planning"),
9
+ ]
10
+
11
+ export function capText(text, budget) {
12
+ if (!text) return ""
13
+ const max = Math.max(0, budget) * 4
14
+ if (text.length <= max) return text.endsWith("\n") ? text : `${text}\n`
15
+ if (max < 8) return ""
16
+ const cut = text.slice(0, max).replace(/\s+\S*$/, "").trimEnd()
17
+ return cut ? `${cut}\n` : ""
18
+ }
19
+
20
+ export function parseBlueprint(text) {
21
+ const normalized = text.replace(/\r\n/g, "\n")
22
+ const data = parseFrontmatter(normalized) || {}
23
+ const phases = []
24
+ let current = null
25
+ for (const line of normalized.split("\n")) {
26
+ const heading = /^### Phase (\d+): (.+)$/.exec(line.trim())
27
+ if (heading) {
28
+ current = { number: Number(heading[1]), title: heading[2].trim(), tasks: [], acceptance: "", gate: "", entries: "" }
29
+ phases.push(current)
30
+ continue
31
+ }
32
+ if (!current) continue
33
+ if (line.startsWith("- ")) current.tasks.push(line.slice(2).trim())
34
+ else if (line.startsWith("Acceptance:")) current.acceptance = line.slice("Acceptance:".length).trim()
35
+ else if (line.startsWith("Gate:")) current.gate = line.slice("Gate:".length).trim()
36
+ else if (line.startsWith("Entries:")) current.entries = line.slice("Entries:".length).trim()
37
+ }
38
+ return { title: data.title || "Plan", phases }
39
+ }
40
+
41
+ export function renderPlan(name, blueprint) {
42
+ const blocks = blueprint.phases.map((phase) => {
43
+ const tasks = phase.tasks.map((task) => `- [ ] ${task}`).join("\n")
44
+ const gate = phase.gate ? `Gate: [ ] ${phase.gate}` : ""
45
+ return [`## Phase ${phase.number}: ${phase.title}`, tasks, phase.acceptance ? `Acceptance: ${phase.acceptance}` : "", gate, phase.entries ? `Entries: ${phase.entries}` : ""]
46
+ .filter(Boolean)
47
+ .join("\n")
48
+ })
49
+ const first = blueprint.phases[0]
50
+ const next = first?.tasks[0] || first?.gate || "Review the plan"
51
+ const phaseLine = first ? `${first.number}. ${first.title}` : "0. Scope"
52
+ return `---
53
+ title: ${blueprint.title} plan
54
+ type: plan
55
+ tags: [plan]
56
+ blueprint: ${name}
57
+ description: Phase ${phaseLine}. Next: ${next}
58
+ ---
59
+
60
+ # ${blueprint.title} plan
61
+
62
+ Current phase: ${phaseLine}
63
+ Next step: ${next}
64
+ Failed gate: none
65
+
66
+ ## Current state
67
+ Phase ${phaseLine} is open. No task is done.
68
+
69
+ ## Next step
70
+ ${next}
71
+
72
+ ${blocks.join("\n\n")}
73
+ `
74
+ }
75
+
76
+ export function planItems(text) {
77
+ const items = []
78
+ let phase = 0
79
+ for (const line of text.replace(/\r\n/g, "\n").split("\n")) {
80
+ const heading = /^## Phase (\d+): /.exec(line)
81
+ if (heading) {
82
+ phase = Number(heading[1])
83
+ continue
84
+ }
85
+ const task = /^- \[([ x])\] (.+)$/.exec(line)
86
+ if (task) {
87
+ items.push({ phase, kind: "task", done: task[1] === "x", text: task[2] })
88
+ continue
89
+ }
90
+ const gate = /^Gate: \[([ x])\] (.+)$/.exec(line)
91
+ if (gate) items.push({ phase, kind: "gate", done: gate[1] === "x", text: gate[2] })
92
+ }
93
+ return items
94
+ }
95
+
96
+ export function planView(text) {
97
+ const data = parseFrontmatter(text) || {}
98
+ const items = planItems(text)
99
+ const open = items.find((item) => !item.done)
100
+ const phaseItem = open || items.at(-1)
101
+ const phaseHeading = phaseItem ? text.match(new RegExp(`^## Phase ${phaseItem.phase}: (.+)$`, "m")) : null
102
+ const failed = items.find((item) => item.kind === "gate" && !item.done && items.some((other) => other.done && other.phase > item.phase))
103
+ return {
104
+ blueprint: data.blueprint || "",
105
+ title: data.title || "Plan",
106
+ phase: phaseHeading ? `${phaseItem.phase}. ${phaseHeading[1]}` : "0",
107
+ next: open ? open.text : "Plan complete",
108
+ failedGate: failed ? `Phase ${failed.phase}: ${failed.text}` : null,
109
+ done: items.filter((item) => item.done).length,
110
+ total: items.length,
111
+ }
112
+ }
113
+
114
+ export function markTaskDone(text, query) {
115
+ const needle = query.trim().toLowerCase()
116
+ if (!needle) throw new Error("Name the task to mark done.")
117
+ let flipped = false
118
+ const next = text.replace(/\r\n/g, "\n").split("\n").map((line) => {
119
+ if (flipped) return line
120
+ const task = /^- \[ \] (.+)$/.exec(line)
121
+ const gate = /^Gate: \[ \] (.+)$/.exec(line)
122
+ const label = task?.[1] || gate?.[1]
123
+ if (!label || !label.toLowerCase().includes(needle)) return line
124
+ flipped = true
125
+ return task ? `- [x] ${task[1]}` : `Gate: [x] ${gate[1]}`
126
+ }).join("\n")
127
+ if (!flipped) throw new Error(`No open task matches "${query}".`)
128
+ const view = planView(next)
129
+ return next
130
+ .replace(/^Current phase: .*$/m, `Current phase: ${view.phase}`)
131
+ .replace(/^Next step: .*$/m, `Next step: ${view.next}`)
132
+ .replace(/^## Next step\n[\s\S]*?(?=\n## )/, () => `## Next step\n${view.next}\n`)
133
+ .replace(/^Failed gate: .*$/m, `Failed gate: ${view.failedGate || "none"}`)
134
+ .replace(/^description: .*$/m, `description: Phase ${view.phase}. Next: ${view.next}`)
135
+ }
136
+
137
+ export function planHookText(text, budget) {
138
+ const view = planView(text)
139
+ const lines = [
140
+ "Read .ctx/START.md before new work.",
141
+ `Current phase: ${view.phase}`,
142
+ `Next step: ${view.next}`,
143
+ ]
144
+ if (view.failedGate) lines.push(`Failed gate: ${view.failedGate}`)
145
+ return capText(`${lines.join("\n")}\n`, budget)
146
+ }
147
+
148
+ export async function readBlueprint(name) {
149
+ for (const dir of BLUEPRINT_DIRS) {
150
+ const file = join(dir, `${name}.md`)
151
+ const data = await readOptional(file)
152
+ if (data) return { file, text: data.toString("utf8") }
153
+ }
154
+ throw new Error(`Unknown blueprint "${name}".`)
155
+ }
156
+
@@ -1,5 +1,6 @@
1
1
  import { join, sep } from "node:path"
2
- import { exists, readOptional, writeAtomic } from "./fs-safe.js"
2
+ import { exists, readOptional } from "./fs-safe.js"
3
+ import { commitWrite } from "./mutate.js"
3
4
  import { POINTER } from "./paths.js"
4
5
 
5
6
  const START = "<!-- ctx:start -->"
@@ -65,8 +66,7 @@ export async function patchPointer(file, preface, report, relative) {
65
66
  report.add("skipped", relative)
66
67
  return
67
68
  }
68
- if (!report.dryRun) await writeAtomic(file, next)
69
- report.add(text === null ? "created" : "changed", relative)
69
+ await commitWrite(file, next, report, relative)
70
70
  }
71
71
 
72
72
  export async function patchTools(root, tools, report) {
@@ -0,0 +1,27 @@
1
+ import { redactSecrets } from "./secrets.js"
2
+
3
+ export function previewCluster(cluster) {
4
+ return redactSecrets(cluster.rows.map((row) => `${row.kind}: ${row.text}`).join("\n"))
5
+ }
6
+
7
+ export function localLesson(cluster) {
8
+ const rows = cluster.rows
9
+ const first = rows[0]
10
+ const fix = rows.find((row) => row.kind === "fix") || rows.find((row) => row.kind === "decision")
11
+ const failure = rows.find((row) => row.kind === "failure")
12
+ const mistake = redactSecrets(failure?.text || first.text)
13
+ const repair = redactSecrets(fix?.text || first.text)
14
+ const files = [...new Set(rows.flatMap((row) => row.files || []))]
15
+ return {
16
+ title: mistake.slice(0, 72) || "Lesson",
17
+ scope: "project",
18
+ trigger: files[0] ? `when editing ${files[0]}` : "when this mistake shows up again",
19
+ mistake,
20
+ fix: repair,
21
+ evidence: `${rows.length} signals, first ${String(first.at || "").slice(0, 10)}`,
22
+ confidence: rows.length >= 5 ? "high" : "medium",
23
+ source: rows.every((row) => row.source === "git") ? "code-derived" : "agent-inferred",
24
+ files: files.join(", "),
25
+ lastSeen: new Date().toISOString().slice(0, 10),
26
+ }
27
+ }
package/src/lib/report.js CHANGED
@@ -1,16 +1,32 @@
1
- export function createReport(dryRun) {
1
+ export function createReport(dryRun, { json = false } = {}) {
2
2
  const events = []
3
3
  return {
4
4
  dryRun,
5
- add(kind, file) {
5
+ json,
6
+ events,
7
+ mutations: [],
8
+ add(kind, file, meta) {
6
9
  events.push({ kind, file })
10
+ if (meta && Object.prototype.hasOwnProperty.call(meta, "previous")) {
11
+ this.mutations.push({ kind, file, previous: meta.previous })
12
+ }
7
13
  },
8
14
  print(stdout) {
9
- for (const event of events) stdout.write(`${event.kind} ${event.file}\n`)
10
15
  const count = (kind) => events.filter((event) => event.kind === kind).length
16
+ const summary = {
17
+ created: count("created"),
18
+ changed: count("changed"),
19
+ skipped: count("skipped"),
20
+ removed: count("removed"),
21
+ }
22
+ if (json) {
23
+ stdout.write(`${JSON.stringify({ ok: true, dryRun, events, summary })}\n`)
24
+ return
25
+ }
26
+ for (const event of events) stdout.write(`${event.kind} ${event.file}\n`)
11
27
  const mode = dryRun ? " (dry-run)" : ""
12
28
  stdout.write(
13
- `summary: ${count("created")} created, ${count("changed")} changed, ${count("skipped")} skipped, ${count("removed")} removed${mode}\n`,
29
+ `summary: ${summary.created} created, ${summary.changed} changed, ${summary.skipped} skipped, ${summary.removed} removed${mode}\n`,
14
30
  )
15
31
  },
16
32
  }
package/src/lib/run.js ADDED
@@ -0,0 +1,73 @@
1
+ import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises"
2
+ import { dirname, join } from "node:path"
3
+ import { writeAtomic } from "./fs-safe.js"
4
+ import { absFromPosix } from "./paths.js"
5
+
6
+ function runStamp(date = new Date()) {
7
+ return date.toISOString().replace(/[:.]/g, "-")
8
+ }
9
+
10
+ export async function sealRun(root, command, report) {
11
+ if (report.dryRun || report.mutations.length === 0) return null
12
+ const id = runStamp()
13
+ const dir = join(root, ".ctx", ".runs", id)
14
+ const files = []
15
+ for (const change of report.mutations) {
16
+ const action = change.kind === "changed" ? "updated" : change.kind
17
+ const entry = { path: change.file, action }
18
+ if (change.previous) {
19
+ const backup = absFromPosix(dir, change.file)
20
+ await mkdir(dirname(backup), { recursive: true })
21
+ await writeFile(backup, change.previous)
22
+ entry.backup = `.ctx/.runs/${id}/${change.file}`
23
+ }
24
+ files.push(entry)
25
+ }
26
+ await mkdir(join(root, ".ctx", ".runs"), { recursive: true })
27
+ await writeFile(join(root, ".ctx", ".runs", `${id}.json`), `${JSON.stringify({ id, command, files }, null, 2)}\n`)
28
+ await pruneRuns(root, 10)
29
+ return id
30
+ }
31
+
32
+ async function listRuns(root) {
33
+ const dir = join(root, ".ctx", ".runs")
34
+ let names = []
35
+ try {
36
+ names = await readdir(dir)
37
+ } catch (error) {
38
+ if (error.code === "ENOENT") return []
39
+ throw error
40
+ }
41
+ return names
42
+ .filter((name) => name.endsWith(".json"))
43
+ .sort()
44
+ .map((name) => ({
45
+ id: name.slice(0, -5),
46
+ json: join(dir, name),
47
+ dir: join(dir, name.slice(0, -5)),
48
+ }))
49
+ }
50
+
51
+ export async function pruneRuns(root, keep) {
52
+ const runs = await listRuns(root)
53
+ const extra = runs.slice(0, Math.max(0, runs.length - keep))
54
+ for (const run of extra) {
55
+ await rm(run.json, { force: true })
56
+ await rm(run.dir, { recursive: true, force: true })
57
+ }
58
+ }
59
+
60
+ export async function undoLastRun(root) {
61
+ const runs = await listRuns(root)
62
+ const latest = runs.at(-1)
63
+ if (!latest) throw new Error("No run to undo.")
64
+ const manifest = JSON.parse(await readFile(latest.json, "utf8"))
65
+ for (const entry of [...manifest.files].reverse()) {
66
+ const abs = absFromPosix(root, entry.path)
67
+ if (entry.action === "created") await rm(abs, { force: true })
68
+ else if (entry.backup) await writeAtomic(abs, await readFile(absFromPosix(root, entry.backup)))
69
+ }
70
+ await rm(latest.json, { force: true })
71
+ await rm(latest.dir, { recursive: true, force: true })
72
+ return manifest
73
+ }
@@ -0,0 +1,40 @@
1
+ export function tokenize(query) {
2
+ return String(query || "")
3
+ .toLowerCase()
4
+ .split(/[^a-z0-9]+/)
5
+ .filter((term) => term.length > 1)
6
+ }
7
+
8
+ export function scoreEntry(entry, terms) {
9
+ if (!terms.length) return 0
10
+ const title = `${entry.title || ""}`.toLowerCase()
11
+ const path = `${entry.path || ""}`.toLowerCase()
12
+ const tags = `${entry.tags || ""} ${entry.description || ""}`.toLowerCase()
13
+ const headings = `${entry.headings || ""}`.toLowerCase()
14
+ const body = `${entry.body || ""}`.toLowerCase()
15
+ let score = 0
16
+ for (const term of terms) {
17
+ if (title.includes(term)) score += 8
18
+ if (path.includes(term)) score += 5
19
+ if (headings.includes(term)) score += 4
20
+ if (tags.includes(term)) score += 3
21
+ let found = 0
22
+ let from = 0
23
+ while (found < 5 && from < body.length) {
24
+ const at = body.indexOf(term, from)
25
+ if (at === -1) break
26
+ found += 1
27
+ from = at + term.length
28
+ }
29
+ score += found
30
+ }
31
+ return score
32
+ }
33
+
34
+ export function rankEntries(entries, query) {
35
+ const terms = tokenize(query)
36
+ return entries
37
+ .map((entry) => ({ ...entry, score: scoreEntry(entry, terms) }))
38
+ .filter((entry) => entry.score > 0)
39
+ .sort((a, b) => b.score - a.score || a.path.localeCompare(b.path))
40
+ }
@@ -0,0 +1,25 @@
1
+ const PATTERNS = [
2
+ { name: "aws-access-key", re: /AKIA[0-9A-Z]{16}/g },
3
+ { name: "private-key", re: /-----BEGIN [A-Z ]*PRIVATE KEY-----/g },
4
+ { name: "stripe-live", re: /sk_live_[0-9a-zA-Z]{8,}/g },
5
+ { name: "openai", re: /\bsk-[A-Za-z0-9]{20,}/g },
6
+ { name: "github-token", re: /\bghp_[A-Za-z0-9]{20,}/g },
7
+ ]
8
+
9
+ export function secretHits(text) {
10
+ const hits = []
11
+ for (const pattern of PATTERNS) {
12
+ pattern.re.lastIndex = 0
13
+ if (pattern.re.test(text)) hits.push(pattern.name)
14
+ }
15
+ return hits
16
+ }
17
+
18
+ export function redactSecrets(text) {
19
+ let next = text
20
+ for (const pattern of PATTERNS) {
21
+ pattern.re.lastIndex = 0
22
+ next = next.replace(pattern.re, "[redacted]")
23
+ }
24
+ return next
25
+ }
@@ -0,0 +1,55 @@
1
+ import { createHash } from "node:crypto"
2
+ import { join } from "node:path"
3
+ import { readOptional } from "./fs-safe.js"
4
+ import { commitWrite } from "./mutate.js"
5
+ import { redactSecrets } from "./secrets.js"
6
+
7
+ export function signalPath(root) {
8
+ return join(root, ".ctx", ".signals", "log.jsonl")
9
+ }
10
+
11
+ export async function readSignals(root) {
12
+ const raw = await readOptional(signalPath(root))
13
+ if (!raw) return []
14
+ const signals = []
15
+ for (const line of raw.toString("utf8").split(/\r?\n/)) {
16
+ if (!line.trim()) continue
17
+ try {
18
+ signals.push(JSON.parse(line))
19
+ } catch {
20
+ // A torn line is ignored so one bad append does not hide the rest.
21
+ }
22
+ }
23
+ return signals
24
+ }
25
+
26
+ export async function appendSignal(root, signal, report) {
27
+ const file = signalPath(root)
28
+ const current = (await readOptional(file))?.toString("utf8") || ""
29
+ const line = `${JSON.stringify(signal)}\n`
30
+ await commitWrite(file, `${current}${line}`, report, ".ctx/.signals/log.jsonl")
31
+ }
32
+
33
+ export function normalizeText(text) {
34
+ return redactSecrets(String(text || ""))
35
+ .toLowerCase()
36
+ .replace(/[^a-z0-9]+/g, " ")
37
+ .trim()
38
+ }
39
+
40
+ export function clusterSignals(signals, minimum = 3) {
41
+ const groups = new Map()
42
+ for (const signal of signals) {
43
+ const key = normalizeText(signal.text)
44
+ if (!key) continue
45
+ if (!groups.has(key)) groups.set(key, [])
46
+ groups.get(key).push(signal)
47
+ }
48
+ return [...groups.entries()]
49
+ .filter(([, rows]) => rows.length >= minimum)
50
+ .map(([key, rows]) => ({
51
+ key,
52
+ id: createHash("sha256").update(key).digest("hex").slice(0, 10),
53
+ rows,
54
+ }))
55
+ }
package/src/lib/sync.js CHANGED
@@ -1,28 +1,36 @@
1
1
  import { readFile } from "node:fs/promises"
2
2
  import { join, relative } from "node:path"
3
- import { readOptional, removeFile, walkFiles, writeAtomic } from "./fs-safe.js"
4
- import { fromRoot } from "./paths.js"
3
+ import { readOptional, walkFiles } from "./fs-safe.js"
4
+ import { parseFrontmatter } from "./frontmatter.js"
5
+ import { commitRemove, commitWrite } from "./mutate.js"
6
+ import { fromRoot, toPosix } from "./paths.js"
5
7
 
6
- export async function syncTree(source, dest, root, { overwrite, report }) {
8
+ function isDraft(bytes, includeDrafts) {
9
+ if (includeDrafts) return false
10
+ const data = parseFrontmatter(bytes.toString("utf8"))
11
+ return data?.status === "draft"
12
+ }
13
+
14
+ export async function syncTree(source, dest, root, { overwrite, report, includeDrafts = false }) {
7
15
  const expected = new Set()
8
16
  for (const file of await walkFiles(source)) {
9
17
  const rel = relative(source, file)
10
- expected.add(rel)
18
+ if (toPosix(rel).startsWith("catalog/")) continue
19
+ const src = await readFile(file)
20
+ if (file.endsWith(".md") && isDraft(src, includeDrafts)) continue
21
+ expected.add(toPosix(rel))
11
22
  const target = join(dest, rel)
12
23
  const display = fromRoot(root, target)
13
- const src = await readFile(file)
14
- const current = await readOptional(target)
15
- if (current && (!overwrite || current.equals(src))) {
24
+ if (!overwrite && (await readOptional(target))) {
16
25
  report.add("skipped", display)
17
26
  continue
18
27
  }
19
- if (!report.dryRun) await writeAtomic(target, src)
20
- report.add(current ? "changed" : "created", display)
28
+ await commitWrite(target, src, report, display)
21
29
  }
22
30
  if (!overwrite) return
23
31
  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))
32
+ const rel = toPosix(relative(dest, file))
33
+ if (expected.has(rel)) continue
34
+ await commitRemove(file, report, fromRoot(root, file))
27
35
  }
28
36
  }