Project K follows the eForth tradition of growing a useful Forth system from a very small kernel.
The question that guides this implementation is not, “How many useful words can we put into the kernel?” It is almost the opposite:
How little can a kernel know, while still giving us enough power to grow a whole system?
Project K carries that idea into a modern JavaScript host. We do not try to reproduce every historical implementation detail of an older machine: a flat dictionary address space, a particular threading model, or the constraints of a particular CPU. We preserve the design principle that matters here: keep the kernel small, make its mechanisms understandable, and let the vocabulary grow the language.
The JavaScript version of Project-K v2 adds ideas that belong to its own time—browser integration, explicit Tasks, resumable execution, and a continuation that can pause while the outside world does something else.
The language-independent contract lives in the conceptual specification. The Python V2 implementation explores the same design in a different host.
Project K requires a JavaScript runtime, not Node.js specifically.
The kernel imports nothing from Node.js. A modern browser can load it directly as an ES module:
<script type="module">
import { VM } from
"https://cdn.jsdelivr.net/gh/hcchengithub/project-k@master/js/projectk.js";
const vm = new VM();
vm.dictate(`
code answer
vm.push(42)
end-code
answer
`);
console.log(vm.pop()); // 42
</script>
There is no npm install, build step, or local copy of Project K in that example. The web page is the host.
For learning, however, you do not need to keep building little HTML files. Open Run the browser lab (source). It is the interactive laboratory used throughout this README: a Forth input area, output, data-stack display, vocabulary display, latest-definition display, and Task status.
Learning tip: Have a question? Make good use of an AI assistant in your browser’s side panel (such as Gemini in Chrome, where available). Keep the README and Lab open, ask questions about any example, and explore the answers step by step. You can do this throughout the README; try the code yourself to verify the explanations.
The games are applications built with Project K, not part of the teaching lab:
All browser HTML files load Project-K from jsDelivr. That keeps them portable: you can download any one HTML file and open it directly in a browser.
js/
├── projectk.js
├── README.md
├── demo.html
├── test.js
├── test-runner-browser.html
├── test-runner-node.js
├── package.json
└── games/
├── sokoban.html
├── rover.html
└── cave.html
The separation is intentional:
| File | Role |
|---|---|
projectk.js |
The kernel. |
demo.html |
The browser REPL/lab that accompanies this README. |
test.js |
Environment-neutral behavioral test cases. |
test-runner-browser.html |
Runs those tests in a browser. |
test-runner-node.js |
Runs the same tests under Node.js. |
games/sokoban.html |
Sokoban-K, a programmable box-pushing game. |
games/rover.html |
Rover-K, a programmable Mars rover game. |
games/cave.html |
CAVE-K, a programmable cave treasure hunt. |
One contract, two runners. The tests do not need separate Browser and Node versions; only the mechanism that runs and reports them is host-specific.
A fresh VM is intentionally almost empty.
A standalone browser module can import the Project-K constructor directly:
import { VM } from
"https://cdn.jsdelivr.net/gh/hcchengithub/project-k@master/js/projectk.js";
The browser lab already imports it and exposes VM for experimentation.
Open the browser lab, press F12 to open the web browser DevTools, choose the Console tab, and create a brand-new VM:
const new_vm = new VM();
Now ask it what words it knows:
[...new_vm.words.keys()]
What do you get? Try it before reading on. The newborn VM should report:
["code", "end-code"]
That is not a toy state we immediately hide. It is the architectural statement.
The two seed words let us describe a new operation in JavaScript and give that operation a Forth name. From there, an extension can grow stack operations, colon-definition syntax, strings, control structures, inspection tools, or an application-specific vocabulary.
Socratic question: if dup, +, :, ;, and if are useful,
why not simply hardwire all of them?
Because usefulness is not the same thing as kernel responsibility. If a facility can be grown naturally from a smaller mechanism, it is worth asking whether it belongs outside the seed.
In the browser lab, key in:
words
The lab prints the vocabulary that has been grown on top of the original
two-word seed, code and end-code.
A code definition borrows the host language. In the browser lab, enter:
code double
vm.push(vm.pop() * 2)
end-code
21 double .s
The stack display should show 42.
What happened?
code read the name double.end-code.double was published in the vocabulary.double found that Word and executed it.This is the first step in the small-kernel growth pattern:
small seed
↓
host words
↓
language-building words
↓
larger vocabulary
↓
application
A Word is a named operation.
The vocabulary maps a name to the Word that is currently visible under that name:
const word = vm.tick("double");
console.log(word.name); // double
console.log(word.category); // code
tick(name) answers a very specific question:
“Which Word is currently visible under this name?”
The VM also maintains its latest-definition reference, exposed in the
JavaScript implementation as vm.latest. During colon building it can even
refer to the provisional Word that is not yet published.
These are different questions:
tick("square"): find by name.vm.latest: identify the most recently established definition context.This distinction matters when an extension implements words such as
immediate: the operation usually wants the definition just created, not a
fresh name lookup supplied by the user.
The Python implementation exposes the same conceptual “last definition” capability through its own host interface. The conceptual specification requires the capability, not one spelling in every language.
Suppose we grow a normal square and then use it inside another colon word:
: square dup * ;
: old-square 6 square ;
Now replace the visible meaning of square:
code square
vm.push(99)
end-code
What should happen here?
old-square square
Project K leaves:
36 99
Why?
When old-square was built, it captured the Word identity of the old
square. Redefining the name changes future lookup; it does not silently
redirect references already compiled into existing colon definitions.
This is a subtle but important property of an evolving Forth system. A name can move forward without secretly changing old compiled behavior.
In the browser lab, key in:
: square dup * ;
: old-square 6 square ;
code square
vm.push(99)
end-code
old-square square .s
The stack display should show 36 99: old-square still refers to the Word
identity captured when it was compiled.
Consider:
3 4 +
How does + know which values to add?
Project K uses the Forth data stack as the ordinary channel between operations. The VM owns it:
vm.push(3, 4);
const right = vm.pop();
const left = vm.pop();
vm.push(left + right);
The public operations include:
push(...values)pop(depth = 0)peek(depth = 0)vm.dstack for host-side inspectionDepth zero is the top.
The kernel does not need to know words such as dup, swap, or
over. Those can be vocabulary:
code pick
vm.push(vm.peek(vm.pop()))
end-code
: dup 0 pick ;
: over 1 pick ;
The same question appears again: if a word can be grown, does it deserve to be a seed primitive?
Forth has long had the idea of a current input buffer and a position within it.
Project K represents that explicitly with an Input object:
| Concept | Project-K v2 JavaScript |
|---|---|
| Logical TIB | input.tib |
| Character position | input.itib |
| Unread portion | input.remaining |
| Active input | vm.input |
Example:
import { Input } from
"https://cdn.jsdelivr.net/gh/hcchengithub/project-k@master/js/projectk.js";
const input = new Input("12 square .");
console.log(input.read()); // "12"
console.log(input.itib); // 2
console.log(input.remaining); // " square ."
Reading advances the cursor; it does not destroy the source.
Why bother keeping an explicit cursor?
Because an extensible language sometimes needs to consume something other than the next whitespace token.
In the browser lab, define a word that reads text up to |:
code text
const value = vm.input.read("|").trimStart()
if (vm.compiling) vm.literal(value)
else vm.push(value)
end-code
immediate
: greeting text Hello from context-sensitive input!| ;
greeting .
A global tokenizer could not know in advance that text wants that region.
The current word knows.
That is why Project K does not reduce input to an array of tokens at the front door. General interpretation reads tokens, but extensions may consume source according to their own syntax.
text consumes source up to |, demonstrating that a Word can decide how
much of the current input to read.
This is one of the mechanisms by which a small kernel gives the user of the language some power to become a designer of the language.
: and ;Project K’s seed does not require colon syntax.
An extension can grow it:
code :
vm.begin(vm.input.read())
end-code
code ;
vm.finish()
end-code
immediate
Now:
: square dup * ;
becomes possible.
The host-side building interface is:
begin(name)comma(operation)literal(value)finish()A colon definition is not merely saved source that must be reparsed every time it runs. Its action is an ordered sequence of captured operations and literals.
In the browser lab, key in:
: square dup * ;
12 square .s
see square
The stack display should show 144, and see square shows the compiled colon
body.
; immediate?While the VM is building a colon word, ordinary words are recorded for later
execution. But ; must act now: it must finish the definition.
That is the purpose of an immediate word.
This reveals an important Forth idea: compile-time behavior is itself extensible. The kernel does not need a giant parser containing special cases for every future language construct. A word can participate in how definitions are built.
The same principle can grow strings, conditionals, loops, and application syntax.
The same small-kernel principle shows up here: syntax itself can grow out of words.
12 square .?There are two different journeys.
First, the outer interpreter walks through input:
12 → square → .
^
input.itib moves through source text
When it reaches square, the inner execution mechanism walks through the
already-built colon body:
square: [dup, *]
^
frame.ip
These are not the same loop and not the same position.
This distinction becomes essential once control flow or suspension can change execution progress.
A colon Word answers:
“What program makes up this word?”
A Frame answers:
“Where has this invocation reached in that program?”
Conceptually:
Frame = reference to colon program + this invocation's IP
The program is shared. The execution position is private.
The same Word could therefore have more than one invocation alive at different positions:
Word "work"
├── Frame A: ip = 2
└── Frame B: ip = 5
This prepares us for the next question:
If execution stops halfway, who remembers all of this?
Project K deliberately assigns different state to different owners:
| Owner | State |
|---|---|
| VM | Data stack, vocabulary, host bindings, latest definition, unfinished colon definition |
| Task | Input contexts, return stack, T-stack, Frames, continuation, status, error |
| Word | Definition identity and executable behavior |
| Frame | One colon invocation’s Word, body reference, and IP |
Why not put everything in the VM?
Because two unfinished activities may need separate execution progress even while they share one vocabulary and one data stack.
Why not put the data stack inside each Task?
Because submissions on one Forth VM normally cooperate through persistent data.
The ownership model tells us what persists, what is private, and what may be shared.
Project K distinguishes several stacks:
| Facility | Owner | Purpose |
|---|---|---|
Data stack dstack |
VM | Ordinary values exchanged by words |
Return stack rstack |
Task | Extension-visible task-private auxiliary storage |
T-stack tstack |
Task | Additional temporary/control storage |
Frame stack frames |
Task | Internal unfinished colon invocations |
The T-stack is an explicit Project K facility. It is not the Frame stack and it is not “a stack of Tasks.”
This separation matters when extensions build control structures. Temporary markers should not accidentally become ordinary application data, and invocation position should not have to masquerade as a user-visible return value.
Run:
const task = vm.dictate("3 4 +");
console.log(task.status); // done
Even though the work finished immediately, dictate() returns the execution
object that carried it out.
Likewise:
const squareTask = vm.execute(vm.tick("square"));
starts one Word directly.
The important distinction is:
dictate(text): start work by interpreting input.execute(word): start work from an operation.yield* vm.evaluate(text): enter more input inside the current Task.yield* vm.call(word): invoke more behavior inside the current Task.Starting another Task and nesting work in the current Task are not the same thing.
Grow:
code pause
yield vm.pause()
end-code
: journey 1 pause 2 ;
Then:
const journeyTask = window.vm.dictate("journey 3");
At the pause:
journeyTask.status → "paused"
data stack → [1]
Control has returned to JavaScript, but the work is not done.
Later:
journeyTask.resume();
and the stack becomes:
[1, 2, 3]
In the browser lab, key in:
: journey 1 pause 2 ;
journey
Execution stops with the Task in the paused state and 1 on the stack.
Click Resume paused task; the same Task continues and pushes 2.
This is Project K’s modern addition to the minimalist Forth story: the kernel remains small, but an execution can retain its path while the host regains control.
This is the question to linger over.
A pause is useful only if “resume” knows what “continue” means.
The retained Task connects:
Nothing keeps “running in the background.” Pause means exactly what it says: the Task has yielded control.
This makes Project K suitable for work that must wait for something external without turning the kernel into a scheduler.
A paused Task with a live input context can accept more text:
const appendedTask = window.vm.dictate("1 pause 2");
appendedTask.appendInput(" 3");
appendedTask.resume();
The result is:
[1, 2, 3]
But once a Task is done, appending does not resurrect it. End-of-input is not a secret “wait for more input” state.
Explicit states make the contract easier to reason about.
There are two different questions: Are we starting a new Task? And are we entering a new Input? The four execution interfaces answer them differently:
| Interface | New Task? | New Input? |
|---|---|---|
vm.dictate(tib) |
Yes | Yes, through evaluate() |
vm.execute(word) |
Yes | No |
yield* vm.evaluate(tib) |
No | Yes, on the current Task |
yield* vm.call(word) |
No | No |
An Input is Task-private, not a global variable stored directly on the VM.
Each Task owns an Input stack (task.inputs). The apparent VM-level property
vm.input is a getter: it returns the top Input of the currently running
Task. Outside an active Task, reading vm.input raises an error.
First, observe both Inputs while the nested evaluation is running. In the browser lab, enter:
code inspect-inputs
console.log(vm.task.inputs.map(input => input.tib))
end-code
code nested
const outer = vm.input
yield* vm.evaluate("10 inspect-inputs 20")
console.assert(vm.input === outer)
end-code
nested .s
Open the browser’s DevTools Console (F12, then Console) to see
the two Input texts logged by inspect-inputs. The Lab’s stack display
should show 10 20. The inspection runs inside the nested evaluation,
while both Inputs still exist. When that evaluation finishes, its Input
is popped, and the assertion checks that vm.input is the same outer
Input object as before.
Why yield*? vm.evaluate(...) is a JavaScript generator function.
Calling it creates a generator object; it does not execute the nested input.
yield* vm.evaluate(...) drives that generator as part of the current Word
and forwards a pause if one occurs. Without yield*, nothing in the
nested input runs. If generators are unfamiliar, ask your browser’s AI
side-panel assistant to explain the difference, step by step.
Now add suspension. In the same Lab, enter:
code nested-pause
const outer = vm.input
yield* vm.evaluate("30 pause 40")
console.assert(vm.input === outer)
end-code
nested-pause .s
The Task pauses after pushing 30. Click Resume paused task: it
continues inside the nested Input, pushes 40, finishes that Input,
and only then returns to the outer Input and checks the assertion.
The stack now contains 10 20 30 40 if you ran both examples without
resetting the Lab.
Why does this work? A paused Task retains its own Input stack and execution
continuation. While it is paused, another Task can run on the same VM with
its own Inputs. When the original Task resumes, vm.input again follows
that Task’s active Input. The VM’s dictionary and data stack, however,
are shared: other Tasks can change stack values during the pause.
The distinction to remember is: evaluate() enters a new Input within
the current Task; dictate() starts a new Task. Similarly, call()
enters a Word in the current Task, whereas execute() starts a Task
for that Word.
Project K distinguishes three forms of non-normal termination:
These are not transactions.
If a word already pushed data, published a completed definition, changed the DOM, or sent something to a host API, termination does not magically undo that effect.
What Project K does protect is the integrity of an unfinished definition: the applicable provisional definition is discarded, and an older published binding remains visible.
This is an important engineering boundary. A small kernel should make its guarantees clear rather than pretending to provide rollback it cannot provide.
In the Python implementation, host words can use Python modules and objects.
In the JavaScript version of Project-K v2, the browser itself offers a huge host environment:
fetchFor example, in the browser lab, enter:
code title
document.title = vm.pop()
end-code
s" Project K owns this browser tab" title
The browser tab title changes, demonstrating that browser capabilities can be borrowed without being built into the kernel.
Notice what the architecture does not require: DOM support inside the kernel.
The browser already knows the DOM. Project K only needs a way for a Word to borrow host capability and present it through a Forth interface.
This is a modern expression of the same old minimalist instinct: do not copy into the kernel what the host already knows how to do.
code ... end-code dynamically compiles JavaScript host bodies. A page whose
Content Security Policy forbids dynamic code generation (unsafe-eval) can
therefore block host definitions.
That is a host security policy, not a Forth parsing failure.
Applications that must operate under a strict CSP can still register trusted
host operations directly with vm.define(), or can choose an integration
strategy appropriate to that environment.
This is where the abstract pieces should earn their keep.
Sokoban-K uses the same Project K kernel rather than embedding another copy of it. Like the other downloadable games, the page imports the shared kernel from jsDelivr:
import { VM, Literal, KernelError } from
"https://cdn.jsdelivr.net/gh/hcchengithub/project-k@master/js/projectk.js";
The game then grows its own vocabulary.
Movement is expressed as Forth words:
u d l r
The data stack records the path. undo can reverse a step. Control words grow
loops and conditionals. A successful route can be turned into a new colon word
and replayed later.
Meanwhile the browser host handles rendering, buttons, keyboard events,
localStorage, and timing.
That division is the point:
Project K kernel
↓
game vocabulary
↓
browser host facilities
↓
Sokoban application
The kernel never had to learn what a box, wall, keyboard, or HTML element is.
A small kernel became an application because the system could grow.
Rover-K and CAVE-K follow the same pattern: each grows a small game-specific vocabulary on top of the shared kernel, while the browser handles rendering, input, persistence, and timing.
That is where the eForth lineage becomes visible in the design itself.
The behavioral tests live in test.js.
They test Project K concepts such as:
None of those test cases needs to be a Node test or a Browser test.
But the environments report tests differently, so there are two intentionally thin adapters:
Open:
It imports test.js, runs the cases, and renders pass/fail results into the
page.
If Node.js 18+ is available:
npm test
or:
node --test test-runner-node.js
The Node runner imports exactly the same tests array and adapts each case to
node:test.
The distinction is simple:
test.js says what must be true; a test runner says how this host executes and reports the tests.
For command-line or automation work:
import { VM } from "./projectk.js";
const vm = new VM();
vm.dictate("code answer vm.push(42) end-code answer");
console.log(vm.pop());
Node.js is a good JavaScript host. It is especially convenient for automated tests.
It is simply no longer the assumption around which the JavaScript README is organized.
Browser and Node host the same kernel; they offer different outside worlds.
Do not start by reading the file top to bottom.
Follow the execution questions:
VM.evaluate() — How does source become numbers and Word execution?Input — How is source retained and consumed?VM.call() — How are host and colon behaviors executed?Frame — Where does one colon invocation remember its IP?Task.resume() — What outcomes can execution have?begin() / comma() / literal() / finish() — How is a colon Word built?_hostDefinition() and hostBoundary() — How does the tiny seed grow
JavaScript-backed words without mistaking end-code inside strings,
templates, regexes, or comments for the real terminator?Then return to the conceptual specification and ask whether the implementation mechanism is serving the contract—or merely looking clever.
The specification is the design authority. JavaScript is one realization.
There is no model client, agent loop, prompt system, or AI vocabulary inside Project K.
That is deliberate.
But imagine a future word that starts an external AI request. The request may take seconds. A traditional blocking call would trap the host; restarting the Forth expression later would lose the execution path.
Project K already has another possibility:
Forth execution
↓
start external request
↓
pause Task
↓
return control to host
↓
response arrives
↓
host supplies result
↓
resume same Task
↓
continue after the wait
Transport, scheduling, authentication, timeout policy, model selection, and response delivery belong outside the kernel.
Again the small-kernel discipline helps: prepare the mechanism; do not confuse one fashionable application with the kernel itself.
Project K contains things eForth did not need to contain: JavaScript host integration, explicit resumable Tasks, browser applications, and a path toward future asynchronous or AI-assisted work.
Those mechanisms are new. The design principle is not: keep the kernel small, understandable, and capable of growth.
Small kernel. Extensible language. A modern continuation of the eForth idea.