harness-craft 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 sese2204
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,49 @@
1
- # Temporary Holding Version
1
+ # harness-craft
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 내 Claude Code·Codex 하네스(MCP·스킬·훅·서브에이전트)와 사용 기록을 픽셀 RPG 캐릭터 시트로 만든다.
4
+ 결과는 혼자 열리는 HTML 한 장이고, 그 파일만 보내면 된다. 네트워크는 쓰지 않는다.
5
+
6
+ Turn your Claude Code and Codex harness into a pixel-RPG character sheet: one self-contained HTML file, no network.
7
+
8
+ ## 쓰는 법
9
+
10
+ ```bash
11
+ npx harness-craft share --name <닉네임>
12
+ # → ./harness-sheet.html
13
+ ```
14
+
15
+ | 옵션 | 동작 |
16
+ |---|---|
17
+ | `--name <이름>` | 시트에 보일 이름(닉네임). 한글·이모지도 되고 32자까지. 기본 `player` |
18
+ | `--hide <glob>` | 이름이 맞는 MCP·스킬·에이전트·플러그인·훅을 파일에서 아예 뺀다. `*` 와일드카드, 대소문자 무시, 여러 번 쓸 수 있다 |
19
+ | `--descriptions` | 스킬·에이전트 설명을 넣는다. 기본은 뺀다 |
20
+ | `--out <파일>` | 저장 위치. 기본 `./harness-sheet.html` |
21
+ | `--no-usage` | 대화 기록 집계를 건너뛴다(빠르지만 레벨·사용 횟수가 0) |
22
+
23
+ 회사 도구처럼 보이고 싶지 않은 이름은 `--hide` 로 뺀다. 예: `--hide 'acme-*' --hide internal-wiki`.
24
+
25
+ 원본 데이터만 필요하면 `npx harness-craft` 로 `harness-profile.json` 을 만든다.
26
+
27
+ ## 무엇을 읽고, 무엇을 담나
28
+
29
+ | 읽는 곳 | 담는 것 |
30
+ |---|---|
31
+ | `~/.claude.json`, `~/.claude/settings.json` | MCP 서버 이름, 훅 이벤트, 모델, 플러그인 |
32
+ | `~/.claude/skills`, `~/.claude/agents`, 플러그인 | 스킬·에이전트 이름(설명은 `--descriptions` 일 때만) |
33
+ | `~/.claude/projects/**/*.jsonl` | 도구·스킬·에이전트·MCP 호출 횟수와 활동일 |
34
+ | `~/.codex/config.toml`, `hooks.json`, `AGENTS.md`(`AGENTS.override.md` 우선) | 같은 항목의 Codex 쪽 값. `enabled = false` 인 MCP·스킬·훅·플러그인은 뺀다 |
35
+ | `~/.codex/skills`(`.system` 포함), `~/.agents/skills` | Codex 스킬 이름. 시스템 스킬은 쓴 적이 있을 때만 |
36
+ | `~/.codex/plugins/cache/**/.codex-plugin/plugin.json` | Codex 플러그인 이름·버전, 플러그인 스킬·훅 |
37
+ | `~/.codex/sessions/**/*.jsonl` | 세션 수(대화형·exec), 스킬·MCP·명령 호출 횟수, 가장 많이 쓴 모델, 활동일 |
38
+ | `~/.codex/agents/*.toml`, `config.toml` 의 `[agents.*]` | Codex 커스텀 에이전트 이름·설명·모델(`developer_instructions` 는 담지 않음) |
39
+ | 위 두 도구의 날짜 | 활동일 수와 첫날·마지막 날(날짜 목록은 담지 않음) |
40
+
41
+ 환경변수 값, 헤더, 명령 인자, 파일 본문, 절대 경로, 대화 내용은 담지 않는다.
42
+ `~/.codex/auth.json`, `~/.claude/.credentials.json`, sqlite 파일은 열지 않는다.
43
+ `$CODEX_HOME` 을 정해 두었으면 `~/.codex` 대신 그 폴더를 읽는다.
44
+ MCP 서버 주소는 공개 서비스로 알려진 곳만 남기고, 공유 파일에서는 그마저 뺀다.
45
+
46
+ ## 라이선스
47
+
48
+ MIT. 공유 HTML 에 들어가는 폰트 NeoDunggeunmo 와 Press Start 2P 는 SIL Open Font License 1.1 이며,
49
+ 원문은 패키지의 `dist/licenses/` 에 있다. React 의 MIT 고지는 공유 HTML 안에 그대로 남는다.
@@ -0,0 +1,34 @@
1
+ import { join } from 'node:path';
2
+ import { isRecord, readJsonOrNull } from '../fsutil.js';
3
+ async function readObject(path, diag) {
4
+ const value = await readJsonOrNull(path, diag);
5
+ if (value === null)
6
+ return {};
7
+ if (!isRecord(value)) {
8
+ diag.warn(path, '최상위가 객체가 아님');
9
+ return {};
10
+ }
11
+ return value;
12
+ }
13
+ export async function readClaudeConfig(home, diag) {
14
+ const claudeDir = join(home, '.claude');
15
+ const settingsPath = join(claudeDir, 'settings.json');
16
+ return {
17
+ claudeDir,
18
+ settingsPath,
19
+ settings: await readObject(settingsPath, diag),
20
+ claudeJson: await readObject(join(home, '.claude.json'), diag),
21
+ };
22
+ }
23
+ export function recordField(obj, key) {
24
+ const v = obj[key];
25
+ return isRecord(v) ? v : {};
26
+ }
27
+ export function numberField(obj, key) {
28
+ const v = obj[key];
29
+ return typeof v === 'number' && Number.isFinite(v) ? v : null;
30
+ }
31
+ export function stringValue(obj, key) {
32
+ const v = obj[key];
33
+ return typeof v === 'string' && v.length > 0 ? v : null;
34
+ }
@@ -0,0 +1,60 @@
1
+ import { join } from 'node:path';
2
+ import { definitionName, toAgent, toSkill, usageKeys, usedBuiltinAgents } from '../definitions.js';
3
+ import { sortByName } from '../fsutil.js';
4
+ import { readFlatDefinitions, readSkillDefinitions } from '../items.js';
5
+ import { numberField, recordField } from './config.js';
6
+ /** Agents that ship with Claude Code (Agent/Task `subagent_type`). Shown only when used. */
7
+ export const CLAUDE_BUILTIN_AGENTS = [
8
+ 'general-purpose', 'Explore', 'Plan', 'claude', 'statusline-setup', 'claude-code-guide',
9
+ ];
10
+ const EMPTY_COUNTS = { skillCalls: new Map(), slashCalls: new Map(), agentCalls: new Map() };
11
+ async function gather(userDir, plugins, sub, ctx) {
12
+ const read = sub === 'skills' ? readSkillDefinitions : readFlatDefinitions;
13
+ const out = (await read(userDir, ctx.diag)).map((def) => ({ def, source: 'user' }));
14
+ for (const p of plugins) {
15
+ if (!p.installPath)
16
+ continue;
17
+ const defs = await read(join(p.installPath, sub), ctx.diag);
18
+ out.push(...defs.map((def) => ({ def, source: `plugin:${p.name}` })));
19
+ }
20
+ return out;
21
+ }
22
+ /**
23
+ * uses = max(skillUsage usageCount, transcript Skill calls + same-name slash calls).
24
+ * Plugin skills look up both '<plugin>:<name>' and '<name>' (summed per side).
25
+ */
26
+ export function skillUsageLookup(claudeJson, counts) {
27
+ const skillUsage = recordField(claudeJson, 'skillUsage');
28
+ return (keys) => {
29
+ let recorded = 0;
30
+ let transcript = 0;
31
+ let last = null;
32
+ for (const key of keys) {
33
+ const entry = recordField(skillUsage, key);
34
+ recorded += numberField(entry, 'usageCount') ?? 0;
35
+ const at = numberField(entry, 'lastUsedAt');
36
+ if (at !== null && (last === null || at > last))
37
+ last = at;
38
+ transcript += (counts.skillCalls.get(key) ?? 0) + (counts.slashCalls.get(key) ?? 0);
39
+ }
40
+ return { uses: Math.max(recorded, transcript), lastUsedAt: last === null ? null : new Date(last).toISOString() };
41
+ };
42
+ }
43
+ export async function collectClaudeSkills(claudeDir, plugins, claudeJson, counts, ctx) {
44
+ const items = await gather(join(claudeDir, 'skills'), plugins, 'skills', ctx);
45
+ const userNames = new Set(items.filter((i) => i.source === 'user').map((i) => definitionName(i.def)));
46
+ const lookup = skillUsageLookup(claudeJson, counts ?? EMPTY_COUNTS);
47
+ return sortByName(items.map(({ def, source }) => toSkill(def, source, lookup(usageKeys(definitionName(def), source, userNames)), ctx)));
48
+ }
49
+ export async function collectClaudeAgents(claudeDir, plugins, counts, ctx) {
50
+ const items = await gather(join(claudeDir, 'agents'), plugins, 'agents', ctx);
51
+ const userNames = new Set(items.filter((i) => i.source === 'user').map((i) => definitionName(i.def)));
52
+ const agentCalls = (counts ?? EMPTY_COUNTS).agentCalls;
53
+ const defined = items.map(({ def, source }) => {
54
+ const uses = usageKeys(definitionName(def), source, userNames).reduce((sum, k) => sum + (agentCalls.get(k) ?? 0), 0);
55
+ return toAgent(def, source, uses, ctx);
56
+ });
57
+ // Any defined agent (user or plugin) with a built-in's bare name takes those calls, so the built-in is not listed.
58
+ const definedNames = new Set(items.map((i) => definitionName(i.def)));
59
+ return sortByName([...defined, ...usedBuiltinAgents(CLAUDE_BUILTIN_AGENTS, definedNames, agentCalls)]);
60
+ }
@@ -0,0 +1,46 @@
1
+ import { join } from 'node:path';
2
+ import { describeError } from '../diagnostics.js';
3
+ import { parseHooks } from '../hooks.js';
4
+ import { pathExists, sortByName } from '../fsutil.js';
5
+ import { readInstructions, readNestedDefinitions } from '../items.js';
6
+ import { toCommand } from '../definitions.js';
7
+ import { scanClaudeTranscripts } from '../usage/claude.js';
8
+ import { numberField, readClaudeConfig, stringValue } from './config.js';
9
+ import { collectClaudeAgents, collectClaudeSkills } from './definitions.js';
10
+ import { collectClaudeMcp } from './mcp.js';
11
+ import { readInstalledPlugins, toPlugins } from './plugins.js';
12
+ const MAX_SHORT_FIELD_LENGTH = 64;
13
+ async function scanUsage(claudeDir, ctx) {
14
+ try {
15
+ return await scanClaudeTranscripts(claudeDir, ctx.diag, ctx.onProgress?.('대화 기록 읽는 중'));
16
+ }
17
+ catch (err) {
18
+ ctx.diag.warn(join(claudeDir, 'projects'), `대화 기록 집계 실패 (${describeError(err)})`);
19
+ return null;
20
+ }
21
+ }
22
+ /** source is null when neither ~/.claude nor ~/.claude.json exists. */
23
+ export async function collectClaudeCode(ctx, options) {
24
+ const claudeDir = join(ctx.home, '.claude');
25
+ const [hasDir, hasJson] = await Promise.all([pathExists(claudeDir), pathExists(join(ctx.home, '.claude.json'))]);
26
+ if (!hasDir && !hasJson)
27
+ return { source: null, days: null };
28
+ const config = await readClaudeConfig(ctx.home, ctx.diag);
29
+ const scan = options.usage ? await scanUsage(claudeDir, ctx) : null;
30
+ const installed = await readInstalledPlugins(claudeDir, ctx);
31
+ const { settings, claudeJson } = config;
32
+ const source = {
33
+ model: ctx.redactor.optional(stringValue(settings, 'model'), MAX_SHORT_FIELD_LENGTH),
34
+ since: ctx.redactor.optional(stringValue(claudeJson, 'claudeCodeFirstTokenDate') ?? stringValue(claudeJson, 'firstStartTime'), MAX_SHORT_FIELD_LENGTH),
35
+ startups: numberField(claudeJson, 'numStartups'),
36
+ mcpServers: collectClaudeMcp(claudeJson, scan?.mcpCalls ?? new Map(), ctx),
37
+ skills: await collectClaudeSkills(claudeDir, installed, claudeJson, scan, ctx),
38
+ agents: await collectClaudeAgents(claudeDir, installed, scan, ctx),
39
+ hooks: parseHooks(settings.hooks, config.settingsPath, ctx.redactor, ctx.diag),
40
+ plugins: toPlugins(installed, settings, claudeJson, ctx),
41
+ commands: sortByName((await readNestedDefinitions(join(claudeDir, 'commands'), ctx.diag)).map((d) => toCommand(d, ctx))),
42
+ instructions: await readInstructions(join(claudeDir, 'CLAUDE.md'), ctx.diag),
43
+ usage: scan?.usage ?? null,
44
+ };
45
+ return { source, days: scan?.days ?? null };
46
+ }
@@ -0,0 +1,25 @@
1
+ import { sortByName } from '../fsutil.js';
2
+ import { buildMcpServer, normalizeServerName } from '../mcp.js';
3
+ import { recordField } from './config.js';
4
+ /**
5
+ * User scope = ~/.claude.json mcpServers; project scope = projects[*].mcpServers, deduplicated by name.
6
+ * A project server whose name is already a user server is dropped. Project paths are never exported.
7
+ */
8
+ export function collectClaudeMcp(claudeJson, calls, ctx) {
9
+ const callsOf = (name) => calls.get(normalizeServerName(name)) ?? 0;
10
+ const user = recordField(claudeJson, 'mcpServers');
11
+ const project = new Map();
12
+ for (const projectEntry of Object.values(recordField(claudeJson, 'projects'))) {
13
+ if (typeof projectEntry !== 'object' || projectEntry === null)
14
+ continue;
15
+ const servers = recordField(projectEntry, 'mcpServers');
16
+ for (const [name, raw] of Object.entries(servers)) {
17
+ if (!(name in user) && !project.has(name))
18
+ project.set(name, raw);
19
+ }
20
+ }
21
+ return sortByName([
22
+ ...Object.entries(user).map(([name, raw]) => buildMcpServer(name, raw, 'user', callsOf(name), ctx.redactor)),
23
+ ...[...project].map(([name, raw]) => buildMcpServer(name, raw, 'project', callsOf(name), ctx.redactor)),
24
+ ]);
25
+ }
@@ -0,0 +1,42 @@
1
+ import { join } from 'node:path';
2
+ import { isRecord, readJsonOrNull, sortByName } from '../fsutil.js';
3
+ import { numberField, recordField } from './config.js';
4
+ const MAX_FIELD_LENGTH = 120;
5
+ export function splitPluginKey(key) {
6
+ const at = key.lastIndexOf('@');
7
+ return at > 0 ? { name: key.slice(0, at), marketplace: key.slice(at + 1) } : { name: key, marketplace: '' };
8
+ }
9
+ export async function readInstalledPlugins(claudeDir, ctx) {
10
+ const path = join(claudeDir, 'plugins', 'installed_plugins.json');
11
+ const json = await readJsonOrNull(path, ctx.diag);
12
+ if (json === null)
13
+ return [];
14
+ const plugins = isRecord(json) ? json.plugins : undefined;
15
+ if (!isRecord(plugins)) {
16
+ ctx.diag.warn(path, 'plugins 필드가 없거나 객체가 아님');
17
+ return [];
18
+ }
19
+ return Object.entries(plugins)
20
+ .map(([key, installs]) => {
21
+ const first = Array.isArray(installs) ? installs[0] : undefined;
22
+ const install = isRecord(first) ? first : {};
23
+ return {
24
+ key,
25
+ ...splitPluginKey(key),
26
+ installPath: typeof install.installPath === 'string' ? install.installPath : null,
27
+ version: typeof install.version === 'string' ? install.version : null,
28
+ };
29
+ })
30
+ .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
31
+ }
32
+ export function toPlugins(installed, settings, claudeJson, ctx) {
33
+ const enabled = recordField(settings, 'enabledPlugins');
34
+ const usage = recordField(claudeJson, 'pluginUsage');
35
+ return sortByName(installed.map((p) => ({
36
+ name: ctx.redactor.text(p.name, MAX_FIELD_LENGTH),
37
+ marketplace: ctx.redactor.text(p.marketplace, MAX_FIELD_LENGTH),
38
+ version: ctx.redactor.optional(p.version, MAX_FIELD_LENGTH),
39
+ enabled: enabled[p.key] === true,
40
+ uses: numberField(recordField(usage, p.key), 'usageCount') ?? 0,
41
+ })));
42
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,137 @@
1
+ #!/usr/bin/env node
2
+ import { writeFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { join, resolve } from 'node:path';
5
+ import { parseArgs } from 'node:util';
6
+ import { collectProfile } from './collect.js';
7
+ import { writeShareSheet, formatShareSummary } from './shareCommand.js';
8
+ import { DEFAULT_SHARE_HANDLE, SHARE_NAME_MAX_LENGTH, validateShareName } from './shareFormat.js';
9
+ import { formatSummary } from './summary.js';
10
+ const DEFAULT_OUT = 'harness-profile.json';
11
+ const DEFAULT_SHARE_OUT = 'harness-sheet.html';
12
+ const USAGE = `사용법: harness-craft [scan] [--out <file>] [--json] [--no-usage] [--home <dir>]
13
+ harness-craft share [--out <file>] [--name <이름>] [--hide <glob>]... [--descriptions] [--no-usage] [--home <dir>]
14
+
15
+ scan (기본) — 설정과 사용 기록을 읽어 harness-profile.json 을 만든다
16
+ --out <file> 저장 위치 (기본 ./${DEFAULT_OUT})
17
+ --json JSON 을 stdout 으로만 내보내고 파일은 쓰지 않음
18
+
19
+ share — 혼자 열리는 캐릭터 시트 HTML 한 장을 만든다
20
+ --out <file> 저장 위치 (기본 ./${DEFAULT_SHARE_OUT})
21
+ --name <이름> 시트에 보일 이름(닉네임). 한글 가능, ${SHARE_NAME_MAX_LENGTH}자까지 (기본 ${DEFAULT_SHARE_HANDLE})
22
+ --hide <glob> 이름이 맞는 MCP·스킬·에이전트·플러그인·명령·훅을 파일에서 뺌 (대소문자 무시, * 가능, 여러 번)
23
+ --descriptions 설명을 파일에 넣음 (기본은 뺌)
24
+
25
+ 공통
26
+ --no-usage 대화 기록 집계를 건너뜀 (usage 는 null)
27
+ --home <dir> 홈 디렉터리 대신 쓸 경로 (테스트·디버그용). 주면 $CODEX_HOME 대신 <dir>/.codex 를 읽음
28
+
29
+ Codex 설정은 $CODEX_HOME (없으면 ~/.codex) 에서 읽는다.
30
+ `;
31
+ class UsageError extends Error {
32
+ }
33
+ const SCAN_ONLY = ['json'];
34
+ const SHARE_ONLY = ['name', 'handle', 'hide', 'descriptions'];
35
+ function parseCli(argv) {
36
+ const { values, positionals } = parseArgs({
37
+ args: [...argv],
38
+ allowPositionals: true,
39
+ strict: true,
40
+ options: {
41
+ out: { type: 'string' },
42
+ json: { type: 'boolean' },
43
+ 'no-usage': { type: 'boolean', default: false },
44
+ home: { type: 'string' },
45
+ name: { type: 'string' },
46
+ // Old spelling of --name, kept working but no longer documented.
47
+ handle: { type: 'string' },
48
+ hide: { type: 'string', multiple: true },
49
+ descriptions: { type: 'boolean' },
50
+ help: { type: 'boolean', short: 'h', default: false },
51
+ },
52
+ });
53
+ if (values.help)
54
+ return 'help';
55
+ const command = positionals[0] ?? 'scan';
56
+ if (positionals.length > 1 || (command !== 'scan' && command !== 'share')) {
57
+ throw new UsageError(`알 수 없는 명령: ${positionals.join(' ')}`);
58
+ }
59
+ const foreign = (command === 'scan' ? SHARE_ONLY : SCAN_ONLY).filter((key) => values[key] !== undefined);
60
+ if (foreign.length > 0)
61
+ throw new UsageError(`${command} 에는 쓸 수 없는 옵션: ${foreign.map((k) => `--${k}`).join(' ')}`);
62
+ const home = resolve(values.home ?? homedir());
63
+ const common = { usage: values['no-usage'] !== true, home, codexHome: codexHomeFor(values.home, home) };
64
+ if (command === 'scan') {
65
+ return { ...common, command, out: resolve(values.out ?? DEFAULT_OUT), json: values.json === true };
66
+ }
67
+ return {
68
+ ...common,
69
+ command,
70
+ out: resolve(values.out ?? DEFAULT_SHARE_OUT),
71
+ handle: shareName(values.name, values.handle),
72
+ hide: values.hide ?? [],
73
+ descriptions: values.descriptions === true,
74
+ };
75
+ }
76
+ /** --home pins everything under it (tests, debugging); otherwise $CODEX_HOME, else ~/.codex. */
77
+ function codexHomeFor(homeFlag, home) {
78
+ const env = process.env.CODEX_HOME;
79
+ return homeFlag === undefined && env !== undefined && env.trim() !== '' ? resolve(env) : join(home, '.codex');
80
+ }
81
+ /** --name, or its old alias --handle. Both at once is an error. */
82
+ function shareName(name, alias) {
83
+ if (name !== undefined && alias !== undefined)
84
+ throw new UsageError('--name 과 --handle 은 같은 옵션입니다. 하나만 쓰세요.');
85
+ const flag = alias !== undefined ? '--handle' : '--name';
86
+ const result = validateShareName(name ?? alias ?? '');
87
+ if (!result.ok)
88
+ throw new UsageError(`${flag} 값이 올바르지 않습니다: ${result.error}`);
89
+ return result.name;
90
+ }
91
+ function progressReporter(label) {
92
+ return (done, total) => {
93
+ process.stderr.write(`\r${label} ${done}/${total}`);
94
+ if (done === total)
95
+ process.stderr.write('\n');
96
+ };
97
+ }
98
+ async function runScan(options) {
99
+ const profile = await collectProfile({ home: options.home, codexHome: options.codexHome, usage: options.usage, onProgress: progressReporter });
100
+ const json = JSON.stringify(profile, null, 2) + '\n';
101
+ if (options.json) {
102
+ process.stdout.write(json);
103
+ process.stderr.write(formatSummary(profile, null));
104
+ }
105
+ else {
106
+ await writeFile(options.out, json, 'utf8');
107
+ process.stderr.write(formatSummary(profile, options.out));
108
+ }
109
+ return 0;
110
+ }
111
+ async function runShare(options) {
112
+ const profile = await collectProfile({ home: options.home, codexHome: options.codexHome, usage: options.usage, onProgress: progressReporter });
113
+ const result = await writeShareSheet(profile, options);
114
+ process.stderr.write(formatShareSummary(result, options.descriptions));
115
+ return 0;
116
+ }
117
+ async function main(argv) {
118
+ let options;
119
+ try {
120
+ options = parseCli(argv);
121
+ }
122
+ catch (err) {
123
+ process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n\n${USAGE}`);
124
+ return 2;
125
+ }
126
+ if (options === 'help') {
127
+ process.stdout.write(USAGE);
128
+ return 0;
129
+ }
130
+ return options.command === 'share' ? runShare(options) : runScan(options);
131
+ }
132
+ main(process.argv.slice(2)).then((code) => {
133
+ process.exitCode = code;
134
+ }, (err) => {
135
+ process.stderr.write(`harness-craft 실패: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}\n`);
136
+ process.exitCode = 1;
137
+ });
@@ -0,0 +1,107 @@
1
+ // Codex custom agents (subagents): ~/.codex/agents/*.toml and [agents.<role>] tables in config.toml (docs/collector-spec.md).
2
+ import { realpath } from 'node:fs/promises';
3
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { usedBuiltinAgents } from '../definitions.js';
5
+ import { describeError } from '../diagnostics.js';
6
+ import { isRecord, listEntries, sortByName } from '../fsutil.js';
7
+ import { stringField } from '../items.js';
8
+ import { readTomlFile } from './config.js';
9
+ const MAX_NAME_LENGTH = 120;
10
+ const MAX_SHORT_FIELD_LENGTH = 64;
11
+ const AGENT_FILE_SUFFIX = '.toml';
12
+ /** Agents that ship with Codex. Shown only when used. */
13
+ export const CODEX_BUILTIN_AGENTS = ['default', 'worker', 'explorer'];
14
+ function pick(name, description, data) {
15
+ return {
16
+ name,
17
+ description,
18
+ model: data ? stringField(data, 'model') : null,
19
+ effort: data ? stringField(data, 'model_reasoning_effort') : null,
20
+ };
21
+ }
22
+ /** `~/.codex/agents/*.toml`, one agent per file. The `name` key wins over the file name. */
23
+ async function readAgentFiles(agentsDir, ctx) {
24
+ const out = [];
25
+ for (const file of await listEntries(agentsDir, 'file', ctx.diag)) {
26
+ if (!file.endsWith(AGENT_FILE_SUFFIX))
27
+ continue;
28
+ const data = await readTomlFile(join(agentsDir, file), ctx.diag);
29
+ if (data === null)
30
+ continue;
31
+ const name = stringField(data, 'name') ?? file.slice(0, -AGENT_FILE_SUFFIX.length);
32
+ out.push(pick(name, stringField(data, 'description'), data));
33
+ }
34
+ return out;
35
+ }
36
+ function isInside(root, path) {
37
+ const rel = relative(root, path);
38
+ return rel === '' || (!isAbsolute(rel) && rel.split(sep)[0] !== '..');
39
+ }
40
+ /**
41
+ * Reads a role's config_file only when it resolves inside ~/.codex, before and after following symlinks.
42
+ * Relative paths are taken from the Codex home (where config.toml lives); `~/` is the home directory.
43
+ */
44
+ async function readRoleFile(role, value, configPath, ctx) {
45
+ const codexDir = ctx.codexHome;
46
+ const target = value.startsWith('~/') ? join(ctx.home, value.slice(2)) : resolve(codexDir, value);
47
+ const outside = `[agents.${role}] config_file 이 ~/.codex 밖을 가리켜 읽지 않음`;
48
+ if (!isInside(codexDir, target)) {
49
+ ctx.diag.warn(configPath, outside);
50
+ return null;
51
+ }
52
+ let real;
53
+ let realRoot;
54
+ try {
55
+ [real, realRoot] = await Promise.all([realpath(target), realpath(codexDir)]);
56
+ }
57
+ catch (err) {
58
+ ctx.diag.warn(configPath, `[agents.${role}] config_file 을 읽지 못함 (${describeError(err)})`);
59
+ return null;
60
+ }
61
+ if (!isInside(realRoot, real)) {
62
+ ctx.diag.warn(configPath, outside);
63
+ return null;
64
+ }
65
+ return readTomlFile(real, ctx.diag);
66
+ }
67
+ /** `[agents.<role>]` sub-tables. Scalar keys under [agents] (max_threads, enabled, …) are settings, not roles. */
68
+ async function readRoleTables(config, configPath, ctx) {
69
+ const agents = isRecord(config.agents) ? config.agents : {};
70
+ const out = [];
71
+ for (const [role, table] of Object.entries(agents)) {
72
+ if (!isRecord(table))
73
+ continue;
74
+ const file = stringField(table, 'config_file');
75
+ const data = file === null ? null : await readRoleFile(role, file, configPath, ctx);
76
+ out.push(pick(role, stringField(table, 'description') ?? (data ? stringField(data, 'description') : null), data));
77
+ }
78
+ return out;
79
+ }
80
+ function toCodexAgent(raw, uses, ctx) {
81
+ const { redactor } = ctx;
82
+ return {
83
+ name: redactor.text(raw.name, MAX_NAME_LENGTH),
84
+ description: redactor.text(raw.description ?? ''),
85
+ model: redactor.optional(raw.model, MAX_SHORT_FIELD_LENGTH),
86
+ effort: redactor.optional(raw.effort, MAX_SHORT_FIELD_LENGTH),
87
+ toolCount: null,
88
+ mcpServers: [],
89
+ source: 'user',
90
+ uses,
91
+ };
92
+ }
93
+ /**
94
+ * Custom agents (standalone files win over role tables of the same name) plus built-ins that were used.
95
+ * `roleCalls` is null without a session scan: uses are 0 and no built-in is listed.
96
+ */
97
+ export async function collectCodexAgents(config, roleCalls, ctx) {
98
+ const codexDir = ctx.codexHome;
99
+ const byName = new Map();
100
+ for (const raw of await readRoleTables(config, join(codexDir, 'config.toml'), ctx))
101
+ byName.set(raw.name, raw);
102
+ for (const raw of await readAgentFiles(join(codexDir, 'agents'), ctx))
103
+ byName.set(raw.name, raw);
104
+ const calls = roleCalls ?? new Map();
105
+ const defined = [...byName.values()].map((raw) => toCodexAgent(raw, calls.get(raw.name) ?? 0, ctx));
106
+ return sortByName([...defined, ...usedBuiltinAgents(CODEX_BUILTIN_AGENTS, new Set(byName.keys()), calls)]);
107
+ }
@@ -0,0 +1,21 @@
1
+ import { parse } from 'smol-toml';
2
+ import { isRecord, readTextOrNull } from '../fsutil.js';
3
+ /** Parses one TOML file. Missing -> null silently; broken -> warning + null. */
4
+ export async function readTomlFile(path, diag) {
5
+ const text = await readTextOrNull(path, diag);
6
+ if (text === null)
7
+ return null;
8
+ try {
9
+ const parsed = parse(text);
10
+ return isRecord(parsed) ? parsed : {};
11
+ }
12
+ catch (err) {
13
+ const message = err instanceof Error ? err.message.split('\n')[0] ?? '' : String(err);
14
+ diag.warn(path, `TOML 파싱 실패 (${message.slice(0, 120)})`);
15
+ return null;
16
+ }
17
+ }
18
+ /** Parses ~/.codex/config.toml. Missing -> {}; broken -> warning + {}. */
19
+ export async function readCodexConfig(path, diag) {
20
+ return (await readTomlFile(path, diag)) ?? {};
21
+ }
@@ -0,0 +1,62 @@
1
+ // Codex hooks: hooks.json, inline [hooks.<Event>] in config.toml and enabled plugins' hooks/hooks.json (docs/collector-spec.md).
2
+ import { join } from 'node:path';
3
+ import { isRecord, readJsonOrNull } from '../fsutil.js';
4
+ import { compareHooks, parseHooks } from '../hooks.js';
5
+ /** `[hooks.state]` holds per-handler trust/enable flags, not handlers. */
6
+ const STATE_KEY = 'state';
7
+ /** `[features] hooks` (or its deprecated alias `codex_hooks`) = false turns every hook off. */
8
+ function hooksEnabled(config) {
9
+ const features = isRecord(config.features) ? config.features : {};
10
+ const flag = typeof features.hooks === 'boolean' ? features.hooks : features.codex_hooks;
11
+ return flag !== false;
12
+ }
13
+ /** PreToolUse -> pre_tool_use, as in hooks.state keys. */
14
+ function snakeEvent(event) {
15
+ return event.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase();
16
+ }
17
+ /**
18
+ * Returns a copy without handlers that `[hooks.state."<file>:<event>:<group>:<handler>"] enabled = false` turns off.
19
+ * The key format was checked against hooks.json entries; config.toml and plugin files use the same scheme as a guess.
20
+ */
21
+ export function withoutDisabled(hooks, file, state) {
22
+ if (!isRecord(hooks))
23
+ return hooks;
24
+ const disabled = (event, g, h) => {
25
+ const entry = state[`${file}:${snakeEvent(event)}:${g}:${h}`];
26
+ return isRecord(entry) && entry.enabled === false;
27
+ };
28
+ return Object.fromEntries(Object.entries(hooks).map(([event, groups]) => [
29
+ event,
30
+ Array.isArray(groups)
31
+ ? groups.map((group, g) => isRecord(group) && Array.isArray(group.hooks)
32
+ ? { ...group, hooks: group.hooks.filter((_, h) => !disabled(event, g, h)) }
33
+ : group)
34
+ : groups,
35
+ ]));
36
+ }
37
+ async function readHooksJson(path, state, ctx) {
38
+ const json = await readJsonOrNull(path, ctx.diag);
39
+ if (json === null)
40
+ return [];
41
+ if (!isRecord(json)) {
42
+ ctx.diag.warn(path, '최상위가 객체가 아님');
43
+ return [];
44
+ }
45
+ return parseHooks(withoutDisabled(json.hooks, path, state), path, ctx.redactor, ctx.diag);
46
+ }
47
+ export async function collectCodexHooks(config, plugins, ctx) {
48
+ if (!hooksEnabled(config))
49
+ return [];
50
+ const configPath = join(ctx.codexHome, 'config.toml');
51
+ const table = isRecord(config.hooks) ? config.hooks : {};
52
+ const state = isRecord(table[STATE_KEY]) ? table[STATE_KEY] : {};
53
+ const inline = Object.fromEntries(Object.entries(table).filter(([key]) => key !== STATE_KEY));
54
+ const lists = [
55
+ await readHooksJson(join(ctx.codexHome, 'hooks.json'), state, ctx),
56
+ parseHooks(withoutDisabled(inline, configPath, state), configPath, ctx.redactor, ctx.diag),
57
+ ];
58
+ for (const plugin of plugins)
59
+ if (plugin.enabled)
60
+ lists.push(await readHooksJson(plugin.hooksFile, state, ctx));
61
+ return lists.flat().sort(compareHooks);
62
+ }