promptlike 0.2.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,45 @@
1
+ # Changelog
2
+
3
+ ## 0.4.0 — 2026-08-10
4
+
5
+ The install is no longer a dead end.
6
+
7
+ ### Local-first mode — no account needed
8
+
9
+ - **`ple save <title>`** writes a prompt to `~/.promptlike/prompts/<slug>.md`
10
+ (body via `-m` or stdin). Plain Markdown with a small frontmatter block —
11
+ greppable, diffable, git-committable.
12
+ - **`list` / `show` / `get` / `copy` / `search` work signed out**, reading the
13
+ local store. Signed in, the same commands read your account library — the
14
+ commands don't change, only where they read from.
15
+ - **`ple sync [--dry-run]`** uploads local prompts into your account — one-way,
16
+ explicit, never automatic on login. Tags travel too when the server supports
17
+ them; when it doesn't, the CLI says so instead of dropping them silently.
18
+ Sync copies; local files are kept.
19
+
20
+ ### Fixes (from the 2026-08-10 audit)
21
+
22
+ - `ple login` now tells you when local prompts exist and how to bring them up
23
+ (`ple sync --dry-run`) — previously they silently disappeared from view
24
+ after signing in.
25
+ - A corrupt session file now warns and falls back to local mode instead of
26
+ silently pretending you never logged in.
27
+ - `ple save` enforces the same limits as the account API (title 200 chars,
28
+ body 100K, description 1000) with clear errors, instead of a raw
29
+ `ENAMETOOLONG` or a silent server-side truncation on sync.
30
+ - Overwriting with `--force` keeps tags and the description you didn't repeat —
31
+ it used to wipe them, unrecoverably.
32
+ - `--project` prints a note when ignored in signed-out mode instead of
33
+ silently returning different results.
34
+
35
+ ### Notes
36
+
37
+ - Local store root is overridable with `PROMPTLIKE_HOME`.
38
+ - `ple get` keeps stdout machine-clean in both modes (warnings go to stderr),
39
+ so piping into an agent behaves identically signed in or out.
40
+
41
+ ## 0.3.x
42
+
43
+ - CLI moved from direct Supabase access to the web API (bearer auth).
44
+ - `ple loop`: test prompt variants against your own agent.
45
+ - `--project` scoping, `ple get --var`, usage recording for Most Used.
package/README.md CHANGED
@@ -6,18 +6,29 @@
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
7
7
  [![Node](https://img.shields.io/badge/node-%E2%89%A518-brightgreen)](https://nodejs.org/)
8
8
 
9
- `ple` lets you reach the prompts you've saved on
10
- [promptlikeengineer.com](https://promptlikeengineer.com) without leaving your
11
- terminal. Search, read, copy. That's it.
9
+ `ple` keeps your prompts one command away. Save, search, read, copy — **no
10
+ account required to start.**
12
11
 
13
12
  ```bash
14
- ple list # see every prompt you've saved
15
- ple copy "code review" # find by title and copy to clipboard
13
+ npm i -g promptlike
14
+ ple save "code review" -m "Review this diff and flag risks: {{diff}}"
15
+ ple get "code review" --var diff="$(git diff)" | claude
16
16
  ```
17
17
 
18
- The CLI talks to the same PromptLikeEngineer web API your account uses, so
19
- anything you save on the web is instantly available here. You need a (free)
20
- PromptLikeEngineer account to log in.
18
+ Prompts live as plain Markdown files in `~/.promptlike/prompts/` — greppable,
19
+ diffable, and yours. Nothing leaves your machine until you ask it to.
20
+
21
+ **Signing in is the upgrade, not the door.** A free
22
+ [promptlikeengineer.com](https://promptlikeengineer.com) account adds version
23
+ history with diff and rollback, the web editor, the Chrome extension, and the
24
+ same library inside any MCP client. Bring your local prompts up with one
25
+ explicit command:
26
+
27
+ ```bash
28
+ ple login
29
+ ple sync --dry-run # see exactly what would be uploaded
30
+ ple sync # one-way, local → account; local files are kept
31
+ ```
21
32
 
22
33
  ---
23
34
 
@@ -66,6 +77,38 @@ Cursor, your shell, anywhere — `ple` doesn't know or care.
66
77
 
67
78
  ## Commands
68
79
 
80
+ > **Signed out, every read command uses the local store; signed in, the same
81
+ > command uses your account library.** The commands do not change — only where
82
+ > they read from.
83
+
84
+ ### `ple save <title>` — no account needed
85
+
86
+ Writes a prompt to `~/.promptlike/prompts/<slug>.md`. Body comes from
87
+ `-m/--message` or from stdin.
88
+
89
+ ```bash
90
+ $ ple save "code review" -m "Review this diff: {{diff}}" -t review
91
+ ✓ Saved: code review (code-review)
92
+ ~/.promptlike/prompts/code-review.md
93
+ variables: {{diff}}
94
+ use it: ple get "code-review" --var diff=...
95
+
96
+ $ pbpaste | ple save "bug triage" # or pipe it in
97
+ ```
98
+
99
+ Saving over an existing prompt needs `--force`, because the local store keeps
100
+ no version history. Tags and the description you do not repeat are carried
101
+ over rather than wiped.
102
+
103
+ ### `ple sync [--dry-run]`
104
+
105
+ Uploads local prompts into your signed-in account. **Explicit on purpose** —
106
+ nothing is uploaded when you log in, only when you ask.
107
+
108
+ One-way (local → account) and it *copies*: your local files stay where they
109
+ are, so running it twice uploads twice. `--dry-run` prints the list and
110
+ changes nothing.
111
+
69
112
  ### `ple login`
70
113
 
71
114
  Authenticates with email + password and stores the session at
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.copyCommand = copyCommand;
4
4
  const api_client_1 = require("../lib/api-client");
5
+ const local_1 = require("./local");
5
6
  const promptResolver_1 = require("../lib/promptResolver");
6
7
  const clipboard_1 = require("../lib/clipboard");
7
8
  const format_1 = require("../lib/format");
@@ -9,9 +10,15 @@ const format_1 = require("../lib/format");
9
10
  * `ple copy <name>` — resolve a prompt by title (or short id) and copy its
10
11
  * content to the system clipboard.
11
12
  */
12
- async function copyCommand(name) {
13
+ async function copyCommand(name, options = {}) {
14
+ if ((0, local_1.isSignedOut)()) {
15
+ (0, local_1.noteIgnoredProject)(options.project);
16
+ await (0, local_1.localCopy)(name);
17
+ return;
18
+ }
13
19
  await (0, api_client_1.ensureAuthed)();
14
- const prompt = await (0, promptResolver_1.resolvePromptByName)(name);
20
+ const projectId = options.project ? await (0, promptResolver_1.resolveProjectId)(options.project) : undefined;
21
+ const prompt = await (0, promptResolver_1.resolvePromptByName)(name, { projectId });
15
22
  if (!prompt) {
16
23
  process.exitCode = 1;
17
24
  return;
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getCommand = getCommand;
4
4
  exports.collectVar = collectVar;
5
5
  const api_client_1 = require("../lib/api-client");
6
+ const local_1 = require("./local");
6
7
  const promptResolver_1 = require("../lib/promptResolver");
7
8
  const clipboard_1 = require("../lib/clipboard");
8
9
  const format_1 = require("../lib/format");
@@ -20,8 +21,14 @@ const promptVariables_1 = require("../lib/promptVariables");
20
21
  * ple get "code review" --var lang=python | claude # pipe to an agent
21
22
  */
22
23
  async function getCommand(name, options = {}) {
24
+ if ((0, local_1.isSignedOut)()) {
25
+ (0, local_1.noteIgnoredProject)(options.project);
26
+ await (0, local_1.localGet)(name, options.var ?? {}, options.copy === true);
27
+ return;
28
+ }
23
29
  await (0, api_client_1.ensureAuthed)();
24
- const prompt = await (0, promptResolver_1.resolvePromptByName)(name);
30
+ const projectId = options.project ? await (0, promptResolver_1.resolveProjectId)(options.project) : undefined;
31
+ const prompt = await (0, promptResolver_1.resolvePromptByName)(name, { projectId });
25
32
  if (!prompt) {
26
33
  process.exitCode = 1;
27
34
  return;
@@ -37,7 +37,8 @@ function parsePick(raw, max) {
37
37
  */
38
38
  async function improveCommand(name, options = {}) {
39
39
  await (0, api_client_1.ensureAuthed)();
40
- const prompt = await (0, promptResolver_1.resolvePromptByName)(name);
40
+ const projectId = options.project ? await (0, promptResolver_1.resolveProjectId)(options.project) : undefined;
41
+ const prompt = await (0, promptResolver_1.resolvePromptByName)(name, { projectId });
41
42
  if (!prompt) {
42
43
  process.exitCode = 1;
43
44
  return;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.listCommand = listCommand;
4
4
  const api_client_1 = require("../lib/api-client");
5
+ const local_1 = require("./local");
5
6
  const constants_1 = require("../lib/constants");
6
7
  const format_1 = require("../lib/format");
7
8
  /**
@@ -13,6 +14,11 @@ const format_1 = require("../lib/format");
13
14
  */
14
15
  async function listCommand(options) {
15
16
  const limit = Math.max(1, Math.min(100, parseInt(options.limit ?? '30', 10) || 30));
17
+ // Signed out → the local store. The install has to be useful on its own.
18
+ if ((0, local_1.isSignedOut)()) {
19
+ (0, local_1.localList)({ tag: options.tag, limit });
20
+ return;
21
+ }
16
22
  await (0, api_client_1.ensureAuthed)();
17
23
  const prompts = await (0, api_client_1.listPrompts)({ tag: options.tag, limit });
18
24
  if (prompts.length === 0) {
@@ -0,0 +1,204 @@
1
+ "use strict";
2
+ /**
3
+ * Logged-out implementations of the read commands.
4
+ *
5
+ * Every read command routes here when there is no session, so the CLI does
6
+ * real work the moment it is installed. The signed-in behaviour is untouched.
7
+ */
8
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
+ if (k2 === undefined) k2 = k;
10
+ var desc = Object.getOwnPropertyDescriptor(m, k);
11
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
+ desc = { enumerable: true, get: function() { return m[k]; } };
13
+ }
14
+ Object.defineProperty(o, k2, desc);
15
+ }) : (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ o[k2] = m[k];
18
+ }));
19
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
20
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
21
+ }) : function(o, v) {
22
+ o["default"] = v;
23
+ });
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.isSignedOut = isSignedOut;
43
+ exports.noteIgnoredProject = noteIgnoredProject;
44
+ exports.emptyHint = emptyHint;
45
+ exports.localList = localList;
46
+ exports.localShow = localShow;
47
+ exports.localGet = localGet;
48
+ exports.localCopy = localCopy;
49
+ exports.localSearch = localSearch;
50
+ const store = __importStar(require("../lib/localStore"));
51
+ const config_1 = require("../lib/config");
52
+ const clipboard_1 = require("../lib/clipboard");
53
+ const format_1 = require("../lib/format");
54
+ const promptVariables_1 = require("../lib/promptVariables");
55
+ /**
56
+ * Routing guard for the read commands: true → use the local store.
57
+ *
58
+ * A corrupt session file routes local like an absent one, but says so first —
59
+ * a signed-in user silently dropped into an (often empty) local list reads it
60
+ * as data loss.
61
+ */
62
+ function isSignedOut() {
63
+ const status = (0, config_1.configStatus)();
64
+ if (status === 'invalid') {
65
+ console.error(format_1.c.warn('⚠ Session file exists but is unreadable — showing local prompts instead.'));
66
+ console.error(format_1.c.muted(' Fix it by signing in again: ple login'));
67
+ }
68
+ return status !== 'valid';
69
+ }
70
+ /**
71
+ * `--project` scopes account repos; local prompts have no projects. Saying so
72
+ * beats silently returning different results than the user asked for.
73
+ */
74
+ function noteIgnoredProject(project) {
75
+ if (project) {
76
+ console.error(format_1.c.muted(`(--project '${project}' is ignored while signed out — local prompts have no projects)`));
77
+ }
78
+ }
79
+ /** Shown once when a command finds nothing locally — never nags mid-flow. */
80
+ function emptyHint() {
81
+ console.log(format_1.c.muted('No local prompts yet.'));
82
+ console.log(format_1.c.muted(' Save one: ple save "code review" -m "Review this diff: {{diff}}"'));
83
+ console.log(format_1.c.muted(' Or sign in to use your account library: ple login'));
84
+ }
85
+ /** Resolve or explain. Returns null when the caller should stop (exit code set). */
86
+ function resolveOrExplain(name) {
87
+ const hit = store.resolve(name);
88
+ if (hit === null) {
89
+ console.error(format_1.c.error(`No local prompt matched '${name}'.`));
90
+ console.error(format_1.c.muted("Run `ple list` to see what you have, or `ple login` for your account library."));
91
+ process.exitCode = 1;
92
+ return null;
93
+ }
94
+ if ('candidates' in hit) {
95
+ console.error(format_1.c.error(`'${name}' matches ${hit.candidates.length} prompts:`));
96
+ for (const p of hit.candidates)
97
+ console.error(format_1.c.muted(` ${p.slug} ${p.title}`));
98
+ console.error(format_1.c.muted('Re-run with the exact name on the left.'));
99
+ process.exitCode = 1;
100
+ return null;
101
+ }
102
+ return hit.prompt;
103
+ }
104
+ function localList(options) {
105
+ let rows = store.list();
106
+ if (options.tag) {
107
+ const tag = options.tag.toLowerCase();
108
+ rows = rows.filter((p) => p.tags.some((t) => t.toLowerCase() === tag));
109
+ }
110
+ if (rows.length === 0) {
111
+ if (options.tag)
112
+ console.log(format_1.c.muted(`No local prompts tagged '${options.tag}'.`));
113
+ else
114
+ emptyHint();
115
+ return;
116
+ }
117
+ rows = rows.slice(0, options.limit);
118
+ console.log(format_1.c.label('NAME TITLE UPDATED'));
119
+ console.log(format_1.c.label('──────────────────────── ──────────────────────────────────────── ──────────'));
120
+ for (const p of rows) {
121
+ const slug = format_1.c.muted((0, format_1.truncate)(p.slug, 24).padEnd(24));
122
+ const title = (0, format_1.truncate)(p.title, 40).padEnd(40);
123
+ const updated = format_1.c.muted(p.updated ? (0, format_1.timeAgo)(p.updated) : '');
124
+ console.log(`${slug} ${title} ${updated}`);
125
+ }
126
+ console.log(format_1.c.muted(`\n${rows.length} local prompt${rows.length === 1 ? '' : 's'} · stored in ${store.promptsDir()}`));
127
+ }
128
+ function localShow(name) {
129
+ const p = resolveOrExplain(name);
130
+ if (!p)
131
+ return;
132
+ console.log();
133
+ console.log(format_1.c.title(p.title));
134
+ const meta = [p.slug, p.updated ? `updated ${(0, format_1.timeAgo)(p.updated)}` : ''].filter(Boolean).join(' · ');
135
+ console.log(format_1.c.muted(meta));
136
+ if (p.description) {
137
+ console.log();
138
+ console.log(format_1.c.label(p.description));
139
+ }
140
+ console.log();
141
+ console.log(p.body);
142
+ console.log();
143
+ if (p.tags.length > 0)
144
+ console.log(format_1.c.muted(`tags: ${p.tags.join(', ')}`));
145
+ }
146
+ async function localGet(name, values, copy) {
147
+ const p = resolveOrExplain(name);
148
+ if (!p)
149
+ return;
150
+ if (!p.body.trim()) {
151
+ console.error(format_1.c.error(`'${p.title}' has empty content.`));
152
+ process.exitCode = 1;
153
+ return;
154
+ }
155
+ const { text } = store.fillVariables(p.body, values);
156
+ // stdout stays machine-clean; warnings go to stderr (same contract as the
157
+ // signed-in `ple get`, so piping behaves identically either way).
158
+ const remaining = (0, promptVariables_1.extractVariables)(text);
159
+ if (remaining.length > 0) {
160
+ console.error(format_1.c.warn(`⚠ Unfilled variables: ${remaining.map((v) => `{{${v}}}`).join(', ')}`));
161
+ }
162
+ process.stdout.write(text.endsWith('\n') ? text : `${text}\n`);
163
+ if (copy) {
164
+ try {
165
+ await (0, clipboard_1.copyToClipboard)(text);
166
+ console.error(format_1.c.success('✓ Copied to clipboard'));
167
+ }
168
+ catch {
169
+ console.error(format_1.c.warn('⚠ Could not copy to clipboard'));
170
+ }
171
+ }
172
+ }
173
+ async function localCopy(name) {
174
+ const p = resolveOrExplain(name);
175
+ if (!p)
176
+ return;
177
+ if (!p.body.trim()) {
178
+ console.error(format_1.c.error(`'${p.title}' has empty content.`));
179
+ process.exitCode = 1;
180
+ return;
181
+ }
182
+ try {
183
+ await (0, clipboard_1.copyToClipboard)(p.body);
184
+ console.log(format_1.c.success(`✓ Copied: ${p.title}`) + format_1.c.muted(` (${p.slug}, ${p.body.length} chars)`));
185
+ }
186
+ catch {
187
+ console.error(format_1.c.error('Could not access the clipboard.'));
188
+ process.exitCode = 1;
189
+ }
190
+ }
191
+ function localSearch(keyword) {
192
+ const rows = store.search(keyword);
193
+ if (rows.length === 0) {
194
+ console.log(format_1.c.muted(`No local prompts matched '${keyword}'.`));
195
+ return;
196
+ }
197
+ console.log(format_1.c.label(`${rows.length} result${rows.length === 1 ? '' : 's'}:`));
198
+ console.log();
199
+ for (const p of rows) {
200
+ console.log(`${format_1.c.title(p.title)} ${format_1.c.muted(`· ${p.slug}${p.updated ? ` · ${(0, format_1.timeAgo)(p.updated)}` : ''}`)}`);
201
+ if (p.description)
202
+ console.log(format_1.c.muted(` ${(0, format_1.truncate)(p.description, 80)}`));
203
+ }
204
+ }
@@ -37,6 +37,7 @@ exports.loginCommand = loginCommand;
37
37
  const readline = __importStar(require("readline"));
38
38
  const stream_1 = require("stream");
39
39
  const api_client_1 = require("../lib/api-client");
40
+ const store = __importStar(require("../lib/localStore"));
40
41
  const format_1 = require("../lib/format");
41
42
  /**
42
43
  * `ple login` — sign in with email + password via the web API.
@@ -61,6 +62,14 @@ async function loginCommand() {
61
62
  const config = await (0, api_client_1.login)(email, password);
62
63
  console.log(format_1.c.success(`✓ Logged in as ${config.email}`));
63
64
  console.log(format_1.c.muted("Next: run 'ple list' to see your prompts."));
65
+ // The commands now read from the ACCOUNT library, so prompts saved while
66
+ // signed out stop showing up. Without this line that reads as data loss —
67
+ // the files are fine, the bridge is `ple sync`, but nothing said so.
68
+ const localCount = store.list().length;
69
+ if (localCount > 0) {
70
+ console.log(format_1.c.muted(`${localCount} local prompt${localCount === 1 ? '' : 's'} on this machine are not shown while signed in — ` +
71
+ 'bring them into your account: ple sync --dry-run'));
72
+ }
64
73
  }
65
74
  /** Read a single line with standard readline. */
66
75
  function prompt(question) {
@@ -32,7 +32,8 @@ function parseRounds(raw) {
32
32
  async function loopCommand(name, options = {}) {
33
33
  const rounds = parseRounds(options.rounds);
34
34
  await (0, api_client_1.ensureAuthed)();
35
- const prompt = await (0, promptResolver_1.resolvePromptByName)(name);
35
+ const projectId = options.project ? await (0, promptResolver_1.resolveProjectId)(options.project) : undefined;
36
+ const prompt = await (0, promptResolver_1.resolvePromptByName)(name, { projectId });
36
37
  if (!prompt) {
37
38
  process.exitCode = 1;
38
39
  return;
@@ -0,0 +1,146 @@
1
+ "use strict";
2
+ /**
3
+ * `ple save <title>` — write a prompt to the local store. **No account needed.**
4
+ *
5
+ * This is the command that makes `npm i -g promptlike` worth something on its
6
+ * own. Body comes from `-m/--message`, or from stdin when piped:
7
+ *
8
+ * ple save "code review" -m "Review this diff: {{diff}}"
9
+ * pbpaste | ple save "code review"
10
+ * cat prompt.txt | ple save "code review" --tag review
11
+ */
12
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ var desc = Object.getOwnPropertyDescriptor(m, k);
15
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
16
+ desc = { enumerable: true, get: function() { return m[k]; } };
17
+ }
18
+ Object.defineProperty(o, k2, desc);
19
+ }) : (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = k;
21
+ o[k2] = m[k];
22
+ }));
23
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
24
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
25
+ }) : function(o, v) {
26
+ o["default"] = v;
27
+ });
28
+ var __importStar = (this && this.__importStar) || (function () {
29
+ var ownKeys = function(o) {
30
+ ownKeys = Object.getOwnPropertyNames || function (o) {
31
+ var ar = [];
32
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
33
+ return ar;
34
+ };
35
+ return ownKeys(o);
36
+ };
37
+ return function (mod) {
38
+ if (mod && mod.__esModule) return mod;
39
+ var result = {};
40
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
41
+ __setModuleDefault(result, mod);
42
+ return result;
43
+ };
44
+ })();
45
+ Object.defineProperty(exports, "__esModule", { value: true });
46
+ exports.collectTag = collectTag;
47
+ exports.saveCommand = saveCommand;
48
+ const store = __importStar(require("../lib/localStore"));
49
+ const format_1 = require("../lib/format");
50
+ const promptVariables_1 = require("../lib/promptVariables");
51
+ /**
52
+ * Same caps the web API enforces (title 200 / body 100K / description 1000).
53
+ * The CLI mirrors them instead of letting `ple sync` discover the mismatch:
54
+ * the server would silently slice, and local ≠ account is exactly the kind of
55
+ * divergence this tool exists to prevent. A too-long title also has a second
56
+ * failure mode of its own — the 255-byte filename limit throws a raw
57
+ * ENAMETOOLONG with no explanation.
58
+ */
59
+ const MAX_TITLE = 200;
60
+ const MAX_BODY = 100000;
61
+ const MAX_DESCRIPTION = 1000;
62
+ /** Collector for repeatable `--tag`. */
63
+ function collectTag(value, previous) {
64
+ return [...previous, value];
65
+ }
66
+ /** Read piped stdin. Returns '' when the CLI is attached to a terminal. */
67
+ function readStdin() {
68
+ if (process.stdin.isTTY)
69
+ return Promise.resolve('');
70
+ return new Promise((resolve) => {
71
+ let data = '';
72
+ let overflowed = false;
73
+ process.stdin.setEncoding('utf-8');
74
+ process.stdin.on('data', (chunk) => {
75
+ // Stop buffering once the input cannot possibly be valid — a
76
+ // mistakenly piped log file must not be read into memory whole.
77
+ // One chunk past the cap is kept so the size check can report
78
+ // "too long" instead of an off-by-one "just fits".
79
+ if (overflowed)
80
+ return;
81
+ data += chunk;
82
+ if (data.length > MAX_BODY + 1)
83
+ overflowed = true;
84
+ });
85
+ process.stdin.on('end', () => resolve(data));
86
+ process.stdin.on('error', () => resolve(''));
87
+ });
88
+ }
89
+ async function saveCommand(title, options = {}) {
90
+ const cleanTitle = title.trim();
91
+ if (!cleanTitle) {
92
+ console.error(format_1.c.error('Title is empty.'));
93
+ process.exitCode = 1;
94
+ return;
95
+ }
96
+ if (cleanTitle.length > MAX_TITLE) {
97
+ console.error(format_1.c.error(`Title is too long (${cleanTitle.length} chars, max ${MAX_TITLE}).`));
98
+ process.exitCode = 1;
99
+ return;
100
+ }
101
+ if (options.description && options.description.length > MAX_DESCRIPTION) {
102
+ console.error(format_1.c.error(`Description is too long (max ${MAX_DESCRIPTION} chars).`));
103
+ process.exitCode = 1;
104
+ return;
105
+ }
106
+ const body = (options.message ?? (await readStdin())).trim();
107
+ if (body.length > MAX_BODY) {
108
+ console.error(format_1.c.error(`Prompt body is too long (over ${MAX_BODY.toLocaleString('en-US')} chars).`));
109
+ console.error(format_1.c.muted('That limit matches the account API — a bigger body could never sync.'));
110
+ process.exitCode = 1;
111
+ return;
112
+ }
113
+ if (!body) {
114
+ console.error(format_1.c.error('No prompt body.'));
115
+ console.error(format_1.c.muted(' ple save "code review" -m "Review this diff: {{diff}}"'));
116
+ console.error(format_1.c.muted(' pbpaste | ple save "code review"'));
117
+ process.exitCode = 1;
118
+ return;
119
+ }
120
+ const slug = store.slugify(cleanTitle);
121
+ // Overwriting someone's prompt silently is the one unrecoverable thing this
122
+ // command could do — the local store keeps no versions.
123
+ if (store.exists(slug) && !options.force) {
124
+ console.error(format_1.c.error(`'${slug}' already exists.`));
125
+ console.error(format_1.c.muted('Overwrite it with --force, or pick a different title.'));
126
+ process.exitCode = 1;
127
+ return;
128
+ }
129
+ // On --force, fields the user did not re-specify are CARRIED OVER.
130
+ // Overwriting the body must not silently wipe tags and the description —
131
+ // the local store keeps no versions, so that loss is unrecoverable.
132
+ const previous = store.read(slug);
133
+ const tags = options.tag && options.tag.length > 0 ? options.tag : (previous?.tags ?? []);
134
+ const description = options.description?.trim() ?? previous?.description ?? '';
135
+ const saved = store.save({ slug, title: cleanTitle, description, tags, body });
136
+ console.log(format_1.c.success(`✓ Saved: ${saved.title}`) + format_1.c.muted(` (${saved.slug})`));
137
+ console.log(format_1.c.muted(` ${store.filePath(saved.slug)}`));
138
+ const vars = (0, promptVariables_1.extractVariables)(saved.body);
139
+ if (vars.length > 0) {
140
+ console.log(format_1.c.muted(` variables: ${vars.map((v) => `{{${v}}}`).join(', ')}`));
141
+ console.log(format_1.c.muted(` use it: ple get "${saved.slug}" --var ${vars[0]}=...`));
142
+ }
143
+ else {
144
+ console.log(format_1.c.muted(` use it: ple copy "${saved.slug}"`));
145
+ }
146
+ }
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.searchCommand = searchCommand;
4
4
  const api_client_1 = require("../lib/api-client");
5
+ const local_1 = require("./local");
5
6
  const format_1 = require("../lib/format");
6
7
  /**
7
8
  * `ple search <keyword>` — search over title + description.
@@ -17,6 +18,10 @@ async function searchCommand(keyword) {
17
18
  process.exitCode = 1;
18
19
  return;
19
20
  }
21
+ if ((0, local_1.isSignedOut)()) {
22
+ (0, local_1.localSearch)(trimmed);
23
+ return;
24
+ }
20
25
  await (0, api_client_1.ensureAuthed)();
21
26
  const rows = await (0, api_client_1.listPrompts)({ search: trimmed, limit: 30 });
22
27
  if (rows.length === 0) {
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.showCommand = showCommand;
4
4
  const api_client_1 = require("../lib/api-client");
5
+ const local_1 = require("./local");
5
6
  const promptResolver_1 = require("../lib/promptResolver");
6
7
  const format_1 = require("../lib/format");
7
8
  /**
@@ -10,9 +11,15 @@ const format_1 = require("../lib/format");
10
11
  * Unlike `copy`, this doesn't touch the clipboard: it renders the three
11
12
  * sections (role / description / context) under readable headers.
12
13
  */
13
- async function showCommand(name) {
14
+ async function showCommand(name, options = {}) {
15
+ if ((0, local_1.isSignedOut)()) {
16
+ (0, local_1.noteIgnoredProject)(options.project);
17
+ (0, local_1.localShow)(name);
18
+ return;
19
+ }
14
20
  await (0, api_client_1.ensureAuthed)();
15
- const prompt = await (0, promptResolver_1.resolvePromptByName)(name);
21
+ const projectId = options.project ? await (0, promptResolver_1.resolveProjectId)(options.project) : undefined;
22
+ const prompt = await (0, promptResolver_1.resolvePromptByName)(name, { projectId });
16
23
  if (!prompt) {
17
24
  process.exitCode = 1;
18
25
  return;
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ /**
3
+ * `ple sync` — upload the local store into the signed-in account.
4
+ *
5
+ * DELIBERATELY EXPLICIT, never automatic on login. Silently uploading files a
6
+ * developer keeps on their own machine is the kind of surprise that costs
7
+ * trust permanently, and this audience notices. So local stays local until
8
+ * someone asks for it.
9
+ *
10
+ * One-way (local → account) on purpose. Pulling the account library down would
11
+ * need conflict rules the local store cannot express — it keeps no versions —
12
+ * and a half-correct merge silently losing an edit is worse than no pull.
13
+ */
14
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ var desc = Object.getOwnPropertyDescriptor(m, k);
17
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
18
+ desc = { enumerable: true, get: function() { return m[k]; } };
19
+ }
20
+ Object.defineProperty(o, k2, desc);
21
+ }) : (function(o, m, k, k2) {
22
+ if (k2 === undefined) k2 = k;
23
+ o[k2] = m[k];
24
+ }));
25
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
26
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
27
+ }) : function(o, v) {
28
+ o["default"] = v;
29
+ });
30
+ var __importStar = (this && this.__importStar) || (function () {
31
+ var ownKeys = function(o) {
32
+ ownKeys = Object.getOwnPropertyNames || function (o) {
33
+ var ar = [];
34
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
35
+ return ar;
36
+ };
37
+ return ownKeys(o);
38
+ };
39
+ return function (mod) {
40
+ if (mod && mod.__esModule) return mod;
41
+ var result = {};
42
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
43
+ __setModuleDefault(result, mod);
44
+ return result;
45
+ };
46
+ })();
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.syncCommand = syncCommand;
49
+ const store = __importStar(require("../lib/localStore"));
50
+ const api_client_1 = require("../lib/api-client");
51
+ const format_1 = require("../lib/format");
52
+ /** The import endpoint caps one request at 50 records. */
53
+ const BATCH = 50;
54
+ async function syncCommand(options = {}) {
55
+ const local = store.list().filter((p) => p.body.trim());
56
+ if (local.length === 0) {
57
+ console.log(format_1.c.muted('Nothing to sync — the local store is empty.'));
58
+ console.log(format_1.c.muted(' ple save "code review" -m "Review this diff: {{diff}}"'));
59
+ return;
60
+ }
61
+ if (options.dryRun) {
62
+ console.log(format_1.c.label(`${local.length} local prompt${local.length === 1 ? '' : 's'} would be uploaded:`));
63
+ for (const p of local)
64
+ console.log(format_1.c.muted(` ${p.slug} ${p.title}`));
65
+ console.log(format_1.c.muted('\nRun `ple sync` without --dry-run to upload.'));
66
+ return;
67
+ }
68
+ await (0, api_client_1.ensureAuthed)();
69
+ const payload = local.map((p) => ({
70
+ title: p.title,
71
+ description: p.description,
72
+ content: p.body,
73
+ tags: p.tags,
74
+ }));
75
+ let imported = 0;
76
+ let failed = 0;
77
+ let skippedInvalid = 0;
78
+ let truncatedByQuota = 0;
79
+ let tagsApplied = 0;
80
+ let serverCarriesTags = true;
81
+ for (let i = 0; i < payload.length; i += BATCH) {
82
+ const res = await (0, api_client_1.importPrompts)(payload.slice(i, i + BATCH));
83
+ imported += res.imported;
84
+ failed += res.failed;
85
+ skippedInvalid += res.skippedInvalid;
86
+ truncatedByQuota += res.truncatedByQuota;
87
+ if (res.tagsApplied === undefined)
88
+ serverCarriesTags = false;
89
+ else
90
+ tagsApplied += res.tagsApplied;
91
+ }
92
+ const tagNote = serverCarriesTags && tagsApplied > 0 ? ` (+${tagsApplied} tag link${tagsApplied === 1 ? '' : 's'})` : '';
93
+ console.log(format_1.c.success(`✓ Uploaded ${imported} prompt${imported === 1 ? '' : 's'}${tagNote}`));
94
+ // Each shortfall gets its own line with its own fix — "12 of 20 synced"
95
+ // with no reason is the kind of message that sends people to support.
96
+ if (truncatedByQuota > 0) {
97
+ console.log(format_1.c.warn(`⚠ ${truncatedByQuota} not uploaded — plan prompt limit reached.`));
98
+ console.log(format_1.c.muted(' Upgrade for unlimited prompts, then run `ple sync` again.'));
99
+ }
100
+ if (skippedInvalid > 0) {
101
+ console.log(format_1.c.warn(`⚠ ${skippedInvalid} skipped — missing a title or body.`));
102
+ }
103
+ if (failed > 0) {
104
+ console.log(format_1.c.warn(`⚠ ${failed} failed to import. Re-run \`ple sync\` to retry those.`));
105
+ }
106
+ // Tags travel since the server started answering with `tagsApplied`. An
107
+ // older deployment ignores the field silently — that is the one case where
108
+ // losing tags without a word would betray the "local ≠ account" promise.
109
+ if (!serverCarriesTags && local.some((p) => p.tags.length > 0)) {
110
+ console.log(format_1.c.muted('Note: tags stayed local — this server does not carry them yet.'));
111
+ }
112
+ // Local files are NOT deleted: sync copies, it does not move. Re-running
113
+ // would duplicate, so say so rather than letting someone find out.
114
+ console.log(format_1.c.muted(`\nLocal files kept in ${store.promptsDir()} (sync copies, it does not move).`));
115
+ console.log(format_1.c.muted('Re-running would upload them again — delete the local copies first if that is not what you want.'));
116
+ }
package/dist/index.js CHANGED
@@ -20,6 +20,8 @@ const search_1 = require("./commands/search");
20
20
  const get_1 = require("./commands/get");
21
21
  const improve_1 = require("./commands/improve");
22
22
  const loop_1 = require("./commands/loop");
23
+ const save_1 = require("./commands/save");
24
+ const sync_1 = require("./commands/sync");
23
25
  /** A single global try/catch — consistent error output for every command. */
24
26
  function runWithErrorHandler(fn) {
25
27
  return async (...args) => {
@@ -38,6 +40,19 @@ program
38
40
  .name(constants_1.CLI_NAME)
39
41
  .description('Terminal access to your PromptLikeEngineer prompt library')
40
42
  .version(constants_1.CLI_VERSION);
43
+ program
44
+ .command('save <title>')
45
+ .description('Save a prompt locally — no account needed')
46
+ .option('-m, --message <text>', 'Prompt body (or pipe it via stdin)')
47
+ .option('-d, --description <text>', 'Short description')
48
+ .option('-t, --tag <name>', 'Tag (repeatable)', save_1.collectTag, [])
49
+ .option('-f, --force', 'Overwrite an existing local prompt')
50
+ .action(runWithErrorHandler(save_1.saveCommand));
51
+ program
52
+ .command('sync')
53
+ .description('Upload your local prompts to your account (one-way, explicit)')
54
+ .option('--dry-run', 'List what would be uploaded, change nothing')
55
+ .action(runWithErrorHandler(sync_1.syncCommand));
41
56
  program
42
57
  .command('login')
43
58
  .description('Sign in with email + password; store the session under ~/.config/promptlike/')
@@ -55,22 +70,26 @@ program
55
70
  program
56
71
  .command('copy <name>')
57
72
  .description('Copy a prompt to the clipboard (by title or short id)')
73
+ .option('--project <repo>', 'Scope to one repo (name, slug, or id) when titles collide')
58
74
  .action(runWithErrorHandler(copy_1.copyCommand));
59
75
  program
60
76
  .command('show <name>')
61
77
  .description('Show a prompt in the terminal')
78
+ .option('--project <repo>', 'Scope to one repo (name, slug, or id) when titles collide')
62
79
  .action(runWithErrorHandler(show_1.showCommand));
63
80
  program
64
81
  .command('get <name>')
65
82
  .description("Print a prompt raw to stdout; fill {{variables}} (agent/pipe friendly)")
66
83
  .option('-v, --var <keyval>', 'Fill a variable — key=value (repeatable)', get_1.collectVar, {})
67
84
  .option('-c, --copy', 'Also copy the output to the clipboard')
85
+ .option('--project <repo>', 'Scope to one repo (name, slug, or id) when titles collide')
68
86
  .action(runWithErrorHandler(get_1.getCommand));
69
87
  program
70
88
  .command('improve <name>')
71
89
  .option('-p, --pick <n>', 'Non-interactive: auto-pick variant N (1..3), 0 to cancel — for scripts/agents')
72
90
  .description('Generate AI variants of a prompt, pick a winner, save it as a new version (Pro)')
73
91
  .option('-f, --focus <hint>', "Steer the variants (e.g. 'shorter', 'more explicit output format')")
92
+ .option('--project <repo>', 'Scope to one repo (name, slug, or id) when titles collide')
74
93
  .action(runWithErrorHandler(improve_1.improveCommand));
75
94
  program
76
95
  .command('loop <name>')
@@ -79,6 +98,7 @@ program
79
98
  .option('-r, --rounds <n>', 'Number of improvement rounds', '1')
80
99
  .option('-f, --focus <hint>', 'Steer the variants')
81
100
  .option('-p, --pick <n>', 'Non-interactive: auto-pick variant N each round + auto-continue — for scripts/agents')
101
+ .option('--project <repo>', 'Scope to one repo (name, slug, or id) when titles collide')
82
102
  .action(runWithErrorHandler(loop_1.loopCommand));
83
103
  program
84
104
  .command('search <keyword>')
@@ -17,6 +17,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.login = login;
18
18
  exports.ensureAuthed = ensureAuthed;
19
19
  exports.listPrompts = listPrompts;
20
+ exports.importPrompts = importPrompts;
21
+ exports.listProjects = listProjects;
20
22
  exports.getPromptById = getPromptById;
21
23
  exports.recordPromptUse = recordPromptUse;
22
24
  const constants_1 = require("./constants");
@@ -172,7 +174,7 @@ async function ensureAuthed() {
172
174
  await refreshSession();
173
175
  }
174
176
  }
175
- /** GET /api/prompts — list the user's prompts (optionally by tag / search). */
177
+ /** GET /api/prompts — list the user's prompts (optionally by tag / search / project). */
176
178
  async function listPrompts(params = {}) {
177
179
  const res = await apiFetch('/api/prompts', {
178
180
  query: {
@@ -180,10 +182,39 @@ async function listPrompts(params = {}) {
180
182
  search: params.search,
181
183
  limit: params.limit,
182
184
  page: params.page,
185
+ projectId: params.projectId,
183
186
  },
184
187
  });
185
188
  return res.prompts ?? [];
186
189
  }
190
+ /**
191
+ * POST /api/prompts/import — bulk-upload prompts into the account.
192
+ *
193
+ * Used by `ple sync` to carry the local store up after someone signs in. The
194
+ * endpoint caps a request at 50 records and enforces plan limits itself, so
195
+ * the caller batches and reports whatever came back rather than assuming
196
+ * everything landed.
197
+ */
198
+ async function importPrompts(prompts) {
199
+ const res = await apiFetch('/api/prompts/import', {
200
+ method: 'POST',
201
+ body: { prompts },
202
+ });
203
+ return {
204
+ imported: res.imported ?? 0,
205
+ failed: res.failed ?? 0,
206
+ skippedInvalid: res.skippedInvalid ?? 0,
207
+ truncatedByQuota: res.truncatedByQuota ?? 0,
208
+ tagsApplied: res.tagsApplied,
209
+ };
210
+ }
211
+ /** GET /api/projects — list the user's accessible repos (for --project resolution). */
212
+ async function listProjects() {
213
+ const res = await apiFetch('/api/projects', {
214
+ query: { limit: 100 },
215
+ });
216
+ return res.projects ?? [];
217
+ }
187
218
  /** GET /api/prompts/{id} — full detail; returns null when not found (404). */
188
219
  async function getPromptById(id) {
189
220
  try {
@@ -35,6 +35,7 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.getConfigPath = getConfigPath;
37
37
  exports.readConfig = readConfig;
38
+ exports.configStatus = configStatus;
38
39
  exports.writeConfig = writeConfig;
39
40
  exports.clearConfig = clearConfig;
40
41
  exports.isTokenExpiringSoon = isTokenExpiringSoon;
@@ -66,6 +67,18 @@ function readConfig() {
66
67
  return null;
67
68
  }
68
69
  }
70
+ /**
71
+ * Three-way session state, for callers that must NOT treat "file is corrupt"
72
+ * the same as "never logged in". The read commands fall back to the local
73
+ * store when signed out; doing that silently on a truncated config file made
74
+ * a logged-in user stare at an empty local list thinking their prompts were
75
+ * gone. 'invalid' lets the router warn first.
76
+ */
77
+ function configStatus() {
78
+ if (!fs.existsSync(CONFIG_FILE))
79
+ return 'absent';
80
+ return readConfig() ? 'valid' : 'invalid';
81
+ }
69
82
  /**
70
83
  * Config'i diske yaz. Klasör yoksa oluştur, dosya izinlerini 0600 yap
71
84
  * (sadece kullanıcı okuyabilir — token sızıntısı önlemi).
@@ -23,6 +23,25 @@ function resolveEnv(key, fallback) {
23
23
  /** Base URL of the web API the CLI calls (no trailing slash). */
24
24
  exports.API_BASE_URL = resolveEnv('PROMPTLIKE_API_URL', BAKED_API_URL).replace(/\/+$/, '');
25
25
  exports.CLI_NAME = 'ple';
26
- exports.CLI_VERSION = '0.2.2';
26
+ /**
27
+ * Sürüm TEK KAYNAKTAN: package.json. Eskiden elle yazılan sabitti ve kayıyordu
28
+ * — yayınlanan 0.3.0 kendini '0.2.2' sanıyordu (`ple --version` yanlış cevap
29
+ * veriyor, destek/hata ayıklamayı yanıltıyordu). `src/lib` ve `dist/lib` aynı
30
+ * derinlikte olduğu için '../../package.json' her iki durumda da paket köküne
31
+ * denk gelir. Yol değişken üzerinden verilir ki tsc JSON'u programa dahil edip
32
+ * rootDir'i bozmasın.
33
+ */
34
+ function readVersion() {
35
+ try {
36
+ const pkgPath = '../../package.json';
37
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
38
+ const pkg = require(pkgPath);
39
+ return pkg.version ?? '0.0.0';
40
+ }
41
+ catch {
42
+ return '0.0.0';
43
+ }
44
+ }
45
+ exports.CLI_VERSION = readVersion();
27
46
  /** Web app URL — shown to the user when their prompt list is empty. */
28
47
  exports.WEB_APP_URL = 'https://promptlikeengineer.com';
@@ -0,0 +1,265 @@
1
+ "use strict";
2
+ /**
3
+ * Local-first prompt store — `~/.promptlike/prompts/*.md`.
4
+ *
5
+ * WHY THIS EXISTS: before this, every CLI command answered
6
+ * `Not logged in. Run 'ple login' first.` A person who ran `npm i -g promptlike`
7
+ * hit a wall before the tool did anything useful, so the install was a dead end.
8
+ * Competing Claude Code plugins deliver value in about five seconds with no
9
+ * account at all.
10
+ *
11
+ * So the account is no longer the door — it is the upgrade. Prompts start as
12
+ * plain files on your machine; signing in adds sync, history and the web app.
13
+ *
14
+ * FORMAT: Markdown with a small YAML-ish frontmatter block. Deliberately not
15
+ * JSON — these files are meant to be greppable, diffable and git-committable,
16
+ * which is the same promise the product makes about prompts.
17
+ *
18
+ * ---
19
+ * title: Code review
20
+ * description: Reviews a diff
21
+ * tags: review, git
22
+ * created: 2026-08-10T12:00:00.000Z
23
+ * updated: 2026-08-10T12:00:00.000Z
24
+ * ---
25
+ * <prompt body>
26
+ */
27
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
28
+ if (k2 === undefined) k2 = k;
29
+ var desc = Object.getOwnPropertyDescriptor(m, k);
30
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
31
+ desc = { enumerable: true, get: function() { return m[k]; } };
32
+ }
33
+ Object.defineProperty(o, k2, desc);
34
+ }) : (function(o, m, k, k2) {
35
+ if (k2 === undefined) k2 = k;
36
+ o[k2] = m[k];
37
+ }));
38
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
39
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
40
+ }) : function(o, v) {
41
+ o["default"] = v;
42
+ });
43
+ var __importStar = (this && this.__importStar) || (function () {
44
+ var ownKeys = function(o) {
45
+ ownKeys = Object.getOwnPropertyNames || function (o) {
46
+ var ar = [];
47
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
48
+ return ar;
49
+ };
50
+ return ownKeys(o);
51
+ };
52
+ return function (mod) {
53
+ if (mod && mod.__esModule) return mod;
54
+ var result = {};
55
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
56
+ __setModuleDefault(result, mod);
57
+ return result;
58
+ };
59
+ })();
60
+ Object.defineProperty(exports, "__esModule", { value: true });
61
+ exports.localRoot = localRoot;
62
+ exports.promptsDir = promptsDir;
63
+ exports.slugify = slugify;
64
+ exports.serialize = serialize;
65
+ exports.parse = parse;
66
+ exports.filePath = filePath;
67
+ exports.exists = exists;
68
+ exports.save = save;
69
+ exports.read = read;
70
+ exports.remove = remove;
71
+ exports.list = list;
72
+ exports.resolve = resolve;
73
+ exports.search = search;
74
+ exports.fillVariables = fillVariables;
75
+ const fs = __importStar(require("fs"));
76
+ const os = __importStar(require("os"));
77
+ const path = __importStar(require("path"));
78
+ /** Root of the local store. Overridable for tests and for people who relocate it. */
79
+ function localRoot() {
80
+ const override = process.env.PROMPTLIKE_HOME;
81
+ if (override && override.trim())
82
+ return override.trim();
83
+ return path.join(os.homedir(), '.promptlike');
84
+ }
85
+ function promptsDir() {
86
+ return path.join(localRoot(), 'prompts');
87
+ }
88
+ /**
89
+ * Turn a title into a filename-safe slug.
90
+ *
91
+ * Unicode letters are kept (`ş`, `ğ`, `é` are valid in filenames on every
92
+ * platform we support), so a Turkish title does not collapse into gibberish.
93
+ * Only path-hostile characters are removed.
94
+ */
95
+ function slugify(input) {
96
+ const cleaned = input
97
+ .toLowerCase()
98
+ .trim()
99
+ .replace(/[/\\:*?"<>|.]+/g, '') // path-hostile on macOS/Linux/Windows
100
+ .replace(/\s+/g, '-')
101
+ .replace(/-{2,}/g, '-')
102
+ .replace(/^-+|-+$/g, '');
103
+ return cleaned || 'prompt';
104
+ }
105
+ function escapeValue(v) {
106
+ // Frontmatter is one value per line; a newline would silently truncate it.
107
+ return v.replace(/\r?\n/g, ' ').trim();
108
+ }
109
+ function serialize(p) {
110
+ // Empty fields are written without a trailing space — these files are meant
111
+ // to be read and diffed by a human, and trailing whitespace shows up in diffs.
112
+ const field = (key, value) => value ? `${key}: ${value}` : `${key}:`;
113
+ const lines = [
114
+ '---',
115
+ field('title', escapeValue(p.title)),
116
+ field('description', escapeValue(p.description)),
117
+ field('tags', p.tags.map(escapeValue).filter(Boolean).join(', ')),
118
+ field('created', p.created),
119
+ field('updated', p.updated),
120
+ '---',
121
+ '',
122
+ ];
123
+ return `${lines.join('\n')}${p.body.replace(/\s+$/, '')}\n`;
124
+ }
125
+ /**
126
+ * Parse a stored file. Tolerant on purpose: a hand-edited file with a missing
127
+ * field or no frontmatter at all still loads, because these are the user's own
128
+ * files and refusing to read them would be the worst possible failure mode.
129
+ */
130
+ function parse(slug, raw) {
131
+ const fallback = {
132
+ slug,
133
+ title: slug,
134
+ description: '',
135
+ tags: [],
136
+ body: raw.trim(),
137
+ created: '',
138
+ updated: '',
139
+ };
140
+ if (!raw.startsWith('---'))
141
+ return fallback;
142
+ const end = raw.indexOf('\n---', 3);
143
+ if (end === -1)
144
+ return fallback;
145
+ const header = raw.slice(3, end);
146
+ const body = raw.slice(end + 4).replace(/^\r?\n/, '');
147
+ const field = (name) => {
148
+ const m = header.match(new RegExp(`^${name}:\\s*(.*)$`, 'm'));
149
+ return m ? m[1].trim() : '';
150
+ };
151
+ const tags = field('tags')
152
+ .split(',')
153
+ .map((t) => t.trim())
154
+ .filter(Boolean);
155
+ return {
156
+ slug,
157
+ title: field('title') || slug,
158
+ description: field('description'),
159
+ tags,
160
+ body: body.trim(),
161
+ created: field('created'),
162
+ updated: field('updated'),
163
+ };
164
+ }
165
+ function ensureDir() {
166
+ const dir = promptsDir();
167
+ if (!fs.existsSync(dir))
168
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
169
+ }
170
+ function filePath(slug) {
171
+ return path.join(promptsDir(), `${slug}.md`);
172
+ }
173
+ function exists(slug) {
174
+ return fs.existsSync(filePath(slug));
175
+ }
176
+ function save(p) {
177
+ ensureDir();
178
+ const now = new Date().toISOString();
179
+ const previous = exists(p.slug) ? read(p.slug) : null;
180
+ const record = {
181
+ ...p,
182
+ // Overwriting keeps the original creation time — the file has a history
183
+ // even though this store does not keep versions.
184
+ created: p.created || previous?.created || now,
185
+ updated: now,
186
+ };
187
+ fs.writeFileSync(filePath(record.slug), serialize(record), { mode: 0o600 });
188
+ return record;
189
+ }
190
+ function read(slug) {
191
+ const file = filePath(slug);
192
+ if (!fs.existsSync(file))
193
+ return null;
194
+ return parse(slug, fs.readFileSync(file, 'utf-8'));
195
+ }
196
+ function remove(slug) {
197
+ const file = filePath(slug);
198
+ if (!fs.existsSync(file))
199
+ return false;
200
+ fs.unlinkSync(file);
201
+ return true;
202
+ }
203
+ function list() {
204
+ const dir = promptsDir();
205
+ if (!fs.existsSync(dir))
206
+ return [];
207
+ return fs
208
+ .readdirSync(dir)
209
+ .filter((f) => f.endsWith('.md'))
210
+ .map((f) => {
211
+ const slug = f.slice(0, -3);
212
+ try {
213
+ return parse(slug, fs.readFileSync(path.join(dir, f), 'utf-8'));
214
+ }
215
+ catch {
216
+ return null; // unreadable file must not take down `ple list`
217
+ }
218
+ })
219
+ .filter((p) => p !== null)
220
+ .sort((a, b) => (b.updated || '').localeCompare(a.updated || ''));
221
+ }
222
+ /**
223
+ * Resolve a user-typed name to one prompt: exact slug, then exact title,
224
+ * then unique case-insensitive partial. Ambiguity is reported, never guessed.
225
+ */
226
+ function resolve(name) {
227
+ const all = list();
228
+ if (all.length === 0)
229
+ return null;
230
+ const needle = name.toLowerCase().trim();
231
+ const bySlug = all.find((p) => p.slug.toLowerCase() === needle);
232
+ if (bySlug)
233
+ return { prompt: bySlug };
234
+ const byTitle = all.filter((p) => p.title.toLowerCase() === needle);
235
+ if (byTitle.length === 1)
236
+ return { prompt: byTitle[0] };
237
+ if (byTitle.length > 1)
238
+ return { candidates: byTitle };
239
+ const partial = all.filter((p) => p.slug.toLowerCase().includes(needle) || p.title.toLowerCase().includes(needle));
240
+ if (partial.length === 1)
241
+ return { prompt: partial[0] };
242
+ if (partial.length > 1)
243
+ return { candidates: partial };
244
+ return null;
245
+ }
246
+ /** Free-text search over title, description, tags and body. */
247
+ function search(query) {
248
+ const needle = query.toLowerCase().trim();
249
+ if (!needle)
250
+ return [];
251
+ return list().filter((p) => [p.title, p.description, p.tags.join(' '), p.body].join('\n').toLowerCase().includes(needle));
252
+ }
253
+ /** Fill `{{variables}}`; report the ones left unfilled rather than shipping them. */
254
+ function fillVariables(body, values) {
255
+ const missing = new Set();
256
+ const text = body.replace(/\{\{\s*([\w.-]+)\s*\}\}/g, (match, key) => {
257
+ const value = values[key];
258
+ if (value === undefined) {
259
+ missing.add(key);
260
+ return match;
261
+ }
262
+ return value;
263
+ });
264
+ return { text, missing: [...missing] };
265
+ }
@@ -1,11 +1,32 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveProjectId = resolveProjectId;
3
4
  exports.resolvePromptByName = resolvePromptByName;
4
5
  exports.fetchPromptContent = fetchPromptContent;
5
6
  const format_1 = require("./format");
6
7
  const api_client_1 = require("./api-client");
7
8
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8
9
  const SHORT_ID_RE = /^[0-9a-f]{8,}$/i;
10
+ /**
11
+ * Resolve a `--project <value>` argument (UUID, exact name, or slug) to a
12
+ * project id. Throws a friendly error when it matches zero or multiple repos.
13
+ */
14
+ async function resolveProjectId(value) {
15
+ const trimmed = value.trim();
16
+ if (UUID_RE.test(trimmed))
17
+ return trimmed;
18
+ const projects = await (0, api_client_1.listProjects)();
19
+ const lower = trimmed.toLowerCase();
20
+ const matches = projects.filter((p) => p.name.toLowerCase() === lower || (p.slug ?? '').toLowerCase() === lower);
21
+ if (matches.length === 1)
22
+ return matches[0].id;
23
+ if (matches.length === 0) {
24
+ throw new Error(`No repo matched '${trimmed}'. Run 'ple list' or use the repo's exact name, slug, or id.`);
25
+ }
26
+ // Multiple repos share this name — ask for the id.
27
+ const hint = matches.map((p) => `${(0, format_1.shortId)(p.id)} ${p.name}`).join(', ');
28
+ throw new Error(`'${trimmed}' matched multiple repos (${hint}). Use the repo id.`);
29
+ }
9
30
  /**
10
31
  * Resolve a user-supplied `<name>` argument to a single prompt.
11
32
  * - Full UUID → direct detail lookup.
@@ -16,21 +37,27 @@ const SHORT_ID_RE = /^[0-9a-f]{8,}$/i;
16
37
  *
17
38
  * Throws on auth/network errors (the command wrapper catches them).
18
39
  */
19
- async function resolvePromptByName(name) {
40
+ async function resolvePromptByName(name, scope = {}) {
20
41
  const trimmed = name.trim();
21
42
  if (!trimmed) {
22
43
  throw new Error('Cannot resolve an empty name.');
23
44
  }
24
- // 1) Full UUID → detail endpoint.
45
+ const projectId = scope.projectId;
46
+ // 1) Full UUID → detail endpoint. (Scope is advisory; verify it belongs.)
25
47
  if (UUID_RE.test(trimmed)) {
26
48
  const found = await (0, api_client_1.getPromptById)(trimmed);
27
- if (found)
49
+ if (found) {
50
+ if (projectId && found.project_id && found.project_id !== projectId) {
51
+ console.error(format_1.c.error(`Prompt '${(0, format_1.shortId)(found.id)}' is not in the selected repo.`));
52
+ return null;
53
+ }
28
54
  return found;
55
+ }
29
56
  // Not found by id — fall through to a title search.
30
57
  }
31
58
  // 2) Short-id prefix (hex, 8+ chars, not a full UUID) → match a page.
32
59
  if (!UUID_RE.test(trimmed) && SHORT_ID_RE.test(trimmed)) {
33
- const page = await (0, api_client_1.listPrompts)({ limit: 100 });
60
+ const page = await (0, api_client_1.listPrompts)({ limit: 100, projectId });
34
61
  const lower = trimmed.toLowerCase();
35
62
  const matches = page.filter((p) => p.id.toLowerCase().startsWith(lower));
36
63
  if (matches.length === 1)
@@ -42,12 +69,13 @@ async function resolvePromptByName(name) {
42
69
  // No id match — fall through to a title search.
43
70
  }
44
71
  // 3) Title / description search.
45
- const results = await (0, api_client_1.listPrompts)({ search: trimmed, limit: 100 });
72
+ const results = await (0, api_client_1.listPrompts)({ search: trimmed, limit: 100, projectId });
46
73
  const lower = trimmed.toLowerCase();
47
74
  const titleMatches = results.filter((p) => p.title.toLowerCase().includes(lower));
48
75
  const pool = titleMatches.length > 0 ? titleMatches : results;
49
76
  if (pool.length === 0) {
50
- console.error(format_1.c.error(`No prompt matched '${trimmed}'.`));
77
+ const where = projectId ? ' in the selected repo' : '';
78
+ console.error(format_1.c.error(`No prompt matched '${trimmed}'${where}.`));
51
79
  return null;
52
80
  }
53
81
  if (pool.length === 1)
@@ -60,9 +88,11 @@ async function resolvePromptByName(name) {
60
88
  return null;
61
89
  }
62
90
  function printAmbiguous(query, rows) {
63
- console.error(format_1.c.warn(`'${query}' matched multiple prompts. Use a more specific name or short id:`));
91
+ console.error(format_1.c.warn(`'${query}' matched multiple prompts. Narrow with --project <repo>, or use a short id:`));
64
92
  for (const r of rows.slice(0, 10)) {
65
- console.error(` ${format_1.c.muted((0, format_1.shortId)(r.id))} ${r.title}`);
93
+ // Repo adını göster (F-analiz): aynı başlık iki repo'daysa hangisi belli olsun.
94
+ const repo = r.project_name ? format_1.c.muted(` (${r.project_name})`) : '';
95
+ console.error(` ${format_1.c.muted((0, format_1.shortId)(r.id))} ${r.title}${repo}`);
66
96
  }
67
97
  }
68
98
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "promptlike",
3
- "version": "0.2.2",
3
+ "version": "0.4.0",
4
4
  "description": "Terminal access to your PromptLikeEngineer prompt library - search, read, and copy your saved prompts without leaving the shell.",
5
5
  "bin": {
6
6
  "ple": "dist/index.js"
@@ -9,6 +9,7 @@
9
9
  "files": [
10
10
  "dist",
11
11
  "README.md",
12
+ "CHANGELOG.md",
12
13
  "LICENSE"
13
14
  ],
14
15
  "scripts": {