@ductape/cli 0.5.9 → 0.6.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.
package/README.md CHANGED
@@ -43,24 +43,6 @@ ductape --help
43
43
 
44
44
  Do not use `sudo npm link`; it mixes root-owned globals with your normal user.
45
45
 
46
- ## Troubleshooting workspace issues
47
-
48
- Run the command in your logged-in CLI context. It uses the active workspace automatically.
49
-
50
- ```bash
51
- ductape troubleshoot
52
- ductape troubleshoot --product ductape:statecraft --since 2h
53
- ductape troubleshoot --since 2026-11-04T00:00:00Z --until 2026-11-05T00:00:00Z --json
54
- ```
55
-
56
- The default window is the last 24 hours. The report groups failures from retained workspace logs,
57
- deployment journals and build history, with evidence references, possible causes and supported next steps.
58
- It reports missing sources and scan limits. Use `--max-logs 10000` or narrow the product/time window
59
- when the default 5000-record limit is reached. Reports show up to 200 issue groups and disclose omissions.
60
- Provider console logs and browser-only failures require separate evidence. Payloads and headers are
61
- omitted and selected messages are redacted. Review reports before sharing them.
62
- The command performs reads only. If every source is unavailable it prints a report and exits with code 1.
63
-
64
46
  ## Quick start
65
47
 
66
48
  ```bash
@@ -128,28 +110,3 @@ npm test
128
110
  ## Changelog
129
111
 
130
112
  See [CHANGELOG.md](./CHANGELOG.md).
131
-
132
- ### Functions inside deployed APIs
133
-
134
- `ductape deploy deployments get <deploymentId>` and deployment list responses include
135
- `servedFunctions` for service deployments. Ductape automatically queries the signed
136
- SDK runtime inventory after the service's health checks pass. Each inventory names
137
- its cloud revision, release hash, traffic allocation, function namespaces, independent
138
- function versions, operation names and contract hashes. Workbench shows the same
139
- inventory in the deployment detail and MCP returns it through `ductape_deploy_status`.
140
-
141
- A discovered handler is **deployed**, with function verification **unverified**.
142
- Discovery never runs a business operation, changes invocation routing, or creates a
143
- standalone deployment. Health checks do not prove individual function correctness.
144
- Replacing a revision removes its functions from the serving view; canaries show both
145
- revisions and rollback restores the previous revision's recorded inventory.
146
-
147
- Use an SDK with signed runtime inventory support and expose its portable HTTP handler.
148
- NestJS does this through its module's portable function controller (with
149
- `NestFactory.create(..., { rawBody: true })`). Service `DUCTAPE_ACCESS_KEY` must reference
150
- an accessible workspace secret. Discovery reuses provider authorization and private
151
- verification transports, across supported service providers. Missing support or failed
152
- discovery is reported as `unavailable`, not as zero functions, and does not fail an
153
- otherwise healthy generic HTTP service. Existing deployments need a redeploy to collect
154
- an inventory. Function contracts retain their own versions independently of the API
155
- version.
@@ -1,14 +1,4 @@
1
1
  import { type CommandInteractiveFlags } from '../lib/interactive-opts.js';
2
- export declare function runAppVersions(opts: {
3
- id: string;
4
- profile?: string;
5
- }): Promise<void>;
6
- export declare function runAppVersionRename(opts: {
7
- id: string;
8
- from: string;
9
- to: string;
10
- profile?: string;
11
- }): Promise<void>;
12
2
  export declare function runApps(verb: string, opts: {
13
3
  profile?: string;
14
4
  status?: string;
@@ -2,21 +2,10 @@ import { schemaKeyForEntity } from '../lib/forms/index.js';
2
2
  import { isInteractive, promptTag } from '../lib/forms/prompt.js';
3
3
  import { toInteractiveOpts } from '../lib/interactive-opts.js';
4
4
  import { bodyRequiredHint, resolveBody } from '../lib/read-body.js';
5
- import { createApp, deleteApp, getApp, getAppVersions, listApps, updateApp, updateAppViaProxy, } from '../lib/platform-api.js';
5
+ import { createApp, deleteApp, getApp, listApps, updateApp, updateAppViaProxy, } from '../lib/platform-api.js';
6
6
  import { printJson } from '../lib/output.js';
7
7
  import { requireWorkspaceContext } from '../lib/workspace-context.js';
8
8
  const VERBS = ['list', 'get', 'create', 'update', 'delete'];
9
- export async function runAppVersions(opts) {
10
- printJson(await getAppVersions(requireWorkspaceContext({ profile: opts.profile }), opts.id), true);
11
- }
12
- export async function runAppVersionRename(opts) {
13
- if (!opts.from || !opts.to || opts.from === opts.to ||
14
- opts.from.trim() !== opts.from || opts.to.trim() !== opts.to) {
15
- throw new Error('Distinct explicit source and destination version labels are required');
16
- }
17
- const ctx = requireWorkspaceContext({ profile: opts.profile });
18
- printJson(await updateApp(ctx, opts.id, { fromVersion: opts.from, version: opts.to }), true);
19
- }
20
9
  export async function runApps(verb, opts, extraArgs) {
21
10
  const v = verb.toLowerCase();
22
11
  if (!VERBS.includes(v)) {
@@ -67,19 +56,11 @@ export async function runApps(verb, opts, extraArgs) {
67
56
  result = await updateApp(ctx, id, body ?? {});
68
57
  break;
69
58
  }
70
- case 'delete': {
71
- let appId = opts.id;
72
- if (!appId && tag) {
73
- const app = (await getApp(ctx, { tag }));
74
- if (!app?._id)
75
- throw new Error(`App "${tag}" not found`);
76
- appId = String(app._id);
77
- }
78
- if (!appId)
79
- throw new Error('delete requires --id <app_id> or --tag <app_tag>');
80
- result = await deleteApp(ctx, appId);
59
+ case 'delete':
60
+ if (!id)
61
+ throw new Error('delete requires --id <app_id>');
62
+ result = await deleteApp(ctx, id);
81
63
  break;
82
- }
83
64
  default:
84
65
  throw new Error(`Unsupported: apps ${v}`);
85
66
  }
@@ -4,9 +4,17 @@ import { ApiClient } from '../lib/api-client.js';
4
4
  import { requireWorkspaceContext, workspaceAuthQuery } from '../lib/workspace-context.js';
5
5
  import { packSource, uploadSource } from '../lib/source-pack.js';
6
6
  import { actorHeaders } from './deploy-remote.js';
7
+ import { recordOnWork } from '../lib/work-delivery.js';
7
8
  const BASE = '/integrations/v1/deploy';
8
9
  const TERMINAL = new Set(['succeeded', 'failed', 'expired', 'cancelled']);
9
10
  const note = (message) => process.stderr.write(`${message}\n`);
11
+ /** A finished build and the release it registered go on the work they were made for. */
12
+ async function recordBuild(build) {
13
+ if (build.id)
14
+ await recordOnWork({ kind: 'build', ref: build.id });
15
+ if (build.releaseHash)
16
+ await recordOnWork({ kind: 'release', ref: build.releaseHash });
17
+ }
10
18
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
11
19
  function readBuildFile(file) {
12
20
  if (!file)
@@ -53,7 +61,10 @@ export async function runDeployBuilds(operation, options) {
53
61
  if (operation === 'status') {
54
62
  if (!options.id)
55
63
  throw new Error('A build id is required');
56
- console.log(JSON.stringify(await call('GET', `/builds/${encodeURIComponent(options.id)}`), null, 2));
64
+ const shown = await call('GET', `/builds/${encodeURIComponent(options.id)}`);
65
+ console.log(JSON.stringify(shown, null, 2));
66
+ if (shown?.status === 'succeeded')
67
+ await recordBuild(shown);
57
68
  return;
58
69
  }
59
70
  const spec = readBuildFile(options.file);
@@ -100,6 +111,8 @@ export async function runDeployBuilds(operation, options) {
100
111
  console.log(JSON.stringify(build, null, 2));
101
112
  if (build.status !== 'succeeded')
102
113
  process.exitCode = 1;
114
+ else
115
+ await recordBuild({ ...build, id: buildId });
103
116
  return;
104
117
  }
105
118
  console.log(JSON.stringify(build, null, 2));
@@ -2,6 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { ApiClient } from '../lib/api-client.js';
4
4
  import { requireWorkspaceContext, workspaceAuthQuery } from '../lib/workspace-context.js';
5
+ import { recordOnWork } from '../lib/work-delivery.js';
5
6
  const BASE = '/integrations/v1/deploy';
6
7
  /** What a step-up code is good for. Must match what the control plane asks for, so a code for one change cannot be spent on another. */
7
8
  export const stepUpScopes = {
@@ -235,4 +236,16 @@ export async function runDeployRemote(operation, args) {
235
236
  default: throw new Error(`Unknown deploy operation ${operation}`);
236
237
  }
237
238
  console.log(JSON.stringify(result, null, 2));
239
+ // What this made goes on the work it was made for; the work tracker checks it against Deploy's records.
240
+ if (operation === 'releases.register') {
241
+ // The control plane answers with the release itself.
242
+ const hash = result?.releaseHash;
243
+ if (hash)
244
+ await recordOnWork({ kind: 'release', ref: hash });
245
+ }
246
+ if (operation === 'plans.apply') {
247
+ const id = result?.id;
248
+ if (id)
249
+ await recordOnWork({ kind: 'deployment', ref: id });
250
+ }
238
251
  }
@@ -4,6 +4,7 @@ import { createRequire } from 'node:module';
4
4
  import path from 'node:path';
5
5
  import { ApiClient } from '../lib/api-client.js';
6
6
  import { requireWorkspaceContext, workspaceAuthQuery } from '../lib/workspace-context.js';
7
+ import { recordOnWork } from '../lib/work-delivery.js';
7
8
  import { actorHeaders } from './deploy-remote.js';
8
9
  /** The largest bundle the control plane accepts. Cloudflare's own limit on a Worker is smaller. */
9
10
  export const MAX_BUNDLE_BYTES = 10 * 1024 * 1024;
@@ -82,4 +83,8 @@ export async function runDeployWorker(args) {
82
83
  ...(release.config ? { config: release.config } : {}), verification: release.verification, bundleDigest: digest,
83
84
  }, actorHeaders());
84
85
  console.log(JSON.stringify({ ...registered, bundle: { digest, bytes: bytes.byteLength } }, null, 2));
86
+ // The control plane answers with the release itself.
87
+ const hash = registered?.releaseHash;
88
+ if (hash)
89
+ await recordOnWork({ kind: 'release', ref: hash });
85
90
  }
@@ -2,6 +2,7 @@ import { type CommandInteractiveFlags } from '../lib/interactive-opts.js';
2
2
  export declare function runSecrets(verb: string, opts: {
3
3
  key?: string;
4
4
  file?: string;
5
+ env?: string;
5
6
  json?: boolean;
6
7
  } & CommandInteractiveFlags): Promise<void>;
7
8
  export declare function runSecretImportEnv(opts: {
@@ -19,15 +19,23 @@ export async function runSecrets(verb, opts) {
19
19
  if (!key && ['fetch', 'delete', 'update'].includes(method) && isInteractive(interactive)) {
20
20
  key = await promptKey();
21
21
  }
22
- const body = crud === 'create' || crud === 'update'
22
+ let body = crud === 'create' || crud === 'update'
23
23
  ? await resolveBody({
24
24
  ...interactive,
25
25
  file: opts.file,
26
26
  schemaKey: `secrets:${crud}`,
27
27
  patch: crud === 'update',
28
28
  requireBody: crud === 'create',
29
+ // -k names the secret, so creating one only asks for its value.
30
+ ...(crud === 'create' && key ? { preset: { key } } : {}),
29
31
  })
30
32
  : undefined;
33
+ if (crud === 'create' && body) {
34
+ if (key && body.key === undefined)
35
+ body = { ...body, key };
36
+ if (opts.env && body.envs === undefined)
37
+ body = { ...body, envs: [opts.env] };
38
+ }
31
39
  if (crud === 'create' && (!body || Object.keys(body).length === 0)) {
32
40
  throw new Error(`create requires a body. ${bodyRequiredHint('secrets:create')}`);
33
41
  }
@@ -0,0 +1,64 @@
1
+ import type { Command } from 'commander';
2
+ /**
3
+ * Coding-agent hooks for the work tracker, so tracking does not depend on the agent remembering to call the tools.
4
+ * One set of behaviours, wired into each client's own hook system:
5
+ * - session start: opens a work session for the repo's product and tells the agent what is assigned and ready.
6
+ * - after a file edit: records the edited files on the task this session holds, which also renews its claim.
7
+ * With --require-claim, an edit made while holding no task is reported back to the agent where the client
8
+ * lets a hook do that (Claude Code and Codex; Cursor's afterFileEdit has no feedback channel).
9
+ * - session end: ends the work session; anything it still holds goes back to ready.
10
+ * A hook never breaks the agent: on any failure it exits 0 and stays quiet, except where noted.
11
+ *
12
+ * Where each client keeps its hooks, and what it sends on stdin, follows its documentation (October 2026):
13
+ * - Claude Code: .claude/settings.json, events SessionStart / PostToolUse / SessionEnd; tool_input.file_path.
14
+ * - Codex: .codex/hooks.json, the same three-level shape; edits arrive as apply_patch, whose patch text is in
15
+ * tool_input.command.
16
+ * - Cursor: .cursor/hooks.json ({ version: 1, hooks: { sessionStart, afterFileEdit, sessionEnd } }); file_path at the
17
+ * top level, workspace_roots instead of cwd, and session-start context returned as JSON additional_context.
18
+ */
19
+ type Wrap = (fn: (...args: any[]) => void | Promise<void>) => (...args: any[]) => void;
20
+ export type HookClient = 'claude-code' | 'codex' | 'cursor';
21
+ export declare const HOOK_CLIENTS: HookClient[];
22
+ /** File paths named in an apply_patch patch: added, updated, deleted, and the target of a move. */
23
+ export declare function patchFiles(patch: string): string[];
24
+ /** The files an agent's edit changed, from the hook input of its client. */
25
+ export declare function editedFiles(input: any, client?: HookClient): string[];
26
+ /** The agent's own id for this conversation: Claude Code and Codex send session_id, Cursor conversation_id. */
27
+ export declare function hookConversation(input: any): string | undefined;
28
+ /**
29
+ * Lines for Claude Code's CLAUDE_ENV_FILE: they are loaded into every shell command the agent runs afterwards, so a
30
+ * deploy or `ductape work test` in that window speaks for this window's work session.
31
+ */
32
+ export declare function envFileLines(client: HookClient, sessionId: string): string;
33
+ /** The folder the agent works in, from its hook input. */
34
+ export declare function hookCwd(input: any): string | undefined;
35
+ /** Settings with the tracker's hooks merged in for one client. Existing hooks are kept; ours are replaced, never duplicated. */
36
+ export declare function mergeHooks(settings: any, opts?: {
37
+ client?: HookClient;
38
+ requireClaim?: boolean;
39
+ }): any;
40
+ /** Where a client keeps the repo's hooks. */
41
+ export declare function hooksFile(root: string, client: HookClient, local?: boolean): string;
42
+ /** The person's note when work was sent back and not yet finished again; undefined otherwise. */
43
+ export declare function sentBack(item: {
44
+ status?: string;
45
+ approvals?: Array<{
46
+ decision: string;
47
+ note: string | null;
48
+ at: string;
49
+ }>;
50
+ }): {
51
+ decision: string;
52
+ note: string | null;
53
+ at: string;
54
+ } | undefined;
55
+ /**
56
+ * Notices for work sent back since the agent last heard, each said once: the key is the item and the time it was
57
+ * sent back, kept in ~/.ductape/work-notices.json (the newest 200).
58
+ */
59
+ export declare function unseenSentBack(items: any[], seen: string[]): Array<{
60
+ key: string;
61
+ message: string;
62
+ }>;
63
+ export declare function registerWorkHooks(work: Command, wrap: Wrap): void;
64
+ export {};
@@ -0,0 +1,335 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { WorkClient, detectRepo } from '../lib/work.js';
4
+ import { pathsOverlap } from '../lib/work-paths.js';
5
+ import { GLOBAL_DIR } from '../lib/config.js';
6
+ export const HOOK_CLIENTS = ['claude-code', 'codex', 'cursor'];
7
+ const HOOK_MARK = 'ductape work hook';
8
+ const CLAUDE_EDIT_TOOLS = 'Edit|Write|MultiEdit|NotebookEdit';
9
+ const CODEX_EDIT_TOOLS = 'apply_patch|Edit|Write';
10
+ function readStdin() {
11
+ try {
12
+ const raw = fs.readFileSync(0, 'utf8');
13
+ return raw.trim() ? JSON.parse(raw) : {};
14
+ }
15
+ catch {
16
+ return {};
17
+ }
18
+ }
19
+ /** File paths named in an apply_patch patch: added, updated, deleted, and the target of a move. */
20
+ export function patchFiles(patch) {
21
+ const out = [];
22
+ for (const line of String(patch ?? '').split('\n')) {
23
+ const m = /^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(line.trim()) ?? /^\*\*\* Move to: (.+)$/.exec(line.trim());
24
+ if (m)
25
+ out.push(m[1].trim());
26
+ }
27
+ return out;
28
+ }
29
+ /** The files an agent's edit changed, from the hook input of its client. */
30
+ export function editedFiles(input, client = 'claude-code') {
31
+ let files = [];
32
+ if (client === 'cursor') {
33
+ files = [input?.file_path];
34
+ }
35
+ else {
36
+ const t = input?.tool_input ?? {};
37
+ files = [t.file_path, t.notebook_path, ...(Array.isArray(t.edits) ? t.edits.map((e) => e?.file_path) : [])];
38
+ if (client === 'codex' && typeof t.command === 'string')
39
+ files.push(...patchFiles(t.command));
40
+ }
41
+ return [...new Set(files.filter((f) => typeof f === 'string' && f.length > 0))];
42
+ }
43
+ /** The agent's own id for this conversation: Claude Code and Codex send session_id, Cursor conversation_id. */
44
+ export function hookConversation(input) {
45
+ const id = input?.session_id ?? input?.conversation_id;
46
+ return typeof id === 'string' && /^[A-Za-z0-9._:-]{1,128}$/.test(id) ? id : undefined;
47
+ }
48
+ /**
49
+ * Lines for Claude Code's CLAUDE_ENV_FILE: they are loaded into every shell command the agent runs afterwards, so a
50
+ * deploy or `ductape work test` in that window speaks for this window's work session.
51
+ */
52
+ export function envFileLines(client, sessionId) {
53
+ return `export DUCTAPE_AGENT_CLIENT=${client}\nexport DUCTAPE_WORK_SESSION=${sessionId}\n`;
54
+ }
55
+ /** The folder the agent works in, from its hook input. */
56
+ export function hookCwd(input) {
57
+ if (typeof input?.cwd === 'string' && input.cwd)
58
+ return input.cwd;
59
+ if (Array.isArray(input?.workspace_roots) && typeof input.workspace_roots[0] === 'string')
60
+ return input.workspace_roots[0];
61
+ return undefined;
62
+ }
63
+ const command = (client, event, extra = '') => `ductape work hook ${event} --client ${client}${extra}`;
64
+ const ours = (h) => String(h?.command ?? '').includes(HOOK_MARK);
65
+ /** Claude Code and Codex share a shape: event -> [{ matcher?, hooks: [{ type, command, timeout? }] }]. */
66
+ function mergeGrouped(settings, client, requireClaim) {
67
+ const out = { ...(settings ?? {}) };
68
+ const hooks = { ...(out.hooks ?? {}) };
69
+ const strip = (groups) => (groups ?? []).map((g) => ({ ...g, hooks: (g.hooks ?? []).filter((h) => !ours(h)) })).filter((g) => g.hooks.length);
70
+ const cmd = (event, extra = '', timeout) => ({ type: 'command', command: command(client, event, extra), ...(timeout ? { timeout } : {}) });
71
+ hooks.SessionStart = [...strip(hooks.SessionStart), { hooks: [cmd('session-start', '', 30)] }];
72
+ hooks.PostToolUse = [
73
+ ...strip(hooks.PostToolUse),
74
+ { matcher: client === 'codex' ? CODEX_EDIT_TOOLS : CLAUDE_EDIT_TOOLS, hooks: [cmd('post-tool-use', requireClaim ? ' --require-claim' : '', 30)] },
75
+ ];
76
+ // Session-end hooks get a short budget (Claude Code about 1.5 s, Codex 1 s by default); if the call is cut off,
77
+ // the claim lease releases the work anyway.
78
+ hooks.SessionEnd = [...strip(hooks.SessionEnd), { hooks: [cmd('session-end')] }];
79
+ out.hooks = hooks;
80
+ return out;
81
+ }
82
+ /** Cursor: { version: 1, hooks: { event: [{ command }] } }. */
83
+ function mergeCursor(settings) {
84
+ const out = { version: 1, ...(settings ?? {}) };
85
+ const hooks = { ...(out.hooks ?? {}) };
86
+ const keep = (list) => (list ?? []).filter((h) => !ours(h));
87
+ hooks.sessionStart = [...keep(hooks.sessionStart), { command: command('cursor', 'session-start'), timeout: 30 }];
88
+ hooks.afterFileEdit = [...keep(hooks.afterFileEdit), { command: command('cursor', 'post-tool-use'), timeout: 30 }];
89
+ hooks.sessionEnd = [...keep(hooks.sessionEnd), { command: command('cursor', 'session-end') }];
90
+ out.hooks = hooks;
91
+ return out;
92
+ }
93
+ /** Settings with the tracker's hooks merged in for one client. Existing hooks are kept; ours are replaced, never duplicated. */
94
+ export function mergeHooks(settings, opts = {}) {
95
+ const client = opts.client ?? 'claude-code';
96
+ return client === 'cursor' ? mergeCursor(settings) : mergeGrouped(settings, client, Boolean(opts.requireClaim));
97
+ }
98
+ /** Where a client keeps the repo's hooks. */
99
+ export function hooksFile(root, client, local = false) {
100
+ if (client === 'codex')
101
+ return path.join(root, '.codex', 'hooks.json');
102
+ if (client === 'cursor')
103
+ return path.join(root, '.cursor', 'hooks.json');
104
+ return path.join(root, '.claude', local ? 'settings.local.json' : 'settings.json');
105
+ }
106
+ /** The person's note when work was sent back and not yet finished again; undefined otherwise. */
107
+ export function sentBack(item) {
108
+ const last = item.approvals?.[item.approvals.length - 1];
109
+ if (!last || last.decision !== 'changes_requested' || item.status === 'done' || item.status === 'awaiting_approval')
110
+ return undefined;
111
+ return last;
112
+ }
113
+ const fmt = (items) => items
114
+ .slice(0, 10)
115
+ .map((i) => {
116
+ const line = ` ${i.ref} [${i.status}, ${i.priority}] ${i.title}${i.components?.length ? ` (${i.components.map((c) => `${c.type}:${c.tag}${c.planned ? ' planned' : ''}`).join(', ')})` : ''}`;
117
+ const back = sentBack(i);
118
+ return back ? `${line}\n Sent back by a person. Their note: "${back.note}" Change that, then complete it again.` : line;
119
+ })
120
+ .join('\n');
121
+ const NOTICES_PATH = path.join(GLOBAL_DIR, 'work-notices.json');
122
+ /**
123
+ * Notices for work sent back since the agent last heard, each said once: the key is the item and the time it was
124
+ * sent back, kept in ~/.ductape/work-notices.json (the newest 200).
125
+ */
126
+ export function unseenSentBack(items, seen) {
127
+ const out = [];
128
+ for (const i of items) {
129
+ const back = sentBack(i);
130
+ if (!back)
131
+ continue;
132
+ const key = `${i.ref}|${back.at}`;
133
+ if (!seen.includes(key))
134
+ out.push({ key, message: `A person sent ${i.ref} (${i.title}) back. Their note: "${back.note}" Change that, then finish it again with ductape_work_complete.` });
135
+ }
136
+ return out;
137
+ }
138
+ function readSeen() {
139
+ try {
140
+ const v = JSON.parse(fs.readFileSync(NOTICES_PATH, 'utf8'));
141
+ return Array.isArray(v) ? v.map(String) : [];
142
+ }
143
+ catch {
144
+ return [];
145
+ }
146
+ }
147
+ function writeSeen(keys) {
148
+ try {
149
+ fs.mkdirSync(GLOBAL_DIR, { recursive: true });
150
+ fs.writeFileSync(NOTICES_PATH, JSON.stringify(keys.slice(-200)), { mode: 0o600 });
151
+ }
152
+ catch {
153
+ // Without it, a notice may be said twice; nothing else depends on it.
154
+ }
155
+ }
156
+ async function sessionStart(client) {
157
+ const input = readStdin();
158
+ const cwd = hookCwd(input);
159
+ if (cwd)
160
+ process.chdir(cwd);
161
+ const w = new WorkClient({ client: client, conversation: hookConversation(input) });
162
+ const product = w.product(process.env.DUCTAPE_PRODUCT);
163
+ let context;
164
+ if (!product) {
165
+ context = 'Ductape work tracking: this folder is not a linked Ductape project and DUCTAPE_PRODUCT is not set, so no work session was started.';
166
+ }
167
+ else {
168
+ // A resumed conversation keeps its session (and the work it holds); a new one starts a session of its own.
169
+ let sessionId;
170
+ let lines;
171
+ if (w.sessionId) {
172
+ try {
173
+ await w.send('POST', '/sessions/heartbeat');
174
+ sessionId = w.sessionId;
175
+ }
176
+ catch {
177
+ sessionId = undefined;
178
+ }
179
+ }
180
+ if (sessionId) {
181
+ const sessions = await w.get('/sessions', { product }, false);
182
+ const held = sessions.find((s) => s.id === sessionId)?.working_on ?? [];
183
+ lines = [
184
+ `Ductape work tracking: continuing session ${sessionId} for product "${product}".`,
185
+ held.length ? `You hold:\n${held.map((h) => ` ${h.ref} ${h.title ?? ''}`).join('\n')}` : 'You hold no work item.',
186
+ ];
187
+ }
188
+ else {
189
+ const res = await w.startSession({ client: client, product, via: 'hook' });
190
+ sessionId = res.session.id;
191
+ lines = [
192
+ `Ductape work tracking is on: product "${product}" in this workspace, session ${sessionId}.`,
193
+ res.assigned.length ? `Assigned to you or your agents:\n${fmt(res.assigned)}` : 'Nothing is assigned to you.',
194
+ res.ready.length ? `Ready to pick up:\n${fmt(res.ready)}` : 'No unassigned work is ready.',
195
+ ];
196
+ }
197
+ const envFile = process.env.CLAUDE_ENV_FILE;
198
+ if (client === 'claude-code' && envFile) {
199
+ try {
200
+ fs.appendFileSync(envFile, envFileLines(client, sessionId));
201
+ }
202
+ catch {
203
+ // Without it, shell commands fall back to finding the work by repo.
204
+ }
205
+ }
206
+ context = [
207
+ ...lines,
208
+ `If you use the Ductape work tools, call ductape_work_start_session with session "${sessionId}" so they share this session.`,
209
+ 'Before changing code, find or create the task, read ductape_work_context, and ductape_work_claim it with the paths you expect to touch. ' +
210
+ 'Build it with the Ductape components the task names; run tests with `ductape work test -- <command>`; finish with ductape_work_complete and the components you created or changed.',
211
+ ].join('\n\n');
212
+ }
213
+ // Claude Code and Codex add plain stdout to the agent's context; Cursor reads JSON additional_context.
214
+ if (client === 'cursor')
215
+ console.log(JSON.stringify({ additional_context: context }));
216
+ else
217
+ console.log(context);
218
+ }
219
+ async function postToolUse(client, requireClaim) {
220
+ const input = readStdin();
221
+ const cwd = hookCwd(input);
222
+ if (cwd)
223
+ process.chdir(cwd);
224
+ const files = editedFiles(input, client);
225
+ if (!files.length)
226
+ return;
227
+ const w = new WorkClient({ client: client, conversation: hookConversation(input) });
228
+ if (!w.sessionId)
229
+ return;
230
+ const root = detectRepo().root ?? process.cwd();
231
+ const rel = files.map((f) => path.relative(root, path.resolve(f)).replace(/\\/g, '/')).filter((f) => f && !f.startsWith('..'));
232
+ if (!rel.length)
233
+ return;
234
+ const sessions = await w.get('/sessions', {}, false);
235
+ const held = sessions.find((s) => s.id === w.sessionId)?.working_on ?? [];
236
+ if (!held.length) {
237
+ // Cursor's afterFileEdit has no way to talk back to the agent, so the reminder is for Claude Code and Codex.
238
+ if (requireClaim && client !== 'cursor') {
239
+ process.stderr.write(`You edited ${rel.join(', ')} without holding a Ductape work item. Claim the task first (ductape_work_find, then ductape_work_claim with its paths).\n`);
240
+ process.exit(2);
241
+ }
242
+ return;
243
+ }
244
+ // Record the files on the task(s) whose paths cover them; with no match, on the one task held.
245
+ const targets = held.filter((h) => (h.paths ?? []).some((p) => rel.some((f) => pathsOverlap(p, f))));
246
+ const updated = [];
247
+ for (const t of targets.length ? targets : held.length === 1 ? held : []) {
248
+ updated.push(await w.send('PATCH', `/items/${encodeURIComponent(t.ref)}`, { files_touched: rel }));
249
+ }
250
+ // Work a person sent back while the agent kept going: tell it once, the way the claim reminder is told.
251
+ if (client === 'cursor')
252
+ return;
253
+ const seen = readSeen();
254
+ const fresh = unseenSentBack(updated, seen);
255
+ if (fresh.length) {
256
+ writeSeen([...seen, ...fresh.map((f) => f.key)]);
257
+ process.stderr.write(`${fresh.map((f) => f.message).join('\n')}\n`);
258
+ process.exit(2);
259
+ }
260
+ }
261
+ async function sessionEnd(client) {
262
+ const input = readStdin();
263
+ const cwd = hookCwd(input);
264
+ if (cwd)
265
+ process.chdir(cwd);
266
+ const w = new WorkClient({ client: client, conversation: hookConversation(input) });
267
+ if (!w.sessionId)
268
+ return;
269
+ await w.endSession(input?.reason ? `${client} session ended (${input.reason})` : undefined);
270
+ }
271
+ const toClient = (value) => {
272
+ const v = String(value ?? 'claude-code');
273
+ if (!HOOK_CLIENTS.includes(v))
274
+ throw new Error(`Hooks are available for ${HOOK_CLIENTS.join(', ')}; got "${v}".`);
275
+ return v;
276
+ };
277
+ export function registerWorkHooks(work, wrap) {
278
+ work
279
+ .command('hook <event>', { hidden: true })
280
+ .description('Run an agent hook: session-start, post-tool-use, session-end (reads the hook input on stdin)')
281
+ .option('--client <client>', 'claude-code, codex or cursor', 'claude-code')
282
+ .option('--require-claim', 'post-tool-use: tell the agent when it edits a file while holding no work item')
283
+ .action(async (event, opts) => {
284
+ try {
285
+ const client = toClient(opts.client);
286
+ if (event === 'session-start')
287
+ await sessionStart(client);
288
+ else if (event === 'post-tool-use')
289
+ await postToolUse(client, Boolean(opts.requireClaim));
290
+ else if (event === 'session-end')
291
+ await sessionEnd(client);
292
+ }
293
+ catch (e) {
294
+ // A tracking failure must never stop the agent's work; leave a trace for whoever looks.
295
+ process.stderr.write(`ductape work hook ${event}: ${e instanceof Error ? e.message : String(e)}\n`);
296
+ }
297
+ process.exit(0);
298
+ });
299
+ work
300
+ .command('install-hooks')
301
+ .description('Add the work tracker hooks to this repo for Claude Code (.claude/settings.json), Codex (.codex/hooks.json) or Cursor (.cursor/hooks.json)')
302
+ .option('--client <clients>', 'claude-code, codex, cursor, or all (comma-separated)', 'claude-code')
303
+ .option('--require-claim', 'Tell the agent whenever it edits a file while holding no work item (Claude Code and Codex)')
304
+ .option('--local', 'Claude Code: write .claude/settings.local.json (not committed) instead')
305
+ .option('--print', 'Print the settings instead of writing them')
306
+ .action(wrap(async (opts) => {
307
+ const root = detectRepo().root ?? process.cwd();
308
+ const clients = String(opts.client) === 'all' ? HOOK_CLIENTS : String(opts.client).split(',').map((c) => toClient(c.trim()));
309
+ for (const client of clients) {
310
+ const file = hooksFile(root, client, Boolean(opts.local));
311
+ let current = {};
312
+ if (fs.existsSync(file)) {
313
+ try {
314
+ current = JSON.parse(fs.readFileSync(file, 'utf8'));
315
+ }
316
+ catch {
317
+ throw new Error(`${file} is not valid JSON; fix it first, nothing was changed.`);
318
+ }
319
+ }
320
+ const next = mergeHooks(current, { client, requireClaim: Boolean(opts.requireClaim) });
321
+ if (opts.print) {
322
+ console.log(`# ${path.relative(root, file)}\n${JSON.stringify(next, null, 2)}`);
323
+ continue;
324
+ }
325
+ fs.mkdirSync(path.dirname(file), { recursive: true });
326
+ fs.writeFileSync(file, `${JSON.stringify(next, null, 2)}\n`);
327
+ const events = client === 'cursor' ? 'sessionStart, afterFileEdit, sessionEnd' : `SessionStart, PostToolUse (${client === 'codex' ? CODEX_EDIT_TOOLS : CLAUDE_EDIT_TOOLS}), SessionEnd`;
328
+ console.log(`${client}: hooks written to ${path.relative(process.cwd(), file) || file} (${events}).`);
329
+ if (client === 'codex')
330
+ console.log(' Codex runs project hooks once the .codex/ folder is trusted: review them with /hooks.');
331
+ if (client === 'cursor' && opts.requireClaim)
332
+ console.log(' Cursor cannot send a hook\'s reminder back to the agent, so --require-claim has no effect there.');
333
+ }
334
+ }));
335
+ }