@ftrdotdev/pi-inquiry 0.7.0 → 0.9.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.
@@ -6,8 +6,8 @@
6
6
  * `QuestionResult`) are the validated internal representation.
7
7
  */
8
8
 
9
- import { Schema } from "effect";
10
- import { stripLeadingEmoji } from "./text.ts";
9
+ import { Effect, Schema } from "effect";
10
+ import { isNonEmptyString, stripLeadingEmoji } from "./text.ts";
11
11
 
12
12
  // ---------------------------------------------------------------------------
13
13
  // Wire schemas (tool parameters) — the single source of truth. The tool's
@@ -21,11 +21,17 @@ export const OptionParamsSchema = Schema.Struct({
21
21
  description: Schema.optionalKey(
22
22
  Schema.String.annotate({ description: "Optional description shown below label" }),
23
23
  ),
24
+ recommended: Schema.optionalKey(
25
+ Schema.Boolean.annotate({
26
+ description:
27
+ "Recommend this option to the user (default: false). On a single-choice question, recommend at most one option. Set multiple: true to recommend more than one option.",
28
+ }),
29
+ ),
24
30
  });
25
31
 
26
32
  export type OptionParams = typeof OptionParamsSchema.Type;
27
33
 
28
- export const QuestionParamsSchema = Schema.Struct({
34
+ const QuestionParamsStruct = Schema.Struct({
29
35
  prompt: Schema.String.annotate({ description: "The full question text to display" }),
30
36
  options: Schema.Array(OptionParamsSchema).annotate({
31
37
  description: "Available options to choose from",
@@ -52,7 +58,33 @@ export const QuestionParamsSchema = Schema.Struct({
52
58
  ),
53
59
  });
54
60
 
55
- export type QuestionParams = typeof QuestionParamsSchema.Type;
61
+ export type QuestionParams = typeof QuestionParamsStruct.Type;
62
+
63
+ /**
64
+ * A single-choice question can recommend at most one option. The rule lives on
65
+ * the wire record. `decodeParams` is then the only rejection point, and its
66
+ * failure text is the message the model already receives. The rule rejects the
67
+ * call and does not trim options. An absent or false `multiple` counts as
68
+ * single-choice. The pointer names the second recommended option. The decoder
69
+ * appends the pointer.
70
+ */
71
+ const atMostOneRecommendation = Schema.makeFilter((q: QuestionParams): Schema.FilterOutput => {
72
+ if (q.multiple ?? false) return undefined;
73
+ const recommended = q.options.flatMap((option, index) =>
74
+ (option.recommended ?? false) ? [index] : [],
75
+ );
76
+ if (recommended.length <= 1) return undefined;
77
+ const name = q.label ?? q.id;
78
+ const subject = name === undefined ? "this question" : `question "${name}"`;
79
+ return {
80
+ path: ["options", recommended[1]!],
81
+ issue:
82
+ `${subject} is single-choice but has ${recommended.length} recommended options; ` +
83
+ `keep at most one recommended option, or set multiple: true`,
84
+ };
85
+ });
86
+
87
+ export const QuestionParamsSchema = QuestionParamsStruct.check(atMostOneRecommendation);
56
88
 
57
89
  export const QuestionListParamsSchema = Schema.Struct({
58
90
  questions: Schema.Array(QuestionParamsSchema).annotate({
@@ -65,7 +97,7 @@ export type QuestionListParams = typeof QuestionListParamsSchema.Type;
65
97
 
66
98
  /**
67
99
  * JSON Schema form of the wire params, passed to pi as the tool's
68
- * `parameters`. `onExcessProperty: "ignore"` mirrors the legacy typebox
100
+ * `parameters`. `onExcessProperty: "ignore"` mirrors the legacy tool
69
101
  * contract (unknown keys such as the old `value` field are tolerated) and
70
102
  * matches Effect's own struct decoding, which ignores unknown keys.
71
103
  */
@@ -85,7 +117,7 @@ export const decodeParams = (input: unknown): QuestionListParams =>
85
117
  * the tool's `prepareArguments` before schema validation.
86
118
  */
87
119
  export const prepareQuestionArgs = (args: unknown): unknown => {
88
- if (args && typeof args === "object") {
120
+ if (typeof args === "object" && args !== null) {
89
121
  const legacy = args as { question?: unknown; options?: unknown; questions?: unknown };
90
122
  if (!Array.isArray(legacy.questions) && typeof legacy.question === "string") {
91
123
  return {
@@ -105,12 +137,27 @@ export const prepareQuestionArgs = (args: unknown): unknown => {
105
137
  // Domain model
106
138
  // ---------------------------------------------------------------------------
107
139
 
108
- export class Option extends Schema.Class<Option>("inquiry/core/domain/Option")({
140
+ /**
141
+ * Collapse the wire recommendation to a concrete boolean at the wire-to-domain
142
+ * boundary. Nothing downstream then distinguishes "absent" from "false". The
143
+ * constructor default keeps hand-built `new Option({ label })` values working.
144
+ */
145
+ const optionRecommended = Schema.Boolean.pipe(
146
+ Schema.withDecodingDefaultType(Effect.succeed(false)),
147
+ Schema.withConstructorDefault(Effect.succeed(false)),
148
+ );
149
+
150
+ export class Option extends Schema.Class<Option, { readonly brand: unique symbol }>(
151
+ "inquiry/core/domain/Option",
152
+ )({
109
153
  label: Schema.String,
110
154
  description: Schema.optionalKey(Schema.String),
155
+ recommended: optionRecommended,
111
156
  }) {}
112
157
 
113
- export class Question extends Schema.Class<Question>("inquiry/core/domain/Question")({
158
+ export class Question extends Schema.Class<Question, { readonly brand: unique symbol }>(
159
+ "inquiry/core/domain/Question",
160
+ )({
114
161
  id: Schema.String,
115
162
  label: Schema.String,
116
163
  prompt: Schema.String,
@@ -119,14 +166,16 @@ export class Question extends Schema.Class<Question>("inquiry/core/domain/Questi
119
166
  multiple: Schema.Boolean,
120
167
  }) {}
121
168
 
122
- export class Answer extends Schema.Class<Answer>("inquiry/core/domain/Answer")({
169
+ export class Answer extends Schema.Class<Answer, { readonly brand: unique symbol }>(
170
+ "inquiry/core/domain/Answer",
171
+ )({
123
172
  id: Schema.String,
124
173
  label: Schema.String,
125
174
  wasCustom: Schema.Boolean,
126
175
  index: Schema.optionalKey(Schema.Int),
127
176
  }) {}
128
177
 
129
- export class QuestionResult extends Schema.Class<QuestionResult>(
178
+ export class QuestionResult extends Schema.Class<QuestionResult, { readonly brand: unique symbol }>(
130
179
  "inquiry/core/domain/QuestionResult",
131
180
  )({
132
181
  questions: Schema.Array(Question),
@@ -144,19 +193,21 @@ export class QuestionResult extends Schema.Class<QuestionResult>(
144
193
  * markers duplicate.
145
194
  */
146
195
  export const normalizeQuestions = (params: QuestionListParams): readonly Question[] =>
147
- params.questions.map(
148
- (q, i) =>
149
- new Question({
150
- id: q.id ?? `q${i + 1}`,
151
- label: stripLeadingEmoji(q.label ?? `Q${i + 1}`),
152
- prompt: stripLeadingEmoji(q.prompt),
153
- options: q.options.map((o) => {
154
- const label = stripLeadingEmoji(o.label);
155
- const description =
156
- o.description === undefined ? undefined : stripLeadingEmoji(o.description);
157
- return description ? new Option({ label, description }) : new Option({ label });
158
- }),
159
- allowOther: q.allowOther !== false,
160
- multiple: q.multiple === true,
196
+ params.questions.map((q, i) =>
197
+ Question.make({
198
+ id: q.id ?? `q${i + 1}`,
199
+ label: stripLeadingEmoji(q.label ?? `Q${i + 1}`),
200
+ prompt: stripLeadingEmoji(q.prompt),
201
+ options: q.options.map((o) => {
202
+ const label = stripLeadingEmoji(o.label);
203
+ const description =
204
+ o.description === undefined ? undefined : stripLeadingEmoji(o.description);
205
+ const recommended = o.recommended ?? false;
206
+ return isNonEmptyString(description)
207
+ ? Option.make({ label, description, recommended })
208
+ : Option.make({ label, recommended });
161
209
  }),
210
+ allowOther: q.allowOther !== false,
211
+ multiple: q.multiple ?? false,
212
+ }),
162
213
  );
@@ -1,4 +1,13 @@
1
- import { describe, expect, it } from "vitest";
1
+ import { assert, describe, expect, it } from "@effect/vitest";
2
+ import { PROPERTY_RUNS } from "@ftrdotdev/pi-test-kit";
3
+ import {
4
+ cursorSeedArbitrary,
5
+ editorInputArbitrary,
6
+ pasteTextArbitrary,
7
+ permittedTextArbitrary,
8
+ singleCodePointArbitrary,
9
+ stepsArbitrary,
10
+ } from "../../test-support/generators.ts";
2
11
  import {
3
12
  editorBackspace,
4
13
  editorDelete,
@@ -29,21 +38,6 @@ describe("editorInsert", () => {
29
38
  expect(s.text).toBe("ab");
30
39
  expect(s.cursor).toBe(2);
31
40
  });
32
-
33
- it("inserts at the cursor position", () => {
34
- const s = editorInsert(editorInsert(emptyEditor(), "ab"), "X");
35
- expect(s.text).toBe("abX");
36
- const moved = editorMoveLeft(editorInsert(emptyEditor(), "ab"));
37
- const inserted = editorInsert(moved, "X");
38
- expect(inserted.text).toBe("aXb");
39
- expect(inserted.cursor).toBe(2);
40
- });
41
-
42
- it("treats surrogate pairs as single characters", () => {
43
- const s = editorInsert(emptyEditor(), "😀");
44
- expect(s.cursor).toBe(1);
45
- expect(s.text).toBe("😀");
46
- });
47
41
  });
48
42
 
49
43
  describe("editorBackspace", () => {
@@ -52,19 +46,6 @@ describe("editorBackspace", () => {
52
46
  expect(s.text).toBe("ab");
53
47
  expect(s.cursor).toBe(2);
54
48
  });
55
-
56
- it("is a no-op at the start", () => {
57
- const s = editorBackspace(emptyEditor());
58
- expect(s).toEqual(emptyEditor());
59
- });
60
-
61
- it("deletes whole code points", () => {
62
- // insert "😀a", move left of the trailing "a", then backspace deletes the emoji
63
- const base = editorInsert(emptyEditor(), "😀a");
64
- const s = editorBackspace(editorMoveLeft(base));
65
- expect(s.text).toBe("a");
66
- expect(s.cursor).toBe(0);
67
- });
68
49
  });
69
50
 
70
51
  describe("editorDelete", () => {
@@ -87,11 +68,6 @@ describe("editor movement", () => {
87
68
  expect(editorMoveRight(emptyEditor()).cursor).toBe(0);
88
69
  });
89
70
 
90
- it("clamps at the boundaries", () => {
91
- expect(editorMoveLeft(emptyEditor()).cursor).toBe(0);
92
- expect(editorMoveRight({ text: "ab", cursor: 2 }).cursor).toBe(2);
93
- });
94
-
95
71
  it("moves by code points", () => {
96
72
  const base = editorInsert(emptyEditor(), "😀a");
97
73
  expect(editorMoveLeft(base).cursor).toBe(1);
@@ -106,10 +82,6 @@ describe("editor movement", () => {
106
82
  });
107
83
 
108
84
  describe("sanitizePaste", () => {
109
- it("normalizes line endings to newlines", () => {
110
- expect(sanitizePaste("a\r\nb\rc")).toBe("a\nb\nc");
111
- });
112
-
113
85
  it("expands tabs to four spaces", () => {
114
86
  expect(sanitizePaste("a\tb")).toBe("a b");
115
87
  });
@@ -117,8 +89,81 @@ describe("sanitizePaste", () => {
117
89
  it("keeps newlines and printable characters", () => {
118
90
  expect(sanitizePaste("line1\nline2 😀")).toBe("line1\nline2 😀");
119
91
  });
120
-
121
- it("drops other control characters", () => {
122
- expect(sanitizePaste("\x03a\x07\x1bb")).toBe("ab");
123
- });
124
92
  });
93
+
94
+ it.prop(
95
+ "the cursor stays within the code point count after any edit",
96
+ { text: permittedTextArbitrary, input: editorInputArbitrary },
97
+ ({ text, input }) => {
98
+ const edits = [
99
+ editorInsert(editorFromText(text), input),
100
+ editorDelete(editorFromText(text)),
101
+ editorBackspace(editorFromText(text)),
102
+ ];
103
+ for (const state of edits) {
104
+ assert.isAtLeast(state.cursor, 0);
105
+ assert.isAtMost(state.cursor, Array.from(state.text).length);
106
+ }
107
+ },
108
+ { arbitrary: { runs: PROPERTY_RUNS } },
109
+ );
110
+
111
+ it.prop(
112
+ "backspace after inserting at the end returns the original text",
113
+ { text: permittedTextArbitrary, input: singleCodePointArbitrary },
114
+ ({ text, input }) => {
115
+ assert.strictEqual(editorBackspace(editorInsert(editorFromText(text), input)).text, text);
116
+ },
117
+ { arbitrary: { runs: PROPERTY_RUNS } },
118
+ );
119
+
120
+ it.prop(
121
+ "insert splices the input at the cursor and advances the cursor by its code point count",
122
+ { text: permittedTextArbitrary, input: editorInputArbitrary, cursorSeed: cursorSeedArbitrary },
123
+ ({ text, input, cursorSeed }) => {
124
+ const chars = Array.from(text);
125
+ const at = cursorSeed % (chars.length + 1);
126
+ const next = editorInsert({ text, cursor: at }, input);
127
+ const inserted = Array.from(input).length;
128
+ assert.strictEqual(Array.from(next.text).length, chars.length + inserted);
129
+ assert.strictEqual(next.cursor, at + inserted);
130
+ assert.strictEqual(next.text, chars.slice(0, at).join("") + input + chars.slice(at).join(""));
131
+ },
132
+ { arbitrary: { runs: PROPERTY_RUNS } },
133
+ );
134
+
135
+ it.prop(
136
+ "movement clamps at both ends",
137
+ { text: permittedTextArbitrary, steps: stepsArbitrary },
138
+ ({ text, steps }) => {
139
+ const count = Array.from(text).length;
140
+ let left = editorFromText(text);
141
+ let right = { text, cursor: 0 };
142
+ for (let step = 0; step < steps; step += 1) {
143
+ const movedLeft = editorMoveLeft(left);
144
+ assert.strictEqual(movedLeft.cursor, left.cursor === 0 ? 0 : left.cursor - 1);
145
+ left = movedLeft;
146
+ const movedRight = editorMoveRight(right);
147
+ assert.strictEqual(movedRight.cursor, right.cursor === count ? count : right.cursor + 1);
148
+ right = movedRight;
149
+ }
150
+ assert.isAtLeast(left.cursor, 0);
151
+ assert.isAtMost(right.cursor, count);
152
+ },
153
+ { arbitrary: { runs: PROPERTY_RUNS } },
154
+ );
155
+
156
+ it.prop(
157
+ "sanitizing a paste leaves no carriage return or control character and is idempotent",
158
+ { text: pasteTextArbitrary },
159
+ ({ text }) => {
160
+ const once = sanitizePaste(text);
161
+ assert.strictEqual(sanitizePaste(once), once);
162
+ assert(!once.includes("\r"));
163
+ for (const character of once) {
164
+ const codePoint = character.codePointAt(0) ?? 0;
165
+ assert(codePoint === 0x0a || codePoint >= 0x20);
166
+ }
167
+ },
168
+ { arbitrary: { runs: PROPERTY_RUNS } },
169
+ );
@@ -7,11 +7,11 @@ import { KeyEvent } from "./keyboard.ts";
7
7
  import type { MachineState } from "./machine.ts";
8
8
 
9
9
  const question = (over: Partial<QuestionType> = {}): QuestionType =>
10
- new Question({
10
+ Question.make({
11
11
  id: "q1",
12
12
  label: "Q1",
13
13
  prompt: "Pick one?",
14
- options: [new Option({ label: "Yes" }), new Option({ label: "No" })],
14
+ options: [Option.make({ label: "Yes" }), Option.make({ label: "No" })],
15
15
  allowOther: true,
16
16
  multiple: false,
17
17
  ...over,
@@ -21,7 +21,7 @@ const question = (over: Partial<QuestionType> = {}): QuestionType =>
21
21
  const scriptedKeyboard = (keys: KeyEvent[]): Keyboard["Service"] => {
22
22
  const remaining = [...keys];
23
23
  return {
24
- nextKey: () => Effect.sync(() => remaining.shift() ?? KeyEvent.escape),
24
+ nextKey: Effect.sync(() => remaining.shift() ?? KeyEvent.escape),
25
25
  };
26
26
  };
27
27
 
@@ -119,6 +119,25 @@ describe("runQuestionnaire", () => {
119
119
  }),
120
120
  );
121
121
 
122
+ it.effect("carries the recommendation in the recorded questions", () =>
123
+ Effect.gen(function* () {
124
+ const harness = yield* run(
125
+ [
126
+ question({
127
+ options: [
128
+ Option.make({ label: "Yes", recommended: true }),
129
+ Option.make({ label: "No" }),
130
+ ],
131
+ }),
132
+ ],
133
+ [KeyEvent.enter],
134
+ );
135
+ expect(harness.completed?.questions[0]?.options[0]?.recommended).toBe(true);
136
+ expect(harness.completed?.questions[0]?.options[1]?.recommended).toBe(false);
137
+ expect(harness.completed?.answers[0]?.index).toBe(1);
138
+ }),
139
+ );
140
+
122
141
  it.effect("collects several answers from a multi-select question", () =>
123
142
  Effect.gen(function* () {
124
143
  const harness = yield* run(
package/src/core/flow.ts CHANGED
@@ -32,7 +32,7 @@ export const runQuestionnaire = Effect.fn("inquiry.core.runQuestionnaire")(funct
32
32
  yield* renderer.present(state);
33
33
 
34
34
  while (true) {
35
- const key = yield* keyboard.nextKey();
35
+ const key = yield* keyboard.nextKey;
36
36
  const previousEditor = state.editor;
37
37
  const stepped = step(state, key);
38
38
  state = stepped.state;
@@ -47,7 +47,7 @@ export const runQuestionnaire = Effect.fn("inquiry.core.runQuestionnaire")(funct
47
47
  const suggestion = state.suggestions;
48
48
  const item =
49
49
  suggestion?.items[Math.min(suggestion.selectedIndex, suggestion.items.length - 1)];
50
- if (suggestion && item) {
50
+ if (suggestion !== null && item !== undefined) {
51
51
  const applied = yield* fileSuggestions.apply(
52
52
  state.editor.text,
53
53
  state.editor.cursor,
@@ -87,7 +87,11 @@ const refreshSuggestions = Effect.fn("inquiry.core.refreshSuggestions")(function
87
87
  fileSuggestions: FileSuggestions["Service"],
88
88
  force: boolean,
89
89
  ): Effect.fn.Return<MachineState> {
90
- if (!force && !state.suggestions && !isAtCompletionContext(textBeforeCursor(state.editor))) {
90
+ if (
91
+ !force &&
92
+ state.suggestions === null &&
93
+ !isAtCompletionContext(textBeforeCursor(state.editor))
94
+ ) {
91
95
  return state;
92
96
  }
93
97
  const result = yield* fileSuggestions.query(state.editor.text, state.editor.cursor, force);
@@ -23,7 +23,7 @@ describe("KeyEvent", () => {
23
23
  expect(new Set(events).size).toBe(13); // distinct instances
24
24
  // each singleton survives a decode round-trip
25
25
  for (const event of events) {
26
- expect(Schema.decodeUnknownSync(KeyEventSchema)(event)).toEqual(event);
26
+ expect(Schema.decodeSync(KeyEventSchema)(event)).toEqual(event);
27
27
  }
28
28
  });
29
29
 
@@ -32,8 +32,8 @@ describe("KeyEvent", () => {
32
32
  const pasted = KeyEvent.paste("hello\nworld");
33
33
  expect(typed).toEqual({ _tag: "char", char: "a" });
34
34
  expect(pasted).toEqual({ _tag: "paste", text: "hello\nworld" });
35
- expect(Schema.decodeUnknownSync(KeyEventSchema)(typed)).toEqual(typed);
36
- expect(Schema.decodeUnknownSync(KeyEventSchema)(pasted)).toEqual(pasted);
35
+ expect(Schema.decodeSync(KeyEventSchema)(typed)).toEqual(typed);
36
+ expect(Schema.decodeSync(KeyEventSchema)(pasted)).toEqual(pasted);
37
37
  });
38
38
 
39
39
  it("rejects unknown tags and missing payloads", () => {
@@ -30,7 +30,7 @@ export const KeyEventSchema = Schema.TaggedUnion({
30
30
  paste: { text: Schema.String },
31
31
  });
32
32
 
33
- export type KeyEvent = Schema.Schema.Type<typeof KeyEventSchema>;
33
+ export type KeyEvent = typeof KeyEventSchema.Type;
34
34
 
35
35
  /**
36
36
  * Canonical event instances, plus factories for the data-carrying variants.
@@ -15,11 +15,11 @@ import {
15
15
  } from "./machine.ts";
16
16
 
17
17
  const question = (over: Partial<QuestionType> = {}): QuestionType =>
18
- new Question({
18
+ Question.make({
19
19
  id: "q1",
20
20
  label: "Q1",
21
21
  prompt: "Pick one?",
22
- options: [new Option({ label: "Yes" }), new Option({ label: "No" })],
22
+ options: [Option.make({ label: "Yes" }), Option.make({ label: "No" })],
23
23
  allowOther: true,
24
24
  multiple: false,
25
25
  ...over,
@@ -258,6 +258,15 @@ describe("multi question", () => {
258
258
  expect(currentOptions(state).every((o) => !o.isOther)).toBe(true);
259
259
  });
260
260
 
261
+ it("carries the recommendation on every option row and false on 'Type something.'", () => {
262
+ const state = initialMachineState([
263
+ question({
264
+ options: [Option.make({ label: "Yes", recommended: true }), Option.make({ label: "No" })],
265
+ }),
266
+ ]);
267
+ expect(currentOptions(state).map((o) => o.recommended)).toEqual([true, false, false]);
268
+ });
269
+
261
270
  it("answers with an index relative to the visible options", () => {
262
271
  let state = initialMachineState([question({ allowOther: false })]);
263
272
  state = step(state, KeyEvent.down).state; // "No" is index 1 of 2
@@ -348,6 +357,20 @@ describe("multi-select question", () => {
348
357
  expect(isMultiEntrySelected(state, multiEntries(state)[0]!)).toBe(false);
349
358
  });
350
359
 
360
+ it("carries the recommendation on option rows only", () => {
361
+ const state = initialMachineState([
362
+ question({
363
+ multiple: true,
364
+ options: [Option.make({ label: "Yes", recommended: true }), Option.make({ label: "No" })],
365
+ }),
366
+ ]);
367
+ const entries = multiEntries(state);
368
+ expect(entries.map((e) => e.kind)).toEqual(["option", "option", "add"]);
369
+ expect(entries[0]).toMatchObject({ recommended: true });
370
+ expect(entries[1]).toMatchObject({ recommended: false });
371
+ expect(Object.keys(entries[2]!)).toEqual(["kind"]);
372
+ });
373
+
351
374
  it("toggles an option on and off with space", () => {
352
375
  let state = initialMachineState([multiQuestion()]);
353
376
  state = step(state, KeyEvent.char(" ")).state; // toggle option 0 on