@zeeshanjamshed/ai-workflow-kit 0.0.0-stage → 0.4.2
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 +158 -2
- package/dist/packages/cli/src/context.js +101 -0
- package/dist/packages/cli/src/coordination.js +147 -0
- package/dist/packages/cli/src/discovery.js +144 -0
- package/dist/packages/cli/src/initialize.js +250 -0
- package/dist/packages/cli/src/instructions.js +18 -0
- package/dist/packages/cli/src/main.js +58 -0
- package/dist/packages/cli/src/onboarding.js +168 -0
- package/dist/packages/cli/src/quickstart.js +103 -0
- package/dist/packages/cli/src/reports.js +58 -0
- package/dist/packages/cli/src/rule-activation.js +58 -0
- package/dist/packages/cli/src/setup-assets.js +18 -0
- package/dist/packages/cli/src/update.js +379 -0
- package/package.json +47 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Zeeshan Jamshed
|
|
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,159 @@
|
|
|
1
|
-
#
|
|
1
|
+
# AI Workflow Kit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A reusable, project-local AI engineering setup for Claude Code, Codex, Cursor, and other compatible coding agents.
|
|
4
|
+
|
|
5
|
+
> **Status:** Work in progress. The CLI is available from this repository for read-only checks, previews, approved initialization, and safe bundled updates. The npm release is pending.
|
|
6
|
+
|
|
7
|
+
## What we're building
|
|
8
|
+
|
|
9
|
+
- **Consistent engineering standards:** Clean, secure, maintainable code, with project-aware practices and no unnecessary complexity.
|
|
10
|
+
- **Approval-first workflow:** Investigate safely, propose a short plan, and request approval before writing code, data, or external state.
|
|
11
|
+
- **Shared project knowledge:** Architecture, decisions, tasks, relevant skills, and handoffs are kept within each project, not trapped in an individual agent session.
|
|
12
|
+
- **Safe adoption:** Support new projects, mature codebases, and existing AI configurations without overwriting important work.
|
|
13
|
+
- **Multi-agent compatibility:** Shared rules and knowledge with lightweight agent-specific entry points and optional parallel coordination.
|
|
14
|
+
- **Independent projects:** Each initialized project owns its setup and can selectively review master updates.
|
|
15
|
+
|
|
16
|
+
## Commands
|
|
17
|
+
|
|
18
|
+
| Command | Behavior |
|
|
19
|
+
| --- | --- |
|
|
20
|
+
| `ai-setup quickstart` | Preview and apply the complete recommended setup with one approval |
|
|
21
|
+
| `ai-setup init` | Discover a project, propose a safe setup, and apply approved steps |
|
|
22
|
+
| `ai-setup init --dry-run` | Preview without modifying the project |
|
|
23
|
+
| `ai-setup update` | Compare bundled defaults with project files and apply approved changes |
|
|
24
|
+
| `ai-setup doctor` | Read-only consistency and health checks |
|
|
25
|
+
|
|
26
|
+
Run these commands from a checkout with Node.js 22.18 or newer.
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
npm run ai-setup -- doctor
|
|
30
|
+
npm run ai-setup -- init --dry-run
|
|
31
|
+
npm test
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
After installing the CLI, run `ai-setup doctor` from the target project. Both commands emit JSON. Doctor exits with code 1 if it finds issues or inspection fails. Unsupported commands exit with code 2.
|
|
35
|
+
|
|
36
|
+
Discovery reports local signals such as Git state, project markers, declared framework versions, and agent paths. The dry run lists candidate paths and flags existing files for review. Doctor checks common instruction entry points, basic manifest validity, and local Markdown links. Confirm agent behavior, rule conflicts, and project-specific context separately. Updates use the baseline bundled with the installed CLI.
|
|
37
|
+
|
|
38
|
+
## One-command quickstart
|
|
39
|
+
|
|
40
|
+
[Install the CLI](#install-the-cli-for-agent-sessions), then run this from the project:
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
ai-setup quickstart
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Review the repository root, tracking policy, paths to add, and existing instruction files that will receive a rule section. Type `apply` once to approve the setup. Use `ai-setup quickstart --dry-run` for the same preview without writing anything. New setups default to mixed tracking, which keeps knowledge, decisions, and handoffs Git-ignored. Existing setups keep their tracking policy and installed baseline.
|
|
47
|
+
|
|
48
|
+
Quickstart sets up missing shared files, the five recommended engineering modules, and native instruction entry points for Claude Code, Codex, and Cursor. It installs guided onboarding skills for Claude Code and Codex. Existing custom rules, skills, knowledge, and instruction text are preserved. Resolve semantic instruction conflicts before approving. A conflicting activation section or privacy policy blocks the operation.
|
|
49
|
+
|
|
50
|
+
If interrupted, rerun `ai-setup quickstart` to review and approve the saved plan. A successful run prints a backup ID. `ai-setup rollback <backup-id>` previews reversal and refuses if any affected file changed afterward. Review rollback carefully because it removes kit-created files from that run. Individual setup commands are still available below.
|
|
51
|
+
|
|
52
|
+
Start a fresh Claude Code or Codex session in the project and run the **guided-project-onboarding** skill. The agent examines the actual code and proposes useful knowledge. Saving that knowledge needs separate approval.
|
|
53
|
+
|
|
54
|
+
## Initialize a project
|
|
55
|
+
|
|
56
|
+
After installing the CLI, run this from the target project's directory:
|
|
57
|
+
|
|
58
|
+
```sh
|
|
59
|
+
ai-setup init
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Choose a tracking policy and optional Claude, Codex, or Cursor entry points. Inspect the preview, which shows exact proposed contents and paths. Type `apply` to approve that plan. Any other response leaves the project untouched. For an exact read-only preview, use `init --dry-run --tracking=mixed --agents=codex`. An empty `--agents=` selects no entry points.
|
|
63
|
+
|
|
64
|
+
- **Tracked** leaves new setup records eligible to commit and share.
|
|
65
|
+
- **Mixed** leaves setup eligible to share and ignores the `.ai/knowledge/`, `.ai/decisions/`, and `.ai/tasks/` directories.
|
|
66
|
+
- **Local-only** ignores the new `.ai/` records. In a Git repository, any new root or Cursor entry point must already be ignored and untracked. Choose no entry points if existing ignore rules do not cover them. Local records need independent backups.
|
|
67
|
+
|
|
68
|
+
Initialization creates missing files and preserves existing instructions, skills, and project knowledge in place. It makes no Git commits or changes to existing files, so there are no overwritten originals to back up. Reconcile existing custom instructions manually. An incompatible privacy rule or an unrecognized manifest blocks initialization. If interrupted, rerun `init` to review and approve the saved plan. The journal remains available for inspection, and a completed manifest makes reruns a no-op. Real agent discovery and approval behavior are verified in a later phase.
|
|
69
|
+
|
|
70
|
+
## Updates, backups, and installation
|
|
71
|
+
|
|
72
|
+
From an initialized project, use `ai-setup update --dry-run` to compare the installed baseline, local files, and the current bundled version. The update checks manifest hashes and works offline. It replaces an unchanged kit file when the bundled default changes and preserves local edits when that default stays the same. If both sides changed, or a managed file is missing, the update stops for review. Existing unmanaged rules, skills, knowledge, and decisions stay in place.
|
|
73
|
+
|
|
74
|
+
- `ai-setup update` shows the plan and waits for `apply`. Use `--version=0.4.2` to select the current bundled release explicitly.
|
|
75
|
+
- `ai-setup pin <version>` pins the installed or current bundled version. Use `ai-setup pin none` to unpin. Both require approval.
|
|
76
|
+
- `ai-setup repair` can restore missing managed files from the installed baseline after approval. It preserves existing files.
|
|
77
|
+
- `ai-setup rollback <backup-id>` previews the inverse operation and requires approval. It refuses to overwrite subsequent edits. If interrupted, rerun `ai-setup update` to review and resume the pending operation.
|
|
78
|
+
|
|
79
|
+
Backups and the recovery journal stay in the ignored `.ai/update-backups/` directory. They contain the before and after contents of files in the operation. Keep secrets out of setup files. Close other editors and avoid concurrent setup operations while applying changes. The current bundle recognizes setup versions 0.1.0, 0.2.0, 0.3.0, 0.4.0, 0.4.1, and 0.4.2. It upgrades to its own version and leaves version downgrades to rollback.
|
|
80
|
+
|
|
81
|
+
### Use npm after publication
|
|
82
|
+
|
|
83
|
+
Once the package is published to npm, run this from the target project:
|
|
84
|
+
|
|
85
|
+
```sh
|
|
86
|
+
npx -y @zeeshanjamshed/ai-workflow-kit quickstart
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
The registry command requires publication first. The npm `-y` flag answers npm's package-install prompt. Quickstart still previews project changes and waits for you to type `apply`. Add `--dry-run` after `quickstart` for a read-only project preview. npm may download and cache the CLI.
|
|
90
|
+
|
|
91
|
+
For repeated use after publication, run `npm install --global @zeeshanjamshed/ai-workflow-kit`, then use `ai-setup quickstart` from your project. Both paths require Node.js 22.18 or newer.
|
|
92
|
+
|
|
93
|
+
### Install the CLI for agent sessions
|
|
94
|
+
|
|
95
|
+
Use Node.js 22.18 or newer. In a checkout of the reviewed kit commit, build the local tarball and install it once with the npm used by your agent shell.
|
|
96
|
+
|
|
97
|
+
```sh
|
|
98
|
+
npm ci --ignore-scripts
|
|
99
|
+
npm pack
|
|
100
|
+
npm install --global --offline --ignore-scripts ./zeeshanjamshed-ai-workflow-kit-0.4.2.tgz
|
|
101
|
+
ai-setup --version
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
npm copies the compiled CLI into its global prefix. You can move or remove the build checkout after installation. On macOS and Linux the launcher is under `$(npm prefix -g)/bin`; on Windows it is directly under the directory printed by `npm prefix -g`. If `ai-setup --version` fails, put that executable directory on your user PATH or use the Node version manager's active environment. Restart Claude Code or Codex from a terminal where the version check succeeds. If you use multiple profiles or launch agents from an IDE, repeat the version check in each launch environment. A Node version manager may keep global packages separate per Node version.
|
|
105
|
+
|
|
106
|
+
Use the tarball flow in place of the previously unsuccessful one-time GitHub package invocation. The installed CLI has no runtime dependencies and works offline. Future kit builds can be installed the same way. The v0.4.0 baseline remains bundled so existing setups can preview upgrades and use their backups.
|
|
107
|
+
|
|
108
|
+
## Guided onboarding and engineering rules
|
|
109
|
+
|
|
110
|
+
From the target checkout, run `ai-setup onboard` and give its output to Claude Code or Codex. The inventory includes project and Git signals, up to 300 tracked paths, known instruction locations, and existing knowledge. The agent reads actual manifests, source, tests, and docs to trace relevant architecture and critical flows. Review its proposed facts, hypotheses, and open questions before saving anything.
|
|
111
|
+
|
|
112
|
+
- `ai-setup onboard install-skills both` previews native project skills for Claude and Codex. Use `claude` or `codex` for one. Restart the agent session and select the guided project onboarding skill.
|
|
113
|
+
- `ai-setup onboard save` accepts the JSON array shown by `onboard` on one input line. Each verified fact needs a tracked source path, line, and exact excerpt. The CLI checks the excerpt and stores the citation. Review the fact itself against the cited code. Enter `apply` after reviewing the exact additions. Use stable record IDs so reruns keep identical records and surface differences.
|
|
114
|
+
- `ai-setup rules minimal` keeps the essential setup. `ai-setup rules recommended` previews the five engineering modules. `ai-setup rules custom architecture testing` previews only the named modules.
|
|
115
|
+
- After reviewing the modules, run `ai-setup rules activate all --dry-run` to preview links for all five existing modules, or use `ai-setup rules activate architecture testing --dry-run` for a subset. Rerun without `--dry-run` and type `apply` after checking for conflicts. Existing v0.4.0 projects can activate the modules they already have, including customized versions.
|
|
116
|
+
- Activation appends a reversible section to existing native entry points. Claude Code uses imports. Codex loads the section through `AGENTS.md` (or `AGENTS.override.md` when present) and is instructed to read the selected files before planning. The kit's Cursor always-applied adapter can also point to them. Restart agents to pick up the entry-point changes and review nested or user-level instructions for precedence conflicts.
|
|
117
|
+
- `ai-setup rules` reports each module's presence, selected entry points, and whether its contents match the bundle or are project-owned. Modules remain editable project files. Activation leaves their contents and update provenance alone. Use `ai-setup rollback <backup-id>` to undo an activation if the affected instructions still match the approved change.
|
|
118
|
+
|
|
119
|
+
These additions require an initialized project. Preview them before applying, especially when existing instruction files might conflict. An existing target with different contents blocks the plan. The CLI flags file conflicts and lists existing instructions for review. The agent and project owner resolve conflicts in meaning. Generated setup guides point agents to the rule inventory. Use the activation preview to review changes to existing entry points.
|
|
120
|
+
|
|
121
|
+
Knowledge, optional skills, and selected modules are project-owned additions. The commands preserve existing files and honor the setup’s Git privacy policy. Customize modules with a separately approved edit. Kit updates leave these additions out of the managed manifest, so version changes and rollback do not replace them.
|
|
122
|
+
|
|
123
|
+
## Agent instructions, skills, and handoffs
|
|
124
|
+
|
|
125
|
+
New setups can generate Claude Code’s `CLAUDE.md`, Codex’s `AGENTS.md`, or a Cursor project rule. Claude imports the shared permissions file. Codex loads `AGENTS.md` and reads shared context on demand. Cursor can use the same `AGENTS.md` when present, or a kit-generated always-applied rule for Cursor-only setups. Existing entries remain authoritative and need manual reconciliation where they differ. Completed older setups stay intact, and interrupted Phase 4 setups resume with their original templates.
|
|
126
|
+
|
|
127
|
+
Run `ai-setup skills` from the project or relevant subdirectory to inventory `SKILL.md` paths in `.claude/skills`, `.agents/skills`, and `.cursor/skills` in project scope and under the current home directory. The inventory shows filesystem candidates, including third-party skills at those paths. It does not execute skills or resolve plugin, managed, synced, or disabled entries. Verify actual availability in the agent UI.
|
|
128
|
+
|
|
129
|
+
Use `ai-setup context` to find project knowledge, decisions, and task handoffs. Use `ai-setup context <task-id>` to read one task with current Git context. For approved handoff writes, use `.ai/tasks/<task-id>.md` and record scope, approvals, affected files, Git branch and commit, verified findings, tests, blockers, and next action. Keep secrets out and verify claims against Git and code before continuing. Ignored and uncommitted records need an explicit sharing mechanism.
|
|
130
|
+
|
|
131
|
+
### Verify an agent in a disposable project
|
|
132
|
+
|
|
133
|
+
1. Initialize a disposable Git repository with the relevant adapter enabled. Add a harmless unique phrase to the fixture’s shared permissions, a sample skill in its native directory, and a task record.
|
|
134
|
+
2. Start a fresh agent session in the fixture using its native safe settings. Ask it to report the phrase, identify the skill, and resume the task. Check that it reads the task, inspects Git, and distinguishes evidence from assumptions.
|
|
135
|
+
3. Ask for a write without granting approval. Check that the agent asks first and that the fixture stays unchanged. Record the runtime version, permissions, and observed result. Repeat with existing custom instructions to check preservation and precedence.
|
|
136
|
+
|
|
137
|
+
Prompt instructions guide behavior. Use the agent’s native sandbox and permissions for enforcement. Automated tests check generated files and read-only commands. Live verification is pending for Claude Code and Cursor, which were unavailable here. Codex CLI 0.167.0-alpha.4 was installed, but its isolated run could not load instructions because the filesystem sandbox helper could not build the bubblewrap command. The isolated profile was also signed out.
|
|
138
|
+
|
|
139
|
+
References: [Claude Code instructions](https://code.claude.com/docs/en/memory), [Claude Code skills](https://code.claude.com/docs/en/skills), [Codex instructions](https://learn.chatgpt.com/docs/agent-configuration/agents-md), [Codex skills](https://learn.chatgpt.com/docs/build-skills), [Cursor rules](https://cursor.com/docs/rules), and [Cursor skills](https://cursor.com/docs/skills).
|
|
140
|
+
|
|
141
|
+
## Coordinate parallel work
|
|
142
|
+
|
|
143
|
+
From the target checkout, run `ai-setup coordinate status` before editing. Use `coordinate claim <task> <agent> <path> [path...]` to claim files or directories, or quote `"*"` for a repository-wide claim. Type `apply` after reviewing the plan. Keep the returned ownership token private. Use it with `coordinate renew <task> <token>` or `coordinate release <task> <token> [.ai/tasks/<id>.md]`.
|
|
144
|
+
|
|
145
|
+
Claims last one hour. Stale claims still block overlapping work until you confirm the old writer stopped and explicitly approve `coordinate takeover <task> <agent> <path> [path...]`. A crashed metadata writer may leave `write.lock` in the reported coordination directory. Clear the empty lock directory manually only after confirming no writer is running.
|
|
146
|
+
|
|
147
|
+
Pass `--worktree` from an explicitly created linked worktree. The command never creates branches or worktrees. Same-clone worktrees share advisory ownership through Git’s common directory. Separate clones and working-file edits are independent. Share durable handoffs through an approved Git or other sync step, and verify the recorded commit, local changes, and handoff before acting. Coordination never authorizes project writes.
|
|
148
|
+
|
|
149
|
+
CI checks Node.js 22 and 24 on Linux, macOS, and Windows, runs strict type checks and fixture tests, verifies offline package installation, and audits npm dependencies. See the [project plan](docs/PROJECT_PLAN.md) for observed results. Workflow fixtures exercise CLI boundaries and handoffs. Live agent behavior is checked separately.
|
|
150
|
+
|
|
151
|
+
## Specification
|
|
152
|
+
|
|
153
|
+
Read the [master specification](docs/SPECIFICATION.md) for the approved requirements, proposed structures, safety boundaries, and acceptance criteria.
|
|
154
|
+
|
|
155
|
+
## Development approach
|
|
156
|
+
|
|
157
|
+
Implementation will be incremental and reviewed before each stage. The first stable `v1.0.0` release will follow testing across new, existing, and AI-configured projects.
|
|
158
|
+
|
|
159
|
+
The repository is licensed under the [MIT License](LICENSE). npm publication requires separate owner approval.
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import { dirname, join, relative, sep } from 'node:path';
|
|
3
|
+
import { readdirSync, realpathSync, statSync } from 'node:fs';
|
|
4
|
+
import { readProjectFile, within } from "./discovery.js";
|
|
5
|
+
const skillRoots = [
|
|
6
|
+
{ agent: 'claude', directory: '.claude/skills', nested: false },
|
|
7
|
+
{ agent: 'codex', directory: '.agents/skills', nested: true },
|
|
8
|
+
{ agent: 'cursor', directory: '.cursor/skills', nested: true },
|
|
9
|
+
];
|
|
10
|
+
function list(path) {
|
|
11
|
+
try {
|
|
12
|
+
return readdirSync(path, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
if (['ENOENT', 'ENOTDIR'].includes(error.code ?? ''))
|
|
16
|
+
return [];
|
|
17
|
+
throw error;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function isFile(path) {
|
|
21
|
+
try {
|
|
22
|
+
return statSync(path).isFile();
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (['ENOENT', 'ENOTDIR', 'ELOOP'].includes(error.code ?? ''))
|
|
26
|
+
return false;
|
|
27
|
+
throw error;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function skillFiles(root, nested) {
|
|
31
|
+
const files = [];
|
|
32
|
+
const pending = [root];
|
|
33
|
+
while (pending.length) {
|
|
34
|
+
const directory = pending.pop();
|
|
35
|
+
for (const entry of list(directory)) {
|
|
36
|
+
const folder = join(directory, entry.name);
|
|
37
|
+
if (entry.name.startsWith('.') || !entry.isDirectory() && !entry.isSymbolicLink())
|
|
38
|
+
continue;
|
|
39
|
+
const file = join(folder, 'SKILL.md');
|
|
40
|
+
if (isFile(file))
|
|
41
|
+
files.push(file);
|
|
42
|
+
else if (nested && entry.isDirectory())
|
|
43
|
+
pending.push(folder);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return files.sort();
|
|
47
|
+
}
|
|
48
|
+
export function discoverSkills(project, cwd, home = homedir()) {
|
|
49
|
+
// Use the same OS canonicalization for the Git-reported root and the working directory.
|
|
50
|
+
const root = realpathSync.native(project.root);
|
|
51
|
+
const directories = [root];
|
|
52
|
+
for (let dir = realpathSync.native(cwd); within(root, dir) && relative(root, dir); dir = dirname(dir)) {
|
|
53
|
+
directories.push(dir);
|
|
54
|
+
}
|
|
55
|
+
const displayPath = (base, path) => relative(base, path).split(sep).join('/');
|
|
56
|
+
return skillRoots.flatMap(({ agent, directory, nested }) => [
|
|
57
|
+
...directories.flatMap(dir => skillFiles(join(dir, directory), nested).map(path => ({
|
|
58
|
+
agent, scope: 'project', path: displayPath(root, path),
|
|
59
|
+
}))),
|
|
60
|
+
...skillFiles(join(home, directory), nested).map(path => ({
|
|
61
|
+
agent, scope: 'user', path: displayPath(home, path),
|
|
62
|
+
})),
|
|
63
|
+
]);
|
|
64
|
+
}
|
|
65
|
+
function records(root, directory) {
|
|
66
|
+
const path = join(root, directory);
|
|
67
|
+
try {
|
|
68
|
+
if (!within(root, realpathSync(path)))
|
|
69
|
+
return [];
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
if (error.code === 'ENOENT')
|
|
73
|
+
return [];
|
|
74
|
+
throw error;
|
|
75
|
+
}
|
|
76
|
+
return list(path)
|
|
77
|
+
.filter(entry => entry.isFile() && /^[a-zA-Z0-9][a-zA-Z0-9._-]*\.md$/.test(entry.name))
|
|
78
|
+
.map(entry => directory + '/' + entry.name);
|
|
79
|
+
}
|
|
80
|
+
export function resumeContext(project, task) {
|
|
81
|
+
const { root } = project;
|
|
82
|
+
const tasks = records(root, '.ai/tasks');
|
|
83
|
+
let handoff;
|
|
84
|
+
if (task !== undefined) {
|
|
85
|
+
const path = '.ai/tasks/' + task + '.md';
|
|
86
|
+
if (!tasks.includes(path))
|
|
87
|
+
throw new Error('Task not found. Run context to list available handoffs.');
|
|
88
|
+
const markdown = readProjectFile(root, path);
|
|
89
|
+
if (markdown === undefined)
|
|
90
|
+
throw new Error('The task record is not readable inside the project.');
|
|
91
|
+
handoff = { path, markdown };
|
|
92
|
+
}
|
|
93
|
+
return {
|
|
94
|
+
root, git: project.git,
|
|
95
|
+
index: ['.ai/README.md', '.ai/rules/permissions.md'].filter(path => readProjectFile(root, path) !== undefined),
|
|
96
|
+
knowledge: records(root, '.ai/knowledge'),
|
|
97
|
+
decisions: records(root, '.ai/decisions'),
|
|
98
|
+
tasks, handoff,
|
|
99
|
+
next: 'Read the project rules. Verify handoff claims against the current Git state and code. Confirm approval before writing.',
|
|
100
|
+
};
|
|
101
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { createInterface } from 'node:readline/promises';
|
|
5
|
+
import { stdin } from 'node:process';
|
|
6
|
+
import { exists, git, readProjectFile } from "./discovery.js";
|
|
7
|
+
const ttl = 60 * 60 * 1000;
|
|
8
|
+
const name = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;
|
|
9
|
+
const tokenPattern = /^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/;
|
|
10
|
+
function scope(path) {
|
|
11
|
+
const parts = path.replaceAll('\\', '/').split('/');
|
|
12
|
+
if (parts.some(part => !/^[a-zA-Z0-9_.-]+$/.test(part) || ['.', '..', '.git'].includes(part.toLowerCase()))) {
|
|
13
|
+
throw new Error('Use repository-relative paths with simple names, or * for the entire repository.');
|
|
14
|
+
}
|
|
15
|
+
return parts.join('/').toLowerCase();
|
|
16
|
+
}
|
|
17
|
+
function overlaps(left, right) {
|
|
18
|
+
return left === '*' || right === '*' || left === right || left.startsWith(right + '/') || right.startsWith(left + '/');
|
|
19
|
+
}
|
|
20
|
+
function readClaims(path) {
|
|
21
|
+
if (!exists(path))
|
|
22
|
+
return [];
|
|
23
|
+
const file = lstatSync(path);
|
|
24
|
+
if (!file.isFile() || file.size > 1024 * 1024)
|
|
25
|
+
throw new Error('Unsafe coordination state file.');
|
|
26
|
+
const data = JSON.parse(readFileSync(path, 'utf8'));
|
|
27
|
+
if (!Array.isArray(data) || data.some(item => !item || typeof item.task !== 'string' || !name.test(item.task) ||
|
|
28
|
+
typeof item.agent !== 'string' || !name.test(item.agent) || typeof item.token !== 'string' || !tokenPattern.test(item.token) ||
|
|
29
|
+
typeof item.checkout !== 'string' || !Number.isSafeInteger(item.expires) || !Array.isArray(item.paths) || !item.paths.length ||
|
|
30
|
+
item.paths.some((p) => typeof p !== 'string' || p !== '*' && scope(p) !== p))) {
|
|
31
|
+
throw new Error('Invalid coordination state.');
|
|
32
|
+
}
|
|
33
|
+
return data;
|
|
34
|
+
}
|
|
35
|
+
export async function coordinate(project, input) {
|
|
36
|
+
const worktree = input.includes('--worktree');
|
|
37
|
+
const args = input.filter(arg => arg !== '--worktree');
|
|
38
|
+
const [action = 'status', task, credential, ...rawPaths] = args;
|
|
39
|
+
const common = git(project.root, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
|
|
40
|
+
const local = git(project.root, ['rev-parse', '--absolute-git-dir']);
|
|
41
|
+
if (!common || !local)
|
|
42
|
+
throw new Error('Coordination requires a Git checkout.');
|
|
43
|
+
if (realpathSync(common) !== realpathSync(local) && !worktree) {
|
|
44
|
+
throw new Error('Use --worktree explicitly to coordinate from this linked worktree.');
|
|
45
|
+
}
|
|
46
|
+
const directory = join(realpathSync(common), 'ai-workflow-kit-coordination');
|
|
47
|
+
const state = join(directory, 'claims.json');
|
|
48
|
+
const lock = join(directory, 'write.lock');
|
|
49
|
+
function checkDirectory() {
|
|
50
|
+
if (exists(directory) && !lstatSync(directory).isDirectory())
|
|
51
|
+
throw new Error('Unsafe coordination directory.');
|
|
52
|
+
}
|
|
53
|
+
checkDirectory();
|
|
54
|
+
const snapshot = readClaims(state);
|
|
55
|
+
if (action === 'status' && args.length <= 1) {
|
|
56
|
+
console.log(JSON.stringify(snapshot.map(({ token, ...claim }) => ({
|
|
57
|
+
...claim, stale: claim.expires <= Date.now(),
|
|
58
|
+
})), null, 2));
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (!task || !name.test(task) || !credential)
|
|
62
|
+
throw new Error('Provide a task ID and agent name or ownership token.');
|
|
63
|
+
const existing = snapshot.find(item => item.task === task);
|
|
64
|
+
const now = Date.now();
|
|
65
|
+
let replacement;
|
|
66
|
+
if (action === 'claim' || action === 'takeover') {
|
|
67
|
+
if (!name.test(credential) || !rawPaths.length || rawPaths.length > 32)
|
|
68
|
+
throw new Error('Provide an agent name and 1–32 paths.');
|
|
69
|
+
if (action === 'claim' && existing && existing.expires !== 0)
|
|
70
|
+
throw new Error('Task is already owned. Check status for expiry.');
|
|
71
|
+
if (action === 'takeover' && (!existing || existing.expires === 0 || existing.expires > now)) {
|
|
72
|
+
throw new Error('Only stale ownership can be taken over.');
|
|
73
|
+
}
|
|
74
|
+
const paths = [...new Set(rawPaths.map(path => path === '*' ? '*' : scope(path)))].sort();
|
|
75
|
+
const conflict = snapshot.find(claim => claim.task !== task && claim.expires !== 0 &&
|
|
76
|
+
paths.some(path => claim.paths.some(other => overlaps(path, other))));
|
|
77
|
+
if (conflict)
|
|
78
|
+
throw new Error(`Scope overlaps task ${conflict.task} (${conflict.expires <= now ? 'stale' : 'active'}).`);
|
|
79
|
+
replacement = { task, agent: credential, token: randomUUID(), paths, checkout: project.root,
|
|
80
|
+
head: project.git.head, expires: now + ttl, handoff: existing?.handoff };
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
if (!existing || existing.token !== credential || existing.checkout !== project.root || existing.expires === 0) {
|
|
84
|
+
throw new Error('The token and checkout must match the current owner.');
|
|
85
|
+
}
|
|
86
|
+
if (action === 'renew' && !rawPaths.length && existing.expires > now) {
|
|
87
|
+
replacement = { ...existing, head: project.git.head, expires: now + ttl };
|
|
88
|
+
}
|
|
89
|
+
else if (action === 'release' && rawPaths.length <= 1) {
|
|
90
|
+
const handoff = rawPaths[0];
|
|
91
|
+
if (handoff && (!/^\.ai\/tasks\/[a-zA-Z0-9_-]+\.md$/.test(handoff) || readProjectFile(project.root, handoff) === undefined)) {
|
|
92
|
+
throw new Error('Use a readable .ai/tasks/<id>.md handoff in this checkout.');
|
|
93
|
+
}
|
|
94
|
+
replacement = { ...existing, head: project.git.head, expires: 0, handoff };
|
|
95
|
+
}
|
|
96
|
+
else
|
|
97
|
+
throw new Error('Invalid coordination operation or stale ownership.');
|
|
98
|
+
}
|
|
99
|
+
const { token, ...preview } = replacement;
|
|
100
|
+
console.log(JSON.stringify({ action, ...preview, state, note: 'Recheck Git and working files before editing. Claims are advisory and shared only within this clone.' }, null, 2));
|
|
101
|
+
const lines = createInterface({ input: stdin, terminal: false });
|
|
102
|
+
let approved = false;
|
|
103
|
+
try {
|
|
104
|
+
console.log('Type apply to approve this coordination change:');
|
|
105
|
+
for await (const line of lines) {
|
|
106
|
+
approved = line.trim() === 'apply';
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
lines.close();
|
|
112
|
+
}
|
|
113
|
+
if (!approved)
|
|
114
|
+
return;
|
|
115
|
+
checkDirectory();
|
|
116
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
117
|
+
try {
|
|
118
|
+
mkdirSync(lock, { mode: 0o700 });
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
throw new Error('Coordination writer is locked. Confirm no writer is running before manually clearing write.lock.');
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
if (JSON.stringify(readClaims(state)) !== JSON.stringify(snapshot) ||
|
|
125
|
+
git(project.root, ['rev-parse', '--verify', 'HEAD']) !== project.git.head) {
|
|
126
|
+
throw new Error('Coordination or Git state changed. Review a fresh plan.');
|
|
127
|
+
}
|
|
128
|
+
if (action === 'renew' && existing.expires <= Date.now())
|
|
129
|
+
throw new Error('Ownership expired. Review takeover.');
|
|
130
|
+
if (replacement.expires !== 0)
|
|
131
|
+
replacement.expires = Date.now() + ttl;
|
|
132
|
+
const temporary = join(directory, randomUUID() + '.tmp');
|
|
133
|
+
try {
|
|
134
|
+
writeFileSync(temporary, JSON.stringify([...snapshot.filter(claim => claim.task !== task), replacement], null, 2) + '\n', { flag: 'wx', mode: 0o600 });
|
|
135
|
+
renameSync(temporary, state);
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
if (exists(temporary))
|
|
139
|
+
unlinkSync(temporary);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
rmdirSync(lock);
|
|
144
|
+
}
|
|
145
|
+
if (action === 'claim' || action === 'takeover')
|
|
146
|
+
console.log(`Ownership token: ${token}`);
|
|
147
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { accessSync, constants, lstatSync, readFileSync, readdirSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
4
|
+
const markers = ['package.json', 'pnpm-workspace.yaml', 'Cargo.toml', 'pyproject.toml', 'go.mod', 'composer.json', 'Gemfile', 'pom.xml', 'build.gradle', 'pubspec.yaml'];
|
|
5
|
+
const agentFiles = {
|
|
6
|
+
claude: ['CLAUDE.md', '.claude/CLAUDE.md', '.claude/rules', '.claude/skills'],
|
|
7
|
+
codex: ['AGENTS.md', 'AGENTS.override.md', '.agents/skills'],
|
|
8
|
+
cursor: ['.cursor/rules', '.cursorrules', '.cursor/skills'],
|
|
9
|
+
other: ['.github/copilot-instructions.md', 'GEMINI.md', '.windsurfrules', '.aider.conf.yml'],
|
|
10
|
+
};
|
|
11
|
+
const frameworkNames = ['next', 'react', 'vue', 'nuxt', 'svelte', '@angular/core', 'expo', 'react-native', 'express', 'astro', '@sveltejs/kit'];
|
|
12
|
+
export function exists(path) {
|
|
13
|
+
try {
|
|
14
|
+
lstatSync(path);
|
|
15
|
+
return true;
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
if (error.code === 'ENOENT' || error.code === 'ENOTDIR')
|
|
19
|
+
return false;
|
|
20
|
+
throw error;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export function within(root, path) {
|
|
24
|
+
const rel = relative(root, path);
|
|
25
|
+
return !isAbsolute(rel) && rel !== '..' && !rel.startsWith('..' + sep);
|
|
26
|
+
}
|
|
27
|
+
export function readProjectFile(root, path) {
|
|
28
|
+
const file = resolve(root, path);
|
|
29
|
+
if (!within(root, file) || !exists(file))
|
|
30
|
+
return undefined;
|
|
31
|
+
const actual = realpathSync(file);
|
|
32
|
+
if (!within(root, actual) || !lstatSync(actual).isFile())
|
|
33
|
+
return undefined;
|
|
34
|
+
if (lstatSync(actual).size > 1024 * 1024)
|
|
35
|
+
return undefined;
|
|
36
|
+
return readFileSync(actual, 'utf8');
|
|
37
|
+
}
|
|
38
|
+
export function readObject(source) {
|
|
39
|
+
if (source === undefined)
|
|
40
|
+
return undefined;
|
|
41
|
+
try {
|
|
42
|
+
const value = JSON.parse(source);
|
|
43
|
+
if (value && typeof value === 'object' && !Array.isArray(value))
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
// Discovery can continue when optional metadata is invalid.
|
|
48
|
+
}
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
function executable(name) {
|
|
52
|
+
const suffixes = process.platform === 'win32' ? ['.exe', '.cmd', '.bat'] : [''];
|
|
53
|
+
return (process.env.PATH ?? '').split(delimiter).filter(isAbsolute).some(dir => suffixes.some(suffix => {
|
|
54
|
+
try {
|
|
55
|
+
const path = join(dir, name + suffix);
|
|
56
|
+
accessSync(path, constants.X_OK);
|
|
57
|
+
return lstatSync(realpathSync(path)).isFile();
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
}));
|
|
63
|
+
}
|
|
64
|
+
function runGit(root, args, input) {
|
|
65
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith('GIT_')));
|
|
66
|
+
return spawnSync('git', [
|
|
67
|
+
'--no-optional-locks', '--no-lazy-fetch', '-c', 'core.fsmonitor=false',
|
|
68
|
+
'-c', 'core.untrackedCache=false', ...args,
|
|
69
|
+
], {
|
|
70
|
+
cwd: root,
|
|
71
|
+
env: { ...env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: process.platform === 'win32' ? 'NUL' : '/dev/null' },
|
|
72
|
+
encoding: 'utf8', input, timeout: 5000, maxBuffer: 4 * 1024 * 1024, windowsHide: true,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
export function git(root, args, input) {
|
|
76
|
+
const result = runGit(root, args, input);
|
|
77
|
+
return result.status === 0 ? result.stdout.trimEnd() : undefined;
|
|
78
|
+
}
|
|
79
|
+
export function inspectGitPath(root, path, kind) {
|
|
80
|
+
if (kind === 'tracked') {
|
|
81
|
+
const result = git(root, ['ls-files', '--', path]);
|
|
82
|
+
return result === undefined ? undefined : result.length > 0;
|
|
83
|
+
}
|
|
84
|
+
const { status } = runGit(root, ['check-ignore', '--no-index', '--quiet', '--', path]);
|
|
85
|
+
return status === 0 ? true : status === 1 ? false : undefined;
|
|
86
|
+
}
|
|
87
|
+
function fallbackRoot(start) {
|
|
88
|
+
for (let dir = start;; dir = dirname(dir)) {
|
|
89
|
+
if (exists(join(dir, '.git')) || markers.some(marker => exists(join(dir, marker))))
|
|
90
|
+
return dir;
|
|
91
|
+
if (dirname(dir) === dir)
|
|
92
|
+
return start;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
export function projectPathExists(root, path) {
|
|
96
|
+
const file = resolve(root, path);
|
|
97
|
+
return within(root, file) && exists(file);
|
|
98
|
+
}
|
|
99
|
+
export function discover(start = process.cwd()) {
|
|
100
|
+
const cwd = realpathSync(start);
|
|
101
|
+
const gitRoot = executable('git') ? git(cwd, ['rev-parse', '--show-toplevel']) : undefined;
|
|
102
|
+
const root = gitRoot ? realpathSync(gitRoot) : fallbackRoot(cwd);
|
|
103
|
+
const files = readdirSync(root).filter(name => name !== '.git').sort();
|
|
104
|
+
const has = (path) => exists(join(root, path));
|
|
105
|
+
const tools = Object.fromEntries(['git', 'node', 'npm', 'pnpm', 'yarn', 'claude', 'codex', 'cursor'].map(name => [name, executable(name)]));
|
|
106
|
+
const agents = Object.entries(agentFiles).map(([name, paths]) => ({
|
|
107
|
+
name, paths: paths.filter(has), onPath: tools[name] ?? false,
|
|
108
|
+
}));
|
|
109
|
+
const manifest = readObject(readProjectFile(root, '.ai/setup-manifest.json'));
|
|
110
|
+
const pkg = readObject(readProjectFile(root, 'package.json'));
|
|
111
|
+
const dependencies = { ...readObjectFromValue(pkg?.dependencies), ...readObjectFromValue(pkg?.devDependencies) };
|
|
112
|
+
const frameworks = Object.fromEntries(frameworkNames.filter(name => typeof dependencies[name] === 'string').map(name => [name, dependencies[name]]));
|
|
113
|
+
// Git status may invoke project-configured clean filters. Disable them before inspecting.
|
|
114
|
+
const filterKeys = gitRoot ? git(root, ['config', '--name-only', '--list', '--null']) : undefined;
|
|
115
|
+
const filterOverrides = filterKeys?.split('\0').flatMap(key => /^filter\..+\.(clean|process|required)$/i.test(key)
|
|
116
|
+
? ['-c', key + (key.toLowerCase().endsWith('.required') ? '=false' : '=')]
|
|
117
|
+
: []);
|
|
118
|
+
const status = filterOverrides ? git(root, [
|
|
119
|
+
...filterOverrides, 'status', '--porcelain=v1', '--untracked-files=normal', '--ignore-submodules=all', '--no-renames',
|
|
120
|
+
]) : undefined;
|
|
121
|
+
const classification = has('.ai/setup-manifest.json') ? 'initialized'
|
|
122
|
+
: has('.ai') || agents.some(agent => agent.paths.length) ? 'existing-ai'
|
|
123
|
+
: files.some(name => !/^(readme(?:\..*)?|license(?:\..*)?|\.gitignore|\.gitattributes)$/i.test(name)) ? 'existing' : 'starter';
|
|
124
|
+
return {
|
|
125
|
+
root, files, classification, agents, tools, frameworks,
|
|
126
|
+
docs: files.filter(name => /^(readme(?:\..*)?|docs)$/i.test(name)),
|
|
127
|
+
projectMarkers: markers.filter(has),
|
|
128
|
+
workspaceMarkers: ['pnpm-workspace.yaml', 'lerna.json', 'nx.json', 'turbo.json', 'packages', 'apps'].filter(has),
|
|
129
|
+
packageWorkspaces: Array.isArray(pkg?.workspaces) || typeof pkg?.workspaces === 'object' && pkg.workspaces !== null,
|
|
130
|
+
packageManager: typeof pkg?.packageManager === 'string' ? pkg.packageManager : undefined,
|
|
131
|
+
version: typeof manifest?.version === 'string' ? manifest.version : undefined,
|
|
132
|
+
git: {
|
|
133
|
+
detected: Boolean(gitRoot || has('.git')),
|
|
134
|
+
branch: gitRoot ? git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']) : undefined,
|
|
135
|
+
head: gitRoot ? git(root, ['rev-parse', '--verify', 'HEAD']) : undefined,
|
|
136
|
+
dirty: status === undefined ? undefined : status.length > 0,
|
|
137
|
+
aiTracked: gitRoot ? Boolean(git(root, ['ls-files', '--', '.ai/'])) : undefined,
|
|
138
|
+
aiIgnored: gitRoot ? git(root, ['check-ignore', '--no-index', '--stdin'], '.ai/\n') !== undefined : undefined,
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
function readObjectFromValue(value) {
|
|
143
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
144
|
+
}
|