@joripspace/cli 0.4.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.
@@ -0,0 +1,2423 @@
1
+ const { projectGithubActionsTemplateFile } = require('./github-workflow.cjs');
2
+ const { templateGithubActionsPublishFile } = require('./template-publish-workflow.cjs');
3
+
4
+ const JORIPSPACE_ONBOARDING_GITIGNORE_ENTRIES = [
5
+ 'node_modules/',
6
+ '.wrangler/',
7
+ '.cache/',
8
+ 'coverage/',
9
+ 'dist/',
10
+ '.env',
11
+ '.env.*',
12
+ '!.env.example',
13
+ '.env.joripspace',
14
+ '.joripspace/local-backups/',
15
+ ];
16
+ const JORIPSPACE_ONBOARDING_GITIGNORE_REMOVALS = ['.joripspace/agent-session.json'];
17
+ const JORIPSPACE_AGENT_GUIDE_UPDATED_AT = '2026-09-05T18:00:00+09:00';
18
+ const JORIPSPACE_WORKFLOW_POLICY = Object.freeze({
19
+ target: 'joripspace',
20
+ guide_required: true,
21
+ external_hosting_deployment: 'blocked',
22
+ generic_scaffold_recovery: 'convert_to_joripspace',
23
+ framework_selection: 'agent_managed_dynamic_worker_or_hono',
24
+ framework_reassessment: 'migrate_pure_worker_to_hono_as_scope_grows',
25
+ rendering_default: 'server_side_all_user_facing_routes',
26
+ user_interaction: 'automatic_unless_business_or_destructive_decision_is_required',
27
+ });
28
+ const JORIPSPACE_PACKAGE_HELPER_SCRIPTS = {
29
+ 'joripspace:doctor': 'node .joripspace/doctor.mjs',
30
+ 'joripspace:save': 'node .joripspace/save.mjs',
31
+ 'joripspace:checkpoints': 'node .joripspace/checkpoints.mjs',
32
+ 'joripspace:restore': 'node .joripspace/restore.mjs',
33
+ 'joripspace:deploy-checkpoint': 'node .joripspace/deploy-checkpoint.mjs',
34
+ 'joripspace:deploy': 'node .joripspace/save.mjs --deploy',
35
+ 'joripspace:pull': 'node .joripspace/pull.mjs',
36
+ 'joripspace:pull:force': 'node .joripspace/pull.mjs --force',
37
+ 'joripspace:install-template': 'node .joripspace/install-template.mjs',
38
+ 'joripspace:template-pull': 'node .joripspace/install-template.mjs --update',
39
+ deploy: 'node .joripspace/save.mjs --deploy',
40
+ };
41
+
42
+ function projectEnvReaderSource() {
43
+ return String.raw`function parseEnvValue(input) {
44
+ const trimmed = String(input || '').trim();
45
+ if (trimmed.length < 2) return trimmed;
46
+ const quote = trimmed[0];
47
+ if ((quote !== '"' && quote !== "'") || trimmed.at(-1) !== quote) return trimmed;
48
+ const inner = trimmed.slice(1, -1);
49
+ if (quote === "'") return inner;
50
+ return inner.replace(/\\n/g, '\n').replace(/\\r/g, '\r').replace(/\\"/g, '"').replace(/\\\\/g, '\\');
51
+ }
52
+
53
+ function readEnv(filePath) {
54
+ const values = {};
55
+ try {
56
+ for (const line of fs.readFileSync(filePath, 'utf8').split(/\r?\n/)) {
57
+ const trimmed = line.trim();
58
+ if (!trimmed || trimmed.startsWith('#')) continue;
59
+ const index = trimmed.indexOf('=');
60
+ if (index <= 0) continue;
61
+ const key = trimmed.slice(0, index).trim();
62
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue;
63
+ values[key] = parseEnvValue(trimmed.slice(index + 1));
64
+ }
65
+ } catch {}
66
+ return values;
67
+ }
68
+
69
+ function readProjectMarker(root) {
70
+ const filePath = path.join(root, '.joripspace', 'project');
71
+ try {
72
+ const stat = fs.lstatSync(filePath);
73
+ if (!stat.isFile() || stat.isSymbolicLink()) return '';
74
+ const source = fs.readFileSync(filePath, 'utf8');
75
+ if (!/^[a-z0-9](?:[a-z0-9-]{1,48}[a-z0-9])?\n?$/.test(source)) return '';
76
+ const slug = source.trim();
77
+ return slug.length >= 3 && slug.length <= 50 ? slug : '';
78
+ } catch {
79
+ return '';
80
+ }
81
+ }
82
+
83
+ function resolveSourceBoundConnection(root) {
84
+ const projectEnv = readEnv(path.join(root, '.env.joripspace'));
85
+ const processToken = String(process.env.JORIPSPACE_API_TOKEN || '').trim();
86
+ if (processToken) {
87
+ return {
88
+ apiBaseUrl: String(process.env.JORIPSPACE_API_URL || process.env.JORIPSPACE_API_BASE_URL || 'https://api.joripspace.com').replace(/\/+$/, ''),
89
+ apiToken: processToken,
90
+ projectEnv
91
+ };
92
+ }
93
+ const projectToken = String(projectEnv.JORIPSPACE_API_TOKEN || '').trim();
94
+ return {
95
+ apiBaseUrl: String(projectToken ? projectEnv.JORIPSPACE_API_BASE_URL || 'https://api.joripspace.com' : 'https://api.joripspace.com').replace(/\/+$/, ''),
96
+ apiToken: projectToken,
97
+ projectEnv
98
+ };
99
+ }`;
100
+ }
101
+
102
+ const JORIPSPACE_PACKAGE_HELPER_DEPENDENCIES = { fflate: '^0.8.2' };
103
+
104
+ const SERVICE_EXAMPLE_LINES = [
105
+ '- Landing or introduction site for a club, class, shop, person, product, event, or portfolio.',
106
+ '- Reservation, booking, application, inquiry, waitlist, survey, or contact intake service.',
107
+ '- Course, lecture, student assignment, club activity, membership, attendance, or small LMS-style service.',
108
+ '- Simple order, payment-preparation, product request, file upload, gallery, download, or admin review service.',
109
+ '- Owner/admin dashboard for records, statuses, files, messages, customers, students, or bookings.',
110
+ '- Realtime inquiry, support room, small group chat, or live status page when the project needs live interaction.',
111
+ ];
112
+
113
+ const BEGINNER_ONBOARDING_LINES = [
114
+ 'Beginner onboarding rules:',
115
+ '- Match the language the user is using. If the user writes Korean, continue in Korean. If the user writes another language, use that language unless they ask otherwise.',
116
+ '- Treat the user as a complete beginner. Students and older users should be able to build by conversation alone.',
117
+ '- Ask short, practical questions before building when the site name, topic, audience, or core workflow is empty or unclear.',
118
+ '- Do not ask platform questions. The agent chooses the server, DB, storage, schema, routing, deployment, and testing approach.',
119
+ '- If the user says they do not know, give 2-3 simple examples, recommend one default, and continue.',
120
+ '- Explain only the next useful action. Avoid long technical explanations unless the user asks.',
121
+ '- If something fails, inspect logs, deployments, and runtime events directly; do not make the user debug technical details.',
122
+ ];
123
+
124
+ const USER_CHOICE_PRESENTATION_RULE_LINES = [
125
+ 'User choice presentation rules:',
126
+ '- Whenever a user-facing reply shows two or more concrete alternatives that the user could select, present them as a readable Markdown table. Apply this even when the user only asks what is available, requests an inventory or comparison, or has not yet been asked to choose. This applies to restore points, rollback versions, templates, projects, and any other user-selectable candidates.',
127
+ '- Use a short numbered first column and only decision-relevant columns. For restore or rollback choices include number, version or identifier, timestamp, label or status, and effect. For template choices include number, template name, suitable use, and included features.',
128
+ '- Mark the recommended choice in the table and explain the recommendation briefly. End with one direct sentence stating exactly what the user should answer, such as "번호로 선택해 주세요."',
129
+ '- Do not use a table for a single available action or a simple yes/no confirmation. Do not turn technical or platform decisions that the agent must make into user choices.',
130
+ '- If the reply states only whether candidates exist or gives only a total count without listing individual candidates, prose is sufficient. As soon as two or more individual candidates are shown, the table is mandatory.',
131
+ '- Never include Secret values, tokens, personal data, or other sensitive values in a choice table.',
132
+ '- If there are many choices, show a manageable page and state that more choices are available instead of dumping an unbounded list.',
133
+ ];
134
+
135
+ const LOCAL_TOOL_READINESS_RULE_LINES = [
136
+ 'Local Git and Node.js readiness during onboarding:',
137
+ '- After the project connection succeeds and the project path is known, check `git --version`, `node --version`, and `npm --version` directly before the first source-sync or local build step that could require them. Do not ask the user to run these commands.',
138
+ '- Show the result in one readable Markdown table with columns for tool, status, version, and whether it is needed for the current project path.',
139
+ '- Decide need from the actual path: Git is required for a connected GitHub repository, clone/fetch, commit, push, or a template installation mode that preserves Git history. Git is not required when the user chooses a files-only template installation. Node.js LTS and npm are required only for project dependency installation, local JavaScript builds, or an explicitly selected verified legacy package helper. The installed JoripSpace CLI handles checkpoint, restore, pull, generated bundles, and large archive deployment without project-local Node.js. Ordinary MCP and CLI onboarding require neither tool.',
140
+ '- If every missing tool is optional for the current path, say it is optional and continue onboarding without asking to install it.',
141
+ '- If a required tool is missing, explain its immediate purpose in one sentence and ask for one explicit approval to install only the missing required tools. Do not install software before approval and do not combine this approval with unrelated choices.',
142
+ "- After approval, install stable Git and/or the current Node.js LTS with npm using the operating system's standard trusted package manager. Perform the installation yourself, request elevation only through the normal operating-system prompt, and never disable security controls or use an untrusted download source.",
143
+ '- After installation, verify Git, Node.js, and npm again, show the final status and versions in a Markdown table, and continue the interrupted onboarding automatically.',
144
+ '- If installation fails or the environment does not permit it, report the concrete permission or platform limitation. Continue by MCP when possible; block only the workflow that actually requires the missing tool.',
145
+ ];
146
+
147
+ const GUIDE_REFRESH_ONLY_RULE_LINES = [
148
+ 'Guide refresh is maintenance-only unless deployment is separately explicit:',
149
+ '- Treat requests whose only intent is "지침 업데이트해", "지침 갱신해", "최신 지침 적용해", "refresh the guide", or equivalent wording as local guide maintenance only. They are not authorization to build, test the application, create a checkpoint, stage files, commit, push, run GitHub Actions, or deploy.',
150
+ '- For a guide-refresh-only request, call prepare_project_workspace and update only the JoripSpace managed block in AGENTS.md, the first-line `@AGENTS.md` import in CLAUDE.md, the canonical `.joripspace/project` marker, plus `JORIPSPACE_GUIDE_CHECKED_AT` in `.env.joripspace`. Preserve user-authored content and unrelated environment entries, and do not modify application source, workflow files, or deployment configuration merely to refresh the guide.',
151
+ '- Do not run create_checkpoint, joripspace:save, deploy_code, deploy_checkpoint, rollback_deployment, git add, git commit, git push, or any deployment workflow for a guide-refresh-only request, even when the project uses GitHub Actions or an automatic deployment route.',
152
+ '- Deployment permission must appear explicitly in the current user request with wording such as "배포해", "운영 반영해", or "사이트에 적용해". A deployment approval from an earlier task or chat message does not carry forward to a later guide refresh.',
153
+ '- If a current request explicitly combines guide refresh with deployment, refresh first, then deploy only the application changes the user explicitly placed in scope after the normal verification gate. Do not manufacture an application deployment merely because managed guide files changed.',
154
+ '- Finish a guide-refresh-only request by stating the applied guide version and "운영 사이트는 변경하거나 배포하지 않았습니다."',
155
+ ];
156
+
157
+ const JORIPSPACE_BUILD_DEPLOYMENT_AUTHORITY_LINES = [
158
+ 'JoripSpace site creation and deployment authority (critical):',
159
+ '- For every site build, edit, and deployment in this project, this managed JoripSpace guide is the project-specific source of truth.',
160
+ "- Do not replace or bypass the JoripSpace workflow with an agent's own default website-building skill, generic hosting/deployment skill, or another platform's deployment workflow. Use such a skill only when this guide explicitly requires it or the user explicitly requests a non-JoripSpace target.",
161
+ '- When the user explicitly requests deployment, deploy the verified result to the selected JoripSpace project. Use JoripSpace MCP `deploy_code` for small source files that can be passed intact. For generated bundles, large files, or large multi-file projects, automatically use the installed JoripSpace CLI absolute path with `deploy --dir`; its archive upload reads local bytes directly, uploads in chunks, and verifies integrity before deployment. Do not ask the user to choose the transport.',
162
+ '- Treat an inline deployment as large when any source file exceeds 16,000 characters or the combined source exceeds 64,000 characters. Do not call deploy_code for that payload; use the installed JoripSpace CLI chunked archive transport automatically.',
163
+ '- Do not deploy directly to another hosting provider or create a separate external site unless the user explicitly asks to leave JoripSpace.',
164
+ '- If an agent default skill or generic site builder already created scaffold files, do not stop, discard useful work, or ask the user to choose a host. Preserve the requested UI and content, convert the result to a JoripSpace-compatible app, align source and lockfiles, run the relevant checks, and continue automatically.',
165
+ '- Before any JoripSpace deployment, the agent must confirm in deployment_verification that the current managed guide was applied, agent_guide_updated_at exactly matches the current server guide, deployment_target is joripspace, no external hosting deployment was performed, and the source is either joripspace_native or converted_to_joripspace. The deployment tool rejects missing, stale, or conflicting evidence and the agent must refresh automatically without asking the user.',
166
+ ];
167
+
168
+ const GITHUB_AGENT_SETUP_LINES = [
169
+ 'GitHub automatic deployment setup:',
170
+ '- The web UI inspects the selected repository and deployment trigger, detects the Worker entrypoint and build script, and directly commits a connection-specific GitHub Actions workflow to the selected deployment branch, or to the repository default branch for a GitHub Release connection.',
171
+ '- A GitHub connection is independent by connection_id. The same repository can have separate branch-push and GitHub Release workflows, and no separate approval or merge is required.',
172
+ '- If automatic detection reports that no Worker entrypoint exists, add a standard worker.js, src/index.js, src/index.ts, src/worker.js, src/worker.ts, server.js, package main, or Wrangler main entrypoint as part of the requested project work, then retry the browser connection.',
173
+ '- Never use the repository root as the artifact directory when it would include `.git`, `node_modules`, secrets, caches, or unrelated source. Stage only deployable output in a clean directory.',
174
+ '- Keep `permissions: contents: read` and `id-token: write`; do not add a long-lived JoripSpace deployment token to GitHub Secrets.',
175
+ '- The connection is recorded after the workflow commit; the first valid OIDC deployment verifies the exact repository, workflow path, trigger, and connection before deployment.',
176
+ ];
177
+
178
+ const FIRST_QUESTION_LINES = [
179
+ 'First questions to ask when details are missing:',
180
+ '1. 서비스 이름은 무엇인가요?',
181
+ '2. 이 서비스는 무엇을 하는 서비스인가요? 한두 문장으로 설명해 주세요.',
182
+ '3. 꼭 필요한 주요 기능 3가지는 무엇인가요?',
183
+ '4. 로그인/회원 기능이 필요한가요?',
184
+ '5. 결제, 이메일, 파일 업로드, 관리자 화면 중 필요한 것이 있나요?',
185
+ '6. 누가 사용하나요? 예: 학생, 고객, 회원, 직원, 관리자.',
186
+ '7. 원하는 분위기, 색상, 로고, 참고 사이트, 꼭 들어갈 문구가 있나요?',
187
+ ];
188
+
189
+ const CODEX_MCP_ONBOARDING_LINES = [
190
+ 'Codex MCP onboarding flow:',
191
+ '- If the user provides only "프로젝트: {project_id}", do not call get_project first by project ID alone.',
192
+ '- First check whether JoripSpace MCP tools are visible in the current agent session, then check the current working folder.',
193
+ '- Without connect_token, do not call start_project_session, select_project, list_my_projects, or prepare_project_workspace.',
194
+ '- Never use an empty string, dummy value, environment bearer token, browser cookie, localStorage value, profile page value, or settings file value as a connect_token.',
195
+ '- If no connection token is available, call start_login or browser_connect and show the returned connect_url. Ask the user to approve the connection in a logged-in browser and paste only the displayed MCP/CLI connection token back into chat.',
196
+ '- After connection approval succeeds, reuse the returned account API token for project tools and write the returned workspace connection files. The user should never have to find, name, or enter JORIPSPACE_API_TOKEN manually.',
197
+ '- Do not ask for email, password, Google app password, SMTP password, personal API key, or payment key in chat.',
198
+ '- If deploy_code, deploy_checkpoint, or rollback_deployment returns deployment_state_unknown, call list_deployments before any retry. If a new successful deployment exists, verify it and do not redeploy. Otherwise retry the same deployment tool at most once.',
199
+ '- Do not restart the connection flow for a deployment timeout. Restart connection only for connection_required, invalid_token, or another explicit authentication error.',
200
+ '- Create local files only after MCP session connection succeeds and workspace_setup.files or local_file_operations are returned.',
201
+ '- Before writing files, verify the current working folder. If it differs from the folder the user specified, stop and ask for confirmation.',
202
+ '- After receiving connect_token, call start_project_session(connect_token, project_id) immediately. Follow source_sync before writing workspace_setup.files when the session reports github_repository_sync_required; otherwise write returned workspace files normally. Do not initialize Git merely for JoripSpace onboarding.',
203
+ '- If start_project_session reports github_repository_sync_required, treat the connected GitHub repository and branch as the source of truth. Using the current user GitHub credentials, clone into an empty current folder or safely fetch and fast-forward the matching clean repository, then write the connection workspace files. Never restore a JoripSpace deployment artifact over a GitHub-connected source workspace, never force-push or hard-reset, and stop with the concrete Git/auth conflict when safe synchronization is impossible.',
204
+ '- If start_project_session reports latest_deployment_sync_required, do not ask whether to restore and do not offer rollback versions. Write the connection workspace files first, call get_deployment_source with deployment_restore.latest_artifact.deployment_id, back up conflicting local files, and apply the returned local_file_operations before asking questions or editing the project.',
205
+ '- For a completely new project, start_project_session embeds the current published templates in onboarding.template_choice.templates. After workspace files are ready, use that embedded list before the first service question. Do not depend on a newly added or separately cached list_templates tool during initial onboarding.',
206
+ '- If onboarding.template_choice.status is auto_selected_existing_project, option 0 is already selected because the project has an existing GitHub source or deployment baseline. Do not show a template table and do not ask new-service questions such as the service name, description, or features. After synchronization or restoration, immediately perform the task already requested by the user; if no task was requested, ask only what they want to work on in the existing project.',
207
+ '- If the embedded template_choice status says retry_required_before_service_questions, retry start_project_session once with the same project and connection token. Do not report that templates are unavailable and silently skip the choice.',
208
+ '- Only when onboarding.template_choice.status is required_before_service_questions, show option 0 as "템플릿 없이 시작" and show the embedded selectable templates in a Markdown table. Wait for the user choice; templates are optional.',
209
+ '- When the user selects a template, run the installed JoripSpace CLI absolute path with `install-template --template TEMPLATE_SLUG --project PROJECT_ID --dir .` without putting any token in the command and without `--force`. Inspect the installed files, then continue the normal service questions and customization. If files collide, overwrite nothing; continue without a template unless the user explicitly approves an overwrite retry.',
210
+ '- If start_project_session fails with connection_required, call start_login again. If it fails with invalid_token, ask for a fresh token. If it returns needs_project_choice, ask the user to choose one project and call start_project_session again. If project_not_found, ask the user to confirm the project ID.',
211
+ '- Only for a completely new project whose template_choice.status is required_before_service_questions, after the optional template choice ask onboarding questions one at a time: service name, what the service does, three required features, whether login is needed, whether payment/email/file upload/admin is needed, then choose or recommend the deployment target yourself.',
212
+ '- When both existing work and a service description are absent, ask once for the company or service, required content, and desired mood. Keep the resulting project brief in the application source only when it is useful to the project.',
213
+ '- Before deployment, verify the project connection, source entrypoint, relevant checks available in the current environment, and target URL. Direct MCP deployment of Worker-compatible source does not require Node.js or Git.',
214
+ '- Never obtain a generated bundle or large source file by printing it through a shell/tool output and copying that output into deploy_code. Tool output can be truncated even when the local file is valid. Use the installed JoripSpace CLI absolute path with `deploy --dir` so local bytes, sizes, and hashes are preserved end to end.',
215
+ '- If get_project or start_project_session times out, follow the returned retryable and next_action fields, retry at most once, then explain briefly that JoripSpace did not respond. Do not ask the beginner to inspect logs, tokens, Node.js, Git, or network internals.',
216
+ '- Preferred quick failure statuses are connection_required, invalid_token, project_not_found, workspace_setup_ready, and timeout instead of a 300-second wait.',
217
+ ];
218
+
219
+ const CODEX_MCP_USER_CONNECT_MESSAGE_LINES = [
220
+ 'JoripSpace 프로젝트를 Codex에 연결하려면 먼저 연결 토큰이 필요합니다.',
221
+ '1. 브라우저에서 아래 링크를 엽니다.',
222
+ '2. JoripSpace에 로그인된 상태에서 연결을 승인합니다.',
223
+ '3. 화면에 표시되는 MCP/CLI 전용 연결 토큰을 이 채팅에 붙여넣습니다.',
224
+ '주의: 이메일이나 비밀번호는 필요하지 않습니다. Google 앱 비밀번호나 SMTP 비밀번호를 채팅에 붙여넣지 마세요. Codex가 브라우저 쿠키나 저장소에서 토큰을 직접 찾으면 안 됩니다. 연결 토큰은 프로젝트 온보딩 세션을 시작하기 위한 값이며, 일반 API bearer token과 다릅니다.',
225
+ ];
226
+
227
+ const SECRET_RULE_LINES = [
228
+ 'Secret and token rules:',
229
+ '- When the user says a Secret or key needs to be generated, entered, added, or registered, do not stop by asking them to determine the key name or purpose. Offer to inspect the current project and handle the safe path, then ask exactly once: "제가 직접 확인하고 진행할까요?" Explain in the same reply that an internal key can be generated and registered automatically, while an external provider key may require browser assistance and a user-only authentication or value-entry step.',
230
+ '- After the user approves with a clear reply such as "네", "진행해", "너가 해", or "ㅇㅇ", inspect the project source, configuration, current task, and safe metadata to infer the required binding name, purpose, and whether it is internal or externally issued. Ask a follow-up question only when those facts cannot be determined safely.',
231
+ '- The initial Secret-work consent covers the described inspection and resulting internal generation or external browser-assisted registration. Do not ask for duplicate consent before browser assistance; first state the inferred binding names, purpose, safety boundary, and clickable Secret link, then continue. Ask new consent only if the scope materially changes.',
232
+ '- Never put API keys, payment keys, SMS/email keys, database URLs, or tokens in source code, README files, browser JavaScript, screenshots, chat summaries, logs, error messages, or audit metadata.',
233
+ '- Store external service keys used by deployed code only as JoripSpace project secrets. Only the selected project User Worker secret binding stores the value; the platform DB keeps project-scoped name, status, and lifecycle timestamps only.',
234
+ '- Never copy project Secret values into source code, env.DB, env.STORAGE, deployment source, checkpoint files, saved copies, logs, error messages, or audit metadata.',
235
+ '- Do not ask the user to paste provider Secret values into chat. Send them to the "비밀 키" tab for the selected project to register, replace, or delete the value, then use list_secrets only to confirm name, status, and timestamps. Secret values never appear in list responses or agent reports.',
236
+ '- Every user-facing request for an external provider credential must include a clickable Markdown link to `https://joripspace.com/projects/{project_id}/?tab=secrets`. Use the selected project slug in place of `{project_id}`. Never mention only the tab name or provide an unlinked URL.',
237
+ '- Before browser assistance for an external provider credential, explain the exact required binding names, what each key enables, and that Secret values must not be pasted into chat. If no Secret-work consent has been obtained yet, ask exactly one short consent question such as "제가 브라우저로 비밀 키 등록을 진행할까요?". If the user already approved "제가 직접 확인하고 진행할까요?", do not ask again.',
238
+ '- Treat clear affirmative replies such as "네", "진행해", "너가 해", or "ㅇㅇ" as approval for that described browser-assisted credential task only. Approval does not authorize unrelated account changes, credential rotation, billing changes, or destructive actions.',
239
+ "- After approval, use an available browser-control tool with the user's existing signed-in session to open the provider and selected JoripSpace project Secret pages and complete safe navigation and form steps. Never inspect cookies, localStorage, sessionStorage, saved passwords, or unrelated account pages.",
240
+ '- Keep provider Secret values out of chat, screenshots, shell commands, clipboard history, local files, tool summaries, and logs. If the browser environment cannot transfer a value without exposing it, or if reauthentication, MFA, CAPTCHA, credential reveal, or other user-only verification is required, stop at that exact visible step and ask the user to complete only that step in the browser. Continue automatically after the user confirms completion.',
241
+ '- After browser-assisted registration, call list_secrets and report only the binding name and registration status. Never repeat, reveal, compare, or summarize the Secret value.',
242
+ '- Store local connection secrets only in ignored files such as `.env.joripspace`. Store the JoripSpace API token only in `.env.joripspace`, never duplicate its value in JSON, TOML, source, another session file, or MCP client configuration. The shared project identity is the one-line `.joripspace/project` slug.',
243
+ '- If an MCP/CLI connect_token or api_token is missing, do not browse around, inspect cookies, read browser storage, or try profile pages to discover it. Ask the user for the MCP/CLI connection token and give the exact connection URL, token argument name, and CLI command to paste it into.',
244
+ '- Secret names must match [_A-Z][_A-Z0-9]* and be at most 128 characters. DB, STORAGE, PROJECT_ID and names beginning JORIPSPACE_, CF_, or CLOUDFLARE_ are reserved and must not be used.',
245
+ '- A project supports at most 60 active secrets, and each value must be 1-5,120 UTF-8 bytes. Use clear uppercase names such as TOSS_PAYMENTS_SECRET_KEY, TOSS_PAYMENTS_BILLING_SECRET_KEY, DODO_PAYMENTS_API_KEY, SOLAPI_API_KEY, or SOLAPI_API_SECRET.',
246
+ '- For app-internal random values such as session signing, CSRF protection, encryption, or test secrets, call generate_project_secret. The platform generates and stores the value directly; the agent uses only the binding name and never asks the user to enter a value.',
247
+ '- The project_agent connection is authorized for value-blind internal Secret generation through project.secrets.generate. It is not authorized to set, replace, read, or delete external provider Secret values.',
248
+ '- If generate_project_secret or another Secret registration API fails because of permission, authorization, access, or write restrictions, do not end with manual registration instructions. Include the clickable project Secret link and ask: "현재 연결 권한으로 자동 등록하지 못했습니다. 제가 브라우저로 직접 진행할까요?".',
249
+ '- On that fallback question, do not ask the user to invent or enter a random value yet. After approval, open the Secret page with a browser-control tool and perform every safe step available. Ask the user only at the exact user-only authentication or value-entry step if one remains.',
250
+ '- Treat the API failure as a change of execution path, not completion. Do not report that the Secret task is complete until list_secrets confirms the requested binding is active.',
251
+ '- Internal random Secret generation does not require browser assistance. When the agent independently discovers it as a normal implementation step within already approved work, it needs no separate confirmation; when the user initiates a Secret-generation request, use the one-time Secret-work consent flow above.',
252
+ '- Secrets are isolated by the immutable internal project id. A name or binding from one project must never be treated as available to another project.',
253
+ '- Normal project deployments and rollbacks preserve secret_text and secret_key bindings. Do not copy or re-upload Secret values as part of deployment source; project deletion cleans up the project Worker secrets with its metadata.',
254
+ '- Browser code may receive only public keys or safe redirect URLs. Server routes must handle private provider calls.',
255
+ ];
256
+
257
+ const PAYMENT_PROVIDER_GUIDANCE_LINES = [
258
+ 'Payment Provider Guidance:',
259
+ '- If the user wants payment features, explain the payment type first in plain language and send the correct JoripSpace partner signup link.',
260
+ '- 결제 연동을 쓰려면 안내된 링크로 가입해 주세요. 해당 링크로 가입해야 JoripSpace 연동 개발과 서비스 이용을 진행할 수 있습니다.',
261
+ '- 토스페이먼츠 일반결제와 빌링결제(정기결제)는 아래 조립스페이스 온보딩 링크로 가입해야 가입비가 면제되고 조립스페이스에서 이용할 수 있습니다. 토스페이먼츠 홈페이지에서 직접 가입하도록 안내하지 말고, 필요한 결제 유형을 확인한 뒤 해당 온보딩 링크로 가입하도록 안내하세요.',
262
+ '- 토스페이먼츠 - 일반결제: 국내 카드, 간편결제, 계좌이체 같은 1회 결제에 사용합니다. 가입 링크: https://onboarding.tosspayments.com/registration/entry/funnelmoa?utm_source=funnelmoa&utm_medium=hosting',
263
+ '- 토스페이먼츠 - 빌링결제(정기결제): 정기결제, 구독, 자동결제처럼 고객 카드를 등록하고 반복 청구할 때 사용합니다. 가입 링크: https://onboarding.tosspayments.com/registration/entry/funnelmoa_bill?utm_source=funnelmoa_bill&utm_medium=hosting',
264
+ '- 런모아 - 헤드리스 쇼핑몰: 추천 링크 https://runmoa.com/?special_referral=joripspace.com 로 가입하면 무료 포인트가 제공되어 결제 카드를 등록하지 않고 이용할 수 있습니다. 일반 가입은 결제 카드 등록이 필수입니다.',
265
+ '- 런모아 연동 개발 전에는 https://api-docs.runmoa.ai/ 의 최신 문서를 직접 확인합니다.',
266
+ '- 도도 페이먼츠 - 글로벌 SaaS 결제: 해외 고객 대상 SaaS 구독, 디지털 상품, 글로벌 카드 결제에 사용합니다. 가입 링크: https://app.dodopayments.com/partners/POhKqoePmZ/signup',
267
+ '- If provider credentials are not ready, build a safe payment_pending flow and explain that real payment activation needs provider signup, keys stored as project secrets, and server-side webhook verification.',
268
+ ];
269
+
270
+ const REALTIME_DEVELOPMENT_RULE_LINES = [
271
+ '- Realtime runtime: never use a Worker-global Map or Set of WebSocket connections for cross-instance broadcast. Worker instances do not share memory; a successful DB write does not push a message to sockets on another instance. Use the platform-managed /_joripspace/realtime endpoint.',
272
+ '- Realtime conversation routing: administrator and customer sessions for one conversation must connect to the same project, room, and resource_type (chat for chat). Do not split rooms by administrator/customer role. Use an opaque, unguessable conversation id for each private conversation; room=main is a public demo only.',
273
+ '- Realtime authorization: check login and conversation membership in the app before revealing the room id. Platform project isolation is not per-customer conversation authorization. Use same-origin WebSocket URLs and never put credentials or personal information in them.',
274
+ '- Realtime delivery: after the socket opens, send JSON { id, type, data } with a stable id per logical message; parse incoming JSON and render its data. Writing directly to D1 does not trigger platform broadcast. Do not report delivery merely because the sender UI updated or the DB write succeeded.',
275
+ '- Realtime reconnect: reconnect closed sockets with bounded backoff, fetch paginated managed room history to recover missed messages, and merge history with live events by message id. Reuse the same id when retrying a message and do not create a second history store.',
276
+ '- Realtime acceptance: before reporting completion, test two independent administrator/customer sessions for bidirectional receipt, reconnect and missed-message recovery without duplicates, and isolation from another room. If these checks cannot run, report them as unverified rather than claiming realtime delivery works.',
277
+ ];
278
+
279
+ const PROJECT_CAPABILITY_LINES = [
280
+ 'JoripSpace capabilities for agents:',
281
+ '- Shared platform policy lives in JoripSpace core contracts. Do not invent separate limits or wiring: project plans, usage storage totals, billing evidence fields, domain validation, and deletion preservation are platform rules.',
282
+ '- Server: write the app in the server entrypoint such as worker.js or src/index.js. Deploy with MCP deploy_code or the installed JoripSpace CLI absolute path only when the user explicitly requests deployment of the current change.',
283
+ "- Page routing is a required build contract, not an optional recommendation. Before implementation, write a route inventory that maps every main screen named or implied by the user's menus to a distinct URL path. Examples: home -> /, booking -> /booking, reservations -> /reservations, admin -> /admin.",
284
+ '- A sidebar item, top navigation item, or other control that replaces the main page content represents an independent screen and must change window.location.pathname. Do not keep the address at / while JavaScript state swaps between monitoring, incidents, status, users, booking, reservations, admin, or equivalent main screens.',
285
+ '- Do not treat independent screens as tabs merely because they share one layout. Only temporary UI such as a modal, dropdown, accordion, or an explicitly requested in-page tab may stay on the current path.',
286
+ '- Every declared route must support direct access and refresh, and the active navigation state must be derived from the current URL. Back and forward navigation must restore the corresponding screen.',
287
+ '- Keep temporary UI state such as modals and accordions inside the current route. Put shareable search, filter, sort, pagination, or tab state in the URL query string, and use dynamic paths such as /reservations/:id for independent detail screens.',
288
+ '- Before completion and again before deployment, verify every route in the route inventory with available automated tests and HTTP requests: each path responds correctly, URL-based routing is implemented, and an unknown path returns a friendly not-found response. Use an interactive browser only when the user explicitly asks for browser or visual verification. If any check fails, fix it and do not deploy.',
289
+ '- DB: app code can use env.DB for structured records. For schema changes or data cleanup, use MCP describe_db, query_db, and run_db_migration, or the CLI db commands. A public app route such as /migrate is not the normal path because DB management tools already exist.',
290
+ '- DB-backed features should consider the full operating loop by default: create, list with pagination, view detail, update, delete/archive, validation, empty states, and safe admin controls unless the user explicitly scopes them out.',
291
+ '- Storage: app code can use env.STORAGE for uploads, generated files, and private downloads. For agent-side file checks or one-off file operations, use MCP storage tools or CLI storage commands.',
292
+ '- Public cache: JoripSpace safely bypasses Workers Cache unless a GET or HEAD response explicitly sets Cache-Control: public with a positive max-age or s-maxage. Use that only for public, reusable files or responses. Keep authenticated, personalized, private, or mutable responses on Cache-Control: private, no-store.',
293
+ '- Realtime: when the user asks to implement realtime chat, use /_joripspace/realtime?room=main and the platform-managed SQLite history/search flow by default. JoripSpace stores accepted message history, preserves room ordering, maintains FTS5 search, and records project usage automatically without asking the user to choose Cloudflare, Durable Object, or FTS5.',
294
+ ...REALTIME_DEVELOPMENT_RULE_LINES,
295
+ '- Realtime storage policy: new accepted messages use application-level plaintext plain_v2 JSON in the managed room SQLite store. Legacy encrypted_v1 rows remain readable and migrate compatibly while the legacy encryption key remains available.',
296
+ '- Realtime data placement: never create a D1 messages/chat_history table for platform realtime history. Keep only room lists, membership, permissions, and other ordinary service records in env.DB; keep attachments in env.STORAGE.',
297
+ '- Realtime privacy: use opaque, unguessable room ids for private rooms, verify membership in the app before revealing a room id, and pass only an app-local opaque user id in the user query parameter. Do not put email, phone, name, or message content in room ids or URLs.',
298
+ '- Realtime history: read a room page from /_joripspace/realtime/rooms/{room}/messages?limit=50&before={cursor}. Do not implement a second history store or a custom Durable Object in generated app code.',
299
+ '- Realtime search: search the same room endpoint with search={query}, limit, and before. Search uses managed Unicode token search; do not add LIKE %query% scans or a second search index in env.DB.',
300
+ '- Realtime usage: duplicate message ids and retried usage event ids are idempotent. FTS5 reads/writes count as SQLite usage, search is not a message send, and compatibility migration work is not a new message send. All usage is attributed to the resolved immutable internal project id.',
301
+ '- Project mail: when the user asks to connect email sending, use MCP connect_mail. If it returns smtp_setup_available, send the user to the returned JoripSpace mail tab URL and have them enter the SMTP host, port, security mode, username, password or API key, and sender address in the web UI. Never ask them to paste SMTP credentials into chat. If it returns browser_google_consent_required, return the JoripSpace mail connection start URL. Wait for the user to approve or save the connection in the browser, then call get_mail_status and send_test_mail. Do not modify project source or implement a separate mail integration.',
302
+ '- Explain these to ordinary users as 서버, DB, 스토리지, and 실시간. Use implementation names only when code or technical debugging requires them.',
303
+ ];
304
+
305
+ const PROJECT_PLAN_LIMIT_LINES = [
306
+ 'Project Plans And Limits:',
307
+ '- Project traffic and platform features are limited by the saved JoripSpace project plan.',
308
+ '- Free: server/API requests 10,000 per month, storage 100MB, DB 50MB, realtime messages 1,000, realtime concurrent connections 5, and no custom domains.',
309
+ '- Starter: server/API requests 100,000 per month, storage 1GB, DB 250MB, realtime messages 100,000, realtime concurrent connections 50, and 1 custom domain by default.',
310
+ '- Pro: server/API requests 300,000 per month, storage 3GB, DB 750MB, realtime messages 300,000, realtime concurrent connections 150, and 1 custom domain by default.',
311
+ '- Business: server/API requests 1,000,000 per month, storage 10GB, DB 2.5GB, realtime messages 1,000,000, realtime concurrent connections 500, and 1 custom domain by default.',
312
+ '- If included usage is exceeded, JoripSpace blocks extra runtime traffic without surprise overage billing and shows the block page with quota_blocked.',
313
+ '- Unlimited metered usage is OFF by default. On Starter, Pro, and Business, if unlimited metered usage is enabled, quota overage is not blocked and usage continues to be recorded in the billing ledger.',
314
+ '- Monthly overage budget is optional. If the budget is empty, it means no budget cap. If a budget is set, overage is allowed only until the projected monthly amount reaches that cap.',
315
+ '- Active unlimited-metered rates are server/API requests +100,000, realtime messages +100,000, DB storage +0.25GB, file storage +1GB, and realtime concurrent users +50.',
316
+ '- Speed boost is available on Starter, Pro, and Business. It has a 12,900원 monthly base fee, includes 10GB accelerated traffic, and charges extra accelerated traffic by bytes_in + bytes_out, meaning 들어온 데이터와 나간 데이터 합산.',
317
+ '- If a Free project tries to add a custom domain, the platform returns plan_required. Explain this as "개인 도메인은 Starter 이상에서 사용할 수 있습니다."',
318
+ '- Paid plans may be selectable during development even before billing automation is fully connected. Do not tell users the selection failed unless the API returns an error.',
319
+ '- User-facing wording: 요금제 제공량을 넘으면 추가 과금 없이 기능이 제한되고 차단 안내 페이지가 표시됩니다.',
320
+ ];
321
+
322
+ const PROJECT_DOMAIN_LINES = [
323
+ 'Project Domains:',
324
+ '- Default project domains on joripspace.run are created and removed with the project lifecycle. Do not try to delete a default domain.',
325
+ '- Personal custom domains are available on Starter, Pro, and Business plans. Free projects return plan_required when a custom domain is added.',
326
+ '- The saved billing plan controls the custom-domain count. Paid plans default to one, and administrators can change the limit without changing agent instructions.',
327
+ '- Accept either an apex/root domain such as example.com or a subdomain such as www.example.com. The platform normalizes an apex/root input to its www subdomain, rejects wildcards, and converts Unicode IDNs to Punycode.',
328
+ '- A project with a custom domain must disconnect it before changing to Free.',
329
+ '- For non-technical users, the web UI domain tab is the easiest path. Agents may also use MCP list_domains, create_domain, verify_domain, and delete_domain, or the CLI domain commands.',
330
+ '- After adding a custom domain, show the project-specific CNAME target clearly and ask the user to set it at their DNS provider, then verify hostname and SSL status separately.',
331
+ '- Do not bypass JoripSpace by editing Cloudflare routes or custom hostnames directly. Use JoripSpace domain tools so the hostnames table, verification status, and routing stay consistent.',
332
+ '- User-facing wording: 개인 도메인은 Starter 이상에서 사용할 수 있습니다. example.com을 입력하면 www.example.com으로 자동 연결됩니다. 도메인을 추가한 뒤 안내된 CNAME 값을 DNS에 설정하고 상태 확인을 누르면 됩니다.',
333
+ ];
334
+
335
+ const PROJECT_CRON_LINES = [
336
+ 'Project scheduled jobs:',
337
+ '- Treat requests such as recurring, periodically, every few minutes, every day, scheduled, automatic, 주기적으로, 정기적으로, 몇 분마다, 매일, 예약 실행, or 자동 실행 as scheduled-job requests.',
338
+ '- A server path alone is not a completed scheduled job. Implement and test the GET or POST target path, then use list_crons and create_cron so the central JoripSpace scheduler can call it.',
339
+ '- Register a cron only when the user requested scheduled operation and the target path is already deployed and verified. If deployment of the current change was not explicitly requested, do not register a cron that points to undeployed code; explain that activation is waiting for deployment.',
340
+ '- Before creating a cron, call list_crons and avoid creating a duplicate with the same schedule, method, and path.',
341
+ '- After creating a cron, call run_cron for an immediate safe verification, then call list_crons again and confirm last_status and next_run_at. Inspect runtime events when the immediate run fails.',
342
+ '- Do not report a scheduled job as active until registration and immediate verification succeed. If registration is unavailable, state clearly that only the server path is ready and scheduled execution is not active.',
343
+ "- JoripSpace schedules use 5-field UTC cron expressions. Convert the user's local schedule carefully and tell the user the resulting local execution time without requiring them to understand cron syntax.",
344
+ ];
345
+
346
+ const IMAGE_AND_FILE_PLACEMENT_LINES = [
347
+ 'Image and file placement defaults:',
348
+ '- Site design assets that are part of the source, such as hero images, section screenshots, icons, logos, and fixed example images, should usually live in the project files, for example public/images/...',
349
+ '- Source assets are part of the deployment source and should be included when the latest deployment is pulled or restored.',
350
+ '- user-uploaded files, gallery photos, attachments, generated documents, and files that change during operation should use project storage through env.STORAGE.',
351
+ '- For public immutable storage downloads, return Cache-Control: public, max-age=3600 or a suitable positive TTL so the platform cache can reduce User Worker CPU and R2 reads. Use a versioned key or purge the matching Cache-Tag whenever cached mutable content changes. Never mark private downloads, signed content, account pages, or authenticated API responses public.',
352
+ '- Store metadata such as title, description, order, owner, visibility, and storage key in env.DB.',
353
+ '- Do not put large file bytes into DB. Keep file bytes in project source for fixed design assets or in env.STORAGE for operational files.',
354
+ '- User-facing wording: 사이트 디자인에 필요한 이미지는 프로젝트 파일에 넣고, 사용자가 올리는 사진이나 첨부파일은 스토리지에 저장합니다.',
355
+ ];
356
+
357
+ const FRAMEWORK_SELECTION_LINES = [
358
+ 'Framework selection rules (agent decides internally):',
359
+ '- Keep the current technology stack for an existing project unless there is a concrete reason to change it.',
360
+ '- Use a pure Cloudflare Worker for a new, single-purpose feature with only simple request handling and no meaningful shared middleware.',
361
+ '- Use Hono when the service has multiple APIs or routes, or needs shared authentication, CORS, validation, error handling, middleware, or similar cross-cutting behavior.',
362
+ '- If routing would otherwise grow into a hand-written if/switch dispatch structure, use Hono instead.',
363
+ '- If the choice between a pure Worker and Hono is ambiguous, choose Hono.',
364
+ '- When Hono is selected for a new project, use the current stable release compatible with the project. Do not downgrade Hono merely because a bundled entrypoint uses `export { app as default }`; JoripSpace accepts valid ES module default export forms.',
365
+ '- Re-evaluate this choice as the service grows. If a pure Worker later reaches the Hono conditions above, migrate it to Hono during the task without asking the user to choose a framework.',
366
+ '- During a pure Worker to Hono migration, preserve existing URLs, request/response behavior, bindings, and user data; update dependencies and the lockfile together; then rerun relevant checks before continuing.',
367
+ '- A short, single-purpose service may keep its implementation in one Worker entry file.',
368
+ '- As routes, authentication, validation, data access, external integrations, admin features, or unrelated responsibilities grow, split the source into role-based modules such as routes, middleware, services, repositories, and utilities.',
369
+ '- Keep the Worker entrypoint focused on application setup and route wiring. Do not combine all implementation into worker.js merely to reduce the source file count.',
370
+ '- With Hono, organize route groups and shared middleware into feature-focused modules when the service has more than a trivial route set.',
371
+ '- Reassess module boundaries during feature work. Split modules when unrelated features change the same file repeatedly, a file becomes difficult to test safely, or responsibilities are no longer cohesive.',
372
+ '- Preserve existing URLs, request/response contracts, bindings, authentication behavior, and user data when splitting modules. Avoid a large refactor based only on file length.',
373
+ '- Multiple source modules still build and deploy as one JoripSpace Worker service; source modularization must not create extra deployed services unless the user explicitly requests that architecture.',
374
+ '- The user does not need to choose the file structure. The agent decides based on current complexity and likely change boundaries.',
375
+ '- The user does not need to know or choose the framework. Ask only when a framework change would create a genuine business, compatibility, or destructive decision that cannot be resolved safely.',
376
+ ];
377
+
378
+ const SEO_SSR_LINES = [
379
+ 'Server-side rendering and SEO rules (agent decides internally):',
380
+ '- Server-side rendering is the default for every user-facing page unless the user explicitly requests a client-only page or a concrete technical constraint makes SSR inappropriate.',
381
+ '- When the user explicitly requests an SPA, client-only application, WebView application, or similar app-style experience, honor that request. Do not require SSR or SEO evidence, and do not block deployment merely because the initial page is client-rendered.',
382
+ '- This SSR default includes public pages, login and signup, account pages, authenticated application screens, admin pages, and dashboards. Treat it as a usability and reliable-first-render requirement, not only an SEO feature.',
383
+ '- When the SSR default applies, every page route must return meaningful, page-specific HTML in the initial HTTP response. Do not ship an accidental empty app shell that depends on client JavaScript to create the title, navigation, form, or primary content.',
384
+ '- Render SSR pages on the server with the selected pure Worker or Hono stack. Do not introduce Next.js solely to obtain SSR.',
385
+ '- Add client-side JavaScript as progressive enhancement or hydration only where interaction needs it. Preserve useful content and navigation when hydration is delayed or unavailable.',
386
+ '- For public indexable routes, include a page-specific title, meta description, canonical URL, social sharing metadata when applicable, and structured data when the page type benefits from it.',
387
+ '- If an existing SPA is client-only by accident rather than user intent or a concrete app requirement, migrate its main routes to server-rendered initial HTML while preserving existing URLs, behavior, authentication, and user data.',
388
+ '- Before deployment, verify every main route follows the intended rendering mode. For SSR routes, inspect the initial HTML without browser JavaScript. For an explicitly requested SPA or WebView app, verify app startup, routing, refresh behavior, authentication, loading, empty, and error states instead.',
389
+ ];
390
+
391
+ const FRAMEWORK_DEPLOYMENT_PRIORITY_LINES = [
392
+ 'Build and deployment defaults:',
393
+ '1. For a landing page, portfolio, guide, or brochure site, render complete HTML from the selected Worker or Hono route and add plain CSS/JS as progressive enhancement.',
394
+ '2. When a larger UI needs React, Vue, Svelte, or similar structure, use Vite assets to hydrate server-rendered initial HTML from the pure Worker or Hono API selected by the framework rules above. Do not return a client-only empty shell.',
395
+ '3. Use other frameworks with a Cloudflare-compatible output only when the existing project or request clearly benefits from them.',
396
+ '4. Existing Next.js user-facing pages should use OpenNext or another Cloudflare-compatible SSR conversion before deployment; do not assume a normal Next.js server can be uploaded directly.',
397
+ '5. Use Next.js static export only when the user explicitly requests a static/client-only result or a concrete constraint makes SSR inappropriate.',
398
+ '6. Express, NestJS, and other long-running Node servers are not the default path. Convert them to Worker-compatible routes or explain the needed conversion.',
399
+ '- Do not ask the user to choose a framework or deployment target. Inspect existing code and package.json, apply the framework selection rules yourself, build locally when needed, and prepare a Worker-compatible result. Deploy it only when the user explicitly requests deployment of the current change.',
400
+ ];
401
+
402
+ const AGENT_OPERATING_RULE_LINES = [
403
+ '- Public pricing page copy is product-approved content. Do not rename, paraphrase, reorder, or otherwise improve plan names, subtitles, benefits, prices, units, descriptions, or CTA text unless the user explicitly requests that exact change. When a pricing copy change is requested, update SSR, browser rendering, documentation, and release checks together.',
404
+ '- JoripSpace execution order: use MCP tools when they are active. Otherwise continue with the installed JoripSpace CLI absolute path returned by `start`. For generated bundles, large files, or large multi-file projects, use that CLI path even when MCP tools are visible because it uploads local bytes in verified chunks.',
405
+ '- MCP-only setup and deploy do not require Node.js or Git. Follow the local tool readiness rules: check and report both tools during onboarding, but install only a missing tool that the current project path actually requires and only after explicit user approval. Never ask the beginner to run npm or git commands.',
406
+ '- If a required MCP/CLI token is missing, stop setup and give precise recovery instructions instead of browsing around: open https://joripspace.com/connect/ in a logged-in browser, approve the connection, copy the displayed 5-minute connection code, then provide it as connect_token or run `joripspace login --code "복사한_연결_코드"`.',
407
+ '- A verified pre-existing package helper is conditional legacy compatibility only. New `start` onboarding does not generate it. Never prefer it over the installed JoripSpace CLI or install Node.js solely to run a JoripSpace helper.',
408
+ '- Use the installed CLI for checkpoint, restore, pull, and archive deployment when MCP is unavailable or inline transport is unsuitable. Node.js readiness is determined only by the project build itself or an explicitly requested legacy helper workflow.',
409
+ '- When MCP is unavailable, use the installed JoripSpace CLI absolute path returned by start. Use its `deploy --dir` command for generated bundles, large files, or large multi-file projects. Do not require an app restart, project-local helper, or Node.js installation, and do not ask the user to choose or run the command.',
410
+ '- If the project folder has no app code, use the installed CLI deployment pull/restore flow after the required safety check. A verified pre-existing `joripspace:pull` package script may be used only as conditional legacy compatibility.',
411
+ '- If the user asks to replace local files with the latest deployed version, use the current CLI restore flow; it backs up overwritten files in the user-specific JoripSpace data directory outside the project first.',
412
+ '- During initial MCP onboarding, if a successful downloadable deployment exists, automatically use the latest successful deployment as the local workspace baseline before starting work. Do not ask whether to restore and do not offer older rollback versions.',
413
+ '- Restore the latest deployed source into the current local workspace after backing up conflicting local files outside the project folder. Never overwrite `.env.joripspace`, `.joripspace/project`, AGENTS.md, CLAUDE.md, agent configuration, or any token file during deployed-source restore.',
414
+ '- When speaking to the user, use simple product terms: say server, DB, storage, and realtime. Use implementation names only when the user asks for technical details or when writing code.',
415
+ '- Read the canonical one-line `.joripspace/project` and source-bound `.env.joripspace` connection before deploying or operating the project. Authentication values and per-collaborator guide-check time live only in `.env.joripspace`.',
416
+ '- A JoripSpace project should already have its server, DB, and storage prepared at project creation. Do not ask the user to choose or configure DB/storage bindings.',
417
+ '- Use MCP/CLI DB tools to inspect schema, run migrations, and query project data when the service needs stored records.',
418
+ '- Use MCP/CLI storage tools to list, read, write, and delete project files when the service needs uploads or generated files.',
419
+ '- Keep secrets out of git. Add provider keys through project secrets or ignored local files only.',
420
+ '- If dependencies are missing, detect the package manager and install what is needed yourself when it is safe. Ask the user only for paid accounts, credentials, or business decisions.',
421
+ '- Git is optional for ordinary JoripSpace MCP onboarding and direct MCP deployment, but required for a connected GitHub source or deployment route. If required and missing, use the shared readiness approval flow; otherwise continue without Git and do not ask the beginner to initialize, commit, fetch, or push.',
422
+ '- If Git is available, initialize the current project folder during onboarding when it is not already a repository. Preserve an existing repository and its history. Never initialize a parent folder or another unrelated folder.',
423
+ '- Before staging a deployment commit, inspect git status and the staged diff, and exclude secrets, tokens, local credential files, dependencies, build caches, and unrelated user changes. `.joripspace/project` may be committed because it contains only the canonical slug. Never use git add -A blindly in a dirty workspace.',
424
+ '- Build the smallest usable version first, then improve it after testing.',
425
+ '- Deploy only when the user explicitly requests deployment of the current change. Otherwise run checks and save a checkpoint without deploying.',
426
+ '- If deploy fails with `project_resources_invalid` or `project_db_binding_invalid`, treat it as a JoripSpace project resource issue, not a user-code bug. Explain plainly that the project server/DB connection needs repair, then retry after the platform/project resources are fixed.',
427
+ ];
428
+
429
+ const DEPLOYMENT_VERIFICATION_RULE_LINES = [
430
+ '- GitHub Actions failures: read deployment history with include_failure_details=true (CLI deployments --include-failure-details --json, or deployment get --deployment ID --json). Inspect the failed commit SHA, stage, error code, file/line and GitHub run link before editing. Fix that failure, run relevant checks, commit and push, then verify the new run; do not treat a successful push as a successful deployment. If diagnostics are pending, unavailable or permission-denied, report the collection state rather than inventing a cause.',
431
+ 'Deployment verification gate:',
432
+ '- Treat any explicit deployment request, including a short request such as "배포해줘", as authorization to deploy only after completing this verification gate. The user does not need to provide a separate testing or security-review prompt.',
433
+ '- Apply the current JoripSpace managed guide before deployment. Set deployment_verification.guide_applied to true, deployment_verification.agent_guide_updated_at to the exact agent_guide.updated_at returned by prepare_project_workspace, deployment_target to joripspace, external_hosting_deployment to false, and source_compatibility to joripspace_native or converted_to_joripspace. Missing, stale, or conflicting values are a blocking policy violation. If rejected as stale, refresh the workspace files and retry automatically without asking the user.',
434
+ '- If generic/default site-builder output exists, preserve useful UI, content, and assets and convert it automatically to JoripSpace-compatible source before checks. Do not ask the user to choose a hosting provider or repeat the original request unless a destructive or business decision is genuinely required.',
435
+ '- For SSR UI deployments, you may record server_rendered_html and ssr_routes as verification evidence after checking meaningful initial HTML without browser JavaScript. These fields are informational and must not block an explicitly requested SPA, client-only application, or WebView application.',
436
+ '- For public indexable routes, you may record seo_required, seo_routes, and seo_metadata after verifying page-specific metadata. These fields are informational and are not deployment gate requirements.',
437
+ '- Before deployment, inspect the completed source and verify that the requested functions are present, connected to the intended project resources, and free of known blocking errors.',
438
+ '- Run the relevant automated checks available in the project, including syntax, type, build, format, contract, and focused tests as applicable. Do not skip an available relevant check merely because the user asked only to deploy.',
439
+ '- Exercise representative user flows with automated tests, direct function calls, or HTTP requests before deployment. Verify at least the primary read flow and, when the service writes data, one safe create/update/read path plus expected validation and error behavior.',
440
+ '- Do not open or control a browser for routine implementation or deployment verification. Use browser-based visual or interactive verification only when the user explicitly asks for browser verification. Without such a request, inspect responsive markup and styles and use automated or HTTP checks without claiming browser verification.',
441
+ '- Perform a focused security review of the changed and exposed paths before deployment. Check authentication and authorization, input validation, injection and unsafe HTML risks, secret or personal-data exposure, sensitive logs/errors, destructive actions, and cache behavior where relevant.',
442
+ '- For a project with a user interface, record a route inventory before deployment. Classify it as single-screen or multi-screen. For multi-screen navigation, record every main path and verify pathname-based routing and direct HTTP access with automated checks. Verify browser back/forward interactively only when the user explicitly requests browser verification. A same-URL main-content swap is a blocking deployment failure.',
443
+ '- If any relevant check or scenario fails, fix the problem and rerun the affected checks and scenarios. Do not deploy with a known blocking functional, security, build, or responsive-layout problem.',
444
+ '- After deployment, verify the actual project root and main changed routes with HTTP requests or available automated checks. Test a safe write flow when applicable, and inspect runtime events when an HTTP response, function, or deployment behaves unexpectedly. Open the project in a browser only when the user explicitly requests browser verification.',
445
+ '- After an explicitly requested deployment succeeds and the non-browser post-deployment checks pass, commit the exact deployed project source when Git is available and there are relevant uncommitted changes. Use a concise commit message based on the completed work. Do not create an empty commit, amend an existing commit, invent Git identity, or push unless the user explicitly requested a push.',
446
+ '- Report which checks and scenarios passed, the deployed URL, and any verification limitation. Never report deployment or verification as successful without evidence.',
447
+ ];
448
+
449
+ const CHECKPOINT_AGENT_RULE_LINES = [
450
+ '- After meaningful work and relevant checks, create a JoripSpace checkpoint with create_checkpoint or the installed CLI `checkpoint save` command. Always provide a concise label describing the change. Identical content is reused instead of creating a duplicate.',
451
+ '- Exception for the GitHub Actions deployment route: when the current task explicitly requests deployment, do not create a separate pre-push agent checkpoint. Commit and push the verified source; the Actions OIDC upload creates the single deployment checkpoint. Create an additional agent checkpoint only when the user explicitly asks to save a separate snapshot without deployment.',
452
+ '- Saving is the default after meaningful work when MCP can complete it directly or the installed JoripSpace CLI absolute path is available. A local_upload_required checkpoint response must not block ordinary MCP work or direct deployment; use the installed CLI without requiring project-local Node.js. Do not enable, assume, or perform automatic deployment during initial onboarding.',
453
+ '- Deploy the saved checkpoint only when the user explicitly asks to deploy the current change or explicitly asks for completed work to be deployed automatically. Without that request, stop after creating and verifying the checkpoint.',
454
+ '- If tests or checks fail, do not deploy. A clearly labeled 작업 중 checkpoint may be created when preserving the current files is useful.',
455
+ '- Documentation-only changes create a checkpoint but do not require a server deployment. Exception: a guide-refresh-only request updates managed guide/session files without creating a checkpoint.',
456
+ '- Before restoring files, create a restore_safety checkpoint and a local backup in the user-specific JoripSpace data directory outside the project. Preview additions, overwrites, deletions, and protected paths first; never overwrite conflicts without approval.',
457
+ '- Treat local file restore and production rollback as separate confirmed actions. 이전 상태로 돌아가 means explain and confirm both independently.',
458
+ '- Whenever two or more restore points or rollback versions are shown, including in response to an availability or inventory question such as "복원 가능한 것들이 있나?", show them as a Markdown table with number, version or identifier, timestamp, label or status, and effect. Do not wait until the user explicitly asks to choose one.',
459
+ '- Customer project secrets, .env files, certificates, and private keys may be included in checkpoints and deployments with redacted warnings; never print their values or file contents. Continue excluding JoripSpace connection credentials, .git, node_modules, .wrangler, agent instructions/configuration, and `.joripspace/project`. Preserve the local canonical marker during restore.',
460
+ '- Prefer MCP checkpoint tools. If MCP is unavailable, use the installed JoripSpace CLI absolute path with checkpoint save, checkpoint list, checkpoint restore, and checkpoint deploy. Existing npm run joripspace:* helpers are conditional legacy compatibility only and are never required by new start onboarding.',
461
+ ];
462
+
463
+ const AFTER_CONNECTION_RULE_LINES = [
464
+ 'After MCP or CLI setup:',
465
+ "- At the start of each new distinct user task, call search_knowledge once with the user's plain request before answering, planning, asking questions, or starting work. Apply the returned user_guidance, recommendation, and actions to both the response and the work, including short user requests. Do not repeat the search for every follow-up in the same task unless the topic changes or current guidance is needed.",
466
+ '- If search_knowledge returns no direct match, use its prioritized fallback guidance and ask at most three short business questions. If the knowledge service fails, continue with the built-in JoripSpace guide and explain only when the failure blocks the task.',
467
+ '- Do not stop with only "yes, it is possible" or a capability checklist.',
468
+ '- If setup cannot continue because connect_token or api_token is missing, do not click through the browser, inspect cookies, localStorage, sessionStorage, or account pages, or attempt login automation. Tell the user exactly where to get the token and how to paste it back.',
469
+ '- The user does not need to say "onboarding". After connection succeeds, continue into project selection, workspace file writing, and the first service questions automatically.',
470
+ '- Prefer a single start_project_session tool call when it is available. It combines session lookup, project choice handling, workspace file instructions, and first questions.',
471
+ '- If an MCP response includes workspace_setup.files, write those files into the current working folder immediately before replying.',
472
+ '- If an MCP response includes local_file_operations, execute those local file writes/appends before replying to the user.',
473
+ '- At the start of every new distinct JoripSpace task, call prepare_project_workspace before answering, planning, asking questions, or starting work. A new chat does not prove that the local guide is current, and a same-day guide update must not be skipped. Do not use cron or ask the user to run a refresh command.',
474
+ '- Compare the returned AGENTS.md managed block and agent_guide.updated_at with the local JoripSpace managed block on every task-start check. When it differs, replace only the JoripSpace block and preserve user-authored content. Keep `@AGENTS.md` as the first unique CLAUDE.md line, validate `.joripspace/project`, and upsert `.env.joripspace` without discarding unrelated entries. Migrate a legacy token-bearing `.joripspace/agent-session.json` into the env file and remove it only after verification.',
475
+ '- Before application work in a Git-history template project, read `.joripspace/template.json` and use the installed JoripSpace CLI `template pull` check to compare its `git_head_sha` with the latest entitled version. This check must not download a bundle or modify Git. When an update exists, report its version plus the local working-tree state and ask for explicit user approval. Only after approval, rerun the CLI command with `--yes`; it replaces `.git/joripspace/upstream.bundle`, fetches `upstream/main`, and merges the official descendant while preserving the user `origin`. If the user declines, continue without updating. Never pull automatically and never download or merge an update automatically; when there are uncommitted changes, rewritten history, divergence, or likely conflicts, stop and explain the safe next action.',
476
+ '- If the current request is only to update or refresh the guide, follow the shared guide-refresh-only rules. Do not turn that maintenance request into source work, a checkpoint, Git activity, GitHub Actions, or deployment.',
477
+ '- When MCP connection and workspace setup succeed, run the local Git and Node.js readiness check before the first service question. Ask about installation only when a missing tool is required for the current path; otherwise continue without installation. Never ask the user to run npm or git commands, locate API environment variables, or repeat the connection token.',
478
+ '- Do not ask the user to paste another start prompt when you already have project context and workspace files.',
479
+ '- If the user has not described the service yet, immediately start with up to three short questions.',
480
+ '- If the user asks what to do next, do not only provide examples. Start the onboarding questions when the project is already selected.',
481
+ '- If the user says they do not know what to build, suggest 2-3 simple service examples and pick a practical default.',
482
+ '- Whenever those examples or any other concrete alternatives require the user to choose, follow the shared user choice presentation rules and show them as a Markdown table.',
483
+ '- End each user-facing reply with the next thing to click, check, or answer.',
484
+ '- If MCP tools do not appear immediately in an app, do not require a restart. Continue the current task with the installed JoripSpace CLI absolute path; prefer MCP automatically in a later session when it is active.',
485
+ ];
486
+
487
+ const REQUIRED_ONBOARDING_MARKERS = [
488
+ 'Match the language the user is using',
489
+ 'Whenever a user-facing reply shows two or more concrete alternatives that the user could select',
490
+ 'Apply this even when the user only asks what is available, requests an inventory or comparison',
491
+ 'As soon as two or more individual candidates are shown, the table is mandatory',
492
+ 'For restore or rollback choices include number, version or identifier, timestamp, label or status, and effect',
493
+ 'For template choices include number, template name, suitable use, and included features',
494
+ 'Local Git and Node.js readiness during onboarding',
495
+ 'check `git --version`, `node --version`, and `npm --version` directly',
496
+ 'ask for one explicit approval to install only the missing required tools',
497
+ 'After installation, verify Git, Node.js, and npm again',
498
+ 'Guide refresh is maintenance-only unless deployment is separately explicit',
499
+ 'They are not authorization to build, test the application, create a checkpoint, stage files, commit, push, run GitHub Actions, or deploy',
500
+ '운영 사이트는 변경하거나 배포하지 않았습니다.',
501
+ 'JoripSpace site creation and deployment authority (critical)',
502
+ "agent's own default website-building skill",
503
+ 'deploy the verified result to the selected JoripSpace project',
504
+ 'convert the result to a JoripSpace-compatible app',
505
+ 'deployment_verification.guide_applied',
506
+ 'deployment_verification.agent_guide_updated_at',
507
+ 'source_compatibility to joripspace_native or converted_to_joripspace',
508
+ 'Framework selection rules (agent decides internally)',
509
+ 'Use a pure Cloudflare Worker for a new, single-purpose feature',
510
+ 'Use Hono when the service has multiple APIs or routes',
511
+ 'If routing would otherwise grow into a hand-written if/switch dispatch structure, use Hono instead',
512
+ 'If the choice between a pure Worker and Hono is ambiguous, choose Hono',
513
+ 'Do not downgrade Hono merely because a bundled entrypoint uses `export { app as default }`',
514
+ 'Re-evaluate this choice as the service grows',
515
+ 'migrate it to Hono during the task without asking the user to choose a framework',
516
+ 'A short, single-purpose service may keep its implementation in one Worker entry file',
517
+ 'split the source into role-based modules such as routes, middleware, services, repositories, and utilities',
518
+ 'Do not combine all implementation into worker.js merely to reduce the source file count',
519
+ 'Multiple source modules still build and deploy as one JoripSpace Worker service',
520
+ 'The user does not need to choose the file structure',
521
+ 'Server-side rendering and SEO rules (agent decides internally)',
522
+ 'Server-side rendering is the default for every user-facing page',
523
+ 'When the user explicitly requests an SPA, client-only application, WebView application, or similar app-style experience, honor that request',
524
+ 'This SSR default includes public pages, login and signup, account pages, authenticated application screens, admin pages, and dashboards',
525
+ 'When the SSR default applies, every page route must return meaningful, page-specific HTML in the initial HTTP response',
526
+ 'Render SSR pages on the server with the selected pure Worker or Hono stack',
527
+ 'Do not introduce Next.js solely to obtain SSR',
528
+ 'For an explicitly requested SPA or WebView app, verify app startup, routing, refresh behavior, authentication, loading, empty, and error states instead',
529
+ 'server_rendered_html and ssr_routes as verification evidence',
530
+ 'These fields are informational and must not block an explicitly requested SPA',
531
+ 'These fields are informational and are not deployment gate requirements',
532
+ 'First questions to ask when details are missing',
533
+ 'Secret and token rules',
534
+ 'do not browse around',
535
+ 'connect_token',
536
+ 'JoripSpace project secrets',
537
+ 'Only the selected project User Worker secret binding stores the value',
538
+ 'Secret values never appear in list responses',
539
+ '제가 직접 확인하고 진행할까요?',
540
+ 'do not stop by asking them to determine the key name or purpose',
541
+ 'Do not ask for duplicate consent before browser assistance',
542
+ 'Every user-facing request for an external provider credential must include a clickable Markdown link',
543
+ '제가 브라우저로 비밀 키 등록을 진행할까요?',
544
+ 'After browser-assisted registration, call list_secrets',
545
+ '현재 연결 권한으로 자동 등록하지 못했습니다. 제가 브라우저로 직접 진행할까요?',
546
+ 'do not end with manual registration instructions',
547
+ 'DB, STORAGE, PROJECT_ID',
548
+ 'JORIPSPACE_, CF_, or CLOUDFLARE_',
549
+ '60 active secrets',
550
+ '1-5,120 UTF-8 bytes',
551
+ 'generate_project_secret',
552
+ 'project.secrets.generate',
553
+ '.env.joripspace',
554
+ 'JORIPSPACE_GUIDE_CHECKED_AT',
555
+ 'never duplicate its value in JSON',
556
+ 'The shared project identity is the one-line `.joripspace/project` slug.',
557
+ 'Realtime inquiry',
558
+ 'After MCP or CLI setup',
559
+ 'start of every new distinct JoripSpace task',
560
+ 'project_db_binding_invalid',
561
+ '아이디어가 아직 정리되지 않아도 됩니다',
562
+ 'JoripSpace capabilities for agents',
563
+ 'Shared platform policy lives in JoripSpace core contracts',
564
+ 'Project Plans And Limits',
565
+ 'Project Domains',
566
+ 'Project scheduled jobs',
567
+ 'A server path alone is not a completed scheduled job.',
568
+ 'list_crons and create_cron',
569
+ 'run_cron for an immediate safe verification',
570
+ 'Project mail',
571
+ 'connect_mail',
572
+ 'get_mail_status',
573
+ 'send_test_mail',
574
+ 'smtp_setup_available',
575
+ 'SMTP credentials',
576
+ 'quota_blocked',
577
+ 'plan_required',
578
+ 'create_domain',
579
+ 'verify_domain',
580
+ 'CNAME',
581
+ 'server/API requests 300,000',
582
+ 'Build and deployment defaults',
583
+ 'Image and file placement defaults',
584
+ 'Use a pure Cloudflare Worker',
585
+ 'Vite assets',
586
+ 'Next.js static export',
587
+ 'OpenNext',
588
+ 'package.json',
589
+ 'public/images',
590
+ 'deployment source',
591
+ 'user-uploaded',
592
+ 'list with pagination',
593
+ 'run_db_migration',
594
+ 'env.DB',
595
+ 'env.STORAGE',
596
+ '/_joripspace/realtime',
597
+ 'plaintext plain_v2 JSON',
598
+ 'duplicate message ids and retried usage event ids are idempotent',
599
+ 'compatibility migration work is not a new message send',
600
+ 'installed JoripSpace CLI absolute path',
601
+ 'Existing npm run joripspace:* scripts are conditional legacy compatibility only',
602
+ 'one-line `.joripspace/project` slug',
603
+ '<!-- joripspace:start -->',
604
+ '<!-- joripspace:end -->',
605
+ 'run the relevant checks',
606
+ 'Deployment verification gate:',
607
+ 'The user does not need to provide a separate testing or security-review prompt.',
608
+ 'Do not open or control a browser for routine implementation or deployment verification.',
609
+ 'only when the user explicitly asks for browser verification',
610
+ 'After an explicitly requested deployment succeeds and the non-browser post-deployment checks pass',
611
+ 'Perform a focused security review',
612
+ 'Do not deploy with a known blocking functional, security, build, or responsive-layout problem.',
613
+ 'MCP-only setup and deploy do not require Node.js or Git.',
614
+ 'Do not install Node.js or Git',
615
+ 'The user should never have to find, name, or enter JORIPSPACE_API_TOKEN manually.',
616
+ 'Do not restart the connection flow for a deployment timeout.',
617
+ 'local_upload_required checkpoint response uses the installed CLI absolute path',
618
+ ];
619
+
620
+ function projectLabel(projectConfig = {}) {
621
+ const projectId = String(projectConfig.project_id || projectConfig.project_slug || '').trim();
622
+ return projectId ? `\n\nProject: ${projectId}` : '';
623
+ }
624
+
625
+ function beginnerStartPrompts(projectConfig = {}) {
626
+ const label = projectLabel(projectConfig);
627
+ const joripspaceBuildInstruction =
628
+ '사이트 제작과 배포에는 AI 에이전트의 기본 사이트 제작·호스팅 스킬이나 다른 플랫폼 방식을 대신 사용하지 말고, JoripSpace 프로젝트 지침과 MCP 흐름을 따라 이 JoripSpace 프로젝트에 제작·배포해 주세요.';
629
+ return {
630
+ create: [
631
+ '이 JoripSpace 프로젝트에서 만들 서비스를 MCP 기본 온보딩 순서대로 질문하면서 정리하고, 필요한 파일을 만든 뒤 배포와 확인까지 진행해 주세요.',
632
+ joripspaceBuildInstruction,
633
+ '아이디어가 아직 정리되지 않아도 됩니다. 사이트 이름, 목적, 사용자, 필요한 기능을 쉬운 예시와 짧은 질문으로 정리해 주세요.',
634
+ 'API 키나 결제 키는 코드에 넣지 말고 JoripSpace 프로젝트 secret 또는 gitignore 처리된 로컬 파일에만 저장해 주세요.',
635
+ label.trimStart().replace('Project:', '프로젝트:'),
636
+ ]
637
+ .filter(Boolean)
638
+ .join('\n'),
639
+ update: [
640
+ '이 JoripSpace 프로젝트의 기존 사이트를 확인한 뒤, 바꾸고 싶은 내용을 짧은 질문으로 정리하고 직접 수정, 배포, 확인까지 진행해 주세요.',
641
+ joripspaceBuildInstruction,
642
+ '요청이 애매하면 쉬운 선택지 2-3개를 보여주고 안전한 기본값을 추천한 뒤 진행해 주세요.',
643
+ 'API 키나 결제 키는 코드에 넣지 말고 JoripSpace 프로젝트 secret 또는 gitignore 처리된 로컬 파일에만 저장해 주세요.',
644
+ label.trimStart().replace('Project:', '프로젝트:'),
645
+ ]
646
+ .filter(Boolean)
647
+ .join('\n'),
648
+ fix: [
649
+ '이 JoripSpace 프로젝트에서 오류나 배포 상태를 확인하고, 로그를 직접 살펴본 뒤 수정, 재배포, 확인까지 진행해 주세요.',
650
+ joripspaceBuildInstruction,
651
+ '결과는 쉬운 말로 설명하고, 제가 다음에 눌러야 할 것, 확인할 것, 답해야 할 것만 명확히 알려주세요.',
652
+ '기술 로그를 직접 보라고 하거나 서버, DB, 스토리지, MCP, 배포 설정을 저에게 고르게 하지 마세요.',
653
+ label.trimStart().replace('Project:', '프로젝트:'),
654
+ ]
655
+ .filter(Boolean)
656
+ .join('\n'),
657
+ };
658
+ }
659
+
660
+ function beginnerStartPrompt(kind = 'create', projectConfig = {}) {
661
+ const prompts = beginnerStartPrompts(projectConfig);
662
+ return prompts[kind] || prompts.create;
663
+ }
664
+
665
+ function projectDeploymentRoutingLines(projectConfig = {}) {
666
+ const deployment =
667
+ projectConfig.deployment && typeof projectConfig.deployment === 'object' ? projectConfig.deployment : {};
668
+ if (deployment.mode === 'github_actions') {
669
+ const repository = String(deployment.repository || '(connected repository)');
670
+ const branch = String(deployment.branch || '(connected branch)');
671
+ const triggerType = String(deployment.trigger_type || 'branch');
672
+ const trigger = triggerType === 'release' ? 'GitHub Release published' : `${branch} branch push`;
673
+ const workflowPath = String(
674
+ deployment.workflow_path || `.github/workflows/joripspace-${projectConfig.project_id || 'deploy'}.yml`
675
+ );
676
+ return [
677
+ 'Current deployment route: GitHub Actions.',
678
+ `- Connected repository: ${repository}`,
679
+ `- Connected deployment trigger: ${trigger}`,
680
+ `- Expected workflow: ${workflowPath}`,
681
+ '- A normal user request such as "배포해줘" is sufficient. Do not ask the user to mention GitHub, Actions, OIDC, workflow setup, commit, or push separately.',
682
+ '- For an explicit deployment request, inspect and update the workflow when missing or stale, run the required checks, commit the exact relevant changes, and safely push them to the connected deployment branch (or the default branch used by a Release connection) so GitHub Actions performs the deployment.',
683
+ '- Do not create a checkpoint through MCP, the installed CLI, or a verified legacy helper before this push. GitHub Actions creates the deployment checkpoint, so a pre-push agent checkpoint would duplicate storage and history. Only create a separate checkpoint when the user explicitly asks to save one independently of deployment.',
684
+ '- Do not call deploy_code, deploy_checkpoint, the installed CLI direct deploy command, or a verified legacy direct package helper for this project while this GitHub route is connected.',
685
+ '- Never force-push or overwrite unrelated user changes. If the connected branch cannot be updated safely, report the concrete Git conflict or permission blocker.',
686
+ '- After the connected source change or GitHub Release, verify the resulting JoripSpace deployment through available deployment status or HTTP checks before reporting success.',
687
+ '- A successful report must state deployment method GitHub Actions, repository, trigger, workflow path, source commit SHA, Actions result, and JoripSpace deployment ID. Do not report only a checkpoint number or deployment ID.',
688
+ ];
689
+ }
690
+ return [
691
+ 'Current deployment route: direct JoripSpace deployment.',
692
+ '- A normal user request such as "배포해줘" is sufficient. Do not ask the user to choose GitHub or repeat deployment plumbing.',
693
+ '- Run the required checks, then use the JoripSpace MCP checkpoint/deployment path when active or the installed JoripSpace CLI absolute path returned by `start`. Use a verified pre-existing direct package helper only as conditional legacy compatibility.',
694
+ '- Do not create a GitHub Actions workflow or push to GitHub solely to deploy while the project connection is absent, disconnected, invalid, or suspended.',
695
+ ];
696
+ }
697
+
698
+ function projectSecretManagementLines(projectConfig = {}) {
699
+ const projectId = String(projectConfig.project_id || projectConfig.project_slug || '').trim();
700
+ const encodedProjectId = projectId ? encodeURIComponent(projectId) : '{project_id}';
701
+ return [
702
+ `- Secret management link (always include this as a clickable Markdown link when an external provider credential is required): https://joripspace.com/projects/${encodedProjectId}/?tab=secrets`,
703
+ ];
704
+ }
705
+
706
+ function projectAgentsFile() {
707
+ return [
708
+ '<!-- joripspace:start -->',
709
+ '',
710
+ 'Before working on this project, read `https://api.joripspace.com/onboarding.md`.',
711
+ '',
712
+ 'The JoripSpace project is stored in `.joripspace/project`.',
713
+ '',
714
+ 'Use the installed JoripSpace CLI for JoripSpace infrastructure, domains, and deployment. Do not configure or wait for MCP.',
715
+ '',
716
+ '<!-- joripspace:end -->',
717
+ ].join('\n');
718
+ }
719
+
720
+ function projectClaudeFile() {
721
+ return '@AGENTS.md\n';
722
+ }
723
+
724
+ function upsertProjectAgentsContent(existingContent = '', projectConfig = {}) {
725
+ const managed = projectAgentsFile(projectConfig).trim();
726
+ const existing = String(existingContent || '');
727
+ if (!existing.trim()) return `${managed}\n`;
728
+ const markerPairs = [
729
+ ['<!-- joripspace:start -->', '<!-- joripspace:end -->'],
730
+ ['<!-- joripspace:managed:start -->', '<!-- joripspace:managed:end -->'],
731
+ ];
732
+ let unmanaged = existing;
733
+ for (const [startMarker, endMarker] of markerPairs) {
734
+ const starts = unmanaged.split(startMarker).length - 1;
735
+ const ends = unmanaged.split(endMarker).length - 1;
736
+ if (starts !== ends) throw new Error('AGENTS.md의 JoripSpace 관리 영역이 손상되었습니다.');
737
+ const escapedStart = startMarker.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
738
+ const escapedEnd = endMarker.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
739
+ unmanaged = unmanaged.replace(new RegExp(`${escapedStart}[\\s\\S]*?${escapedEnd}`, 'g'), '');
740
+ }
741
+ const preserved = unmanaged.trim();
742
+ return preserved ? `${preserved}\n\n${managed}\n` : `${managed}\n`;
743
+ }
744
+
745
+ function projectMarkerFile(projectConfig = {}) {
746
+ const projectSlug = String(projectConfig.project_slug || projectConfig.project_id || '')
747
+ .trim()
748
+ .toLowerCase();
749
+ if (
750
+ projectSlug.length < 3 ||
751
+ projectSlug.length > 50 ||
752
+ !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(projectSlug)
753
+ ) {
754
+ throw new Error('JoripSpace 프로젝트 slug가 올바르지 않습니다.');
755
+ }
756
+ return `${projectSlug}\n`;
757
+ }
758
+
759
+ function projectPackageHelperScripts() {
760
+ return { ...JORIPSPACE_PACKAGE_HELPER_SCRIPTS };
761
+ }
762
+
763
+ function projectPackageHelperDependencies() {
764
+ return { ...JORIPSPACE_PACKAGE_HELPER_DEPENDENCIES };
765
+ }
766
+
767
+ function projectDoctorHelperFile() {
768
+ return String.raw`#!/usr/bin/env node
769
+ import crypto from 'node:crypto';
770
+ import fs from 'node:fs';
771
+ import path from 'node:path';
772
+ import process from 'node:process';
773
+
774
+ const ROOT = process.cwd();
775
+ const REQUIRED_SCRIPTS = {
776
+ 'joripspace:doctor': 'node .joripspace/doctor.mjs',
777
+ 'joripspace:save': 'node .joripspace/save.mjs',
778
+ 'joripspace:checkpoints': 'node .joripspace/checkpoints.mjs',
779
+ 'joripspace:restore': 'node .joripspace/restore.mjs',
780
+ 'joripspace:deploy-checkpoint': 'node .joripspace/deploy-checkpoint.mjs',
781
+ 'joripspace:deploy': 'node .joripspace/save.mjs --deploy',
782
+ 'joripspace:pull': 'node .joripspace/pull.mjs',
783
+ 'joripspace:pull:force': 'node .joripspace/pull.mjs --force',
784
+ 'joripspace:install-template': 'node .joripspace/install-template.mjs',
785
+ 'joripspace:template-pull': 'node .joripspace/install-template.mjs --update'
786
+ };
787
+ const OPTIONAL_DEPLOY_SCRIPT = 'node .joripspace/save.mjs --deploy';
788
+ const ENTRYPOINT_CANDIDATES = ['worker.js', 'src/worker.js', 'src/index.js', 'server.js', 'dist/worker.js'];
789
+ const RECOMMENDED_STACK_ORDER = [
790
+ '1. Keep the current stack for an existing project unless complexity or compatibility requires a change.',
791
+ '2. Pure Worker for one simple purpose without shared middleware.',
792
+ '3. Hono for multiple routes, shared auth/CORS/validation/error handling, hand-written routing growth, or ambiguity.',
793
+ '4. Re-evaluate and migrate a growing pure Worker to Hono while preserving behavior.',
794
+ '5. Server-render every user-facing route by default, including login, account, admin, and dashboards.',
795
+ '6. Plain HTML/CSS/JS or Vite frontend structure as appropriate, with server-rendered initial HTML.',
796
+ '7. Other Cloudflare-compatible framework output when the existing project requires it.',
797
+ '8. Next.js static export or OpenNext conversion only when the existing stack or request requires Next.js.',
798
+ '9. Express, NestJS, or long-running Node servers only after converting to Worker-compatible routes.'
799
+ ];
800
+ const IMAGE_AND_FILE_PLACEMENT = {
801
+ source_assets: [
802
+ 'Hero images, section screenshots, icons, logos, and fixed example images live in project files such as public/images/...',
803
+ 'These files are part of the deployment source and are restored when the latest deployment source is pulled.'
804
+ ],
805
+ storage_files: [
806
+ 'user-uploaded files, gallery photos, attachments, generated documents, and operational files live in env.STORAGE.',
807
+ 'Store title, description, order, owner, visibility, and storage key metadata in env.DB.'
808
+ ],
809
+ user_words: '사이트 디자인에 필요한 이미지는 프로젝트 파일에 넣고, 사용자가 올리는 사진이나 첨부파일은 스토리지에 저장합니다.'
810
+ };
811
+ const CAPABILITIES = {
812
+ server: {
813
+ available: true,
814
+ agent_path: 'Use MCP deploy_code for intact small source. Use the installed JoripSpace CLI absolute path for generated bundles and large projects so local bytes are uploaded in verified chunks.',
815
+ user_words: '서버 배포 가능'
816
+ },
817
+ db: {
818
+ available: true,
819
+ app_code: 'Use env.DB inside server code for structured records.',
820
+ agent_path: 'Use MCP describe_db, query_db, and run_db_migration, or CLI db commands, for schema/data work.',
821
+ user_words: 'DB 사용 가능'
822
+ },
823
+ storage: {
824
+ available: true,
825
+ app_code: 'Use env.STORAGE inside server code for uploads and generated files.',
826
+ agent_path: 'Use MCP list/read/write/delete_storage_object tools or CLI storage commands for one-off file work.',
827
+ user_words: '스토리지 사용 가능'
828
+ },
829
+ realtime: {
830
+ available: true,
831
+ app_code: 'Use /_joripspace/realtime?room=main from browser code. Accepted history and Unicode FTS5 search are managed by the platform; page or search /_joripspace/realtime/rooms/{room}/messages.',
832
+ agent_path: 'No extra binding or custom Durable Object is required. Never create a D1 chat-history table for platform realtime.',
833
+ user_words: '실시간 기능 사용 가능'
834
+ },
835
+ plan_limits: {
836
+ user_words: '요금제 제공량을 넘으면 추가 과금 없이 기능이 제한되고 차단 안내 페이지가 표시됩니다.',
837
+ unlimited_metered_usage: 'OFF by default. Starter and higher plans can enable it so overage is not blocked and usage is still recorded.',
838
+ unlimited_metered_budget: 'Optional. Empty means no budget cap. A numeric monthly budget caps overage and blocks when projected overage exceeds it.',
839
+ speed_boost:
840
+ 'Starter 이상 프로젝트는 속도 부스트를 켤 수 있습니다. 개인 도메인은 프로젝트 기본 주소를 CNAME 대상으로 한 번만 연결하며, 이후 속도 부스트를 켜거나 끌 때 고객 DNS를 다시 변경하지 않습니다. 기존 직접 CNAME만 프로젝트 기본 주소로 한 번 변경합니다. 프로젝트별 Argo 데이터 사용량은 별도로 집계하거나 과금하지 않습니다.',
841
+ speed_boost_ledger_items: [],
842
+ quota_error: 'quota_blocked',
843
+ custom_domain_error: 'plan_required',
844
+ free: {
845
+ requests_per_month: 10000,
846
+ storage: '100MB',
847
+ db: '50MB',
848
+ realtime_messages_per_month: 1000,
849
+ realtime_concurrent_connections: 5,
850
+ custom_domain: false
851
+ ,custom_domain_limit: 0
852
+ },
853
+ starter: {
854
+ requests_per_month: 100000,
855
+ storage: '1GB',
856
+ db: '250MB',
857
+ realtime_messages_per_month: 100000,
858
+ realtime_concurrent_connections: 50,
859
+ custom_domain: true
860
+ ,custom_domain_limit: 1
861
+ },
862
+ pro: {
863
+ requests_per_month: 300000,
864
+ storage: '3GB',
865
+ db: '750MB',
866
+ realtime_messages_per_month: 300000,
867
+ realtime_concurrent_connections: 150,
868
+ custom_domain: true
869
+ ,custom_domain_limit: 1
870
+ },
871
+ business: {
872
+ requests_per_month: 1000000,
873
+ storage: '10GB',
874
+ db: '2.5GB',
875
+ realtime_messages_per_month: 1000000,
876
+ realtime_concurrent_connections: 500,
877
+ custom_domain: true
878
+ ,custom_domain_limit: 1
879
+ }
880
+ },
881
+ project_domains: {
882
+ user_words: '개인 도메인은 Starter 이상에서 사용할 수 있습니다. DNS에 CNAME 값을 설정한 뒤 상태 확인을 누릅니다.',
883
+ default_domain_delete: false,
884
+ free_error: 'plan_required',
885
+ agent_path: 'Use web UI for non-technical users, or MCP list_domains/create_domain/verify_domain/delete_domain and CLI domain commands when agent tools are available.',
886
+ dns_record: 'CNAME',
887
+ wildcard: false,
888
+ apex: false,
889
+ idn: 'punycode',
890
+ free_downgrade_requires_disconnect: true
891
+ },
892
+ recommended_stack_order: RECOMMENDED_STACK_ORDER,
893
+ image_and_file_placement: IMAGE_AND_FILE_PLACEMENT
894
+ };
895
+
896
+ function readJson(filePath) {
897
+ try {
898
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
899
+ } catch {
900
+ return null;
901
+ }
902
+ }
903
+
904
+ ${projectEnvReaderSource()}
905
+
906
+ function writeJson(filePath, value) {
907
+ fs.writeFileSync(filePath, JSON.stringify(value, null, 2) + '\n');
908
+ }
909
+
910
+ function ensurePackageScripts() {
911
+ const packagePath = path.join(ROOT, 'package.json');
912
+ const packageJson = readJson(packagePath) || { private: true, scripts: {} };
913
+ if (!packageJson.scripts || typeof packageJson.scripts !== 'object' || Array.isArray(packageJson.scripts)) {
914
+ packageJson.scripts = {};
915
+ }
916
+ for (const [name, command] of Object.entries(REQUIRED_SCRIPTS)) {
917
+ if (!packageJson.scripts[name]) packageJson.scripts[name] = command;
918
+ }
919
+ if (!packageJson.scripts.deploy) packageJson.scripts.deploy = OPTIONAL_DEPLOY_SCRIPT;
920
+ writeJson(packagePath, packageJson);
921
+ }
922
+
923
+ function hasGitignoreEntry(entry) {
924
+ try {
925
+ return fs.readFileSync(path.join(ROOT, '.gitignore'), 'utf8').split(/\r?\n/).map((line) => line.trim()).includes(entry);
926
+ } catch {
927
+ return false;
928
+ }
929
+ }
930
+
931
+ function detectEntrypoint() {
932
+ return ENTRYPOINT_CANDIDATES.find((candidate) => fs.existsSync(path.join(ROOT, candidate))) || '';
933
+ }
934
+
935
+ function main() {
936
+ const jsonMode = process.argv.includes('--json');
937
+ const fixMode = process.argv.includes('--fix');
938
+ if (fixMode) ensurePackageScripts();
939
+
940
+ const env = readEnv(path.join(ROOT, '.env.joripspace'));
941
+ const project = { project_slug: readProjectMarker(ROOT) };
942
+ const packageJson = readJson(path.join(ROOT, 'package.json')) || {};
943
+ const scripts = packageJson.scripts && typeof packageJson.scripts === 'object' ? packageJson.scripts : {};
944
+ const issues = [];
945
+
946
+ const projectId = project.project_slug || env.JORIPSPACE_PROJECT_ID || '';
947
+ const apiBaseUrl = env.JORIPSPACE_API_BASE_URL || project.api_base_url || '';
948
+ const tokenPresent = Boolean(process.env.JORIPSPACE_API_TOKEN || env.JORIPSPACE_API_TOKEN);
949
+ const entrypoint = detectEntrypoint();
950
+
951
+ if (!projectId) issues.push({ code: 'missing_project_id', message: 'JoripSpace 프로젝트 ID를 찾지 못했습니다.', next_action: 'MCP 연결 또는 joripspace link를 다시 실행하세요.' });
952
+ if (!apiBaseUrl) issues.push({ code: 'missing_api_base_url', message: 'JoripSpace API 주소를 찾지 못했습니다.', next_action: 'MCP 연결 또는 joripspace link를 다시 실행하세요.' });
953
+ if (!tokenPresent) issues.push({ code: 'missing_api_token', message: '배포 토큰을 찾지 못했습니다.', next_action: 'JoripSpace 연결을 다시 승인해 주세요.' });
954
+ for (const [name, command] of Object.entries(REQUIRED_SCRIPTS)) {
955
+ if (scripts[name] !== command) issues.push({ code: 'missing_package_script', script: name, message: 'package.json에 ' + name + ' 스크립트가 없습니다.', next_action: 'npm run joripspace:doctor -- --fix 를 실행하세요.' });
956
+ }
957
+ if (!entrypoint) issues.push({ code: 'missing_entrypoint', message: '배포할 서버 진입 파일을 찾지 못했습니다.', next_action: 'worker.js 또는 src/index.js처럼 export default가 있는 서버 파일을 만들어 주세요.' });
958
+ if (!hasGitignoreEntry('.env.joripspace')) issues.push({ code: 'gitignore_missing_env', message: '.env.joripspace가 .gitignore에 없습니다.', next_action: '.env.joripspace를 .gitignore에 추가하세요.' });
959
+
960
+ const result = {
961
+ ok: issues.length === 0,
962
+ project_id: projectId || null,
963
+ api_base_url: apiBaseUrl || null,
964
+ token_present: tokenPresent,
965
+ entrypoint: entrypoint || null,
966
+ package_scripts: {
967
+ 'joripspace:doctor': scripts['joripspace:doctor'] || null,
968
+ 'joripspace:save': scripts['joripspace:save'] || null,
969
+ 'joripspace:checkpoints': scripts['joripspace:checkpoints'] || null,
970
+ 'joripspace:restore': scripts['joripspace:restore'] || null,
971
+ 'joripspace:deploy-checkpoint': scripts['joripspace:deploy-checkpoint'] || null,
972
+ 'joripspace:deploy': scripts['joripspace:deploy'] || null,
973
+ 'joripspace:pull': scripts['joripspace:pull'] || null,
974
+ deploy: scripts.deploy || null
975
+ },
976
+ capabilities: CAPABILITIES,
977
+ issues
978
+ };
979
+
980
+ if (jsonMode) {
981
+ console.log(JSON.stringify(result, null, 2));
982
+ process.exitCode = result.ok ? 0 : 1;
983
+ return;
984
+ }
985
+
986
+ if (result.ok) {
987
+ console.log('JoripSpace 연결 상태가 정상입니다.');
988
+ console.log('배포 준비가 된 파일: ' + entrypoint);
989
+ console.log('배포 명령: npm run joripspace:deploy');
990
+ console.log('사용 가능 기능: 서버, DB, 스토리지, 실시간');
991
+ console.log('DB 구조 변경은 MCP/CLI 마이그레이션 도구를 사용하면 됩니다.');
992
+ console.log('스토리지 파일 작업은 MCP/CLI 스토리지 도구를 사용하면 됩니다.');
993
+ console.log('실시간 메시지는 /_joripspace/realtime?room=main 으로 연결하면 됩니다.');
994
+ return;
995
+ }
996
+
997
+ console.log('JoripSpace 연결 설정을 확인해야 합니다.');
998
+ for (const issue of issues) {
999
+ console.log('- ' + issue.message + ' ' + issue.next_action);
1000
+ }
1001
+ process.exitCode = 1;
1002
+ }
1003
+
1004
+ main();
1005
+ `;
1006
+ }
1007
+
1008
+ function projectDeployHelperFile() {
1009
+ return String.raw`#!/usr/bin/env node
1010
+ import fs from 'node:fs';
1011
+ import path from 'node:path';
1012
+ import process from 'node:process';
1013
+
1014
+ const ROOT = process.cwd();
1015
+ const ENTRYPOINT_CANDIDATES = ['worker.js', 'src/worker.js', 'src/index.js', 'server.js', 'dist/worker.js'];
1016
+ const IGNORED_DIRS = new Set(['.git', '.joripspace', '.agents', '.claude', '.codex', '.cursor', '.gemini', '.opencode', '.wrangler', 'node_modules', '.cache', 'coverage']);
1017
+ const IGNORED_FILES = new Set(['agents.md', 'claude.md', '.npmrc', '.pypirc', '.netrc', '_netrc']);
1018
+
1019
+ function readJson(filePath) {
1020
+ try {
1021
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
1022
+ } catch {
1023
+ return null;
1024
+ }
1025
+ }
1026
+
1027
+ ${projectEnvReaderSource()}
1028
+
1029
+ function argValue(name) {
1030
+ const index = process.argv.indexOf(name);
1031
+ return index >= 0 ? process.argv[index + 1] || '' : '';
1032
+ }
1033
+
1034
+ function toPosix(value) {
1035
+ return value.split(path.sep).join('/');
1036
+ }
1037
+
1038
+ function shouldIgnore(relativePath) {
1039
+ const normalized = toPosix(relativePath).toLowerCase();
1040
+ const parts = normalized.split('/');
1041
+ const base = parts.at(-1) || '';
1042
+ if (IGNORED_FILES.has(base)) return true;
1043
+ if (base.startsWith('.env') || base.startsWith('.dev.vars')) return true;
1044
+ if (parts.includes('.ssh') || normalized === '.aws/credentials') return true;
1045
+ if (/\.(pem|key|p12|pfx)$/i.test(base)) return true;
1046
+ if (normalized.startsWith('.joripspace/')) return true;
1047
+ if (normalized.startsWith('tests/') || normalized.startsWith('test/') || normalized.startsWith('docs/')) return true;
1048
+ return parts.some((part) => IGNORED_DIRS.has(part));
1049
+ }
1050
+
1051
+ function walkFiles(dir) {
1052
+ const files = [];
1053
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
1054
+ const fullPath = path.join(dir, entry.name);
1055
+ const relative = path.relative(ROOT, fullPath);
1056
+ if (shouldIgnore(relative)) continue;
1057
+ if (entry.isDirectory()) files.push(...walkFiles(fullPath));
1058
+ if (entry.isFile()) files.push(fullPath);
1059
+ }
1060
+ return files;
1061
+ }
1062
+
1063
+ function detectEntrypoint() {
1064
+ const explicit = argValue('--entrypoint');
1065
+ if (explicit) return toPosix(explicit);
1066
+ return ENTRYPOINT_CANDIDATES.find((candidate) => fs.existsSync(path.join(ROOT, candidate))) || '';
1067
+ }
1068
+
1069
+ function loadConnection() {
1070
+ const connection = resolveSourceBoundConnection(ROOT);
1071
+ const env = connection.projectEnv;
1072
+ const project = { project_slug: readProjectMarker(ROOT) };
1073
+ return {
1074
+ project,
1075
+ projectId: project.project_slug || process.env.JORIPSPACE_PROJECT_ID || env.JORIPSPACE_PROJECT_ID || '',
1076
+ apiBaseUrl: connection.apiBaseUrl,
1077
+ apiToken: connection.apiToken
1078
+ };
1079
+ }
1080
+
1081
+ function hasModuleWorkerDefaultExport(source) {
1082
+ const text = String(source || '');
1083
+ return /\bexport\s+default\b/.test(text) ||
1084
+ /\bexport\s*\{[^}]*\bas\s+default\b[^}]*\}/s.test(text) ||
1085
+ /\bexport\s*\{[^}]*\bdefault\b[^}]*\}\s*from\s*['"]/s.test(text);
1086
+ }
1087
+
1088
+ function buildPayload(entrypoint) {
1089
+ if (!entrypoint) {
1090
+ throw new Error('배포할 서버 진입 파일을 찾지 못했습니다. worker.js 또는 src/index.js처럼 기본 내보내기가 있는 파일을 만들어 주세요.');
1091
+ }
1092
+ const entrypointPath = path.join(ROOT, entrypoint);
1093
+ if (!fs.existsSync(entrypointPath)) {
1094
+ throw new Error('지정한 entrypoint 파일이 없습니다: ' + entrypoint);
1095
+ }
1096
+
1097
+ const files = {};
1098
+ for (const filePath of walkFiles(ROOT)) {
1099
+ const relative = toPosix(path.relative(ROOT, filePath));
1100
+ files[relative] = fs.readFileSync(filePath, 'utf8');
1101
+ }
1102
+
1103
+ if (!Object.prototype.hasOwnProperty.call(files, entrypoint)) {
1104
+ files[entrypoint] = fs.readFileSync(entrypointPath, 'utf8');
1105
+ }
1106
+ if (!hasModuleWorkerDefaultExport(files[entrypoint])) {
1107
+ throw new Error('서버 진입 파일 형식이 올바르지 않습니다. 유효한 ES 모듈 기본 내보내기가 필요합니다: ' + entrypoint);
1108
+ }
1109
+ return { entrypoint, files };
1110
+ }
1111
+
1112
+ function friendlyError(body, fallback) {
1113
+ const error = body && body.error ? body.error : {};
1114
+ const code = error.code || body?.code || '';
1115
+ const message = error.message || body?.message || fallback;
1116
+ if (code === 'project_resources_invalid' || code === 'project_db_binding_invalid') {
1117
+ return formatDeploymentFailure('JoripSpace 프로젝트 서버/DB 연결 설정을 복구해야 합니다. 사용자 코드 문제가 아니므로 관리자 복구 후 다시 배포해 주세요. (' + code + ')', error.details);
1118
+ }
1119
+ return formatDeploymentFailure(message, error.details);
1120
+ }
1121
+
1122
+ function formatDeploymentFailure(message, details) {
1123
+ if (!details || typeof details !== 'object' || !details.deployment_id) return message;
1124
+ const lines = [message, '배포 ID: ' + details.deployment_id];
1125
+ if (details.error_stage) lines.push('실패 단계: ' + details.error_stage);
1126
+ if (details.error_code) lines.push('오류 코드: ' + details.error_code);
1127
+ if (details.error_details && details.error_details !== message) lines.push('상세 오류: ' + details.error_details);
1128
+ return lines.join('\n');
1129
+ }
1130
+
1131
+ async function main() {
1132
+ const { project, projectId, apiBaseUrl, apiToken } = loadConnection();
1133
+ if (!projectId) throw new Error('JoripSpace 프로젝트 ID를 찾지 못했습니다. MCP 연결 또는 joripspace link를 다시 실행하세요.');
1134
+ if (!apiToken) throw new Error('JoripSpace 배포 토큰을 찾지 못했습니다. JoripSpace 연결을 다시 승인해 주세요.');
1135
+
1136
+ const entrypoint = detectEntrypoint();
1137
+ const payload = buildPayload(entrypoint);
1138
+ const label = argValue('--label').trim();
1139
+ if (!label) throw new Error('--label에 배포한 내용을 입력해 주세요.');
1140
+ if (label.length > 120) throw new Error('배포 이름은 120자 이하여야 합니다.');
1141
+ const response = await fetch(apiBaseUrl + '/v1/projects/' + encodeURIComponent(projectId) + '/deploy', {
1142
+ method: 'POST',
1143
+ headers: {
1144
+ authorization: 'Bearer ' + apiToken,
1145
+ 'content-type': 'application/json',
1146
+ 'x-joripspace-session-context': 'package-helper'
1147
+ },
1148
+ body: JSON.stringify({ ...payload, label })
1149
+ });
1150
+ const text = await response.text();
1151
+ let body = {};
1152
+ try {
1153
+ body = text ? JSON.parse(text) : {};
1154
+ } catch {
1155
+ body = { message: text };
1156
+ }
1157
+ if (!response.ok) {
1158
+ throw new Error(friendlyError(body, '배포에 실패했습니다. 잠시 후 다시 시도해 주세요.'));
1159
+ }
1160
+ console.log('JoripSpace 배포가 완료되었습니다.');
1161
+ console.log('프로젝트: ' + projectId);
1162
+ if (body.default_url) console.log('URL: ' + body.default_url);
1163
+ if (body.deployment_id) console.log('Deployment: ' + body.deployment_id);
1164
+ for (const warning of body.warnings || []) console.warn('경고: ' + warning.message);
1165
+ }
1166
+
1167
+ main().catch((error) => {
1168
+ console.error(error instanceof Error ? error.message : String(error));
1169
+ process.exitCode = 1;
1170
+ });
1171
+ `;
1172
+ }
1173
+
1174
+ function projectPullHelperFile() {
1175
+ return String.raw`#!/usr/bin/env node
1176
+ import fs from 'node:fs';
1177
+ import path from 'node:path';
1178
+ import process from 'node:process';
1179
+
1180
+ const ROOT = process.cwd();
1181
+ const PROTECTED_PREFIXES = ['.git/', '.joripspace/', '.agents/', '.claude/', '.codex/', '.cursor/', '.gemini/', '.opencode/', 'node_modules/'];
1182
+ const PROTECTED_FILES = new Set(['.gitignore', 'agents.md', 'claude.md', 'package-lock.json', 'pnpm-lock.yaml', 'yarn.lock']);
1183
+
1184
+ function readJson(filePath) {
1185
+ try {
1186
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
1187
+ } catch {
1188
+ return null;
1189
+ }
1190
+ }
1191
+
1192
+
1193
+
1194
+ ${projectEnvReaderSource()}
1195
+
1196
+ function argValue(name) {
1197
+ const index = process.argv.indexOf(name);
1198
+ return index >= 0 ? process.argv[index + 1] || '' : '';
1199
+ }
1200
+
1201
+ function toPosix(value) {
1202
+ return value.split(path.sep).join('/');
1203
+ }
1204
+
1205
+ function safeRelativePath(fileName) {
1206
+ const normalized = toPosix(String(fileName || ''));
1207
+ if (!normalized || path.isAbsolute(normalized) || normalized.split('/').some((part) => !part || part === '.' || part === '..' || /[ .]$/.test(part) || /[<>:"|?*\x00-\x1f]/.test(part) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i.test(part))) {
1208
+ throw new Error('배포본에 안전하지 않은 파일 경로가 있습니다: ' + fileName);
1209
+ }
1210
+ return normalized;
1211
+ }
1212
+
1213
+ function protectedRestorePath(fileName) {
1214
+ const normalized = toPosix(String(fileName || '')).replace(/^\/+/, '');
1215
+ const lower = normalized.toLowerCase();
1216
+ const parts = lower.split('/');
1217
+ const base = parts.at(-1) || '';
1218
+ return PROTECTED_FILES.has(lower) ||
1219
+ PROTECTED_PREFIXES.some((prefix) => lower.startsWith(prefix)) ||
1220
+ base === '.env.joripspace';
1221
+ }
1222
+
1223
+ function assertNonOverlappingPlan(relatives) {
1224
+ const paths = new Map();
1225
+ for (const relative of relatives) {
1226
+ const key = relative.toLowerCase();
1227
+ if (paths.has(key)) throw new Error('배포본에 중복된 교차 플랫폼 경로가 있습니다: ' + relative);
1228
+ paths.set(key, relative);
1229
+ }
1230
+ for (const relative of paths.values()) {
1231
+ const parts = relative.split('/');
1232
+ for (let length = 1; length < parts.length; length += 1) {
1233
+ if (paths.has(parts.slice(0, length).join('/').toLowerCase())) throw new Error('배포본에 파일/디렉터리 경로 충돌이 있습니다: ' + relative);
1234
+ }
1235
+ }
1236
+ }
1237
+
1238
+ function restoreTarget(relative) {
1239
+ const root = fs.realpathSync.native(ROOT);
1240
+ const parts = relative.split('/');
1241
+ const target = path.resolve(root, ...parts);
1242
+ const fromRoot = path.relative(root, target);
1243
+ if (fromRoot === '..' || fromRoot.startsWith('..' + path.sep) || path.isAbsolute(fromRoot)) throw new Error('복원 경로가 프로젝트 밖을 가리킵니다: ' + relative);
1244
+ const blockers = [];
1245
+ let current = root;
1246
+ for (let index = 0; index < parts.length; index += 1) {
1247
+ current = path.join(current, parts[index]);
1248
+ let stat;
1249
+ try { stat = fs.lstatSync(current); } catch (error) {
1250
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') continue;
1251
+ throw error;
1252
+ }
1253
+ if (stat.isSymbolicLink()) throw new Error('복원 경로에 심볼릭 링크 또는 junction이 있습니다: ' + parts.slice(0, index + 1).join('/'));
1254
+ const isTarget = index === parts.length - 1;
1255
+ if ((!isTarget && !stat.isDirectory()) || (isTarget && !stat.isFile())) {
1256
+ blockers.push(parts.slice(0, index + 1).join('/'));
1257
+ break;
1258
+ }
1259
+ }
1260
+ return { blockers, target };
1261
+ }
1262
+
1263
+ function backupDirectory(relative) {
1264
+ const normalized = toPosix(relative);
1265
+ const root = fs.realpathSync.native(ROOT);
1266
+ const target = path.resolve(root, ...normalized.split('/'));
1267
+ const fromRoot = path.relative(root, target);
1268
+ if (fromRoot === '..' || fromRoot.startsWith('..' + path.sep) || path.isAbsolute(fromRoot)) throw new Error('백업 경로가 프로젝트 밖을 가리킵니다: ' + relative);
1269
+ let current = root;
1270
+ const parts = normalized.split('/');
1271
+ for (let index = 0; index < parts.length; index += 1) {
1272
+ current = path.join(current, parts[index]);
1273
+ let stat;
1274
+ try { stat = fs.lstatSync(current); } catch (error) {
1275
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') continue;
1276
+ throw error;
1277
+ }
1278
+ if (stat.isSymbolicLink()) throw new Error('백업 경로에 심볼릭 링크 또는 junction이 있습니다: ' + parts.slice(0, index + 1).join('/'));
1279
+ if (!stat.isDirectory()) throw new Error('백업 디렉터리가 파일에 막혀 있습니다: ' + normalized);
1280
+ }
1281
+ return target;
1282
+ }
1283
+
1284
+ function backupAndRemove(relatives, backupRoot) {
1285
+ const sorted = [...new Set(relatives)].sort((left, right) => left.split('/').length - right.split('/').length || left.localeCompare(right));
1286
+ const selected = sorted.filter((candidate) => !sorted.some((parent) => parent !== candidate && candidate.startsWith(parent + '/')));
1287
+ const safeBackupRoot = backupDirectory(toPosix(path.relative(ROOT, backupRoot)));
1288
+ fs.mkdirSync(safeBackupRoot, { recursive: true });
1289
+ for (const relative of selected) {
1290
+ const location = restoreTarget(relative);
1291
+ if (location.blockers.length) throw new Error('백업 경로가 로컬 파일에 막혀 있습니다: ' + relative);
1292
+ let stat;
1293
+ try { stat = fs.lstatSync(location.target); } catch (error) {
1294
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') continue;
1295
+ throw error;
1296
+ }
1297
+ const backup = path.join(safeBackupRoot, ...relative.split('/'));
1298
+ fs.mkdirSync(path.dirname(backup), { recursive: true });
1299
+ if (stat.isDirectory()) fs.cpSync(location.target, backup, { recursive: true, errorOnExist: true });
1300
+ else fs.copyFileSync(location.target, backup, fs.constants.COPYFILE_EXCL);
1301
+ fs.rmSync(location.target, { recursive: stat.isDirectory(), force: true });
1302
+ }
1303
+ }
1304
+
1305
+ function loadConnection() {
1306
+ const connection = resolveSourceBoundConnection(ROOT);
1307
+ const env = connection.projectEnv;
1308
+ const project = { project_slug: readProjectMarker(ROOT) };
1309
+ return {
1310
+ projectId: project.project_slug || process.env.JORIPSPACE_PROJECT_ID || env.JORIPSPACE_PROJECT_ID || '',
1311
+ apiBaseUrl: connection.apiBaseUrl,
1312
+ apiToken: connection.apiToken
1313
+ };
1314
+ }
1315
+
1316
+ async function fetchSource(connection, deploymentId) {
1317
+ const target = deploymentId || 'latest';
1318
+ const response = await fetch(connection.apiBaseUrl + '/v1/projects/' + encodeURIComponent(connection.projectId) + '/deployments/' + encodeURIComponent(target) + '/source', {
1319
+ method: 'GET',
1320
+ headers: {
1321
+ authorization: 'Bearer ' + connection.apiToken,
1322
+ 'x-joripspace-session-context': 'package-helper'
1323
+ }
1324
+ });
1325
+ const text = await response.text();
1326
+ let body = {};
1327
+ try {
1328
+ body = text ? JSON.parse(text) : {};
1329
+ } catch {
1330
+ body = { message: text };
1331
+ }
1332
+ if (!response.ok) {
1333
+ const message = body?.error?.message || body?.message || '최신 배포본을 가져오지 못했습니다.';
1334
+ throw new Error(message);
1335
+ }
1336
+ return body;
1337
+ }
1338
+
1339
+ function writeFiles(source, force) {
1340
+ const files = source.files && typeof source.files === 'object' && !Array.isArray(source.files) ? source.files : null;
1341
+ if (!files) throw new Error('배포본 파일 목록이 올바르지 않습니다.');
1342
+
1343
+ const protectedFiles = Object.keys(files).filter(protectedRestorePath);
1344
+ const planned = Object.entries(files)
1345
+ .filter(([name]) => !protectedRestorePath(name))
1346
+ .map(([name, content]) => [safeRelativePath(name), String(content)]);
1347
+ assertNonOverlappingPlan(planned.map(([relative]) => relative));
1348
+ const conflicts = new Set();
1349
+ for (const [relative, content] of planned) {
1350
+ const location = restoreTarget(relative);
1351
+ if (location.blockers.length) location.blockers.forEach((blocker) => conflicts.add(blocker));
1352
+ else if (fs.existsSync(location.target) && fs.readFileSync(location.target, 'utf8') !== content) conflicts.add(relative);
1353
+ }
1354
+
1355
+ if (conflicts.size > 0 && !force) {
1356
+ console.log('로컬 파일과 최신 배포본이 충돌합니다. 아무 파일도 바꾸지 않았습니다.');
1357
+ for (const relative of conflicts) console.log('- ' + relative);
1358
+ console.log('교체하려면 사용자 승인 후 npm run joripspace:pull:force 를 실행하세요.');
1359
+ process.exitCode = 1;
1360
+ return;
1361
+ }
1362
+
1363
+ const backupRoot = path.join(ROOT, '.joripspace', 'local-backups', new Date().toISOString().replace(/[:.]/g, '-'));
1364
+ if (conflicts.size > 0) backupAndRemove([...conflicts], backupRoot);
1365
+
1366
+ for (const [relative, content] of planned) {
1367
+ const location = restoreTarget(relative);
1368
+ if (location.blockers.length) throw new Error('복원 대상이 로컬 파일에 막혀 있습니다: ' + location.blockers.join(', '));
1369
+ fs.mkdirSync(path.dirname(location.target), { recursive: true });
1370
+ fs.writeFileSync(location.target, content);
1371
+ }
1372
+
1373
+ console.log('최신 배포본을 로컬 파일로 가져왔습니다.');
1374
+ console.log('프로젝트: ' + source.project_id);
1375
+ console.log('배포 버전: ' + source.version);
1376
+ console.log('파일 수: ' + planned.length);
1377
+ if (protectedFiles.length > 0) {
1378
+ console.log('연결 토큰과 온보딩 설정을 보호하기 위해 제외한 파일: ' + protectedFiles.length);
1379
+ }
1380
+ if (conflicts.size > 0) console.log('교체 전 파일 백업: ' + path.relative(ROOT, backupRoot));
1381
+ }
1382
+
1383
+ async function main() {
1384
+ const force = process.argv.includes('--force');
1385
+ const deploymentId = argValue('--deployment') || argValue('--deployment-id') || '';
1386
+ const connection = loadConnection();
1387
+ if (!connection.projectId) throw new Error('JoripSpace 프로젝트 ID를 찾지 못했습니다. MCP 연결 또는 joripspace link를 다시 실행하세요.');
1388
+ if (!connection.apiToken) throw new Error('JoripSpace 토큰을 찾지 못했습니다. JoripSpace 연결을 다시 승인해 주세요.');
1389
+ const source = await fetchSource(connection, deploymentId);
1390
+ writeFiles(source, force);
1391
+ }
1392
+
1393
+ main().catch((error) => {
1394
+ console.error(error instanceof Error ? error.message : String(error));
1395
+ process.exitCode = 1;
1396
+ });
1397
+ `;
1398
+ }
1399
+
1400
+ function projectCheckpointClientFile() {
1401
+ return String.raw`import fs from 'node:fs';
1402
+ import path from 'node:path';
1403
+ import process from 'node:process';
1404
+ import crypto from 'node:crypto';
1405
+ import { spawnSync } from 'node:child_process';
1406
+ import { strToU8, unzipSync, zipSync } from 'fflate';
1407
+
1408
+ const ROOT = process.cwd();
1409
+ const HARD_DIRS = new Set(['.git', '.agents', '.claude', '.codex', '.cursor', '.gemini', '.opencode', 'node_modules', '.wrangler', '.cache', 'coverage', 'tmp', 'temp']);
1410
+ const HARD_FILES = new Set(['.ds_store', 'thumbs.db', 'desktop.ini', 'agents.md', 'claude.md']);
1411
+ const LOCAL_IDENTITY_FILE = '.joripspace/project';
1412
+ const LOCAL_RESTORE_MARKERS = new Set([LOCAL_IDENTITY_FILE, '.gitignore']);
1413
+ const TEXT_ENCODER = new TextEncoder();
1414
+
1415
+ function readJson(filePath) {
1416
+ try { return JSON.parse(fs.readFileSync(filePath, 'utf8')); } catch { return null; }
1417
+ }
1418
+
1419
+ ${projectEnvReaderSource()}
1420
+
1421
+ function connection() {
1422
+ ensureProjectEnvSafety();
1423
+ const connection = resolveSourceBoundConnection(ROOT);
1424
+ const env = connection.projectEnv;
1425
+ const result = {
1426
+ projectId: readProjectMarker(ROOT) || process.env.JORIPSPACE_PROJECT_ID || env.JORIPSPACE_PROJECT_ID || '',
1427
+ apiBaseUrl: connection.apiBaseUrl,
1428
+ apiToken: connection.apiToken
1429
+ };
1430
+ if (!result.projectId || !result.apiToken) throw new Error('JoripSpace 프로젝트 연결 정보가 없습니다. 연결을 다시 승인해 주세요.');
1431
+ return result;
1432
+ }
1433
+
1434
+ function arg(name) {
1435
+ const index = process.argv.indexOf(name);
1436
+ return index >= 0 ? process.argv[index + 1] || '' : '';
1437
+ }
1438
+
1439
+ function decodedArg(plainName, encodedName) {
1440
+ const encoded = arg(encodedName);
1441
+ if (!encoded) return arg(plainName);
1442
+ if (!/^[A-Za-z0-9_-]+$/.test(encoded)) throw new Error(encodedName + ' 값이 올바르지 않습니다.');
1443
+ const decoded = Buffer.from(encoded, 'base64url').toString('utf8');
1444
+ if (!decoded || Buffer.from(decoded, 'utf8').toString('base64url') !== encoded) {
1445
+ throw new Error(encodedName + ' 값이 올바르지 않습니다.');
1446
+ }
1447
+ return decoded;
1448
+ }
1449
+
1450
+ function ensureProjectEnvSafety() {
1451
+ const tracked = spawnSync('git', ['-C', ROOT, 'ls-files', '--error-unmatch', '--', '.env.joripspace'], { encoding: 'utf8', windowsHide: true });
1452
+ if (tracked.status === 0) throw new Error('.env.joripspace가 Git에 추적되고 있습니다. git rm --cached -- .env.joripspace 후 다시 실행하세요.');
1453
+ if (tracked.error?.code === 'ENOENT' && fs.existsSync(path.join(ROOT, '.git'))) {
1454
+ throw new Error('.env.joripspace의 Git 추적 상태를 확인하려면 Git이 필요합니다.');
1455
+ }
1456
+ const location = restoreTarget('.gitignore');
1457
+ if (location.blockers.length) throw new Error('.gitignore 경로가 로컬 파일에 막혀 있습니다.');
1458
+ let source = '';
1459
+ try { source = fs.readFileSync(location.target, 'utf8'); } catch {}
1460
+ const lines = source.split(/\r?\n/).filter((line) => line.trim() !== '.env.joripspace');
1461
+ while (lines.at(-1) === '') lines.pop();
1462
+ lines.push('.env.joripspace');
1463
+ const next = lines.join('\n') + '\n';
1464
+ if (next !== source) fs.writeFileSync(location.target, next, 'utf8');
1465
+ }
1466
+
1467
+ function posix(value) { return value.split(path.sep).join('/'); }
1468
+
1469
+ function portablePathKey(relative) { return posix(String(relative || '')).toLowerCase(); }
1470
+ function isLocalIdentityFile(relative) { return portablePathKey(relative) === LOCAL_IDENTITY_FILE; }
1471
+ function isLocalRestoreMarker(relative) { return LOCAL_RESTORE_MARKERS.has(portablePathKey(relative)); }
1472
+
1473
+ function hardExcluded(relative) {
1474
+ const normalized = posix(relative).replace(/^\.\//, '');
1475
+ const lower = normalized.toLowerCase();
1476
+ const parts = lower.split('/');
1477
+ const base = parts.at(-1) || '';
1478
+ return HARD_FILES.has(base) || parts.some((part) => HARD_DIRS.has(part)) ||
1479
+ parts.includes('.joripspace') || base === '.env.joripspace' ||
1480
+ /\.(log|tmp|temp)$/i.test(base);
1481
+ }
1482
+
1483
+ function ignoreRules() {
1484
+ const rules = [];
1485
+ for (const name of ['.gitignore', '.ignore', '.joripspaceignore']) {
1486
+ try {
1487
+ for (const line of fs.readFileSync(path.join(ROOT, name), 'utf8').split(/\r?\n/)) {
1488
+ const value = line.trim();
1489
+ if (value && !value.startsWith('#')) rules.push(value);
1490
+ }
1491
+ } catch {}
1492
+ }
1493
+ return rules;
1494
+ }
1495
+
1496
+ function globRegex(pattern) {
1497
+ const clean = pattern.replace(/^!/, '').replace(/^\//, '').replace(/\/$/, '/**');
1498
+ const escaped = clean.replace(/[.+^$(){}|[\]\\]/g, '\\$&').replace(/\*\*/g, '§§').replace(/\*/g, '[^/]*').replace(/§§/g, '.*').replace(/\?/g, '.');
1499
+ return new RegExp('^(?:' + escaped + ')(?:/.*)?$');
1500
+ }
1501
+
1502
+ function ignored(relative, rules) {
1503
+ if (hardExcluded(relative)) return true;
1504
+ const normalized = posix(relative);
1505
+ let result = false;
1506
+ for (const rule of rules) {
1507
+ if (globRegex(rule).test(normalized)) result = !rule.startsWith('!');
1508
+ }
1509
+ return result;
1510
+ }
1511
+
1512
+ function projectFiles() {
1513
+ const rules = ignoreRules();
1514
+ const files = [];
1515
+ function walk(directory) {
1516
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
1517
+ const full = path.join(directory, entry.name);
1518
+ const relative = posix(path.relative(ROOT, full));
1519
+ if (hardExcluded(relative)) continue;
1520
+ const excluded = ignored(relative, rules);
1521
+ if (excluded && (!entry.isDirectory() || !negatedRuleCanInclude(relative, rules))) continue;
1522
+ const stat = fs.lstatSync(full);
1523
+ if (stat.isSymbolicLink()) throw new Error('심볼릭 링크는 저장본에 포함할 수 없습니다: ' + relative);
1524
+ if (entry.isDirectory()) {
1525
+ if (!excluded || negatedRuleCanInclude(relative, rules)) walk(full);
1526
+ } else if (entry.isFile() && !excluded) {
1527
+ files.push([relative, new Uint8Array(fs.readFileSync(full))]);
1528
+ }
1529
+ }
1530
+ }
1531
+ walk(ROOT);
1532
+ return files;
1533
+ }
1534
+
1535
+ function negatedRuleCanInclude(directory, rules) {
1536
+ const prefix = posix(directory).replace(/\/$/, '') + '/';
1537
+ return rules.some((rule) => {
1538
+ if (!rule.startsWith('!')) return false;
1539
+ const target = rule.slice(1).replace(/^\//, '').replace(/\*.*$/, '');
1540
+ return target.startsWith(prefix) || prefix.startsWith(target.replace(/\/$/, '') + '/');
1541
+ });
1542
+ }
1543
+
1544
+ async function apiFetch(connection, route, options = {}) {
1545
+ const response = await fetch(connection.apiBaseUrl + route, {
1546
+ method: options.method || 'GET',
1547
+ headers: {
1548
+ authorization: 'Bearer ' + connection.apiToken,
1549
+ 'x-joripspace-session-context': 'package-helper',
1550
+ ...(options.json === undefined ? {} : { 'content-type': 'application/json' }),
1551
+ ...(options.headers || {})
1552
+ },
1553
+ body: options.bytes || (options.json === undefined ? undefined : JSON.stringify(options.json))
1554
+ });
1555
+ if (options.raw) {
1556
+ if (!response.ok) throw new Error('저장본 파일을 받지 못했습니다. (' + response.status + ')');
1557
+ return response;
1558
+ }
1559
+ const text = await response.text();
1560
+ let body = {};
1561
+ try { body = text ? JSON.parse(text) : {}; } catch { body = { message: text }; }
1562
+ if (!response.ok) {
1563
+ const message = body?.error?.message || body?.message || 'JoripSpace 요청에 실패했습니다. (' + response.status + ')';
1564
+ const details = body?.error?.details;
1565
+ if (!details || typeof details !== 'object' || !details.deployment_id) throw new Error(message);
1566
+ const lines = [message, '배포 ID: ' + details.deployment_id];
1567
+ if (details.error_stage) lines.push('실패 단계: ' + details.error_stage);
1568
+ if (details.error_code) lines.push('오류 코드: ' + details.error_code);
1569
+ if (details.error_details && details.error_details !== message) lines.push('상세 오류: ' + details.error_details);
1570
+ throw new Error(lines.join('\n'));
1571
+ }
1572
+ return body;
1573
+ }
1574
+
1575
+ async function waitReady(connection, checkpointId) {
1576
+ for (let attempt = 0; attempt < 120; attempt += 1) {
1577
+ const result = await apiFetch(connection, '/v1/projects/' + encodeURIComponent(connection.projectId) + '/checkpoints/' + encodeURIComponent(checkpointId));
1578
+ if (result.status === 'ready') return result;
1579
+ if (result.status === 'failed' || result.status === 'deleted') throw new Error(result.error_message || '저장본 처리에 실패했습니다.');
1580
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1581
+ }
1582
+ throw new Error('저장본 처리 시간이 길어지고 있습니다. 저장본 목록에서 상태를 확인해 주세요.');
1583
+ }
1584
+
1585
+ function printWarnings(warnings) {
1586
+ for (const warning of warnings || []) console.warn('경고: ' + warning.message);
1587
+ }
1588
+
1589
+ export async function saveCheckpoint(label = '', deploy = false, sourceType = 'agent') {
1590
+ const target = connection();
1591
+ const normalizedLabel = String(label || '').trim();
1592
+ if (!normalizedLabel) throw new Error('--label에 저장하거나 배포한 내용을 입력해 주세요.');
1593
+ if (normalizedLabel.length > 120) throw new Error('저장본 이름은 120자 이하여야 합니다.');
1594
+ const files = projectFiles();
1595
+ if (!files.length) throw new Error('저장할 프로젝트 파일이 없습니다.');
1596
+ assertNonOverlappingPlan(files.map(([relative]) => relative));
1597
+ const archive = zipSync(Object.fromEntries(files.map(([name, bytes]) => [name, [bytes, { level: 6 }]])), { level: 6 });
1598
+ const session = await apiFetch(target, '/v1/projects/' + encodeURIComponent(target.projectId) + '/checkpoint-uploads', {
1599
+ method: 'POST',
1600
+ json: { label: normalizedLabel, source_type: sourceType, idempotency_key: crypto.randomUUID() }
1601
+ });
1602
+ const chunkSize = Number(session.chunk_size || 6 * 1024 * 1024);
1603
+ let part = 1;
1604
+ for (let offset = 0; offset < archive.byteLength; offset += chunkSize) {
1605
+ const route = String(session.upload_part_url_template).replace('{part_number}', String(part));
1606
+ await apiFetch(target, route, { method: 'PUT', bytes: archive.subarray(offset, Math.min(offset + chunkSize, archive.byteLength)) });
1607
+ part += 1;
1608
+ }
1609
+ await apiFetch(target, session.complete_url, { method: 'POST', json: {} });
1610
+ const ready = await waitReady(target, session.checkpoint_id);
1611
+ console.log('저장본 #' + ready.sequence + '을 만들었습니다. 파일 ' + ready.file_count + '개');
1612
+ printWarnings(ready.warnings);
1613
+ if (deploy) {
1614
+ if (!ready.deployable) throw new Error('이 저장본은 백업 전용이라 서버에 배포할 수 없습니다.');
1615
+ const result = await apiFetch(target, '/v1/projects/' + encodeURIComponent(target.projectId) + '/checkpoints/' + encodeURIComponent(ready.checkpoint_id) + '/deploy', { method: 'POST', json: {} });
1616
+ console.log('같은 저장본으로 배포했습니다: ' + (result.url || target.projectId));
1617
+ }
1618
+ return ready;
1619
+ }
1620
+
1621
+ async function listCheckpoints() {
1622
+ const target = connection();
1623
+ const result = await apiFetch(target, '/v1/projects/' + encodeURIComponent(target.projectId) + '/checkpoints?limit=100');
1624
+ for (const item of result.checkpoints || []) {
1625
+ console.log('#' + item.sequence + ' ' + (item.label || '(이름 없음)') + ' · ' + item.status + (item.deployable ? ' · 배포 가능' : ' · 백업 전용'));
1626
+ }
1627
+ }
1628
+
1629
+ function safeRestorePath(name) {
1630
+ const normalized = posix(String(name || ''));
1631
+ if (!normalized || path.isAbsolute(normalized) || normalized.split('/').some((part) => part === '..' || part === '' || part === '.' || /[ .]$/.test(part) || /[<>:"|?*\x00-\x1f]/.test(part) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i.test(part))) throw new Error('안전하지 않은 복원 경로입니다: ' + name);
1632
+ if (hardExcluded(normalized)) throw new Error('보호된 파일은 복원할 수 없습니다: ' + normalized);
1633
+ return normalized;
1634
+ }
1635
+
1636
+ function verifyRestoreArchive(plan, extracted) {
1637
+ if (!plan || !Array.isArray(plan.files)) throw new Error('저장본 복원 계획에 파일 목록이 없습니다.');
1638
+ const expected = new Map();
1639
+ for (const file of plan.files) {
1640
+ const relative = safeRestorePath(file?.path);
1641
+ if (expected.has(relative)) throw new Error('저장본 복원 계획에 중복 경로가 있습니다: ' + relative);
1642
+ const byteSize = Number(file?.byte_size);
1643
+ if (!Number.isSafeInteger(byteSize) || byteSize < 0 || typeof file?.content_hash !== 'string') throw new Error('저장본 복원 메타데이터가 올바르지 않습니다: ' + relative);
1644
+ expected.set(relative, { byteSize, contentHash: file.content_hash });
1645
+ }
1646
+ const planned = [];
1647
+ for (const [name, bytes] of Object.entries(extracted)) {
1648
+ const relative = safeRestorePath(name);
1649
+ const metadata = expected.get(relative);
1650
+ if (!metadata) throw new Error('저장본 압축 파일에 계획되지 않은 파일이 있습니다: ' + relative);
1651
+ if (bytes.byteLength !== metadata.byteSize) throw new Error('파일 크기 확인에 실패했습니다: ' + relative);
1652
+ const actual = crypto.createHash('sha256').update(bytes).digest('base64url');
1653
+ if (!metadata.contentHash || metadata.contentHash !== actual) throw new Error('파일 무결성 확인에 실패했습니다: ' + relative);
1654
+ planned.push([relative, bytes]);
1655
+ expected.delete(relative);
1656
+ }
1657
+ if (expected.size) throw new Error('저장본 압축 파일에 계획된 파일이 없습니다: ' + [...expected.keys()].join(', '));
1658
+ assertNonOverlappingPlan(planned.map(([relative]) => relative));
1659
+ return planned;
1660
+ }
1661
+
1662
+ function verifyCheckpointIdentity(planned, projectId) {
1663
+ const entry = planned.find(([relative]) => isLocalIdentityFile(relative));
1664
+ if (!entry) return;
1665
+ const identity = Buffer.from(entry[1]).toString('utf8').trim();
1666
+ if (!identity || identity !== String(projectId)) {
1667
+ throw new Error('저장본 프로젝트 연결 정보가 현재 프로젝트와 일치하지 않습니다.');
1668
+ }
1669
+ }
1670
+
1671
+ function assertNonOverlappingPlan(relatives) {
1672
+ const paths = new Map();
1673
+ for (const relative of relatives) {
1674
+ const key = relative.toLowerCase();
1675
+ if (paths.has(key)) throw new Error('저장본에 중복된 교차 플랫폼 경로가 있습니다: ' + relative);
1676
+ paths.set(key, relative);
1677
+ }
1678
+ for (const relative of paths.values()) {
1679
+ const parts = relative.split('/');
1680
+ for (let length = 1; length < parts.length; length += 1) {
1681
+ if (paths.has(parts.slice(0, length).join('/').toLowerCase())) throw new Error('저장본에 파일/디렉터리 경로 충돌이 있습니다: ' + relative);
1682
+ }
1683
+ }
1684
+ }
1685
+
1686
+ function restoreTarget(relative) {
1687
+ const root = fs.realpathSync.native(ROOT);
1688
+ const parts = relative.split('/');
1689
+ const target = path.resolve(root, ...parts);
1690
+ const fromRoot = path.relative(root, target);
1691
+ if (fromRoot === '..' || fromRoot.startsWith('..' + path.sep) || path.isAbsolute(fromRoot)) throw new Error('복원 경로가 프로젝트 밖을 가리킵니다: ' + relative);
1692
+ const blockers = [];
1693
+ let current = root;
1694
+ for (let index = 0; index < parts.length; index += 1) {
1695
+ current = path.join(current, parts[index]);
1696
+ let stat;
1697
+ try { stat = fs.lstatSync(current); } catch (error) {
1698
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') continue;
1699
+ throw error;
1700
+ }
1701
+ if (stat.isSymbolicLink()) throw new Error('복원 경로에 심볼릭 링크 또는 junction이 있습니다: ' + parts.slice(0, index + 1).join('/'));
1702
+ const actual = fs.realpathSync.native(current);
1703
+ const actualRelative = path.relative(root, actual);
1704
+ if (actualRelative === '..' || actualRelative.startsWith('..' + path.sep) || path.isAbsolute(actualRelative)) throw new Error('복원 경로가 프로젝트 밖을 가리킵니다: ' + relative);
1705
+ const isTarget = index === parts.length - 1;
1706
+ if ((!isTarget && !stat.isDirectory()) || (isTarget && !stat.isFile())) {
1707
+ blockers.push(parts.slice(0, index + 1).join('/'));
1708
+ break;
1709
+ }
1710
+ }
1711
+ return { blockers, target };
1712
+ }
1713
+
1714
+ function backupAndRemove(relatives, backupRoot) {
1715
+ const sorted = [...new Set(relatives)].sort((left, right) => left.split('/').length - right.split('/').length || left.localeCompare(right));
1716
+ const selected = sorted.filter((candidate) => !sorted.some((parent) => parent !== candidate && candidate.startsWith(parent + '/')));
1717
+ const backupRelative = posix(path.relative(ROOT, backupRoot));
1718
+ const backupTarget = restoreDirectoryTarget(backupRelative);
1719
+ fs.mkdirSync(backupTarget, { recursive: true });
1720
+ for (const relative of selected) {
1721
+ const location = restoreTarget(relative);
1722
+ if (location.blockers.length) throw new Error('백업 경로가 로컬 파일에 막혀 있습니다: ' + relative);
1723
+ let stat;
1724
+ try { stat = fs.lstatSync(location.target); } catch (error) {
1725
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') continue;
1726
+ throw error;
1727
+ }
1728
+ const backup = path.join(backupTarget, ...relative.split('/'));
1729
+ fs.mkdirSync(path.dirname(backup), { recursive: true });
1730
+ if (stat.isDirectory()) fs.cpSync(location.target, backup, { recursive: true, errorOnExist: true });
1731
+ else fs.copyFileSync(location.target, backup, fs.constants.COPYFILE_EXCL);
1732
+ fs.rmSync(location.target, { recursive: stat.isDirectory(), force: true });
1733
+ }
1734
+ }
1735
+
1736
+ function restoreDirectoryTarget(relative) {
1737
+ const normalized = posix(String(relative || '')).replace(/^\/+/, '');
1738
+ if (!normalized || path.isAbsolute(normalized) || normalized.split('/').some((part) => part === '..' || part === '' || part === '.' || /[ .]$/.test(part) || /[<>:"|?*\x00-\x1f]/.test(part))) throw new Error('안전하지 않은 백업 경로입니다: ' + relative);
1739
+ const root = fs.realpathSync.native(ROOT);
1740
+ const target = path.resolve(root, ...normalized.split('/'));
1741
+ const fromRoot = path.relative(root, target);
1742
+ if (fromRoot === '..' || fromRoot.startsWith('..' + path.sep) || path.isAbsolute(fromRoot)) throw new Error('백업 경로가 프로젝트 밖을 가리킵니다: ' + relative);
1743
+ let current = root;
1744
+ for (const [index, part] of normalized.split('/').entries()) {
1745
+ current = path.join(current, part);
1746
+ let stat;
1747
+ try { stat = fs.lstatSync(current); } catch (error) {
1748
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') continue;
1749
+ throw error;
1750
+ }
1751
+ if (stat.isSymbolicLink()) throw new Error('백업 경로에 심볼릭 링크 또는 junction이 있습니다: ' + normalized.split('/').slice(0, index + 1).join('/'));
1752
+ if (!stat.isDirectory()) throw new Error('백업 디렉터리 경로가 파일에 막혀 있습니다: ' + normalized);
1753
+ }
1754
+ return target;
1755
+ }
1756
+
1757
+ async function restoreCheckpoint() {
1758
+ const checkpointId = decodedArg('--checkpoint', '--checkpoint-base64') || arg('--checkpoint-id');
1759
+ if (!checkpointId) throw new Error('--checkpoint 저장본_ID가 필요합니다.');
1760
+ const target = connection();
1761
+ const base = '/v1/projects/' + encodeURIComponent(target.projectId) + '/checkpoints/' + encodeURIComponent(checkpointId);
1762
+ const plan = await apiFetch(target, base + '/restore-plan');
1763
+ const response = await apiFetch(target, base + '/download', { raw: true });
1764
+ const extracted = unzipSync(new Uint8Array(await response.arrayBuffer()));
1765
+ const planned = verifyRestoreArchive(plan, extracted);
1766
+ verifyCheckpointIdentity(planned, target.projectId);
1767
+ const writable = planned.filter(([relative]) => !isLocalRestoreMarker(relative));
1768
+ const plannedPaths = new Set([...planned.map(([relative]) => portablePathKey(relative)), ...LOCAL_RESTORE_MARKERS]);
1769
+ const additions = [];
1770
+ const overwrites = [];
1771
+ const conflictPaths = new Set();
1772
+ for (const [relative, bytes] of writable) {
1773
+ const location = restoreTarget(relative);
1774
+ if (location.blockers.length) {
1775
+ overwrites.push(relative);
1776
+ for (const blocker of location.blockers) conflictPaths.add(blocker);
1777
+ } else if (!fs.existsSync(location.target)) additions.push(relative);
1778
+ else if (!Buffer.from(fs.readFileSync(location.target)).equals(Buffer.from(bytes))) {
1779
+ overwrites.push(relative);
1780
+ conflictPaths.add(relative);
1781
+ }
1782
+ }
1783
+ const deletions = projectFiles().map(([relative]) => relative).filter((relative) => !plannedPaths.has(portablePathKey(relative)));
1784
+ console.log('추가 ' + additions.length + '개, 덮어쓰기 ' + overwrites.length + '개, 삭제 ' + deletions.length + '개');
1785
+ for (const name of additions) console.log('+ ' + name);
1786
+ for (const name of overwrites) console.log('~ ' + name);
1787
+ for (const name of deletions) console.log('- ' + name);
1788
+ if (!process.argv.includes('--apply')) {
1789
+ console.log('미리보기만 했습니다. 승인 후 --apply를 붙여 다시 실행하세요.');
1790
+ return;
1791
+ }
1792
+ await saveCheckpoint('복원 전 안전 저장본', false, 'restore_safety');
1793
+ const backupRoot = path.join(ROOT, '.joripspace', 'local-backups', new Date().toISOString().replace(/[:.]/g, '-'));
1794
+ backupAndRemove([...conflictPaths, ...deletions], backupRoot);
1795
+ for (const [relative, bytes] of writable) {
1796
+ const location = restoreTarget(relative);
1797
+ if (location.blockers.length) throw new Error('복원 대상이 로컬 파일에 막혀 있습니다: ' + location.blockers.join(', '));
1798
+ fs.mkdirSync(path.dirname(location.target), { recursive: true });
1799
+ fs.writeFileSync(location.target, bytes);
1800
+ }
1801
+ ensureProjectEnvSafety();
1802
+ for (const [relative, bytes] of writable) {
1803
+ const restored = fs.readFileSync(restoreTarget(relative).target);
1804
+ if (!Buffer.from(restored).equals(Buffer.from(bytes))) throw new Error('복원 후 무결성 확인에 실패했습니다: ' + relative);
1805
+ }
1806
+ console.log('로컬 파일을 복원했습니다. 운영 서버는 변경하지 않았습니다.');
1807
+ }
1808
+
1809
+ async function deployCheckpoint() {
1810
+ const checkpointId = decodedArg('--checkpoint', '--checkpoint-base64') || arg('--checkpoint-id');
1811
+ if (!checkpointId) throw new Error('--checkpoint 저장본_ID가 필요합니다.');
1812
+ const target = connection();
1813
+ const result = await apiFetch(target, '/v1/projects/' + encodeURIComponent(target.projectId) + '/checkpoints/' + encodeURIComponent(checkpointId) + '/deploy', { method: 'POST', json: {} });
1814
+ console.log('저장본을 배포했습니다: ' + (result.url || target.projectId));
1815
+ }
1816
+
1817
+ export async function runCheckpointCommand(command) {
1818
+ if (command === 'save') return saveCheckpoint(decodedArg('--label', '--label-base64'), process.argv.includes('--deploy'));
1819
+ if (command === 'list') return listCheckpoints();
1820
+ if (command === 'restore') return restoreCheckpoint();
1821
+ if (command === 'deploy') return deployCheckpoint();
1822
+ throw new Error('알 수 없는 저장본 명령입니다.');
1823
+ }
1824
+ `;
1825
+ }
1826
+
1827
+ function checkpointHelperWrapper(command) {
1828
+ return `#!/usr/bin/env node\nimport { runCheckpointCommand } from './checkpoint-client.mjs';\nrunCheckpointCommand('${command}').catch((error) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; });\n`;
1829
+ }
1830
+
1831
+ function projectSaveHelperFile() {
1832
+ return checkpointHelperWrapper('save');
1833
+ }
1834
+ function projectCheckpointsHelperFile() {
1835
+ return checkpointHelperWrapper('list');
1836
+ }
1837
+ function projectRestoreHelperFile() {
1838
+ return checkpointHelperWrapper('restore');
1839
+ }
1840
+ function projectDeployCheckpointHelperFile() {
1841
+ return checkpointHelperWrapper('deploy');
1842
+ }
1843
+
1844
+ function projectInstallTemplateHelperFile() {
1845
+ return String.raw`#!/usr/bin/env node
1846
+ import crypto from 'node:crypto';
1847
+ import fs from 'node:fs';
1848
+ import os from 'node:os';
1849
+ import path from 'node:path';
1850
+ import process from 'node:process';
1851
+ import { spawnSync } from 'node:child_process';
1852
+
1853
+ const args = parseArgs(process.argv.slice(2));
1854
+ const template = required(args.template, '--template');
1855
+ const project = required(args.project || readProjectId(), '--project');
1856
+ const target = path.resolve(args.dir || '.');
1857
+ const connection = resolveSourceBoundConnection(process.cwd());
1858
+ const apiUrl = connection.apiBaseUrl;
1859
+ const token = required(connection.apiToken, 'JORIPSPACE_API_TOKEN');
1860
+ const headers = { Authorization: 'Bearer ' + token, 'X-Joripspace-Session-Context': 'agent-helper' };
1861
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'joripspace-template-'));
1862
+ try {
1863
+ const claim = await fetch(apiUrl + '/v1/templates/' + encodeURIComponent(template) + '/claim', { method: 'POST', headers });
1864
+ if (!claim.ok && ![404, 409].includes(claim.status)) throw await responseError(claim);
1865
+ let granted = null;
1866
+ let updateCurrent = false;
1867
+ if (!args.filesOnly) {
1868
+ if (args.update) {
1869
+ const state = templateState(target);
1870
+ if (!state || state.slug !== template) throw new Error('현재 작업공간의 템플릿 계보가 일치하지 않습니다.');
1871
+ const check = await fetch(apiUrl + '/v1/templates/' + encodeURIComponent(template) + '/git-update?project_id=' + encodeURIComponent(project) + '&current_head=' + encodeURIComponent(state.git_head_sha), { headers });
1872
+ if (!check.ok) throw await responseError(check);
1873
+ const available = await check.json();
1874
+ if (!available.update_available) {
1875
+ console.log('Template is already current: ' + template);
1876
+ console.log('Template HEAD: ' + state.git_head_sha);
1877
+ updateCurrent = true;
1878
+ }
1879
+ if (!updateCurrent && !args.yes) throw new Error('템플릿 업데이트 ' + available.version + '을 사용할 수 있습니다. 변경 내용을 확인하고 사용자 동의를 받은 뒤 --yes를 붙여 다시 실행하세요.');
1880
+ }
1881
+ if (!updateCurrent) {
1882
+ const grant = await fetch(apiUrl + '/v1/templates/' + encodeURIComponent(template) + '/git-bundle-grants?project_id=' + encodeURIComponent(project), { method: 'POST', headers });
1883
+ if (grant.ok) {
1884
+ const metadata = await grant.json();
1885
+ const bundle = await fetch(metadata.download_url);
1886
+ if (!bundle.ok) throw await responseError(bundle);
1887
+ granted = { metadata, bytes: Buffer.from(await bundle.arrayBuffer()) };
1888
+ } else if (grant.status !== 409) throw await responseError(grant);
1889
+ }
1890
+ }
1891
+ if (updateCurrent) {
1892
+ // Availability checks are read-only and need no further action.
1893
+ } else if (granted) {
1894
+ await applyGitHistory(target, template, granted.bytes, granted.metadata, Boolean(args.update), temp);
1895
+ } else {
1896
+ if (args.update) throw new Error('파일만 설치한 템플릿은 template pull로 업데이트할 수 없습니다.');
1897
+ const response = await fetch(apiUrl + '/v1/templates/' + encodeURIComponent(template) + '/download?project_id=' + encodeURIComponent(project), { headers });
1898
+ if (!response.ok) throw await responseError(response);
1899
+ const archive = path.join(temp, 'template.tar.gz');
1900
+ fs.writeFileSync(archive, Buffer.from(await response.arrayBuffer()));
1901
+ const extract = path.join(temp, 'extract');
1902
+ fs.mkdirSync(extract);
1903
+ const inventory = spawnSync('tar', ['-tzf', archive], { encoding: 'utf8' });
1904
+ if (inventory.status !== 0) throw new Error('템플릿 압축 목록을 확인하지 못했습니다.');
1905
+ for (const line of String(inventory.stdout || '').split(/\r?\n/).filter(Boolean)) {
1906
+ const archivePath = line.replace(/\\/g, '/');
1907
+ const parts = archivePath.split('/');
1908
+ if (archivePath.startsWith('/') || parts.some((part) => part === '..')) {
1909
+ throw new Error('템플릿 압축에 안전하지 않은 경로가 포함되어 있습니다.');
1910
+ }
1911
+ }
1912
+ const types = spawnSync('tar', ['-tzvf', archive], { encoding: 'utf8' });
1913
+ if (types.status !== 0 || String(types.stdout || '').split(/\r?\n/).some((line) => ['l', 'h'].includes(line[0]))) {
1914
+ throw new Error('템플릿 압축에 안전하지 않은 링크가 포함되어 있습니다.');
1915
+ }
1916
+ const unpack = spawnSync('tar', ['-xzf', archive, '-C', extract], { encoding: 'utf8' });
1917
+ if (unpack.status !== 0) throw new Error('템플릿 압축을 풀지 못했습니다: ' + String(unpack.stderr || unpack.stdout || 'tar 실행 실패').trim());
1918
+ const roots = fs.readdirSync(extract, { withFileTypes: true }).filter((entry) => entry.isDirectory());
1919
+ if (roots.length !== 1) throw new Error('템플릿 압축 구조가 올바르지 않습니다.');
1920
+ const repositoryRoot = path.join(extract, roots[0].name);
1921
+ const manifest = JSON.parse(fs.readFileSync(path.join(repositoryRoot, 'joripspace-template.json'), 'utf8'));
1922
+ const sourceRoot = safeRelative(String(manifest.source_root || '.'));
1923
+ const source = sourceRoot === '.' ? repositoryRoot : path.join(repositoryRoot, ...sourceRoot.split('/'));
1924
+ const files = collectFiles(source);
1925
+ const collisions = files.map((file) => path.join(target, ...file.relative.split('/'))).filter(fs.existsSync);
1926
+ if (collisions.length && !args.force) throw new Error('템플릿이 기존 파일 ' + collisions.length + '개와 충돌합니다. 아무 파일도 덮어쓰지 않았습니다.');
1927
+ for (const file of files) {
1928
+ const destination = path.join(target, ...file.relative.split('/'));
1929
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
1930
+ fs.copyFileSync(file.absolute, destination);
1931
+ }
1932
+ console.log('Template installed: ' + template);
1933
+ console.log('Directory: ' + target);
1934
+ console.log('Files: ' + files.length);
1935
+ }
1936
+ } finally {
1937
+ fs.rmSync(temp, { recursive: true, force: true });
1938
+ }
1939
+
1940
+ function parseArgs(values) {
1941
+ const result = {};
1942
+ for (let index = 0; index < values.length; index += 1) {
1943
+ const key = values[index];
1944
+ if (!key.startsWith('--')) continue;
1945
+ if (key === '--force' || key === '--update' || key === '--files-only' || key === '--yes') {
1946
+ result[key.slice(2).replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())] = true;
1947
+ }
1948
+ else result[key.slice(2)] = values[++index] || '';
1949
+ }
1950
+ return result;
1951
+ }
1952
+ function required(value, label) { if (!value) throw new Error(label + ' 값이 필요합니다.'); return String(value); }
1953
+ ${projectEnvReaderSource()}
1954
+ function readProjectId() {
1955
+ return readProjectMarker(process.cwd());
1956
+ }
1957
+ function safeRelative(value) {
1958
+ const normalized = value.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/$/, '') || '.';
1959
+ if (normalized === '.') return normalized;
1960
+ const parts = normalized.split('/');
1961
+ if (normalized.startsWith('/') || parts.some((part) => !part || part === '.' || part === '..')) throw new Error('템플릿 source_root가 안전하지 않습니다.');
1962
+ return normalized;
1963
+ }
1964
+ function collectFiles(root) {
1965
+ if (!fs.statSync(root).isDirectory()) throw new Error('템플릿 source_root를 찾을 수 없습니다.');
1966
+ const files = [];
1967
+ const visit = (directory, prefix = '') => {
1968
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
1969
+ if (entry.isSymbolicLink()) throw new Error('템플릿에 심볼릭 링크가 포함되어 있습니다.');
1970
+ const relative = prefix ? prefix + '/' + entry.name : entry.name;
1971
+ const absolute = path.join(directory, entry.name);
1972
+ if (entry.isDirectory()) visit(absolute, relative);
1973
+ else if (entry.isFile()) files.push({ relative: safeRelative(relative), absolute });
1974
+ }
1975
+ };
1976
+ visit(root);
1977
+ if (!files.length) throw new Error('템플릿에 설치할 파일이 없습니다.');
1978
+ return files;
1979
+ }
1980
+ function installPublicGitClone(target, slug, source, temp) {
1981
+ const remoteUrl = githubRemoteUrl(source.remote_url);
1982
+ const remoteRef = gitBranchRef(source.remote_ref);
1983
+ const remoteBranch = remoteRef.slice('refs/heads/'.length);
1984
+ fs.mkdirSync(target, { recursive: true });
1985
+ const existingRepository = isGitRepository(target);
1986
+ if (existingRepository) {
1987
+ if (gitResult(target, ['rev-parse', '--verify', 'HEAD']).status === 0) return null;
1988
+ if (git(target, ['ls-files', '-z']).length) return null;
1989
+ }
1990
+ const cloneDir = path.join(temp, 'public-clone');
1991
+ const clone = gitResult(target, [...cloneLocalConfigArgs(target), 'clone', '--branch', remoteBranch, '--single-branch', '--no-tags', remoteUrl, cloneDir]);
1992
+ if (clone.status !== 0) return null;
1993
+ const head = gitSha(git(cloneDir, ['rev-parse', 'HEAD']).trim());
1994
+ const files = git(cloneDir, ['ls-files', '-z']).split('\0').filter(Boolean);
1995
+ const allowedCollisions = new Set(['package.json', '.gitignore']);
1996
+ const collisions = files.filter((file) => fs.existsSync(path.join(target, ...file.split('/'))) && !allowedCollisions.has(file));
1997
+ if (collisions.length) return null;
1998
+ const previousPackage = readJson(path.join(target, 'package.json'));
1999
+ const previousGitignore = readOptionalText(path.join(target, '.gitignore'));
2000
+ if (!existingRepository) git(target, ['init']);
2001
+ const branch = gitResult(target, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
2002
+ const branchName = branch.status === 0 && String(branch.stdout || '').trim() ? String(branch.stdout || '').trim() : 'main';
2003
+ for (const file of allowedCollisions) {
2004
+ const destination = path.join(target, file);
2005
+ if (fs.existsSync(destination)) fs.rmSync(destination, { force: true });
2006
+ }
2007
+ try {
2008
+ git(target, ['fetch', '--no-tags', cloneDir, remoteRef]);
2009
+ git(target, ['checkout', '-B', branchName, 'FETCH_HEAD']);
2010
+ } catch (error) {
2011
+ restoreOptionalText(path.join(target, 'package.json'), previousPackage && JSON.stringify(previousPackage, null, 2) + '\n');
2012
+ restoreOptionalText(path.join(target, '.gitignore'), previousGitignore);
2013
+ throw error;
2014
+ }
2015
+ mergeManagedPackageScripts(path.join(target, 'package.json'), previousPackage);
2016
+ mergeGitignore(path.join(target, '.gitignore'), previousGitignore);
2017
+ configureTemplateRemote(target, remoteUrl, remoteRef);
2018
+ git(target, ['update-ref', 'refs/remotes/joripspace-template/main', head]);
2019
+ writeClonedTemplateState(target, slug, source, head);
2020
+ return { head };
2021
+ }
2022
+ function cloneLocalConfigArgs(target) {
2023
+ const result = [];
2024
+ const rewrites = gitResult(target, ['config', '--get-regexp', '^url\\..*\\.insteadOf$']);
2025
+ if (rewrites.status === 0) {
2026
+ for (const line of String(rewrites.stdout || '').split(/\r?\n/).filter(Boolean)) {
2027
+ const separator = line.search(/\s/);
2028
+ if (separator > 0) result.push('-c', line.slice(0, separator) + '=' + line.slice(separator).trim());
2029
+ }
2030
+ }
2031
+ const fileProtocol = gitResult(target, ['config', '--get', 'protocol.file.allow']);
2032
+ if (fileProtocol.status === 0 && String(fileProtocol.stdout || '').trim()) {
2033
+ result.push('-c', 'protocol.file.allow=' + String(fileProtocol.stdout || '').trim());
2034
+ }
2035
+ return result;
2036
+ }
2037
+ async function applyGitHistory(target, slug, bundle, metadata, updateOnly, temp) {
2038
+ const expectedHash = String(metadata.bundle_sha256 || '').toLowerCase();
2039
+ const actualHash = crypto.createHash('sha256').update(bundle).digest('hex');
2040
+ if (!/^[0-9a-f]{64}$/.test(expectedHash) || !crypto.timingSafeEqual(Buffer.from(actualHash, 'hex'), Buffer.from(expectedHash, 'hex'))) {
2041
+ throw new Error('템플릿 Git bundle 무결성 확인에 실패했습니다.');
2042
+ }
2043
+ const head = gitSha(metadata.git_head_sha);
2044
+ const sourceRef = gitBranchRef(metadata.git_ref);
2045
+ if (!['refs/heads/main', 'refs/heads/joripspace-template-main'].includes(sourceRef)) throw new Error('템플릿 Git ref가 올바르지 않습니다.');
2046
+ git(target, ['--version'], true);
2047
+ if (!isGitRepository(target)) {
2048
+ if (updateOnly) throw new Error('템플릿 업데이트는 Git 저장소에서만 실행할 수 있습니다.');
2049
+ fs.mkdirSync(target, { recursive: true });
2050
+ git(target, ['init']);
2051
+ }
2052
+ const gitDirectory = path.resolve(target, git(target, ['rev-parse', '--git-dir']).trim());
2053
+ const bundleDirectory = path.join(gitDirectory, 'joripspace');
2054
+ fs.mkdirSync(bundleDirectory, { recursive: true });
2055
+ const candidatePath = path.join(bundleDirectory, 'upstream-' + crypto.randomUUID() + '.bundle');
2056
+ const bundlePath = path.join(bundleDirectory, 'upstream.bundle');
2057
+ const backupPath = path.join(bundleDirectory, 'upstream.bundle.previous');
2058
+ fs.writeFileSync(candidatePath, bundle, { flag: 'wx' });
2059
+ git(target, ['bundle', 'verify', candidatePath]);
2060
+ git(target, ['fetch', '--no-tags', candidatePath, sourceRef + ':refs/joripspace/candidate']);
2061
+ const fetchedHead = git(target, ['rev-parse', 'refs/joripspace/candidate']).trim().toLowerCase();
2062
+ if (fetchedHead !== head) throw new Error('템플릿 Git HEAD가 bundle과 일치하지 않습니다.');
2063
+ const state = templateState(target);
2064
+ if (updateOnly) {
2065
+ if (!state || state.slug !== slug) throw new Error('현재 작업공간의 템플릿 계보가 일치하지 않습니다.');
2066
+ if (state.git_head_sha === head) {
2067
+ installBundleRemote(target, candidatePath, bundlePath, backupPath, sourceRef);
2068
+ writeTemplateState(target, slug, metadata, head);
2069
+ git(target, ['add', '.joripspace/template.json']);
2070
+ if (gitResult(target, ['diff', '--cached', '--quiet']).status !== 0) {
2071
+ ensureGitIdentity(target);
2072
+ git(target, ['commit', '-m', '조립스페이스 공식 업데이트 채널 연결: ' + slug]);
2073
+ }
2074
+ console.log('Template is already current: ' + slug);
2075
+ return;
2076
+ }
2077
+ if (gitResult(target, ['merge-base', '--is-ancestor', gitSha(state.git_head_sha), head]).status !== 0) {
2078
+ throw new Error('템플릿 히스토리가 변경되어 자동 업데이트를 중단했습니다.');
2079
+ }
2080
+ if (git(target, ['status', '--porcelain']).trim()) {
2081
+ throw new Error('커밋되지 않은 변경이 있습니다. commit 또는 stash 후 다시 실행하세요.');
2082
+ }
2083
+ ensureGitIdentity(target);
2084
+ const merge = gitResult(target, ['merge', '--no-ff', '--no-commit', head]);
2085
+ if (merge.status !== 0) {
2086
+ throw new Error('템플릿 병합 충돌이 발생했습니다. 강제 덮어쓰기 없이 충돌을 해결해 주세요.\n' + String(merge.stderr || merge.stdout || '').trim());
2087
+ }
2088
+ installBundleRemote(target, candidatePath, bundlePath, backupPath, sourceRef);
2089
+ writeTemplateState(target, slug, metadata, head);
2090
+ git(target, ['add', '.joripspace/template.json']);
2091
+ git(target, ['commit', '-m', '조립스페이스 템플릿 업데이트: ' + slug]);
2092
+ console.log('Template updated: ' + slug);
2093
+ console.log('Template HEAD: ' + head);
2094
+ return;
2095
+ }
2096
+
2097
+ if (state) throw new Error('이미 템플릿 계보가 연결된 작업공간입니다. 업데이트 명령을 사용하세요.');
2098
+ ensureGitIdentity(target);
2099
+ const extract = path.join(temp, 'git-tree');
2100
+ const treeArchive = path.join(temp, 'git-tree.tar');
2101
+ fs.mkdirSync(extract);
2102
+ git(target, ['archive', '--format=tar', '--output', treeArchive, head]);
2103
+ const unpack = spawnSync('tar', ['-xf', treeArchive, '-C', extract], { encoding: 'utf8', windowsHide: true });
2104
+ if (unpack.status !== 0) throw new Error('템플릿 Git 트리를 풀지 못했습니다: ' + String(unpack.stderr || unpack.stdout || '').trim());
2105
+ const files = collectFiles(extract);
2106
+ const collisions = files.filter((file) => file.relative !== 'package.json').map((file) => path.join(target, ...file.relative.split('/'))).filter(fs.existsSync);
2107
+ if (collisions.length && !args.force) throw new Error('템플릿이 기존 파일 ' + collisions.length + '개와 충돌합니다. 아무 파일도 덮어쓰지 않았습니다.');
2108
+ const previousPackage = readJson(path.join(target, 'package.json'));
2109
+ for (const file of files) {
2110
+ const destination = path.join(target, ...file.relative.split('/'));
2111
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
2112
+ fs.copyFileSync(file.absolute, destination);
2113
+ }
2114
+ mergeManagedPackageScripts(path.join(target, 'package.json'), previousPackage);
2115
+ installBundleRemote(target, candidatePath, bundlePath, backupPath, sourceRef);
2116
+ writeTemplateState(target, slug, metadata, head);
2117
+ for (const file of files) git(target, ['add', '--', file.relative]);
2118
+ git(target, ['add', '.joripspace/template.json']);
2119
+ if (gitResult(target, ['diff', '--cached', '--quiet']).status !== 0) {
2120
+ git(target, ['commit', '-m', '조립스페이스 템플릿 설치: ' + slug]);
2121
+ }
2122
+ const lineage = gitResult(target, ['merge', '--strategy=ours', '--no-edit', '--allow-unrelated-histories', head]);
2123
+ if (lineage.status !== 0) throw new Error('템플릿 Git 계보를 연결하지 못했습니다: ' + String(lineage.stderr || lineage.stdout || '').trim());
2124
+ console.log('Template installed with Git history: ' + slug);
2125
+ console.log('Directory: ' + target);
2126
+ console.log('Template HEAD: ' + head);
2127
+ }
2128
+ function installBundleRemote(target, candidatePath, bundlePath, backupPath, sourceRef) {
2129
+ const current = gitResult(target, ['config', '--get', 'remote.upstream.url']);
2130
+ if (current.status === 0 && String(current.stdout || '').trim() !== '.git/joripspace/upstream.bundle') {
2131
+ throw new Error('기존 upstream remote는 조립스페이스 관리 채널이 아닙니다.');
2132
+ }
2133
+ if (fs.existsSync(backupPath)) fs.rmSync(backupPath, { force: true });
2134
+ if (fs.existsSync(bundlePath)) fs.renameSync(bundlePath, backupPath);
2135
+ try { fs.renameSync(candidatePath, bundlePath); }
2136
+ catch (error) {
2137
+ if (fs.existsSync(backupPath)) fs.renameSync(backupPath, bundlePath);
2138
+ throw error;
2139
+ }
2140
+ if (current.status !== 0) git(target, ['remote', 'add', 'upstream', '.git/joripspace/upstream.bundle']);
2141
+ git(target, ['config', '--replace-all', 'remote.upstream.fetch', sourceRef + ':refs/remotes/upstream/main']);
2142
+ git(target, ['config', '--replace-all', 'remote.upstream.tagOpt', '--no-tags']);
2143
+ git(target, ['fetch', '--no-tags', 'upstream']);
2144
+ git(target, ['update-ref', '-d', 'refs/joripspace/candidate']);
2145
+ if (gitResult(target, ['remote', 'get-url', 'joripspace-template']).status === 0) git(target, ['remote', 'remove', 'joripspace-template']);
2146
+ if (fs.existsSync(backupPath)) fs.rmSync(backupPath, { force: true });
2147
+ }
2148
+ function templateState(target) {
2149
+ const file = path.join(target, '.joripspace', 'template.json');
2150
+ if (!fs.existsSync(file)) return null;
2151
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); }
2152
+ catch { throw new Error('.joripspace/template.json 형식이 올바르지 않습니다.'); }
2153
+ }
2154
+ function writeTemplateState(target, slug, metadata, head) {
2155
+ const directory = path.join(target, '.joripspace');
2156
+ fs.mkdirSync(directory, { recursive: true });
2157
+ fs.writeFileSync(path.join(directory, 'template.json'), JSON.stringify({
2158
+ schema_version: 3,
2159
+ slug,
2160
+ template_id: String(metadata.template_id || ''),
2161
+ version_id: String(metadata.version_id || ''),
2162
+ version: String(metadata.version || ''),
2163
+ git_head_sha: head,
2164
+ remote_ref: 'refs/remotes/upstream/main'
2165
+ }, null, 2) + '\n');
2166
+ }
2167
+ function applyGitRemote(target, slug, remoteUrl, remoteRef) {
2168
+ const state = templateState(target);
2169
+ if (!state || state.slug !== slug) throw new Error('현재 작업공간의 템플릿 계보가 일치하지 않습니다.');
2170
+ if (!isGitRepository(target)) throw new Error('템플릿 업데이트는 Git 저장소에서만 실행할 수 있습니다.');
2171
+ if (git(target, ['status', '--porcelain']).trim()) {
2172
+ throw new Error('커밋되지 않은 변경이 있습니다. commit 또는 stash 후 다시 실행하세요.');
2173
+ }
2174
+ git(target, ['fetch', '--no-tags', remoteUrl, remoteRef]);
2175
+ const head = gitSha(git(target, ['rev-parse', 'FETCH_HEAD']).trim());
2176
+ const previousHead = gitSha(state.git_head_sha);
2177
+ if (head === previousHead) {
2178
+ configureTemplateRemote(target, remoteUrl, remoteRef);
2179
+ git(target, ['update-ref', 'refs/remotes/joripspace-template/main', head]);
2180
+ console.log('Template is already current: ' + slug);
2181
+ console.log('Template HEAD: ' + head);
2182
+ return;
2183
+ }
2184
+ if (gitResult(target, ['merge-base', '--is-ancestor', previousHead, head]).status !== 0) {
2185
+ throw new Error('템플릿 히스토리가 변경되어 자동 업데이트를 중단했습니다.');
2186
+ }
2187
+ ensureGitIdentity(target);
2188
+ const merge = gitResult(target, ['merge', '--no-ff', '--no-commit', head]);
2189
+ if (merge.status !== 0) {
2190
+ throw new Error('템플릿 병합 충돌이 발생했습니다. 강제 덮어쓰기 없이 충돌을 해결해 주세요.\n' + String(merge.stderr || merge.stdout || '').trim());
2191
+ }
2192
+ configureTemplateRemote(target, remoteUrl, remoteRef);
2193
+ git(target, ['update-ref', 'refs/remotes/joripspace-template/main', head]);
2194
+ writeRemoteTemplateState(target, state, remoteUrl, remoteRef, head);
2195
+ git(target, ['add', '.joripspace/template.json']);
2196
+ git(target, ['commit', '-m', '조립스페이스 템플릿 업데이트: ' + slug]);
2197
+ console.log('Template updated: ' + slug);
2198
+ console.log('Template HEAD: ' + head);
2199
+ }
2200
+ function writeRemoteTemplateState(target, state, remoteUrl, remoteRef, head) {
2201
+ const directory = path.join(target, '.joripspace');
2202
+ fs.mkdirSync(directory, { recursive: true });
2203
+ fs.writeFileSync(path.join(directory, 'template.json'), JSON.stringify({
2204
+ ...state,
2205
+ schema_version: 2,
2206
+ git_head_sha: head,
2207
+ remote_ref: 'refs/remotes/joripspace-template/main',
2208
+ remote_url: remoteUrl,
2209
+ remote_branch_ref: remoteRef
2210
+ }, null, 2) + '\n');
2211
+ }
2212
+ function writeClonedTemplateState(target, slug, source, head) {
2213
+ const directory = path.join(target, '.joripspace');
2214
+ fs.mkdirSync(directory, { recursive: true });
2215
+ fs.writeFileSync(path.join(directory, 'template.json'), JSON.stringify({
2216
+ schema_version: 2,
2217
+ slug,
2218
+ template_id: source.template_id,
2219
+ version_id: source.version_id,
2220
+ version: source.version,
2221
+ git_head_sha: head,
2222
+ remote_ref: 'refs/remotes/joripspace-template/main',
2223
+ remote_url: githubRemoteUrl(source.remote_url),
2224
+ remote_branch_ref: gitBranchRef(source.remote_ref)
2225
+ }, null, 2) + '\n');
2226
+ }
2227
+ function configureTemplateRemote(target, remoteUrl, remoteRef) {
2228
+ const current = gitResult(target, ['config', '--get', 'remote.joripspace-template.url']);
2229
+ if (current.status === 0) {
2230
+ if (String(current.stdout || '').trim() !== remoteUrl) throw new Error('기존 joripspace-template remote가 다른 저장소를 가리킵니다.');
2231
+ } else {
2232
+ git(target, ['remote', 'add', 'joripspace-template', remoteUrl]);
2233
+ }
2234
+ git(target, ['config', '--replace-all', 'remote.joripspace-template.fetch', '+' + remoteRef + ':refs/remotes/joripspace-template/main']);
2235
+ git(target, ['config', '--replace-all', 'remote.joripspace-template.pushurl', 'disabled://joripspace-template-push']);
2236
+ configureTemplateUpstream(target, remoteRef);
2237
+ }
2238
+ function configureTemplateUpstream(target, remoteRef) {
2239
+ const origin = gitResult(target, ['config', '--get', 'remote.origin.url']);
2240
+ if (origin.status === 0 && String(origin.stdout || '').trim()) return;
2241
+ const branch = gitResult(target, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
2242
+ const branchName = String(branch.stdout || '').trim();
2243
+ if (branch.status !== 0 || !branchName) return;
2244
+ git(target, ['config', 'branch.' + branchName + '.remote', 'joripspace-template']);
2245
+ git(target, ['config', 'branch.' + branchName + '.merge', remoteRef]);
2246
+ git(target, ['config', 'branch.' + branchName + '.rebase', 'false']);
2247
+ }
2248
+ function githubRemoteUrl(value) {
2249
+ let url;
2250
+ try { url = new URL(String(value || '')); }
2251
+ catch { throw new Error('템플릿 Git remote URL이 올바르지 않습니다.'); }
2252
+ const parts = url.pathname.replace(/^\/+|\/+$/g, '').split('/');
2253
+ if (url.protocol !== 'https:' || url.hostname.toLowerCase() !== 'github.com' || url.username || url.password || parts.length !== 2 || parts.some((part) => !/^[A-Za-z0-9_.-]+(?:\.git)?$/.test(part))) {
2254
+ throw new Error('템플릿 Git remote URL이 올바르지 않습니다.');
2255
+ }
2256
+ return 'https://github.com/' + parts[0] + '/' + parts[1].replace(/\.git$/i, '') + '.git';
2257
+ }
2258
+ function gitBranchRef(value) {
2259
+ const normalized = String(value || '');
2260
+ if (!/^refs\/heads\/[A-Za-z0-9][A-Za-z0-9._\/-]*$/.test(normalized) || normalized.includes('..')) throw new Error('템플릿 Git remote ref가 올바르지 않습니다.');
2261
+ return normalized;
2262
+ }
2263
+ function readJson(file) {
2264
+ if (!fs.existsSync(file)) return null;
2265
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); }
2266
+ catch { return null; }
2267
+ }
2268
+ function mergeManagedPackageScripts(file, previous) {
2269
+ if (!fs.existsSync(file) || !previous) return;
2270
+ const current = readJson(file);
2271
+ if (!current) return;
2272
+ current.scripts = current.scripts && typeof current.scripts === 'object' ? current.scripts : {};
2273
+ for (const [name, command] of Object.entries(previous.scripts || {})) {
2274
+ if (name.startsWith('joripspace:')) current.scripts[name] = command;
2275
+ }
2276
+ fs.writeFileSync(file, JSON.stringify(current, null, 2) + '\n');
2277
+ }
2278
+ function readOptionalText(file) {
2279
+ return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
2280
+ }
2281
+ function restoreOptionalText(file, value) {
2282
+ if (value !== null && value !== undefined) fs.writeFileSync(file, value);
2283
+ }
2284
+ function mergeGitignore(file, previous) {
2285
+ if (previous === null) return;
2286
+ const current = readOptionalText(file) || '';
2287
+ const lines = current.split(/\r?\n/).filter(Boolean);
2288
+ const seen = new Set(lines);
2289
+ for (const line of previous.split(/\r?\n/).filter(Boolean)) {
2290
+ if (!seen.has(line)) {
2291
+ lines.push(line);
2292
+ seen.add(line);
2293
+ }
2294
+ }
2295
+ fs.writeFileSync(file, lines.join('\n') + '\n');
2296
+ }
2297
+ function isGitRepository(target) {
2298
+ const result = gitResult(target, ['rev-parse', '--is-inside-work-tree']);
2299
+ return result.status === 0 && String(result.stdout || '').trim() === 'true';
2300
+ }
2301
+ function ensureGitIdentity(target) {
2302
+ const name = gitResult(target, ['config', '--get', 'user.name']);
2303
+ const email = gitResult(target, ['config', '--get', 'user.email']);
2304
+ if (name.status !== 0 || email.status !== 0 || !String(name.stdout || '').trim() || !String(email.stdout || '').trim()) {
2305
+ throw new Error('Git user.name과 user.email 설정이 필요합니다.');
2306
+ }
2307
+ }
2308
+ function git(target, values, withoutDirectory = false) {
2309
+ const result = withoutDirectory
2310
+ ? spawnSync('git', values, { encoding: 'utf8', windowsHide: true })
2311
+ : gitResult(target, values);
2312
+ if (result.error?.code === 'ENOENT') throw new Error('git 명령을 찾을 수 없습니다.');
2313
+ if (result.status !== 0) throw new Error(String(result.stderr || result.stdout || 'git 실행 실패').trim());
2314
+ return String(result.stdout || '');
2315
+ }
2316
+ function gitResult(target, values) {
2317
+ return spawnSync('git', ['-C', target, ...values], { encoding: 'utf8', windowsHide: true });
2318
+ }
2319
+ function header(headers, name) {
2320
+ const value = String(headers.get(name) || '').trim();
2321
+ if (!value) throw new Error('템플릿 응답에 ' + name + ' 값이 없습니다.');
2322
+ return value;
2323
+ }
2324
+ function gitSha(value) {
2325
+ const normalized = String(value || '').toLowerCase();
2326
+ if (!/^[0-9a-f]{40}$/.test(normalized)) throw new Error('템플릿 Git SHA가 올바르지 않습니다.');
2327
+ return normalized;
2328
+ }
2329
+ async function responseError(response) {
2330
+ const text = await response.text();
2331
+ try { const parsed = JSON.parse(text); return new Error(parsed?.error?.message || parsed?.message || 'HTTP ' + response.status); }
2332
+ catch { return new Error(text || 'HTTP ' + response.status); }
2333
+ }
2334
+ `;
2335
+ }
2336
+
2337
+ function onboardingGitignoreContent() {
2338
+ return `${JORIPSPACE_ONBOARDING_GITIGNORE_ENTRIES.join('\n')}\n`;
2339
+ }
2340
+
2341
+ function projectAgentSessionFile(projectConfig = {}) {
2342
+ const projectId = String(projectConfig.project_id || '');
2343
+ const projectSlug = String(projectConfig.project_slug || projectId);
2344
+ return `${JSON.stringify(
2345
+ {
2346
+ schema_version: 2,
2347
+ scope: 'shared_workspace',
2348
+ project: {
2349
+ id: projectId,
2350
+ slug: projectSlug,
2351
+ config_file: '.joripspace/project',
2352
+ },
2353
+ agent_guide: {
2354
+ updated_at: String(projectConfig.agent_guide_updated_at || JORIPSPACE_AGENT_GUIDE_UPDATED_AT),
2355
+ },
2356
+ collaboration: {
2357
+ git_tracked: true,
2358
+ },
2359
+ local_auth: {
2360
+ env_file: '.env.joripspace',
2361
+ required_environment: ['JORIPSPACE_API_TOKEN'],
2362
+ credential_values_in_session: false,
2363
+ },
2364
+ },
2365
+ null,
2366
+ 2
2367
+ )}\n`;
2368
+ }
2369
+
2370
+ module.exports = {
2371
+ JORIPSPACE_AGENT_GUIDE_UPDATED_AT,
2372
+ JORIPSPACE_WORKFLOW_POLICY,
2373
+ JORIPSPACE_ONBOARDING_GITIGNORE_ENTRIES,
2374
+ JORIPSPACE_PACKAGE_HELPER_SCRIPTS,
2375
+ JORIPSPACE_PACKAGE_HELPER_DEPENDENCIES,
2376
+ SERVICE_EXAMPLE_LINES,
2377
+ BEGINNER_ONBOARDING_LINES,
2378
+ USER_CHOICE_PRESENTATION_RULE_LINES,
2379
+ LOCAL_TOOL_READINESS_RULE_LINES,
2380
+ GUIDE_REFRESH_ONLY_RULE_LINES,
2381
+ JORIPSPACE_BUILD_DEPLOYMENT_AUTHORITY_LINES,
2382
+ FIRST_QUESTION_LINES,
2383
+ CODEX_MCP_ONBOARDING_LINES,
2384
+ CODEX_MCP_USER_CONNECT_MESSAGE_LINES,
2385
+ SECRET_RULE_LINES,
2386
+ PAYMENT_PROVIDER_GUIDANCE_LINES,
2387
+ PROJECT_CAPABILITY_LINES,
2388
+ REALTIME_DEVELOPMENT_RULE_LINES,
2389
+ PROJECT_PLAN_LIMIT_LINES,
2390
+ PROJECT_DOMAIN_LINES,
2391
+ PROJECT_CRON_LINES,
2392
+ IMAGE_AND_FILE_PLACEMENT_LINES,
2393
+ FRAMEWORK_SELECTION_LINES,
2394
+ SEO_SSR_LINES,
2395
+ FRAMEWORK_DEPLOYMENT_PRIORITY_LINES,
2396
+ AGENT_OPERATING_RULE_LINES,
2397
+ DEPLOYMENT_VERIFICATION_RULE_LINES,
2398
+ CHECKPOINT_AGENT_RULE_LINES,
2399
+ AFTER_CONNECTION_RULE_LINES,
2400
+ REQUIRED_ONBOARDING_MARKERS,
2401
+ beginnerStartPrompt,
2402
+ beginnerStartPrompts,
2403
+ projectAgentsFile,
2404
+ projectClaudeFile,
2405
+ projectMarkerFile,
2406
+ upsertProjectAgentsContent,
2407
+ projectPackageHelperScripts,
2408
+ projectPackageHelperDependencies,
2409
+ projectDoctorHelperFile,
2410
+ projectDeployHelperFile,
2411
+ projectPullHelperFile,
2412
+ projectCheckpointClientFile,
2413
+ projectSaveHelperFile,
2414
+ projectCheckpointsHelperFile,
2415
+ projectRestoreHelperFile,
2416
+ projectDeployCheckpointHelperFile,
2417
+ projectInstallTemplateHelperFile,
2418
+ projectGithubActionsTemplateFile,
2419
+ templateGithubActionsPublishFile,
2420
+ onboardingGitignoreContent,
2421
+ projectAgentSessionFile,
2422
+ JORIPSPACE_ONBOARDING_GITIGNORE_REMOVALS,
2423
+ };