sneakoscope 8.0.2 → 8.0.3

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 (122) hide show
  1. package/README.md +47 -23
  2. package/config/skills-hash-ledger.v1.json +1 -1
  3. package/crates/sks-core/Cargo.lock +1 -1
  4. package/crates/sks-core/Cargo.toml +1 -1
  5. package/dist/bin/fast-inline.js +55 -13
  6. package/dist/bin/sks-dispatch.js +1 -1
  7. package/dist/cli/command-manifest-lite.js +4 -0
  8. package/dist/cli/command-registry.js +4 -0
  9. package/dist/cli/install-helpers-codex-lb-chain.js +187 -0
  10. package/dist/cli/install-helpers-codex-lb-config.js +74 -8
  11. package/dist/cli/install-helpers.js +89 -44
  12. package/dist/commands/codex-lb.js +117 -19
  13. package/dist/commands/doctor.js +697 -37
  14. package/dist/config/skills-manifest.json +3 -2
  15. package/dist/core/agents/agent-runner-codex-exec.js +5 -3
  16. package/dist/core/codex/codex-config-guard.js +238 -52
  17. package/dist/core/codex-adapter.js +5 -3
  18. package/dist/core/codex-app/menubar/constants.js +10 -1
  19. package/dist/core/codex-app/menubar/global-install.js +288 -0
  20. package/dist/core/codex-app/menubar/installer.js +79 -14
  21. package/dist/core/codex-app/menubar/launch-agent.js +267 -45
  22. package/dist/core/codex-app/menubar/paths.js +3 -0
  23. package/dist/core/codex-app/menubar/rollback.js +55 -7
  24. package/dist/core/codex-app/menubar/status.js +75 -4
  25. package/dist/core/codex-control/codex-0139-image-path-real-probe.js +3 -1
  26. package/dist/core/codex-control/codex-0139-web-search-probe.js +3 -1
  27. package/dist/core/codex-control/codex-app-server-runtime-env.js +13 -4
  28. package/dist/core/codex-control/codex-app-server-v2-client.js +3 -3
  29. package/dist/core/codex-exec-output-schema.js +4 -1
  30. package/dist/core/codex-lb/codex-lb-env.js +63 -72
  31. package/dist/core/codex-lb/codex-lb-setup.js +15 -2
  32. package/dist/core/codex-lb/desktop-center-credentials.js +517 -58
  33. package/dist/core/codex-lb/desktop-controller.js +153 -24
  34. package/dist/core/codex-lb/routing-truth.js +327 -0
  35. package/dist/core/codex-native/core-skill-manifest.js +1 -1
  36. package/dist/core/commands/basic-cli.js +7 -1
  37. package/dist/core/commands/qa-loop-command.js +3 -1
  38. package/dist/core/commands/telegram-command.js +241 -0
  39. package/dist/core/config-adopt/config-adopt-command.js +35 -0
  40. package/dist/core/config-adopt/config-adopt.js +346 -0
  41. package/dist/core/config-adopt/index.js +3 -0
  42. package/dist/core/doctor/command-alias-cleanup.js +4 -1
  43. package/dist/core/doctor/current-project-guidance-nested.js +37 -6
  44. package/dist/core/doctor/current-project-guidance.js +11 -6
  45. package/dist/core/doctor/doctor-readiness-matrix.js +14 -0
  46. package/dist/core/doctor/retired-managed-residue-private.js +1 -1
  47. package/dist/core/doctor/sks-menubar-doctor.js +4 -0
  48. package/dist/core/feature-fixtures.js +8 -0
  49. package/dist/core/hooks-runtime/hook-context.js +9 -0
  50. package/dist/core/hooks-runtime/managed-skill-admission.js +54 -4
  51. package/dist/core/hooks-runtime/official-subagent-lifecycle.js +69 -1
  52. package/dist/core/hooks-runtime/subagent-skill-availability-contract.js +2 -2
  53. package/dist/core/hooks-runtime/subagent-skill-availability-evidence.js +3 -3
  54. package/dist/core/hooks-runtime/subagent-skill-availability-guards.js +43 -5
  55. package/dist/core/hooks-runtime/subagent-skill-availability.js +64 -30
  56. package/dist/core/hooks-runtime/subagent-stop-hook.js +15 -2
  57. package/dist/core/hooks-runtime.js +148 -4
  58. package/dist/core/imagegen/imagegen-capability.js +46 -0
  59. package/dist/core/imagegen/require-imagegen.js +2 -2
  60. package/dist/core/init/skills.js +17 -3
  61. package/dist/core/install/installed-package-smoke.js +8 -2
  62. package/dist/core/naruto/hardware-capacity-probe.js +9 -3
  63. package/dist/core/naruto/naruto-concurrency-governor.js +68 -24
  64. package/dist/core/perf/import-graph-budget.js +0 -1
  65. package/dist/core/product-design-app-server.js +13 -1
  66. package/dist/core/release/package-size-budget.js +2 -2
  67. package/dist/core/release/release-pack-receipt.js +1 -2
  68. package/dist/core/routes/dollar-manifest-lite.js +1 -1
  69. package/dist/core/routes.js +1 -1
  70. package/dist/core/security/private-credential-file.js +209 -0
  71. package/dist/core/subagents/agent-catalog.js +17 -32
  72. package/dist/core/subagents/naruto-help-contract.js +5 -5
  73. package/dist/core/subagents/official-subagent-config.js +16 -6
  74. package/dist/core/subagents/official-subagent-preparation.js +34 -15
  75. package/dist/core/subagents/official-subagent-prompt.js +4 -4
  76. package/dist/core/subagents/official-subagent-runner.js +27 -4
  77. package/dist/core/subagents/thread-budget.js +19 -12
  78. package/dist/core/subagents/wave-lifecycle.js +18 -6
  79. package/dist/core/telegram/access.js +54 -0
  80. package/dist/core/telegram/client.js +144 -0
  81. package/dist/core/telegram/confirmation.js +37 -0
  82. package/dist/core/telegram/doctor.js +151 -0
  83. package/dist/core/telegram/index.js +9 -0
  84. package/dist/core/telegram/keychain.js +265 -0
  85. package/dist/core/telegram/liveness.js +109 -0
  86. package/dist/core/telegram/poller.js +90 -0
  87. package/dist/core/telegram/redaction.js +15 -0
  88. package/dist/core/telegram/types.js +1 -0
  89. package/dist/core/update/update-diagnostics.js +52 -0
  90. package/dist/core/update/update-migration-state.js +5 -1
  91. package/dist/core/update/update-operation.js +2 -1
  92. package/dist/core/update/update-stage-diagnostics.js +38 -0
  93. package/dist/core/update/update-status.js +2 -9
  94. package/dist/core/update-check.js +147 -31
  95. package/dist/core/version.js +1 -1
  96. package/dist/core/zellij/zellij-launcher.js +23 -4
  97. package/dist/native/sks-menubar/Sources/AppDelegate.swift +13 -0
  98. package/dist/native/sks-menubar/Sources/AppIdentity.swift +7 -0
  99. package/dist/native/sks-menubar/Sources/OperationCoordinator.swift +3 -2
  100. package/dist/native/sks-menubar/Sources/ProvidersConnectTest.swift +115 -0
  101. package/dist/native/sks-menubar/Sources/ProvidersFastMode.swift +17 -0
  102. package/dist/native/sks-menubar/Sources/ProvidersRoutingTruth.swift +190 -0
  103. package/dist/native/sks-menubar/Sources/ProvidersViewController.swift +100 -59
  104. package/dist/native/sks-menubar/Sources/SingletonInstanceGuard.swift +328 -0
  105. package/dist/native/sks-menubar/Sources/TelegramPrivateFileStore.swift +320 -0
  106. package/dist/native/sks-menubar/Sources/TelegramPrivateFileSupport.swift +303 -0
  107. package/dist/native/sks-menubar/Sources/TelegramProcessGateway.swift +238 -0
  108. package/dist/native/sks-menubar/Sources/TelegramRuntimeSupport.swift +56 -0
  109. package/dist/native/sks-menubar/Sources/TelegramSupport.swift +56 -0
  110. package/dist/native/sks-menubar/Sources/TelegramTransport.swift +474 -0
  111. package/dist/native/sks-menubar/Sources/main.swift +15 -1
  112. package/dist/native/sks-menubar/Tests/OperationCoordinatorTests.swift +4 -3
  113. package/dist/native/sks-menubar/Tests/ProvidersViewControllerTests.swift +129 -0
  114. package/dist/native/sks-menubar/Tests/SingletonInstanceGuardTests.swift +183 -0
  115. package/dist/native/sks-menubar/Tests/TelegramRuntimeSmokeTests.swift +267 -0
  116. package/dist/native/sks-menubar/Tests/TelegramRuntimeTests.swift +222 -0
  117. package/dist/scripts/codex-lb-fast-mode-truth-check.js +1 -1
  118. package/dist/scripts/codex-lb-fast-ui-preservation-check.js +1 -1
  119. package/dist/scripts/current-command-surface-check.js +2 -4
  120. package/dist/scripts/official-subagent-workflow-check.js +1 -1
  121. package/dist/scripts/packlist-performance-check.js +1 -2
  122. package/package.json +1 -1
@@ -17,6 +17,7 @@ import { writeSelftestRouteProof } from '../proof/selftest-proof-fixtures.js';
17
17
  import { createMission } from '../mission.js';
18
18
  import { formatSksUpdateStatusText, runSksUpdateNow, runSksUpdateReview, runSksUpdateRollback, runSksUpdateStatus } from '../update-check.js';
19
19
  import { persistSksUpdateNoticeFromVersions } from '../update/update-notice.js';
20
+ import { updateStageFailureDiagnostics } from '../update/update-stage-diagnostics.js';
20
21
  import { withSecretPreservationGuard } from '../config/config-migration-journal.js';
21
22
  const REMOVED_USAGE_TOPICS = new Set(['db', 'ui']);
22
23
  export async function helpCommand(args = []) {
@@ -261,7 +262,7 @@ export async function updateCommand(sub = 'now', args = []) {
261
262
  if (result.rollback?.command)
262
263
  console.log(`Rollback: ${result.rollback.command}`);
263
264
  for (const stage of result.stages || [])
264
- console.log(`Stage ${stage.id}: ${stage.ok ? 'ok' : 'failed'} ${stage.status}`);
265
+ console.log(formatSksUpdateStageText(stage, result.project_root));
265
266
  if (result.verification?.length) {
266
267
  console.log('Self verification:');
267
268
  cliUi.table([
@@ -275,6 +276,11 @@ export async function updateCommand(sub = 'now', args = []) {
275
276
  if (result.error)
276
277
  console.log(`Error: ${result.error}`);
277
278
  }
279
+ export function formatSksUpdateStageText(stage, projectRoot) {
280
+ const line = `Stage ${stage.id}: ${stage.ok ? 'ok' : 'failed'} ${stage.status}`;
281
+ const diagnostics = updateStageFailureDiagnostics(stage, projectRoot);
282
+ return diagnostics.length ? `${line} — ${diagnostics.join('; ')}` : line;
283
+ }
278
284
  export function updateCommandResultRequiresFailureExit(result) {
279
285
  return result?.source === 'error'
280
286
  || result?.ok === false
@@ -21,6 +21,7 @@ import { buildQaLoopBudgetPolicy, selectQaLoopEscalatedEffort } from '../qa-loop
21
21
  import { initializeQaRuntimeArtifacts } from '../qa-loop/qa-runtime-artifacts.js';
22
22
  import { DEFAULT_QA_MAX_CYCLES, QA_SURFACE_SELECTION_ARTIFACT } from '../qa-loop/qa-types.js';
23
23
  import { writeCodexModelEffortCapabilityArtifact } from '../codex-control/codex-model-capabilities.js';
24
+ import { prepareCodexAppServerRuntimeEnv } from '../codex-control/codex-app-server-runtime-env.js';
24
25
  import { discoverImageArtifactsInDir, writeImageArtifactPathContract } from '../image/image-artifact-path-contract.js';
25
26
  import { pluginAppTemplatePolicy } from '../codex-plugins/codex-plugin-json.js';
26
27
  import { confirmQaLoopAppHandoff } from '../qa-loop/qa-loop-app-handoff-confirmation.js';
@@ -422,6 +423,7 @@ async function qaLoopRun(args) {
422
423
  emitStreamEvent('result', { schema: 'sks.qa-loop-run.v1', ok: false, mission_id: id, status: 'blocked', blocker: 'codex_cli_missing' });
423
424
  return;
424
425
  }
426
+ const codexRuntimeEnv = await prepareCodexAppServerRuntimeEnv({ env: process.env });
425
427
  let last = '';
426
428
  for (let cycle = 1; cycle <= maxCycles; cycle += 1) {
427
429
  const cycleDir = path.join(dir, 'qa-loop', `cycle-${cycle}`);
@@ -430,7 +432,7 @@ async function qaLoopRun(args) {
430
432
  await appendJsonlBounded(path.join(dir, 'events.jsonl'), { ts: nowIso(), type: 'qaloop.cycle.start', cycle });
431
433
  if (stream)
432
434
  emitStreamEvent('progress', { mission_id: id, type: 'qaloop.cycle.start', cycle, max_cycles: maxCycles });
433
- const result = await runCodexExec({ root, prompt, outputFile, json: true, profile, logDir: cycleDir });
435
+ const result = await runCodexExec({ root, prompt, outputFile, json: true, profile, logDir: cycleDir, env: codexRuntimeEnv });
434
436
  await writeJsonAtomic(path.join(cycleDir, 'process.json'), { code: result.code, stdout_tail: result.stdout, stderr_tail: result.stderr, stdout_bytes: result.stdoutBytes, stderr_bytes: result.stderrBytes, truncated: result.truncated, timed_out: result.timedOut });
435
437
  last = await safeReadTextFile(fsp, outputFile, result.stdout || result.stderr || '');
436
438
  if (containsUserQuestion(last)) {
@@ -0,0 +1,241 @@
1
+ import { commandContract, outputCapFor, timeoutFor } from '../safety/command-contract/contracts.js';
2
+ import { validateJsonSchema } from '../safety/command-contract/json-schema.js';
3
+ import { probeTelegram, telegramSelfHealAction } from '../telegram/doctor.js';
4
+ import { readTelegramLivenessReceipt, telegramLivenessPath } from '../telegram/liveness.js';
5
+ import { TELEGRAM_TOKEN_ENV_NAMES, issueTelegramPairingCode, storeTelegramToken } from '../telegram/keychain.js';
6
+ import { spawn } from 'node:child_process';
7
+ import { TelegramClient } from '../telegram/client.js';
8
+ export const TELEGRAM_COMMAND_WHITELIST = new Set([
9
+ 'gates', 'paths', 'pipeline', 'proof', 'search', 'stats', 'status',
10
+ 'stop-gate', 'trust', 'update-check', 'validate-artifacts'
11
+ ]);
12
+ export const TELEGRAM_CONFIRMATION_REQUIRED = new Set([
13
+ 'gates', 'stop-gate', 'validate-artifacts'
14
+ ]);
15
+ export function createTelegramCommandDispatcher(adapter, lookup = commandContract) {
16
+ const resolve = (request) => {
17
+ if (!TELEGRAM_COMMAND_WHITELIST.has(request.name))
18
+ return { error: 'telegram_command_not_whitelisted' };
19
+ const contract = lookup(request.name);
20
+ if (!contract || !contract.remote_allowed || contract.risk === 'R3')
21
+ return { error: 'telegram_command_not_remote_allowed' };
22
+ const validation = validateJsonSchema(request.input, contract.input_schema);
23
+ if (!validation.ok)
24
+ return { error: `telegram_command_input_invalid:${validation.issues[0]?.code ?? 'schema'}` };
25
+ return { contract, argv: contract.argv_builder(validation.value) };
26
+ };
27
+ return {
28
+ prepare(request) {
29
+ const resolved = resolve(request);
30
+ if ('error' in resolved)
31
+ return { ok: false, error: resolved.error };
32
+ if (requiresConfirmation(resolved.contract))
33
+ return { ok: true, confirmation_required: true };
34
+ return {
35
+ ok: true,
36
+ confirmation_required: false,
37
+ execute: () => adapter.executeArgv(resolved.argv, resolved.contract)
38
+ };
39
+ },
40
+ async executeConfirmed(request) {
41
+ const resolved = resolve(request);
42
+ if ('error' in resolved)
43
+ throw new Error(resolved.error);
44
+ if (!requiresConfirmation(resolved.contract))
45
+ throw new Error('telegram_confirmation_not_required');
46
+ return adapter.executeArgv(resolved.argv, resolved.contract);
47
+ }
48
+ };
49
+ }
50
+ function requiresConfirmation(contract) {
51
+ return TELEGRAM_CONFIRMATION_REQUIRED.has(contract.name) || !contract.read_only || contract.risk !== 'R0';
52
+ }
53
+ export function usage() {
54
+ return [
55
+ 'Usage: sks telegram status|doctor|pair|setup [--json]',
56
+ '',
57
+ ' status Read the secret-free resident poller liveness receipt.',
58
+ ' doctor Evaluate getMe, pairing, poller, and liveness evidence.',
59
+ ' pair Issue a short-lived code in the private Telegram state file.',
60
+ ' setup --token-stdin Read a bot token only from stdin and store it in the user secret file.',
61
+ ' prepare --stdin-json Validate an authorized native request through the typed contract.',
62
+ ' execute --stdin-json Execute a prepared request; destructive requests also need --confirmed.',
63
+ '',
64
+ 'The bot token is never accepted in argv, printed, or written to a config file.'
65
+ ].join('\n');
66
+ }
67
+ export async function telegramCommand(args = [], dependencies = {}) {
68
+ if (args.some((value) => ['help', '--help', '-h'].includes(value.toLowerCase()))) {
69
+ console.log(usage());
70
+ return { schema: 'sks.telegram-command.v1', ok: true, action: 'help' };
71
+ }
72
+ const action = args[0] && !args[0].startsWith('-') ? args[0].toLowerCase() : 'status';
73
+ const json = args.includes('--json');
74
+ const receiptPath = dependencies.receiptPath ?? telegramLivenessPath();
75
+ try {
76
+ if (action === 'status') {
77
+ const state = await readTelegramLivenessReceipt(receiptPath);
78
+ const result = state.ok
79
+ ? { schema: 'sks.telegram-status.v1', ok: !state.stale && state.receipt.running, stale: state.stale, age_ms: state.age_ms, receipt: state.receipt }
80
+ : { schema: 'sks.telegram-status.v1', ok: false, blocker: state.blocker };
81
+ if (!result.ok)
82
+ process.exitCode = 1;
83
+ return emit(result, json);
84
+ }
85
+ if (action === 'doctor') {
86
+ const probe = await probeTelegram({ receiptPath });
87
+ const result = { ...probe, self_heal_action: telegramSelfHealAction(probe) };
88
+ if (!result.ok)
89
+ process.exitCode = 1;
90
+ return emit(result, json);
91
+ }
92
+ if (action === 'pair') {
93
+ const issued = await (dependencies.issuePairingCode ?? issueTelegramPairingCode)();
94
+ return emit({
95
+ schema: 'sks.telegram-pair-command.v1', ok: true,
96
+ code: issued.code, expires_at: issued.expires_at,
97
+ instruction: `Send /start ${issued.code} to the configured bot from the intended private chat.`
98
+ }, json);
99
+ }
100
+ if (action === 'setup') {
101
+ if (!args.includes('--token-stdin'))
102
+ return fail('telegram_token_stdin_required', json);
103
+ const token = await (dependencies.readTokenStdin ?? readBoundedTokenStdin)();
104
+ await (dependencies.verifyToken ?? verifyTelegramToken)(token);
105
+ await (dependencies.storeToken ?? storeTelegramToken)(token);
106
+ return emit({
107
+ schema: 'sks.telegram-setup-command.v1', ok: true,
108
+ getme_verified: true, token_stored: true, storage: 'user_secret_file', restart_required: true
109
+ }, json);
110
+ }
111
+ if (action === 'prepare' || action === 'execute') {
112
+ if (!args.includes('--stdin-json'))
113
+ return fail('telegram_command_stdin_json_required', json);
114
+ const request = await (dependencies.readCommandStdin ?? readBoundedCommandStdin)();
115
+ const dispatcher = createTelegramCommandDispatcher(dependencies.executionAdapter ?? { executeArgv: executeTypedArgv });
116
+ const prepared = dispatcher.prepare(request);
117
+ if (action === 'prepare') {
118
+ return emit(prepared.ok
119
+ ? { schema: 'sks.telegram-command-preparation.v1', ok: true, allowed: true, confirmation_required: prepared.confirmation_required, public_error: null }
120
+ : { schema: 'sks.telegram-command-preparation.v1', ok: false, allowed: false, confirmation_required: false, public_error: prepared.error }, json);
121
+ }
122
+ if (!prepared.ok)
123
+ return fail(prepared.error, json);
124
+ if (prepared.confirmation_required && !args.includes('--confirmed'))
125
+ return fail('telegram_confirmation_required', json);
126
+ const output = prepared.confirmation_required
127
+ ? await dispatcher.executeConfirmed(request)
128
+ : await prepared.execute();
129
+ return emit({ schema: 'sks.telegram-command-execution.v1', ok: true, output }, json);
130
+ }
131
+ return fail('telegram_unknown_action', json, ['status', 'doctor', 'pair', 'setup', 'prepare', 'execute']);
132
+ }
133
+ catch (error) {
134
+ return fail(error instanceof Error ? error.message : String(error), json);
135
+ }
136
+ }
137
+ async function verifyTelegramToken(token) {
138
+ const client = new TelegramClient({ tokenProvider: { loadToken: async () => token } });
139
+ const identity = await client.getMe();
140
+ if (!identity.is_bot)
141
+ throw new Error('telegram_getme_not_bot');
142
+ }
143
+ async function readBoundedCommandStdin() {
144
+ if (process.stdin.isTTY)
145
+ throw new Error('telegram_command_stdin_json_required');
146
+ process.stdin.setEncoding('utf8');
147
+ let value = '';
148
+ for await (const chunk of process.stdin) {
149
+ value += String(chunk);
150
+ if (Buffer.byteLength(value, 'utf8') > 32 * 1024)
151
+ throw new Error('telegram_command_stdin_json_too_large');
152
+ }
153
+ let parsed;
154
+ try {
155
+ parsed = JSON.parse(value);
156
+ }
157
+ catch {
158
+ throw new Error('telegram_command_stdin_json_invalid');
159
+ }
160
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
161
+ throw new Error('telegram_command_stdin_json_invalid');
162
+ const row = parsed;
163
+ if (typeof row.name !== 'string' || !row.input || typeof row.input !== 'object' || Array.isArray(row.input)) {
164
+ throw new Error('telegram_command_stdin_json_invalid');
165
+ }
166
+ return { name: row.name, input: row.input };
167
+ }
168
+ async function executeTypedArgv(argv, contract) {
169
+ const entrypoint = process.argv[1];
170
+ if (!entrypoint)
171
+ throw new Error('telegram_cli_entrypoint_unavailable');
172
+ const timeoutMs = timeoutFor(contract.latency);
173
+ const outputLimit = outputCapFor(contract.latency);
174
+ const childEnv = { ...process.env };
175
+ for (const name of TELEGRAM_TOKEN_ENV_NAMES)
176
+ delete childEnv[name];
177
+ return new Promise((resolve, reject) => {
178
+ const child = spawn(process.execPath, [entrypoint, ...argv], {
179
+ cwd: process.cwd(), env: childEnv, stdio: ['ignore', 'pipe', 'pipe'], shell: false
180
+ });
181
+ let output = Buffer.alloc(0);
182
+ let settled = false;
183
+ const timer = setTimeout(() => finish(new Error('telegram_command_timeout')), timeoutMs);
184
+ const append = (chunk) => {
185
+ if (settled)
186
+ return;
187
+ output = Buffer.concat([output, chunk]);
188
+ if (output.length > outputLimit)
189
+ finish(new Error('telegram_command_output_limit'));
190
+ };
191
+ const finish = (error, code) => {
192
+ if (settled)
193
+ return;
194
+ settled = true;
195
+ clearTimeout(timer);
196
+ if (child.exitCode === null)
197
+ child.kill('SIGKILL');
198
+ if (error)
199
+ return reject(error);
200
+ const text = output.toString('utf8').trim();
201
+ if (code !== 0)
202
+ return reject(new Error(`telegram_command_failed:exit_${code ?? 'signal'}`));
203
+ try {
204
+ resolve(JSON.parse(text));
205
+ }
206
+ catch {
207
+ resolve(text);
208
+ }
209
+ };
210
+ child.stdout.on('data', append);
211
+ child.stderr.on('data', append);
212
+ child.once('error', (error) => finish(new Error(`telegram_command_spawn_failed:${error.message}`)));
213
+ child.once('close', (code) => finish(undefined, code));
214
+ });
215
+ }
216
+ async function readBoundedTokenStdin() {
217
+ if (process.stdin.isTTY)
218
+ throw new Error('telegram_token_stdin_required');
219
+ process.stdin.setEncoding('utf8');
220
+ let value = '';
221
+ for await (const chunk of process.stdin) {
222
+ value += String(chunk);
223
+ if (Buffer.byteLength(value, 'utf8') > 1024)
224
+ throw new Error('telegram_token_stdin_too_large');
225
+ }
226
+ const token = value.trim();
227
+ if (!token)
228
+ throw new Error('telegram_token_stdin_empty');
229
+ return token;
230
+ }
231
+ function fail(error, json, supported) {
232
+ process.exitCode = 1;
233
+ return emit({
234
+ schema: 'sks.telegram-command.v1', ok: false, error,
235
+ ...(supported ? { supported } : {})
236
+ }, json);
237
+ }
238
+ function emit(value, _json) {
239
+ console.log(JSON.stringify(value, null, 2));
240
+ return value;
241
+ }
@@ -0,0 +1,35 @@
1
+ import path from 'node:path';
2
+ import { formatSksConfigAdoptText, runSksConfigAdopt } from './config-adopt.js';
3
+ export function usage(command = 'config') {
4
+ return `Usage: sks ${command === 'config' ? 'config' : command} adopt [--project-root <path>] [--dry-run] [--json]`;
5
+ }
6
+ export async function configCommand(subcommand = 'adopt', args = []) {
7
+ if (subcommand !== 'adopt') {
8
+ process.exitCode = 1;
9
+ console.error(usage('config'));
10
+ return null;
11
+ }
12
+ const root = valueAfter(args, '--project-root') || valueAfter(args, '--root') || process.cwd();
13
+ const result = await runSksConfigAdopt({
14
+ root: path.resolve(root),
15
+ dryRun: args.includes('--dry-run')
16
+ });
17
+ if (!result.ok)
18
+ process.exitCode = 1;
19
+ if (args.includes('--json'))
20
+ console.log(JSON.stringify(result, null, 2));
21
+ else
22
+ console.log(formatSksConfigAdoptText(result));
23
+ return result;
24
+ }
25
+ export async function run(_command, args) {
26
+ const [subcommand = 'adopt', ...rest] = args;
27
+ return configCommand(subcommand, rest);
28
+ }
29
+ function valueAfter(args, flag) {
30
+ const index = args.indexOf(flag);
31
+ if (index < 0)
32
+ return null;
33
+ const value = args[index + 1];
34
+ return value && !value.startsWith('-') ? value : null;
35
+ }
@@ -0,0 +1,346 @@
1
+ import fsp from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { canonicalFilesystemPath, randomId, sha256, writeJsonAtomic } from '../fsx.js';
4
+ import { hasExplicitSksManagedCodexConfigMarker, isProjectCodexConfig, SKS_MANAGED_CODEX_CONFIG_MARKER, writeCodexConfigGuarded } from '../codex/codex-config-guard.js';
5
+ import { validateCodexConfigRoundTrip } from '../codex/codex-config-toml.js';
6
+ import { ensureConfinedDirectory, inspectConfinedPath } from '../managed-path-safety.js';
7
+ export const SKS_CONFIG_ADOPT_SCHEMA = 'sks.config-adopt.v1';
8
+ export const SKS_CONFIG_ADOPT_RECEIPT_SCHEMA = 'sks.config-adopt-receipt.v1';
9
+ export async function runSksConfigAdopt(options = {}) {
10
+ const requestedRoot = path.resolve(options.root || process.cwd());
11
+ const projectRoot = await canonicalFilesystemPath(requestedRoot);
12
+ const configPath = path.resolve(options.configPath || path.join(projectRoot, '.codex', 'config.toml'));
13
+ const base = {
14
+ schema: SKS_CONFIG_ADOPT_SCHEMA,
15
+ project_root: projectRoot,
16
+ config_path: configPath,
17
+ marker: SKS_MANAGED_CODEX_CONFIG_MARKER
18
+ };
19
+ if (projectRoot === path.parse(projectRoot).root) {
20
+ return blocked(base, 'config_adopt_filesystem_root_refused');
21
+ }
22
+ if (!isProjectCodexConfig(projectRoot, configPath)) {
23
+ return blocked(base, 'config_adopt_project_config_path_required');
24
+ }
25
+ const snapshot = await readAdoptableConfig(projectRoot, configPath);
26
+ if (!snapshot.ok)
27
+ return blocked(base, snapshot.blocker);
28
+ const before = snapshot.text;
29
+ const beforeSha256 = sha256(before);
30
+ const validation = validateCodexConfigRoundTrip(before);
31
+ if (!validation.ok)
32
+ return blocked(base, 'config_adopt_toml_invalid', beforeSha256);
33
+ if (hasExplicitSksManagedCodexConfigMarker(before)) {
34
+ return {
35
+ ...base,
36
+ ok: true,
37
+ status: 'already_adopted',
38
+ changed: false,
39
+ backup_path: null,
40
+ receipt_path: null,
41
+ before_sha256: beforeSha256,
42
+ after_sha256: beforeSha256,
43
+ blocker: null,
44
+ remedy: null
45
+ };
46
+ }
47
+ const after = insertSksManagedCodexConfigMarker(before);
48
+ const afterSha256 = sha256(after);
49
+ if (options.dryRun === true) {
50
+ return {
51
+ ...base,
52
+ ok: true,
53
+ status: 'would_adopt',
54
+ changed: false,
55
+ backup_path: null,
56
+ receipt_path: null,
57
+ before_sha256: beforeSha256,
58
+ after_sha256: afterSha256,
59
+ blocker: null,
60
+ remedy: null
61
+ };
62
+ }
63
+ const now = options.now || (() => new Date());
64
+ const receiptId = `config-adopt-${now().toISOString().replace(/[:.]/g, '-')}-${randomId(10)}`;
65
+ const receiptDirectory = path.join(projectRoot, '.sneakoscope', 'receipts', 'config-adopt');
66
+ const receiptPath = path.join(receiptDirectory, `${receiptId}.json`);
67
+ try {
68
+ await ensureConfinedDirectory(projectRoot, receiptDirectory);
69
+ }
70
+ catch {
71
+ return blocked(base, 'config_adopt_receipt_directory_unavailable', beforeSha256);
72
+ }
73
+ const receiptBase = {
74
+ schema: SKS_CONFIG_ADOPT_RECEIPT_SCHEMA,
75
+ id: receiptId,
76
+ generated_at: now().toISOString(),
77
+ project_root: projectRoot,
78
+ config_path: configPath,
79
+ marker: SKS_MANAGED_CODEX_CONFIG_MARKER,
80
+ before_sha256: beforeSha256,
81
+ after_sha256: afterSha256
82
+ };
83
+ try {
84
+ await writeAdoptReceipt(projectRoot, receiptPath, {
85
+ ...receiptBase,
86
+ status: 'prepared',
87
+ changed: false,
88
+ backup_path: null,
89
+ blocker: null
90
+ });
91
+ }
92
+ catch {
93
+ return blocked(base, 'config_adopt_receipt_prepare_failed', beforeSha256);
94
+ }
95
+ let guard;
96
+ try {
97
+ guard = await writeCodexConfigGuarded({
98
+ root: projectRoot,
99
+ configPath,
100
+ before,
101
+ mutate: async () => {
102
+ await options.beforeCommit?.();
103
+ return after;
104
+ },
105
+ cause: 'config-adopt',
106
+ backupTag: 'config-adopt',
107
+ ownershipVerified: true,
108
+ verifyUnchangedBeforeWrite: true,
109
+ expectedBeforeExists: true,
110
+ expectedBeforeMode: snapshot.mode,
111
+ preserveFastUiKeys: false,
112
+ preserveTextFormatting: true
113
+ });
114
+ }
115
+ catch (error) {
116
+ const blocker = `config_adopt_guard_failed:${errorCode(error)}`;
117
+ await writeAdoptReceipt(projectRoot, receiptPath, {
118
+ ...receiptBase,
119
+ status: 'blocked',
120
+ changed: false,
121
+ backup_path: null,
122
+ blocker
123
+ }).catch(() => undefined);
124
+ return blocked(base, blocker, beforeSha256, receiptPath);
125
+ }
126
+ if (!guard.ok) {
127
+ const blocker = guard.status === 'concurrent_change_detected'
128
+ ? 'config_adopt_concurrent_change_detected'
129
+ : `config_adopt_guard:${guard.status}`;
130
+ const receiptStatus = guard.changed ? 'adopted_receipt_unconfirmed' : 'blocked';
131
+ await writeAdoptReceipt(projectRoot, receiptPath, {
132
+ ...receiptBase,
133
+ status: receiptStatus,
134
+ changed: guard.changed,
135
+ backup_path: guard.backup_path,
136
+ blocker
137
+ }).catch(() => undefined);
138
+ if (guard.changed) {
139
+ const observed = await readAdoptableConfig(projectRoot, configPath);
140
+ return {
141
+ ...base,
142
+ ok: false,
143
+ status: 'adopted_receipt_unconfirmed',
144
+ changed: true,
145
+ backup_path: guard.backup_path,
146
+ receipt_path: receiptPath,
147
+ before_sha256: beforeSha256,
148
+ after_sha256: observed.ok ? sha256(observed.text) : null,
149
+ blocker,
150
+ remedy: remedyForConfigAdoptBlocker(blocker, configPath)
151
+ };
152
+ }
153
+ return blocked(base, blocker, beforeSha256, receiptPath, guard.backup_path);
154
+ }
155
+ const committed = await readAdoptableConfig(projectRoot, configPath);
156
+ const backup = guard.backup_path
157
+ ? await readAdoptableConfig(projectRoot, guard.backup_path)
158
+ : null;
159
+ const commitVerified = committed.ok
160
+ && committed.text === after
161
+ && committed.mode === 0o600
162
+ && backup?.ok === true
163
+ && backup.text === before
164
+ && backup.mode === 0o600;
165
+ if (!commitVerified) {
166
+ const blocker = 'config_adopt_postwrite_verification_failed';
167
+ await writeAdoptReceipt(projectRoot, receiptPath, {
168
+ ...receiptBase,
169
+ status: 'adopted_receipt_unconfirmed',
170
+ changed: guard.changed,
171
+ backup_path: guard.backup_path,
172
+ blocker
173
+ }).catch(() => undefined);
174
+ return {
175
+ ...base,
176
+ ok: false,
177
+ status: 'adopted_receipt_unconfirmed',
178
+ changed: guard.changed,
179
+ backup_path: guard.backup_path,
180
+ receipt_path: receiptPath,
181
+ before_sha256: beforeSha256,
182
+ after_sha256: committed.ok ? sha256(committed.text) : null,
183
+ blocker,
184
+ remedy: remedyForConfigAdoptBlocker(blocker, configPath)
185
+ };
186
+ }
187
+ const finalReceipt = {
188
+ ...receiptBase,
189
+ status: 'adopted',
190
+ changed: true,
191
+ backup_path: guard.backup_path,
192
+ blocker: null
193
+ };
194
+ try {
195
+ await writeAdoptReceipt(projectRoot, receiptPath, finalReceipt);
196
+ }
197
+ catch {
198
+ const blocker = 'config_adopt_receipt_finalize_failed';
199
+ return {
200
+ ...base,
201
+ ok: false,
202
+ status: 'adopted_receipt_unconfirmed',
203
+ changed: true,
204
+ backup_path: guard.backup_path,
205
+ receipt_path: receiptPath,
206
+ before_sha256: beforeSha256,
207
+ after_sha256: afterSha256,
208
+ blocker,
209
+ remedy: remedyForConfigAdoptBlocker(blocker, configPath)
210
+ };
211
+ }
212
+ return {
213
+ ...base,
214
+ ok: true,
215
+ status: 'adopted',
216
+ changed: true,
217
+ backup_path: guard.backup_path,
218
+ receipt_path: receiptPath,
219
+ before_sha256: beforeSha256,
220
+ after_sha256: afterSha256,
221
+ blocker: null,
222
+ remedy: null
223
+ };
224
+ }
225
+ export const adoptSksCodexConfig = runSksConfigAdopt;
226
+ export async function adoptProjectCodexConfig(input) {
227
+ return runSksConfigAdopt({
228
+ root: input.projectRoot,
229
+ ...(input.dryRun === undefined ? {} : { dryRun: input.dryRun })
230
+ });
231
+ }
232
+ export function insertSksManagedCodexConfigMarker(text) {
233
+ const source = String(text || '');
234
+ if (hasExplicitSksManagedCodexConfigMarker(source))
235
+ return source;
236
+ const bom = source.startsWith('\uFEFF') ? '\uFEFF' : '';
237
+ const body = bom ? source.slice(1) : source;
238
+ return `${bom}${SKS_MANAGED_CODEX_CONFIG_MARKER}\n${body}`;
239
+ }
240
+ export function formatSksConfigAdoptText(result) {
241
+ const lines = [
242
+ result.ok
243
+ ? result.status === 'would_adopt'
244
+ ? 'SKS Codex config would be adopted; no files were changed.'
245
+ : result.changed ? 'SKS Codex config adopted.' : 'SKS Codex config was already adopted.'
246
+ : 'SKS Codex config adoption failed.',
247
+ `File: ${result.config_path}`
248
+ ];
249
+ if (result.backup_path)
250
+ lines.push(`Backup: ${result.backup_path}`);
251
+ if (result.receipt_path)
252
+ lines.push(`Receipt: ${result.receipt_path}`);
253
+ if (!result.ok) {
254
+ lines.push(`Blocker: ${result.blocker || 'config_adopt_failed'}`);
255
+ lines.push(`Remedy: ${result.remedy || remedyForConfigAdoptBlocker(result.blocker || '', result.config_path)}`);
256
+ }
257
+ return lines.join('\n');
258
+ }
259
+ export function remedyForConfigAdoptBlocker(blocker, configPath) {
260
+ if (blocker === 'user_owned_file_without_sks_marker') {
261
+ return `\`${configPath}\` has no \`${SKS_MANAGED_CODEX_CONFIG_MARKER}\` marker → add it as line 1 or run \`sks config adopt\`.`;
262
+ }
263
+ if (blocker === 'config_adopt_toml_invalid') {
264
+ return `Fix the TOML syntax in ${configPath}, then rerun sks config adopt.`;
265
+ }
266
+ if (blocker === 'config_adopt_concurrent_change_detected') {
267
+ return `Review the latest ${configPath} and rerun sks config adopt; no adoption write was committed.`;
268
+ }
269
+ if (blocker.includes('symlink') || blocker.includes('non_regular') || blocker.includes('ancestor')) {
270
+ return `Replace ${configPath} with a regular project-owned file, then rerun sks config adopt.`;
271
+ }
272
+ if (blocker.includes('missing')) {
273
+ return `Create ${configPath} as a valid TOML file, then rerun sks config adopt.`;
274
+ }
275
+ if (blocker.includes('receipt') || blocker.includes('postwrite')) {
276
+ return `Inspect ${configPath} and its reported backup before retrying; adoption completion could not be proven.`;
277
+ }
278
+ return `Resolve ${blocker || 'the reported blocker'} for ${configPath}, then rerun sks config adopt.`;
279
+ }
280
+ export function formatUpdateBlockerWithRemedy(blocker, configPath) {
281
+ const value = String(blocker || '').trim();
282
+ if (!value)
283
+ return '';
284
+ const adoptBlocker = 'user_owned_file_without_sks_marker';
285
+ if (value !== adoptBlocker && !value.endsWith(`:${adoptBlocker}`))
286
+ return value;
287
+ return `${value}: ${remedyForConfigAdoptBlocker(adoptBlocker, configPath)}`;
288
+ }
289
+ async function readAdoptableConfig(root, configPath) {
290
+ let inspected;
291
+ try {
292
+ inspected = await inspectConfinedPath(root, configPath);
293
+ }
294
+ catch (error) {
295
+ const code = typeof error === 'object' && error && 'code' in error
296
+ ? String(error.code || 'config_adopt_path_unsafe')
297
+ : 'config_adopt_path_unsafe';
298
+ return { ok: false, blocker: `config_adopt_path:${code}` };
299
+ }
300
+ if (!inspected.exists)
301
+ return { ok: false, blocker: 'config_adopt_config_missing' };
302
+ if (inspected.leafSymlink)
303
+ return { ok: false, blocker: 'config_adopt_config_symlink_refused' };
304
+ if (!inspected.stat?.isFile())
305
+ return { ok: false, blocker: 'config_adopt_config_non_regular_refused' };
306
+ try {
307
+ return {
308
+ ok: true,
309
+ text: await fsp.readFile(configPath, 'utf8'),
310
+ mode: inspected.stat.mode & 0o777
311
+ };
312
+ }
313
+ catch {
314
+ return { ok: false, blocker: 'config_adopt_config_read_failed' };
315
+ }
316
+ }
317
+ async function writeAdoptReceipt(root, file, receipt) {
318
+ const expected = `${JSON.stringify(receipt, null, 2)}\n`;
319
+ await writeJsonAtomic(file, receipt, { mode: 0o600 });
320
+ const observed = await readAdoptableConfig(root, file);
321
+ if (!observed.ok || observed.text !== expected || observed.mode !== 0o600) {
322
+ throw new Error('config_adopt_receipt_verification_failed');
323
+ }
324
+ }
325
+ function blocked(base, blocker, beforeSha256 = null, receiptPath = null, backupPath = null) {
326
+ return {
327
+ ...base,
328
+ ok: false,
329
+ status: 'blocked',
330
+ changed: false,
331
+ backup_path: backupPath,
332
+ receipt_path: receiptPath,
333
+ before_sha256: beforeSha256,
334
+ after_sha256: null,
335
+ blocker,
336
+ remedy: remedyForConfigAdoptBlocker(blocker, base.config_path)
337
+ };
338
+ }
339
+ function errorCode(error) {
340
+ if (error && typeof error === 'object' && 'code' in error) {
341
+ const code = String(error.code || '').trim();
342
+ if (/^[A-Za-z0-9_.-]{1,80}$/.test(code))
343
+ return code;
344
+ }
345
+ return 'unexpected_error';
346
+ }
@@ -0,0 +1,3 @@
1
+ export * from './config-adopt.js';
2
+ export { configCommand } from './config-adopt-command.js';
3
+ export { usage } from './config-adopt-command.js';