estimetry 0.1.2 → 0.3.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 (65) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +88 -16
  3. package/dist/application/contracts/skill-mention.js +20 -0
  4. package/dist/application/estimetry.js +2 -0
  5. package/dist/application/hooks/context-limit.js +10 -2
  6. package/dist/application/hooks/hook-context.js +12 -4
  7. package/dist/application/hooks/receive-session-hook.js +15 -4
  8. package/dist/application/hooks/session-end-import.js +6 -7
  9. package/dist/application/project/init-defaults.js +17 -4
  10. package/dist/application/project/init-project.js +4 -1
  11. package/dist/application/project/install-copy.js +8 -1
  12. package/dist/application/project/show-init-choices.js +1 -1
  13. package/dist/application/project/tool-notices.js +8 -0
  14. package/dist/application/task/import-session-logs.js +4 -1
  15. package/dist/application/task/show-calibration.js +12 -8
  16. package/dist/application/task/task-cards.js +1 -1
  17. package/dist/bootstrap/container.js +23 -6
  18. package/dist/bootstrap/hook-receiver.js +7 -14
  19. package/dist/bootstrap/main.js +1 -1
  20. package/dist/domain/calibration/applicable-coefficient.js +35 -19
  21. package/dist/domain/calibration/calibration-policy.js +39 -0
  22. package/dist/domain/calibration/calibration.js +21 -36
  23. package/dist/domain/calibration/level-parts.js +41 -0
  24. package/dist/domain/calibration/ratio-samples.js +34 -0
  25. package/dist/domain/code/code-classes.js +1 -1
  26. package/dist/domain/estimate/estimate.js +22 -5
  27. package/dist/domain/progress/progress-record-parser.js +6 -0
  28. package/dist/domain/progress/session-log.js +2 -1
  29. package/dist/domain/usage/task-usage.js +24 -7
  30. package/dist/infrastructure/persistence/records.js +1 -1
  31. package/dist/infrastructure/persistence/yaml-config-store.js +6 -5
  32. package/dist/infrastructure/persistence/yaml-estimate-reader.js +20 -12
  33. package/dist/integrations/tools/claude-code/claude-code-adapter.js +29 -48
  34. package/dist/integrations/tools/claude-code/hook-events.js +4 -0
  35. package/dist/integrations/tools/claude-code/hook-translation.js +16 -34
  36. package/dist/integrations/tools/claude-code/importer/claude-code-logs.js +1 -1
  37. package/dist/integrations/tools/claude-code/skill-file.js +7 -19
  38. package/dist/integrations/tools/codex/codex-adapter.js +161 -0
  39. package/dist/integrations/tools/codex/hook-events.js +23 -0
  40. package/dist/integrations/tools/codex/hook-translation.js +76 -0
  41. package/dist/integrations/tools/codex/hook-trust.js +69 -0
  42. package/dist/integrations/tools/codex/importer/codex-logs.js +208 -0
  43. package/dist/integrations/tools/codex/importer/rollout-parser.js +163 -0
  44. package/dist/integrations/tools/codex/sandbox-rules.js +38 -0
  45. package/dist/integrations/tools/codex/skill-file.js +22 -0
  46. package/dist/integrations/tools/codex/trust-tables.js +96 -0
  47. package/dist/integrations/tools/content/commands.js +35 -26
  48. package/dist/integrations/tools/shared/generated-file.js +26 -0
  49. package/dist/integrations/tools/shared/hook-payload.js +33 -0
  50. package/dist/integrations/tools/{claude-code → shared}/hook-settings.js +37 -22
  51. package/dist/integrations/tools/shared/instructions-block.js +39 -0
  52. package/dist/integrations/tools/shared/skills-plan.js +39 -0
  53. package/dist/interface/cli/commands/calibrate-command.js +11 -0
  54. package/dist/interface/cli/commands/hook-command.js +1 -1
  55. package/dist/interface/cli/commands/init-command.js +16 -7
  56. package/dist/interface/cli/commands/status-command.js +5 -2
  57. package/dist/interface/cli/help.js +3 -1
  58. package/dist/interface/cli/presenters/text/closing-text.js +7 -3
  59. package/dist/interface/cli/presenters/text/estimate-text.js +35 -13
  60. package/dist/interface/cli/presenters/text/notices-text.js +1 -0
  61. package/dist/interface/cli/presenters/text/task-text.js +1 -1
  62. package/dist/interface/cli/presenters/text-presenter.js +3 -3
  63. package/package.json +1 -1
  64. package/dist/integrations/tools/claude-code/claude-md.js +0 -28
  65. /package/dist/integrations/tools/{claude-code/importer → shared}/log-lines.js +0 -0
@@ -1,4 +1,4 @@
1
- import { DEFAULT_MIN_TASKS } from '../../domain/calibration/calibration.js';
1
+ import { CalibrationPolicy } from '../../domain/calibration/calibration-policy.js';
2
2
  import { isShareMode } from '../../application/ports/sharing-preference.js';
3
3
  import { IdlePolicy } from '../../domain/measurement/idle-policy.js';
4
4
  import { Author } from '../../domain/shared/author.js';
@@ -60,11 +60,12 @@ export class YamlConfigStore {
60
60
  problem: `${this.layout.configFile}: measurement.checkpointMinutes must be a whole number from 10 to 30; using ${DEFAULT_CHECKPOINT_MINUTES}`,
61
61
  };
62
62
  }
63
- /** `calibration.minTasks`: a whole number ≥ 1, 5 by default; anything else gives the default. */
64
- minTasks() {
63
+ /** `calibration.minTasks` and `calibration.shrink`; a value that is not a number counts as not given. */
64
+ policy() {
65
65
  const calibration = this.read()['calibration'];
66
- const value = typeof calibration === 'object' && calibration !== null ? calibration['minTasks'] : undefined;
67
- return typeof value === 'number' && Number.isInteger(value) && value >= 1 ? value : DEFAULT_MIN_TASKS;
66
+ const settings = typeof calibration === 'object' && calibration !== null ? calibration : {};
67
+ const number = (value) => (typeof value === 'number' ? value : undefined);
68
+ return CalibrationPolicy.fromConfig({ minTasks: number(settings['minTasks']), shrink: number(settings['shrink']) });
68
69
  }
69
70
  /** `author.aliases`: strings other than the author's own id; anything but a list counts as none. */
70
71
  authorAliases() {
@@ -74,7 +74,7 @@ class EstimateParser {
74
74
  this.issue('calibrated', 'expected true or false');
75
75
  }
76
76
  const codeVolume = this.codeVolume(value['codeVolume']);
77
- const coefficient = this.coefficient(value['calibration']);
77
+ const calibration = this.calibration(value['calibration']);
78
78
  if (this.issues.length > 0 || parts.some((part) => part === undefined)) {
79
79
  return undefined;
80
80
  }
@@ -86,24 +86,32 @@ class EstimateParser {
86
86
  ...(rationale === undefined ? {} : { rationale }),
87
87
  ...(codeVolume === undefined ? {} : { codeVolume }),
88
88
  calibrated: calibrated === true,
89
- ...(coefficient === undefined ? {} : { coefficient }),
89
+ ...calibration,
90
90
  }));
91
91
  }
92
- coefficient(value) {
92
+ calibration(value) {
93
93
  if (value === undefined) {
94
- return undefined;
94
+ return {};
95
95
  }
96
96
  if (!isObject(value)) {
97
97
  this.issue('calibration', 'expected a mapping with `coefficient`');
98
- return undefined;
99
- }
100
- this.unknownFields(value, ['coefficient'], 'calibration.');
101
- const coefficient = value['coefficient'];
102
- if (typeof coefficient !== 'number' || !(coefficient > 0)) {
103
- this.issue('calibration.coefficient', 'expected a number greater than 0');
104
- return undefined;
98
+ return {};
105
99
  }
106
- return coefficient;
100
+ this.unknownFields(value, ['coefficient', 'pessimistic'], 'calibration.');
101
+ const positive = (field) => {
102
+ const number = value[field];
103
+ if (typeof number !== 'number' || !(number > 0)) {
104
+ this.issue(`calibration.${field}`, 'expected a number greater than 0');
105
+ return undefined;
106
+ }
107
+ return number;
108
+ };
109
+ const coefficient = positive('coefficient');
110
+ const pessimistic = value['pessimistic'] === undefined ? undefined : positive('pessimistic');
111
+ return {
112
+ ...(coefficient === undefined ? {} : { coefficient }),
113
+ ...(pessimistic === undefined ? {} : { pessimisticCoefficient: pessimistic }),
114
+ };
107
115
  }
108
116
  part(value, path) {
109
117
  if (!isObject(value)) {
@@ -1,14 +1,19 @@
1
1
  import { join } from 'node:path';
2
- import { COMMANDS, ESTIMETRY_SKILL } from '../content/commands.js';
3
- import { withBlock, withoutBlock } from './claude-md.js';
2
+ import { COMMANDS, ESTIMATE_REMINDER_BLOCK, ESTIMETRY_SKILL } from '../content/commands.js';
4
3
  import { estimetryCommand } from '../../../application/contracts/estimetry-command.js';
5
- import { hasOurHooks, isBrokenJson, withHooks, withoutHooks } from './hook-settings.js';
6
- import { CLAUDE_CODE_HOOK_EVENTS, SYNCHRONOUS_HOOK_EVENTS } from './hook-events.js';
7
- import { ownership, renderSkill } from './skill-file.js';
4
+ import { hasOurHooks, isBrokenJson, withHooks, withoutHooks } from '../shared/hook-settings.js';
5
+ import { instructionsPlan } from '../shared/instructions-block.js';
6
+ import { nameSkills } from '../../../application/contracts/skill-mention.js';
7
+ import { skillsPlan } from '../shared/skills-plan.js';
8
+ import { CLAUDE_CODE_HOOK_EVENTS, SYNCHRONOUS_HOOK_EVENTS, claudeCodeSkillRef } from './hook-events.js';
9
+ import { renderSkill } from './skill-file.js';
8
10
  export { CLAUDE_CODE_HOOK_EVENTS } from './hook-events.js';
9
11
  const SHARED_SETTINGS = join('.claude', 'settings.json');
10
12
  const LOCAL_SETTINGS = join('.claude', 'settings.local.json');
11
13
  const SKILLS = [ESTIMETRY_SKILL, ...COMMANDS];
14
+ /** Our hooks in the settings: `estimetry hook claude-code …`, in any form `estimetryCommand` gives. */
15
+ const OURS = 'hook claude-code';
16
+ const CLAUDE_MD_BLOCK = nameSkills(ESTIMATE_REMINDER_BLOCK, claudeCodeSkillRef);
12
17
  /**
13
18
  * Claude Code: hooks in the project settings, skills (which are also its slash
14
19
  * commands) in the user's directory or, for a shared install, in the project.
@@ -19,6 +24,8 @@ export class ClaudeCodeAdapter {
19
24
  aliases = ['claude'];
20
25
  title = 'Claude Code';
21
26
  hookEvents = CLAUDE_CODE_HOOK_EVENTS;
27
+ /** Claude Code runs the hooks in its settings as they are. */
28
+ asksTrust = false;
22
29
  /** `configDir` is the user's Claude Code directory: `$CLAUDE_CONFIG_DIR` or `~/.claude`. */
23
30
  constructor(configDir) {
24
31
  this.configDir = configDir;
@@ -26,17 +33,20 @@ export class ClaudeCodeAdapter {
26
33
  state(projectRoot, files) {
27
34
  const sharedText = files.read(join(projectRoot, SHARED_SETTINGS));
28
35
  const localText = files.read(join(projectRoot, LOCAL_SETTINGS));
29
- const shared = hasOurHooks(sharedText);
36
+ const shared = hasOurHooks(sharedText, OURS);
30
37
  const broken = [
31
38
  ...(isBrokenJson(sharedText) ? [SHARED_SETTINGS] : []),
32
39
  ...(isBrokenJson(localText) ? [LOCAL_SETTINGS] : []),
33
40
  ];
34
41
  return {
35
- installed: shared || hasOurHooks(localText),
42
+ installed: shared || hasOurHooks(localText, OURS),
36
43
  shared,
37
44
  ...(broken.length === 0 ? {} : { unreadable: `${broken.join(' and ')} ${broken.length === 1 ? 'is' : 'are'} not valid JSON` }),
38
45
  };
39
46
  }
47
+ present(files) {
48
+ return files.isDirectory(this.configDir);
49
+ }
40
50
  personalFiles() {
41
51
  return [LOCAL_SETTINGS];
42
52
  }
@@ -51,18 +61,18 @@ export class ClaudeCodeAdapter {
51
61
  hooks({ projectRoot, files, shared, runner }) {
52
62
  const [target, previous] = shared ? [SHARED_SETTINGS, LOCAL_SETTINGS] : [LOCAL_SETTINGS, SHARED_SETTINGS];
53
63
  // Personal settings run this installation by its paths; settings the team commits hold no paths of this machine.
54
- const command = (event) => estimetryCommand(shared ? undefined : runner, `hook claude-code ${event}`);
64
+ const command = (event) => estimetryCommand(shared ? undefined : runner, `${OURS} ${event}`);
55
65
  const changes = [
56
66
  {
57
67
  path: join(projectRoot, target),
58
- content: withHooks(files.read(join(projectRoot, target)), { events: this.hookEvents, synchronous: SYNCHRONOUS_HOOK_EVENTS, command }, target),
68
+ content: withHooks(files.read(join(projectRoot, target)), { ours: OURS, events: this.hookEvents, synchronous: SYNCHRONOUS_HOOK_EVENTS, command }, target),
59
69
  },
60
70
  ];
61
71
  const warnings = [];
62
72
  const old = files.read(join(projectRoot, previous));
63
73
  if (old !== undefined) {
64
74
  try {
65
- const cleaned = withoutHooks(old, previous);
75
+ const cleaned = withoutHooks(old, OURS, previous);
66
76
  changes.push(cleaned === undefined
67
77
  ? { path: join(projectRoot, previous), remove: true }
68
78
  : { path: join(projectRoot, previous), content: cleaned });
@@ -75,48 +85,19 @@ export class ClaudeCodeAdapter {
75
85
  return { changes, skipped: [], warnings };
76
86
  }
77
87
  skills({ projectRoot, files, shared, force, version }) {
78
- const changes = [];
79
- const skipped = [];
80
- const projectSkills = join(projectRoot, '.claude', 'skills');
81
- const target = shared ? projectSkills : join(this.configDir, 'skills');
82
- for (const skill of SKILLS) {
83
- const path = join(target, skill.id, 'SKILL.md');
84
- const current = files.read(path);
85
- const owner = current === undefined ? 'ours' : ownership(current);
86
- if (owner === 'foreign') {
87
- skipped.push({ path, reason: 'not created by estimetry, left as it is' });
88
- }
89
- else if (owner === 'edited' && !force) {
90
- skipped.push({ path, reason: 'edited after install; run init --force to overwrite it' });
91
- }
92
- else {
93
- changes.push({ path, content: renderSkill(skill, version) });
94
- }
95
- // A personal install takes the skills out of the project; a shared one keeps the personal ones for other projects.
96
- if (!shared) {
97
- const inProject = join(projectSkills, skill.id, 'SKILL.md');
98
- const text = files.read(inProject);
99
- if (text !== undefined && ownership(text) === 'ours') {
100
- changes.push({ path: inProject, remove: true });
101
- }
102
- else if (text !== undefined && ownership(text) === 'edited') {
103
- skipped.push({ path: inProject, reason: 'edited after install, so it stays in the project' });
104
- }
105
- }
106
- }
107
- return { changes, skipped, warnings: [] };
88
+ return skillsPlan(SKILLS, {
89
+ files,
90
+ projectDir: join(projectRoot, '.claude', 'skills'),
91
+ userDir: join(this.configDir, 'skills'),
92
+ shared,
93
+ force,
94
+ render: (skill) => renderSkill(skill, version),
95
+ });
108
96
  }
109
97
  /** The reminder goes to the committed CLAUDE.md only with a shared install. */
110
98
  claudeMd({ projectRoot, files, shared }) {
111
99
  const path = join(projectRoot, 'CLAUDE.md');
112
- const current = files.read(path);
113
- if (shared) {
114
- return { changes: [{ path, content: withBlock(current) }], skipped: [], warnings: [] };
115
- }
116
- if (current === undefined) {
117
- return { changes: [], skipped: [], warnings: [] };
118
- }
119
- return { changes: [{ path, content: withoutBlock(current) }], skipped: [], warnings: [] };
100
+ return instructionsPlan(path, files.read(path), shared, CLAUDE_MD_BLOCK);
120
101
  }
121
102
  }
122
103
  //# sourceMappingURL=claude-code-adapter.js.map
@@ -15,4 +15,8 @@ export const CLAUDE_CODE_HOOK_EVENTS = [
15
15
  ];
16
16
  /** Hooks the agent must wait for: their context has to reach it in the same turn, or the session is ending. */
17
17
  export const SYNCHRONOUS_HOOK_EVENTS = ['SessionStart', 'UserPromptSubmit', 'SessionEnd'];
18
+ /** How Claude Code calls a skill: as a slash command. One rule for the context of hooks and the bodies of skills. */
19
+ export function claudeCodeSkillRef(id) {
20
+ return `/${id}`;
21
+ }
18
22
  //# sourceMappingURL=hook-events.js.map
@@ -1,6 +1,5 @@
1
- import { SessionId } from '../../../domain/measurement/session-id.js';
2
- import { InvalidValue } from '../../../domain/shared/domain-error.js';
3
- import { CLAUDE_CODE_HOOK_EVENTS } from './hook-events.js';
1
+ import { additionalContext, payloadText, translateHook } from '../shared/hook-payload.js';
2
+ import { CLAUDE_CODE_HOOK_EVENTS, claudeCodeSkillRef } from './hook-events.js';
4
3
  /*
5
4
  * Claude Code hook payloads → activity events (claude-code-hooks spec). Prompt
6
5
  * texts, tool inputs and outputs are read only to classify the call and never
@@ -28,39 +27,25 @@ export const claudeCodeHooks = {
28
27
  id: 'claude-code',
29
28
  aliases: ['claude'],
30
29
  hookEvents: CLAUDE_CODE_HOOK_EVENTS,
30
+ projectDirVariable: 'CLAUDE_PROJECT_DIR',
31
+ // Claude Code waits for the synchronous SessionEnd within the timeout of the hook (10 s); the spec gives the import 5 s.
32
+ sessionEndBudgetMs: 5_000,
31
33
  translate(event, payload) {
32
- if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
33
- throw new InvalidValue(`claude-code ${event}: stdin is not a JSON object`);
34
- }
35
- const p = payload;
36
- if (typeof p['session_id'] !== 'string') {
37
- throw new InvalidValue(`claude-code ${event}: session_id is missing`);
38
- }
39
- const session = SessionId.parse(p['session_id']);
40
- const cwd = typeof p['cwd'] === 'string' ? p['cwd'] : undefined;
41
- const transcript = typeof p['transcript_path'] === 'string' && p['transcript_path'] !== '' ? p['transcript_path'] : undefined;
42
- return {
43
- session,
44
- ...(cwd === undefined ? {} : { cwd }),
45
- ...(transcript === undefined ? {} : { transcript }),
46
- kind: KINDS[event] ?? 'other',
47
- events: translateEvent(event, p),
48
- };
49
- },
50
- renderContext(event, text) {
51
- return JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: text } });
34
+ return translateHook('claude-code', event, payload, KINDS, translateEvent);
52
35
  },
36
+ skillRef: claudeCodeSkillRef,
37
+ renderContext: additionalContext,
53
38
  };
54
39
  function translateEvent(event, p) {
55
- const agent = text(p['agent_id']);
40
+ const agent = payloadText(p['agent_id']);
56
41
  const onAgent = agent === undefined ? {} : { agent };
57
- const turn = agent === undefined && text(p['prompt_id']) !== undefined ? { turn: text(p['prompt_id']) } : {};
58
- const tool = text(p['tool_name']);
59
- const toolUseId = text(p['tool_use_id']);
42
+ const turn = agent === undefined && payloadText(p['prompt_id']) !== undefined ? { turn: payloadText(p['prompt_id']) } : {};
43
+ const tool = payloadText(p['tool_name']);
44
+ const toolUseId = payloadText(p['tool_use_id']);
60
45
  const call = { ...onAgent, ...(tool === undefined ? {} : { tool }), ...(toolUseId === undefined ? {} : { toolUseId }) };
61
46
  switch (event) {
62
47
  case 'SessionStart': {
63
- const source = text(p['source']);
48
+ const source = payloadText(p['source']);
64
49
  if (agent !== undefined || source === 'clear' || source === 'compact') {
65
50
  return []; // a subagent's start, or the same session going on
66
51
  }
@@ -85,7 +70,7 @@ function translateEvent(event, p) {
85
70
  ? []
86
71
  : [{ type: 'turn.awaiting-input', data: { ...onAgent, reason: 'permission', ...turn } }];
87
72
  case 'Notification': {
88
- const type = text(p['notification_type']);
73
+ const type = payloadText(p['notification_type']);
89
74
  return type !== undefined && QUESTION_NOTIFICATIONS.has(type)
90
75
  ? [{ type: 'turn.awaiting-input', data: { ...onAgent, reason: 'question', ...turn } }]
91
76
  : [];
@@ -96,7 +81,7 @@ function translateEvent(event, p) {
96
81
  const launched = tool !== undefined && SUBAGENT_TOOLS.has(tool) && typeof response === 'object' && response !== null
97
82
  ? response
98
83
  : undefined;
99
- const child = launched?.['status'] === 'async_launched' ? text(launched['agentId']) : undefined;
84
+ const child = launched?.['status'] === 'async_launched' ? payloadText(launched['agentId']) : undefined;
100
85
  return child === undefined ? [used] : [used, { type: 'agent.detached', data: { agent: child } }];
101
86
  }
102
87
  case 'PostToolUseFailure': {
@@ -106,7 +91,7 @@ function translateEvent(event, p) {
106
91
  : [used];
107
92
  }
108
93
  case 'SubagentStart': {
109
- const type = text(p['agent_type']);
94
+ const type = payloadText(p['agent_type']);
110
95
  return agent === undefined ? [] : [{ type: 'agent.started', data: { agent, ...(type === undefined ? {} : { agentType: type }) } }];
111
96
  }
112
97
  case 'SubagentStop':
@@ -119,7 +104,4 @@ function duration(p) {
119
104
  const value = typeof p['duration_ms'] === 'string' ? Number(p['duration_ms']) : p['duration_ms'];
120
105
  return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? { durationMs: Math.round(value) } : {};
121
106
  }
122
- function text(value) {
123
- return typeof value === 'string' && value !== '' ? value : undefined;
124
- }
125
107
  //# sourceMappingURL=hook-translation.js.map
@@ -3,7 +3,7 @@ import { basename, dirname, join } from 'node:path';
3
3
  import { performance } from 'node:perf_hooks';
4
4
  import { SessionLogFailure, } from '../../../../application/contracts/session-logs.js';
5
5
  import { AgentLogParser, MainLogParser } from './log-parser.js';
6
- import { logLines } from './log-lines.js';
6
+ import { logLines } from '../../shared/log-lines.js';
7
7
  const AGENT_FILE = /^agent-(.+)\.jsonl$/;
8
8
  /**
9
9
  * Session logs of Claude Code: `<config>/projects/<folder>/<session>.jsonl`
@@ -1,31 +1,19 @@
1
- import { createHash } from 'node:crypto';
1
+ import { renderBody } from '../../../application/contracts/skill-mention.js';
2
+ import { generatedBy, stamp } from '../shared/generated-file.js';
3
+ import { claudeCodeSkillRef } from './hook-events.js';
2
4
  const ALLOWED_TOOLS = 'Bash(emt *) Bash(estimetry *)';
3
- const HASH_LINE = /^ {2}contentHash: "[0-9a-f]*"\n/m;
4
5
  /** A skill file in Claude Code's format, stamped with the version and a hash of its own text. */
5
6
  export function renderSkill(content, version) {
6
- const unhashed = [
7
+ return stamp([
7
8
  '---',
8
9
  `name: ${content.id}`,
9
10
  `description: ${JSON.stringify(content.description)}`,
10
11
  ...(content.argumentHint === undefined ? [] : [`argument-hint: ${JSON.stringify(content.argumentHint)}`]),
11
12
  `allowed-tools: ${ALLOWED_TOOLS}`,
12
- 'metadata:',
13
- ` generatedBy: "estimetry ${version}"`,
13
+ ...generatedBy(version),
14
14
  '---',
15
15
  '',
16
- content.body,
17
- ].join('\n');
18
- return unhashed.replace(/^ {2}generatedBy: .*\n/m, (line) => `${line} contentHash: "${hashOf(unhashed)}"\n`);
19
- }
20
- /** Whose the file is: ours and untouched, ours but edited by the user, or the user's own. */
21
- export function ownership(text) {
22
- if (!/^ {2}generatedBy: "estimetry /m.test(text)) {
23
- return 'foreign';
24
- }
25
- const stamped = /^ {2}contentHash: "([0-9a-f]*)"$/m.exec(text)?.[1];
26
- return stamped !== undefined && stamped === hashOf(text.replace(HASH_LINE, '')) ? 'ours' : 'edited';
27
- }
28
- function hashOf(text) {
29
- return createHash('sha256').update(text).digest('hex').slice(0, 12);
16
+ renderBody(content.body, claudeCodeSkillRef, '$ARGUMENTS'),
17
+ ].join('\n'));
30
18
  }
31
19
  //# sourceMappingURL=skill-file.js.map
@@ -0,0 +1,161 @@
1
+ import { join } from 'node:path';
2
+ import { estimetryCommand } from '../../../application/contracts/estimetry-command.js';
3
+ import { COMMANDS, ESTIMATE_REMINDER_BLOCK, ESTIMETRY_SKILL } from '../content/commands.js';
4
+ import { HOOK_TIMEOUT_SECONDS, hasOurHooks, isBrokenJson, withHooks, withoutHooks } from '../shared/hook-settings.js';
5
+ import { instructionsPlan } from '../shared/instructions-block.js';
6
+ import { nameSkills } from '../../../application/contracts/skill-mention.js';
7
+ import { skillsPlan } from '../shared/skills-plan.js';
8
+ import { CODEX_HOOK_EVENTS, CODEX_SHORT_TIMEOUT_EVENTS, CODEX_SHORT_TIMEOUT_SECONDS, CODEX_SYNCHRONOUS_EVENTS, codexSkillRef, } from './hook-events.js';
9
+ import { hookTrusts, untrustedHooks, withTrusts } from './hook-trust.js';
10
+ import { SANDBOX_RULES, isOurRules } from './sandbox-rules.js';
11
+ import { renderSkill } from './skill-file.js';
12
+ const PROJECT_HOOKS = join('.codex', 'hooks.json');
13
+ const SKILLS = [ESTIMETRY_SKILL, ...COMMANDS];
14
+ /** Our hooks in a hooks file: `estimetry hook codex …`, in any form `estimetryCommand` gives. */
15
+ const OURS = 'hook codex';
16
+ const AGENTS_MD_BLOCK = nameSkills(ESTIMATE_REMINDER_BLOCK, codexSkillRef);
17
+ const TRUST_HINT = 'Codex runs no hook you have not trusted, so it does not measure your sessions yet: ' +
18
+ 'run `estimetry init --tools codex --trust-hooks`, or open /hooks in Codex and trust the estimetry hooks';
19
+ const CONFIG_REFUSED = 'the config.toml of Codex has a form estimetry does not change by itself (an inline or dotted hooks table, a ' +
20
+ 'multi-line string): open /hooks in Codex and trust the estimetry hooks there';
21
+ const UNTRUSTED = 'Codex has no trust of the estimetry hooks in its config.toml, so it may not run them: ' +
22
+ 'run `estimetry init --tools codex --trust-hooks`, or open /hooks in Codex and trust them';
23
+ /**
24
+ * Codex: hooks in `hooks.json` (the user's one, which serves every project, or the project's one for the team),
25
+ * skills in `.agents/skills`, the reminder in `AGENTS.md` with a shared install. Codex has no personal settings
26
+ * inside a project, so a personal install writes nothing there (design.md of codex-adapter, D3).
27
+ */
28
+ export class CodexAdapter {
29
+ dirs;
30
+ id = 'codex';
31
+ aliases = ['openai-codex'];
32
+ title = 'Codex';
33
+ hookEvents = CODEX_HOOK_EVENTS;
34
+ /** Codex runs a hook only once the user trusts it, and runs commands of the agent in a sandbox. */
35
+ asksTrust = true;
36
+ constructor(dirs) {
37
+ this.dirs = dirs;
38
+ }
39
+ state(projectRoot, files) {
40
+ const userText = files.read(this.userHooks());
41
+ const projectText = files.read(join(projectRoot, PROJECT_HOOKS));
42
+ const shared = hasOurHooks(projectText, OURS);
43
+ const installed = shared || hasOurHooks(userText, OURS);
44
+ const broken = [
45
+ ...(isBrokenJson(userText) ? [this.userHooks()] : []),
46
+ ...(isBrokenJson(projectText) ? [PROJECT_HOOKS] : []),
47
+ ];
48
+ const untrusted = installed && this.untrusted(files, shared ? join(projectRoot, PROJECT_HOOKS) : this.userHooks());
49
+ return {
50
+ installed,
51
+ shared,
52
+ ...(broken.length === 0 ? {} : { unreadable: `${broken.join(' and ')} ${broken.length === 1 ? 'is' : 'are'} not valid JSON` }),
53
+ // The user's hooks file serves every project: such an install belongs to no copy of its own.
54
+ ...(installed && !shared ? { machineWide: true } : {}),
55
+ ...(untrusted ? { notice: UNTRUSTED } : {}),
56
+ };
57
+ }
58
+ present(files) {
59
+ return files.isDirectory(this.dirs.home);
60
+ }
61
+ personalFiles() {
62
+ return [];
63
+ }
64
+ plan(context) {
65
+ const plans = [this.hooks(context), this.skills(context), this.agentsMd(context)];
66
+ return {
67
+ changes: plans.flatMap((plan) => plan.changes),
68
+ skipped: plans.flatMap((plan) => plan.skipped),
69
+ warnings: plans.flatMap((plan) => plan.warnings),
70
+ };
71
+ }
72
+ userHooks() {
73
+ return join(this.dirs.home, 'hooks.json');
74
+ }
75
+ config() {
76
+ return join(this.dirs.home, 'config.toml');
77
+ }
78
+ untrusted(files, hooksPath) {
79
+ return untrustedHooks(files.read(this.config()), hookTrusts(hooksPath, files.read(hooksPath), OURS));
80
+ }
81
+ hooks(context) {
82
+ const { projectRoot, files, shared, runner } = context;
83
+ const projectPath = join(projectRoot, PROJECT_HOOKS);
84
+ const [target, display] = shared ? [projectPath, PROJECT_HOOKS] : [this.userHooks(), this.userHooks()];
85
+ // The user's hooks run this installation by its paths; hooks the team commits hold no paths of this machine.
86
+ const command = (event) => estimetryCommand(shared ? undefined : runner, `${OURS} ${event}`);
87
+ const current = files.read(target);
88
+ const content = withHooks(current, {
89
+ ours: OURS,
90
+ events: this.hookEvents,
91
+ synchronous: CODEX_SYNCHRONOUS_EVENTS,
92
+ command,
93
+ timeout: (event) => (CODEX_SHORT_TIMEOUT_EVENTS.includes(event) ? CODEX_SHORT_TIMEOUT_SECONDS : HOOK_TIMEOUT_SECONDS),
94
+ }, display);
95
+ const trust = this.trustPlan(context, target, content);
96
+ const changes = [{ path: target, content }, ...trust.changes];
97
+ const warnings = [...trust.warnings];
98
+ if (shared) {
99
+ if (hasOurHooks(files.read(this.userHooks()), OURS)) {
100
+ warnings.push(`the estimetry hooks are also in ${this.userHooks()}, which serves every project: Codex runs both, ` +
101
+ 'so each hook runs twice here (the fact stays right). Remove them from that file if this project is enough');
102
+ }
103
+ }
104
+ else {
105
+ const old = files.read(projectPath);
106
+ if (old !== undefined && hasOurHooks(old, OURS)) {
107
+ const cleaned = withoutHooks(old, OURS, PROJECT_HOOKS);
108
+ changes.push(cleaned === undefined ? { path: projectPath, remove: true } : { path: projectPath, content: cleaned });
109
+ }
110
+ }
111
+ return { changes, skipped: trust.skipped, warnings };
112
+ }
113
+ /**
114
+ * The trust of the hooks and the rule for the task commands, with the user's consent. The consent is our rules file
115
+ * in the user's Codex directory: `trust: true` writes it, `trust: false` takes it away, and without an answer (an
116
+ * upgrade) a rules file of ours means the user agreed before, so the hooks changed now are trusted again. The rule
117
+ * is the user's own even with a shared install: one person's consent does not go into the team's repository.
118
+ */
119
+ trustPlan(context, target, content) {
120
+ const { files, version } = context;
121
+ const config = files.read(this.config());
122
+ const rules = join(this.dirs.home, 'rules', 'estimetry.rules');
123
+ const existing = files.read(rules);
124
+ const ownRules = existing !== undefined && isOurRules(existing);
125
+ const trust = context.trust ?? ownRules;
126
+ const wanted = hookTrusts(target, content, OURS);
127
+ if (!trust) {
128
+ return {
129
+ changes: context.trust === false && ownRules ? [{ path: rules, remove: true }] : [],
130
+ skipped: [],
131
+ warnings: untrustedHooks(config, wanted) ? [TRUST_HINT] : [],
132
+ };
133
+ }
134
+ const trusted = withTrusts(config, wanted);
135
+ const foreignRules = existing !== undefined && !ownRules;
136
+ return {
137
+ changes: [
138
+ ...(trusted === undefined ? [] : [{ path: this.config(), content: trusted }]),
139
+ ...(foreignRules ? [] : [{ path: rules, content: SANDBOX_RULES(version) }]),
140
+ ],
141
+ skipped: foreignRules ? [{ path: rules, reason: 'not created by estimetry, left as it is' }] : [],
142
+ warnings: trusted === undefined ? [CONFIG_REFUSED] : [],
143
+ };
144
+ }
145
+ skills({ projectRoot, files, shared, force, version }) {
146
+ return skillsPlan(SKILLS, {
147
+ files,
148
+ projectDir: join(projectRoot, '.agents', 'skills'),
149
+ userDir: this.dirs.userSkills,
150
+ shared,
151
+ force,
152
+ render: (skill) => renderSkill(skill, version),
153
+ });
154
+ }
155
+ /** The reminder goes to the committed AGENTS.md only with a shared install. */
156
+ agentsMd({ projectRoot, files, shared }) {
157
+ const path = join(projectRoot, 'AGENTS.md');
158
+ return instructionsPlan(path, files.read(path), shared, AGENTS_MD_BLOCK);
159
+ }
160
+ }
161
+ //# sourceMappingURL=codex-adapter.js.map
@@ -0,0 +1,23 @@
1
+ /** Hook events of Codex that the activity contract needs (design.md of codex-adapter, D3 and D5). */
2
+ export const CODEX_HOOK_EVENTS = [
3
+ 'SessionStart',
4
+ 'SessionEnd',
5
+ 'UserPromptSubmit',
6
+ 'Stop',
7
+ 'Interrupt',
8
+ 'PermissionRequest',
9
+ 'PreToolUse',
10
+ 'PostToolUse',
11
+ 'SubagentStart',
12
+ 'SubagentStop',
13
+ ];
14
+ /** Hooks Codex runs synchronously: their context reaches the agent in the same turn, and `SessionEnd` is always synchronous. */
15
+ export const CODEX_SYNCHRONOUS_EVENTS = ['SessionStart', 'UserPromptSubmit', 'SessionEnd'];
16
+ /** Codex waits for `SessionEnd` and `Interrupt` at most 3 seconds; other hooks get the timeout of estimetry. */
17
+ export const CODEX_SHORT_TIMEOUT_EVENTS = ['SessionEnd', 'Interrupt'];
18
+ export const CODEX_SHORT_TIMEOUT_SECONDS = 3;
19
+ /** How Codex calls a skill: `$name`. One rule for the context of hooks and the bodies of skills. */
20
+ export function codexSkillRef(id) {
21
+ return `$${id}`;
22
+ }
23
+ //# sourceMappingURL=hook-events.js.map
@@ -0,0 +1,76 @@
1
+ import { additionalContext, payloadText, translateHook } from '../shared/hook-payload.js';
2
+ import { CODEX_HOOK_EVENTS, codexSkillRef } from './hook-events.js';
3
+ /*
4
+ * Codex hook payloads → activity events (codex-hooks spec). Prompts, tool inputs and outputs and the last message of
5
+ * the agent are never read beyond their presence and never leave this module. Kept apart from the installer, so the
6
+ * hook receiver does not load skill texts and settings merging on every tool call.
7
+ */
8
+ /** Tools that wait for the user's answer rather than doing work (checked on a live session, tasks.md 10.2). */
9
+ const QUESTION_TOOLS = new Set(['request_user_input']);
10
+ const KINDS = {
11
+ SessionStart: 'session-start',
12
+ SessionEnd: 'session-end',
13
+ UserPromptSubmit: 'prompt',
14
+ Stop: 'turn-end',
15
+ Interrupt: 'turn-end',
16
+ PostToolUse: 'tool-done',
17
+ };
18
+ export const codexHooks = {
19
+ kind: 'session',
20
+ id: 'codex',
21
+ aliases: ['openai-codex'],
22
+ hookEvents: CODEX_HOOK_EVENTS,
23
+ // Codex names no project root in the environment: the `cwd` of the payload decides.
24
+ // It waits for SessionEnd at most 3 seconds; the import keeps a second for the rest of the hook.
25
+ sessionEndBudgetMs: 2_000,
26
+ translate(event, payload) {
27
+ return translateHook('codex', event, payload, KINDS, translateEvent);
28
+ },
29
+ skillRef: codexSkillRef,
30
+ renderContext: additionalContext,
31
+ };
32
+ function translateEvent(event, p) {
33
+ // Inside a subagent Codex adds its thread id; the session id stays the root one.
34
+ const agent = payloadText(p['agent_id']);
35
+ const onAgent = agent === undefined ? {} : { agent };
36
+ const turnId = payloadText(p['turn_id']);
37
+ const turn = agent === undefined && turnId !== undefined ? { turn: turnId } : {};
38
+ const tool = payloadText(p['tool_name']);
39
+ const toolUseId = payloadText(p['tool_use_id']);
40
+ const call = { ...onAgent, ...(tool === undefined ? {} : { tool }), ...(toolUseId === undefined ? {} : { toolUseId }) };
41
+ switch (event) {
42
+ case 'SessionStart': {
43
+ const source = payloadText(p['source']);
44
+ if (agent !== undefined || source === 'clear' || source === 'compact') {
45
+ return []; // a subagent's thread starting, or the same session going on
46
+ }
47
+ return [{ type: 'session.started', data: source === 'resume' || source === 'fork' ? { resumed: true } : {} }];
48
+ }
49
+ case 'SessionEnd':
50
+ return [{ type: 'session.ended', data: {} }];
51
+ case 'UserPromptSubmit':
52
+ // Codex sends no prompts of its own on behalf of the user; a subagent's prompt is written by its parent.
53
+ return [{ type: 'turn.started', data: { ...onAgent, origin: agent === undefined ? 'user' : 'automated', ...turn } }];
54
+ case 'Stop':
55
+ return [{ type: 'turn.ended', data: { ...onAgent, outcome: 'completed', ...turn } }];
56
+ case 'Interrupt':
57
+ return [{ type: 'turn.ended', data: { ...onAgent, outcome: 'interrupted', ...turn } }];
58
+ case 'PreToolUse':
59
+ return tool !== undefined && QUESTION_TOOLS.has(tool)
60
+ ? [{ type: 'turn.awaiting-input', data: { ...onAgent, reason: 'question', ...turn } }]
61
+ : [{ type: 'tool.started', data: call }];
62
+ case 'PermissionRequest':
63
+ return [{ type: 'turn.awaiting-input', data: { ...onAgent, reason: 'permission', ...turn } }];
64
+ case 'PostToolUse':
65
+ return [{ type: 'tool.used', data: call }];
66
+ case 'SubagentStart': {
67
+ const type = payloadText(p['agent_type']);
68
+ return agent === undefined ? [] : [{ type: 'agent.started', data: { agent, ...(type === undefined ? {} : { agentType: type }) } }];
69
+ }
70
+ case 'SubagentStop':
71
+ return agent === undefined ? [] : [{ type: 'agent.stopped', data: { agent } }];
72
+ default:
73
+ return [];
74
+ }
75
+ }
76
+ //# sourceMappingURL=hook-translation.js.map