@moritakaaz/markflow 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.
Files changed (39) hide show
  1. package/README.md +31 -2
  2. package/package.json +21 -4
  3. package/src/agents.js +17 -0
  4. package/src/discover.js +184 -0
  5. package/src/doctor.js +166 -0
  6. package/src/hash.js +7 -0
  7. package/src/index.js +58 -0
  8. package/src/init.js +186 -0
  9. package/src/templates.js +17 -0
  10. package/src/update.js +132 -0
  11. package/src/versions.js +6 -0
  12. package/templates/AGENTS.md +25 -0
  13. package/templates/markflow/.agents/MEMORY.md +17 -0
  14. package/templates/markflow/.agents/PROMPTS.md +17 -0
  15. package/templates/markflow/.agents/RULES.md +7 -0
  16. package/templates/markflow/.agents/mcp.json +3 -0
  17. package/templates/markflow/.agents/workflows/create-feature.md +14 -0
  18. package/templates/markflow/.agents/workflows/implement-spec.md +13 -0
  19. package/templates/markflow/.agents/workflows/pre-deploy-check.md +13 -0
  20. package/templates/markflow/.agents/workflows/review-spec.md +13 -0
  21. package/templates/markflow/.agents/workflows/sync-docs.md +13 -0
  22. package/templates/markflow/CHANGELOG.md +9 -0
  23. package/templates/markflow/README.md +30 -0
  24. package/templates/markflow/TASKS.md +13 -0
  25. package/templates/markflow/docs/API.md +24 -0
  26. package/templates/markflow/docs/ARCHITECTURE.md +29 -0
  27. package/templates/markflow/docs/CODING_STANDARDS.md +38 -0
  28. package/templates/markflow/docs/DATA_MODEL.md +23 -0
  29. package/templates/markflow/docs/DEPLOY.md +23 -0
  30. package/templates/markflow/docs/GLOSSARY.md +11 -0
  31. package/templates/markflow/docs/MCP.md +19 -0
  32. package/templates/markflow/docs/PRD.md +29 -0
  33. package/templates/markflow/docs/STACK.md +18 -0
  34. package/templates/markflow/docs/TESTING.md +27 -0
  35. package/templates/markflow/docs/adr/001-initial-stack.md +25 -0
  36. package/templates/markflow/docs/adr/_template.md +27 -0
  37. package/templates/markflow/specs/_template.md +33 -0
  38. package/templates/markflow/specs/index.md +14 -0
  39. package/test/cli.test.js +297 -0
package/README.md CHANGED
@@ -1,3 +1,32 @@
1
- # Temporary Holding Version
1
+ # CLI
2
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.
3
+ This folder holds the Markflow command line tool. Read it when you work on the init command.
4
+
5
+ ## Tests
6
+
7
+ Run tests with npm test from this folder. Tests use temp dirs only. They never touch a real repo. They cover discovery, init, doctor, update, the command parser, and agent adapters.
8
+
9
+ ## Usage
10
+
11
+ Install it with npx @moritakaaz/markflow init. Then run one of these commands. A command you do not know is rejected and creates no files.
12
+
13
+ - `markflow init` creates the docs layer in the current repo.
14
+ - `markflow init --agent claude` also creates CLAUDE.md. Use `--agent codex` for Codex, which reads AGENTS.md. Use `--agent cursor` for .cursor/rules/markflow.mdc. Use `--agent copilot` for .github/copilot-instructions.md.
15
+ - `markflow doctor` checks the docs layer for missing files, leftover placeholders, broken internal links, and specs missing from the index. It reports errors, warnings, and info. Only errors make it exit with 1.
16
+ - `markflow update` restores missing files and updates files the user did not change. It also protects AGENTS.md and agent files with the same hash check. Use `markflow update --preview` to see what would change without changing any file. The CLI, methodology, and template each have their own version. See src/versions.js for the methodology and template versions.
17
+ - `markflow --help` shows the commands.
18
+ - `markflow --version` shows the CLI version.
19
+
20
+ Init reads a repo, then copies the base templates into it. It is non-interactive by default. It does not init a framework. It does not install app dependencies.
21
+
22
+ Use --agent to pick the agent file. The default is generic and creates AGENTS.md only. Use --agent claude to also create CLAUDE.md. Use --agent cursor to also create .cursorrules.
23
+
24
+ Init also writes markflow/.markflow.json. That file holds the cli, methodology, and template versions used at init time.
25
+
26
+ Doctor checks a repo for missing Markflow files. Run it with doctor. It reports missing files and placeholders that were not replaced. It exits with 1 when it finds issues.
27
+
28
+ Update restores missing files and updates files the user did not change. Run it with update. It never overwrites a file the user changed. It reports skipped files instead. It updates the version marker after it runs.
29
+
30
+ Init detects stacks from manifest files at the root and in packages and apps members. It scans nested members up to three levels deep. It reports each stack with its evidence file and confidence, and it marks a repo as a monorepo when workspace evidence exists or when it finds manifests in more than one member. It also records test and CI configs it finds at the root. Init writes what it found into markflow/docs/ARCHITECTURE.md and markflow/docs/STACK.md, and it stores the full discovery result in markflow/.markflow.json. It only fills docs that it just created. It never changes docs the user already edited.
31
+
32
+ See docs/PROJECT_DISCOVERY.md for how discovery works.
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
+ "bin": {
3
+ "markflow": "./src/index.js"
4
+ },
5
+ "description": "Create a Markflow docs layer in a repo.",
6
+ "engines": {
7
+ "node": ">=18"
8
+ },
9
+ "files": [
10
+ "src",
11
+ "test",
12
+ "templates",
13
+ "README.md"
14
+ ],
15
+ "license": "MIT",
2
16
  "name": "@moritakaaz/markflow",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
17
+ "scripts": {
18
+ "prepack": "rm -rf templates && cp -r ../../templates/base templates",
19
+ "test": "node --test"
20
+ },
21
+ "type": "module",
22
+ "version": "0.1.0"
23
+ }
package/src/agents.js ADDED
@@ -0,0 +1,17 @@
1
+ // Agent adapters map an agent name to its instruction files.
2
+ // AGENTS.md is created for every agent, so it is not listed here.
3
+ // Each entry lists the extra files the agent needs.
4
+ // A file entry can add frontmatter for formats that need it.
5
+ export const AGENTS = {
6
+ generic: [],
7
+ codex: [],
8
+ claude: [{ path: "CLAUDE.md" }],
9
+ cursor: [
10
+ {
11
+ path: ".cursor/rules/markflow.mdc",
12
+ frontmatter:
13
+ "---\ndescription: Markflow project instructions\nglobs:\nalwaysApply: true\n---\n",
14
+ },
15
+ ],
16
+ copilot: [{ path: ".github/copilot-instructions.md" }],
17
+ };
@@ -0,0 +1,184 @@
1
+ // Discovery reads manifest files in a repo.
2
+ // It checks many manifests, not only package.json.
3
+ // It reports every stack it finds, with its evidence.
4
+ // It scans nested members and reads workspace evidence.
5
+ import { readdir, readFile } from "node:fs/promises";
6
+ import { basename, join } from "node:path";
7
+
8
+ const MANIFESTS = {
9
+ "package.json": "JavaScript",
10
+ "composer.json": "PHP",
11
+ "go.mod": "Go",
12
+ "Cargo.toml": "Rust",
13
+ "pyproject.toml": "Python",
14
+ "requirements.txt": "Python",
15
+ "pom.xml": "Java",
16
+ "build.gradle": "Java",
17
+ "build.gradle.kts": "Kotlin",
18
+ "pubspec.yaml": "Dart",
19
+ "Gemfile": "Ruby",
20
+ };
21
+
22
+ const WORKSPACE_FILES = ["pnpm-workspace.yaml", "lerna.json"];
23
+
24
+ const CONFIG_PATTERNS = [
25
+ "vitest.config.js",
26
+ "vitest.config.ts",
27
+ "jest.config.js",
28
+ "jest.config.ts",
29
+ "pytest.ini",
30
+ "phpunit.xml",
31
+ ".gitlab-ci.yml",
32
+ ];
33
+
34
+ const SKIP_DIRS = new Set([
35
+ "node_modules",
36
+ ".git",
37
+ "dist",
38
+ "build",
39
+ "coverage",
40
+ "markflow",
41
+ ".markflow",
42
+ "vendor",
43
+ ]);
44
+
45
+ function stackFromEntry(name) {
46
+ if (name in MANIFESTS) {
47
+ return MANIFESTS[name];
48
+ }
49
+ if (name.endsWith(".csproj") || name.endsWith(".sln")) {
50
+ return "C#";
51
+ }
52
+ return null;
53
+ }
54
+
55
+ export async function discover(root) {
56
+ const projectName = basename(root);
57
+ const stacks = [];
58
+ const manifests = [];
59
+ const configs = [];
60
+ const workspaceEvidence = [];
61
+ const memberDirs = new Set();
62
+ const seen = new Set();
63
+ function addStack(name, evidence, confidence) {
64
+ manifests.push(evidence);
65
+ if (seen.has(name)) {
66
+ return;
67
+ }
68
+ seen.add(name);
69
+ stacks.push({ name, evidence, confidence });
70
+ }
71
+ async function scanDir(dir, rel, confidence, depth) {
72
+ let entries;
73
+ try {
74
+ entries = await readdir(dir, { withFileTypes: true });
75
+ } catch {
76
+ return;
77
+ }
78
+ for (const entry of entries) {
79
+ const childRel = rel ? rel + "/" + entry.name : entry.name;
80
+ if (entry.isDirectory()) {
81
+ if (SKIP_DIRS.has(entry.name)) {
82
+ continue;
83
+ }
84
+ if (
85
+ depth === 0 &&
86
+ (entry.name === "packages" || entry.name === "apps")
87
+ ) {
88
+ continue;
89
+ }
90
+ if (depth < 3) {
91
+ await scanDir(join(dir, entry.name), childRel, confidence, depth + 1);
92
+ }
93
+ continue;
94
+ }
95
+ const name = stackFromEntry(entry.name);
96
+ if (name) {
97
+ addStack(name, childRel, confidence);
98
+ if (rel) {
99
+ memberDirs.add(rel.split("/").slice(0, 2).join("/"));
100
+ }
101
+ }
102
+ }
103
+ }
104
+ await scanDir(root, "", "high", 0);
105
+ let rootEntries = [];
106
+ try {
107
+ rootEntries = await readdir(root, { withFileTypes: true });
108
+ } catch {
109
+ rootEntries = [];
110
+ }
111
+ for (const entry of rootEntries) {
112
+ if (!entry.isDirectory()) {
113
+ continue;
114
+ }
115
+ if (entry.name !== "packages" && entry.name !== "apps") {
116
+ continue;
117
+ }
118
+ let members = [];
119
+ try {
120
+ members = await readdir(join(root, entry.name), { withFileTypes: true });
121
+ } catch {
122
+ continue;
123
+ }
124
+ for (const member of members) {
125
+ if (!member.isDirectory() || SKIP_DIRS.has(member.name)) {
126
+ continue;
127
+ }
128
+ await scanDir(
129
+ join(root, entry.name, member.name),
130
+ entry.name + "/" + member.name,
131
+ "medium",
132
+ 0
133
+ );
134
+ }
135
+ }
136
+ for (const file of WORKSPACE_FILES) {
137
+ try {
138
+ await readFile(join(root, file), "utf8");
139
+ workspaceEvidence.push(file);
140
+ } catch {
141
+ // No workspace file with this name.
142
+ }
143
+ }
144
+ try {
145
+ const pkg = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
146
+ if (pkg.workspaces) {
147
+ workspaceEvidence.push("package.json workspaces");
148
+ }
149
+ } catch {
150
+ // No readable package.json at the root.
151
+ }
152
+ for (const pattern of CONFIG_PATTERNS) {
153
+ try {
154
+ await readFile(join(root, pattern), "utf8");
155
+ configs.push(pattern);
156
+ } catch {
157
+ // No config file with this name.
158
+ }
159
+ }
160
+ try {
161
+ await readdir(join(root, ".github/workflows"));
162
+ configs.push(".github/workflows");
163
+ } catch {
164
+ // No workflows folder.
165
+ }
166
+ const hasFiles = rootEntries.some(
167
+ (e) => e.name !== ".git" && e.name !== "markflow"
168
+ );
169
+ const mode = stacks.length > 0 || hasFiles ? "brownfield" : "greenfield";
170
+ const monorepo = workspaceEvidence.length > 0 || memberDirs.size > 1;
171
+ return {
172
+ stack: stacks.length > 0 ? stacks[0].name : "TBD",
173
+ stacks,
174
+ manifests,
175
+ configs,
176
+ workspace: {
177
+ detected: workspaceEvidence.length > 0,
178
+ evidence: workspaceEvidence,
179
+ },
180
+ monorepo,
181
+ mode,
182
+ projectName,
183
+ };
184
+ }
package/src/doctor.js ADDED
@@ -0,0 +1,166 @@
1
+ // Doctor checks a repo for missing Markflow files.
2
+ // It reports errors, warnings, and info.
3
+ // Errors fail the check. Warnings and info do not.
4
+ import { readdir, readFile, stat } from "node:fs/promises";
5
+ import { dirname, join, resolve } from "node:path";
6
+
7
+ const REQUIRED = [
8
+ "AGENTS.md",
9
+ "markflow/README.md",
10
+ "markflow/TASKS.md",
11
+ "markflow/CHANGELOG.md",
12
+ "markflow/docs/PRD.md",
13
+ "markflow/docs/ARCHITECTURE.md",
14
+ "markflow/docs/CODING_STANDARDS.md",
15
+ "markflow/docs/STACK.md",
16
+ "markflow/docs/TESTING.md",
17
+ "markflow/specs/index.md",
18
+ "markflow/.markflow.json",
19
+ ];
20
+
21
+ const AGENT_FILES = ["CLAUDE.md", ".cursorrules"];
22
+
23
+ async function walk(dir, out) {
24
+ let entries;
25
+ try {
26
+ entries = await readdir(dir, { withFileTypes: true });
27
+ } catch {
28
+ return;
29
+ }
30
+ for (const entry of entries) {
31
+ const full = join(dir, entry.name);
32
+ if (entry.isDirectory()) {
33
+ await walk(full, out);
34
+ continue;
35
+ }
36
+ if (entry.name.endsWith(".md")) {
37
+ out.push(full);
38
+ }
39
+ }
40
+ }
41
+
42
+ function findLinks(text) {
43
+ const links = [];
44
+ const re = /\[[^\]]*\]\(([^)\s]+)\)/g;
45
+ let match;
46
+ while ((match = re.exec(text)) !== null) {
47
+ links.push(match[1]);
48
+ }
49
+ return links;
50
+ }
51
+
52
+ export async function runDoctor(options) {
53
+ const root = (options && options.target) || process.cwd();
54
+ const errors = [];
55
+ const warnings = [];
56
+ for (const file of REQUIRED) {
57
+ try {
58
+ await stat(join(root, file));
59
+ console.log("OK " + file);
60
+ } catch {
61
+ console.log("Error Missing " + file);
62
+ errors.push(file);
63
+ }
64
+ }
65
+ let marker = null;
66
+ try {
67
+ marker = JSON.parse(
68
+ await readFile(join(root, "markflow/.markflow.json"), "utf8")
69
+ );
70
+ if (!marker.cli || !marker.template || !marker.methodology) {
71
+ console.log("Error Missing version in .markflow.json");
72
+ errors.push("markflow/.markflow.json");
73
+ }
74
+ } catch {
75
+ // Missing marker is already reported above.
76
+ }
77
+ if (marker && marker.files) {
78
+ for (const rel of Object.keys(marker.files)) {
79
+ try {
80
+ await stat(join(root, "markflow", rel));
81
+ } catch {
82
+ console.log("Warning Tracked file missing " + rel);
83
+ warnings.push(rel);
84
+ }
85
+ }
86
+ }
87
+ const mdFiles = [];
88
+ await walk(join(root, "markflow"), mdFiles);
89
+ mdFiles.push(join(root, "AGENTS.md"));
90
+ for (const file of AGENT_FILES) {
91
+ mdFiles.push(join(root, file));
92
+ }
93
+ let tbd = 0;
94
+ for (const file of mdFiles) {
95
+ let text;
96
+ try {
97
+ text = await readFile(file, "utf8");
98
+ } catch {
99
+ continue;
100
+ }
101
+ const rel = file.slice(root.length + 1);
102
+ if (text.includes("{{project_name}}")) {
103
+ console.log("Error Placeholder left in " + rel);
104
+ errors.push(rel);
105
+ }
106
+ tbd += text.split("TBD").length - 1;
107
+ for (const link of findLinks(text)) {
108
+ if (
109
+ link.startsWith("http") ||
110
+ link.startsWith("#") ||
111
+ link.startsWith("mailto:")
112
+ ) {
113
+ continue;
114
+ }
115
+ const target = link.split("#")[0];
116
+ if (!target) {
117
+ continue;
118
+ }
119
+ const dest = resolve(dirname(file), target);
120
+ try {
121
+ await stat(dest);
122
+ } catch {
123
+ console.log("Error Broken link in " + rel + " to " + target);
124
+ errors.push(rel);
125
+ }
126
+ }
127
+ }
128
+ let specTotal = 0;
129
+ let specDraft = 0;
130
+ try {
131
+ const specFiles = [];
132
+ await walk(join(root, "markflow/specs"), specFiles);
133
+ const indexText = await readFile(
134
+ join(root, "markflow/specs/index.md"),
135
+ "utf8"
136
+ );
137
+ for (const file of specFiles) {
138
+ const name = file.split("/").pop();
139
+ if (name === "index.md" || name === "_template.md") {
140
+ continue;
141
+ }
142
+ specTotal += 1;
143
+ const text = await readFile(file, "utf8");
144
+ if (text.includes("Status") && text.includes("Draft")) {
145
+ specDraft += 1;
146
+ }
147
+ if (!indexText.includes(name)) {
148
+ const rel = file.slice(root.length + 1);
149
+ console.log("Warning Spec not listed in index " + rel);
150
+ warnings.push(rel);
151
+ }
152
+ }
153
+ } catch {
154
+ // Missing specs folder is already reported above.
155
+ }
156
+ console.log("Info " + tbd + " TBD left in docs.");
157
+ console.log("Info " + specTotal + " specs, " + specDraft + " draft.");
158
+ if (errors.length === 0 && warnings.length === 0) {
159
+ console.log("Doctor found no issues.");
160
+ } else {
161
+ console.log(
162
+ "Doctor found " + errors.length + " errors, " + warnings.length + " warnings."
163
+ );
164
+ }
165
+ return { ok: errors.length === 0, errors, warnings, issues: errors };
166
+ }
package/src/hash.js ADDED
@@ -0,0 +1,7 @@
1
+ // Hash helper for change detection.
2
+ // It returns a short hash of text.
3
+ import { createHash } from "node:crypto";
4
+
5
+ export function hashText(text) {
6
+ return createHash("sha256").update(text).digest("hex").slice(0, 12);
7
+ }
package/src/index.js ADDED
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env node
2
+ // Entry point for the markflow command.
3
+ import { readFile } from "node:fs/promises";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { runDoctor } from "./doctor.js";
7
+ import { runInit } from "./init.js";
8
+ import { runUpdate } from "./update.js";
9
+
10
+ const HELP = [
11
+ "Usage",
12
+ " markflow init [--agent generic|claude|codex|cursor|copilot]",
13
+ " markflow doctor",
14
+ " markflow update [--preview]",
15
+ " markflow --help",
16
+ " markflow --version",
17
+ ].join("\n");
18
+
19
+ function parseAgent(args) {
20
+ const idx = args.indexOf("--agent");
21
+ if (idx !== -1 && args[idx + 1]) {
22
+ return args[idx + 1];
23
+ }
24
+ const eq = args.find((a) => a.startsWith("--agent="));
25
+ if (eq) {
26
+ return eq.slice("--agent=".length);
27
+ }
28
+ return "generic";
29
+ }
30
+
31
+ async function printVersion() {
32
+ const srcDir = dirname(fileURLToPath(import.meta.url));
33
+ const pkg = JSON.parse(await readFile(join(srcDir, "../package.json"), "utf8"));
34
+ console.log(pkg.version);
35
+ }
36
+
37
+ const args = process.argv.slice(2);
38
+ if (args.length === 0) {
39
+ console.log(HELP);
40
+ process.exitCode = 1;
41
+ } else if (args[0] === "--help" || args[0] === "-h") {
42
+ console.log(HELP);
43
+ } else if (args[0] === "--version" || args[0] === "-v") {
44
+ await printVersion();
45
+ } else if (args[0] === "doctor") {
46
+ const result = await runDoctor();
47
+ process.exitCode = result.ok ? 0 : 1;
48
+ } else if (args[0] === "update") {
49
+ const result = await runUpdate({ preview: args.includes("--preview") });
50
+ process.exitCode = result.ok ? 0 : 1;
51
+ } else if (args[0] === "init") {
52
+ const result = await runInit({ agent: parseAgent(args.slice(1)) });
53
+ process.exitCode = result.ok === false ? 1 : 0;
54
+ } else {
55
+ console.log("Unknown command " + args[0] + ".");
56
+ console.log(HELP);
57
+ process.exitCode = 1;
58
+ }
package/src/init.js ADDED
@@ -0,0 +1,186 @@
1
+ // Init copies the base templates into a repo.
2
+ // It is non-interactive by default.
3
+ // It never overwrites an existing file.
4
+ import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
5
+ import { dirname, join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { discover } from "./discover.js";
8
+ import { hashText } from "./hash.js";
9
+ import { AGENTS } from "./agents.js";
10
+ import { findTemplatesDir } from "./templates.js";
11
+ import { METHODOLOGY_VERSION, TEMPLATE_VERSION } from "./versions.js";
12
+
13
+ async function copyDir(src, dest, projectName) {
14
+ let created = 0;
15
+ const entries = await readdir(src, { withFileTypes: true });
16
+ for (const entry of entries) {
17
+ const srcPath = join(src, entry.name);
18
+ const destPath = join(dest, entry.name);
19
+ if (entry.isDirectory()) {
20
+ await mkdir(destPath, { recursive: true });
21
+ created += await copyDir(srcPath, destPath, projectName);
22
+ continue;
23
+ }
24
+ try {
25
+ await stat(destPath);
26
+ continue;
27
+ } catch {
28
+ // File does not exist yet, so init can create it.
29
+ }
30
+ const text = await readFile(srcPath, "utf8");
31
+ const replaced = text.split("{{project_name}}").join(projectName);
32
+ await mkdir(dirname(destPath), { recursive: true });
33
+ await writeFile(destPath, replaced);
34
+ created += 1;
35
+ }
36
+ return created;
37
+ }
38
+
39
+ export async function runInit(options) {
40
+ const agent = options.agent || "generic";
41
+ if (!(agent in AGENTS)) {
42
+ console.log("Unknown agent.");
43
+ return { agent, copied: 0, ok: false };
44
+ }
45
+ const target = options.target || process.cwd();
46
+ const context = await discover(target);
47
+ const srcDir = dirname(fileURLToPath(import.meta.url));
48
+ const templatesDir = await findTemplatesDir();
49
+ const markflowDest = join(target, "markflow");
50
+ await mkdir(markflowDest, { recursive: true });
51
+ async function exists(path) {
52
+ try {
53
+ await stat(path);
54
+ return true;
55
+ } catch {
56
+ return false;
57
+ }
58
+ }
59
+ const archPath = join(markflowDest, "docs/ARCHITECTURE.md");
60
+ const stackPath = join(markflowDest, "docs/STACK.md");
61
+ const archExisted = await exists(archPath);
62
+ const stackExisted = await exists(stackPath);
63
+ const created = await copyDir(
64
+ join(templatesDir, "markflow"),
65
+ markflowDest,
66
+ context.projectName
67
+ );
68
+ if (context.stacks.length > 0) {
69
+ const names = context.stacks.map((s) => s.name).join(", ");
70
+ const evidence = context.stacks
71
+ .map((s) => s.evidence + " (" + s.confidence + ")")
72
+ .join(", ");
73
+ if (!archExisted) {
74
+ const arch = await readFile(archPath, "utf8");
75
+ const filled = arch
76
+ .replace("- Language. TBD", "- Language. " + names)
77
+ .replace(
78
+ "- Framework. TBD",
79
+ "- Framework. TBD\n- Evidence. " +
80
+ evidence +
81
+ "\n- Monorepo. " +
82
+ (context.monorepo ? "Yes" : "No")
83
+ );
84
+ await writeFile(archPath, filled);
85
+ }
86
+ if (!stackExisted) {
87
+ const stack = await readFile(stackPath, "utf8");
88
+ const lines = context.stacks.map(
89
+ (s) => "- " + s.name + " from " + s.evidence + ", confidence " + s.confidence
90
+ );
91
+ const filled =
92
+ stack + "\n## Detected stacks\n\nDiscovery found these stacks.\n\n" + lines.join("\n") + "\n";
93
+ await writeFile(stackPath, filled);
94
+ }
95
+ }
96
+ const agentsSrc = join(templatesDir, "AGENTS.md");
97
+ const agentsDest = join(target, "AGENTS.md");
98
+ const rootFiles = {};
99
+ let agentsText = "";
100
+ try {
101
+ await stat(agentsDest);
102
+ console.log("AGENTS.md already exists.");
103
+ agentsText = await readFile(agentsDest, "utf8");
104
+ } catch {
105
+ const text = await readFile(agentsSrc, "utf8");
106
+ agentsText = text.split("{{project_name}}").join(context.projectName);
107
+ await writeFile(agentsDest, agentsText);
108
+ rootFiles["AGENTS.md"] = hashText(agentsText);
109
+ console.log("Created AGENTS.md.");
110
+ }
111
+ for (const file of AGENTS[agent]) {
112
+ const agentDest = join(target, file.path);
113
+ try {
114
+ await stat(agentDest);
115
+ console.log(file.path + " already exists.");
116
+ continue;
117
+ } catch {
118
+ // File does not exist yet, so init can create it.
119
+ }
120
+ const content = file.frontmatter
121
+ ? file.frontmatter + "\n" + agentsText
122
+ : agentsText;
123
+ await mkdir(dirname(agentDest), { recursive: true });
124
+ await writeFile(agentDest, content);
125
+ rootFiles[file.path] = hashText(content);
126
+ console.log("Created " + file.path + ".");
127
+ }
128
+ const pkg = JSON.parse(
129
+ await readFile(join(srcDir, "../package.json"), "utf8")
130
+ );
131
+ const markerPath = join(markflowDest, ".markflow.json");
132
+ let marker = null;
133
+ try {
134
+ marker = JSON.parse(await readFile(markerPath, "utf8"));
135
+ } catch {
136
+ marker = {
137
+ cli: pkg.version,
138
+ methodology: METHODOLOGY_VERSION,
139
+ template: TEMPLATE_VERSION,
140
+ project: context.projectName,
141
+ agent,
142
+ files: {},
143
+ rootFiles: {},
144
+ };
145
+ }
146
+ if (!marker.rootFiles) {
147
+ marker.rootFiles = {};
148
+ }
149
+ for (const [path, hash] of Object.entries(rootFiles)) {
150
+ if (!(path in marker.rootFiles)) {
151
+ marker.rootFiles[path] = hash;
152
+ }
153
+ }
154
+ marker.agent = marker.agent || agent;
155
+ marker.discovery = {
156
+ mode: context.mode,
157
+ stacks: context.stacks,
158
+ manifests: context.manifests,
159
+ monorepo: context.monorepo,
160
+ };
161
+ async function collectHashes(dir) {
162
+ const entries = await readdir(dir, { withFileTypes: true });
163
+ for (const entry of entries) {
164
+ const full = join(dir, entry.name);
165
+ if (entry.isDirectory()) {
166
+ await collectHashes(full);
167
+ continue;
168
+ }
169
+ if (entry.name === ".markflow.json") {
170
+ continue;
171
+ }
172
+ const rel = full.slice(markflowDest.length + 1);
173
+ if (!(rel in marker.files)) {
174
+ marker.files[rel] = hashText(await readFile(full, "utf8"));
175
+ }
176
+ }
177
+ }
178
+ await collectHashes(markflowDest);
179
+ await writeFile(markerPath, JSON.stringify(marker, null, 2) + "\n");
180
+ if (created > 0) {
181
+ console.log("Created markflow folder.");
182
+ } else {
183
+ console.log("markflow folder already exists.");
184
+ }
185
+ return { ...context, agent, copied: created };
186
+ }